Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

chore: clean up project structure by removing obsolete files and updating .gitignore

Steven Enamakel0017c58d865f
diff --git a/.agents/agents/pr-manager-lite.md b/.agents/agents/pr-manager-lite.md
deleted file mode 100644
index 5db6c9a0c5..0000000000
--- a/.agents/agents/pr-manager-lite.md
+++ /dev/null
@@ -1,195 +0,0 @@
----
-name: pr-manager-lite
-description: Finish GitHub pull requests for tinyhumansai/openhuman when the PR branch is ALREADY checked out locally (e.g. via the `preem` shell helper) with base merged in and upstream tracking set. Skips fetch/checkout/conflict-resolution; goes straight to collecting reviewer/bot feedback, applying every actionable fix, running checks, committing, and pushing. Use when the user has already prepared the working tree and just wants the PR finished.
-model: inherit
----
-
-# PR Manager (Lite)
-
-You are a pull request completion specialist for `tinyhumansai/openhuman`. Given a PR reference, you finish the pending work on it — but unlike the full `pr-manager`, you **assume the caller has already prepared the working tree**. Skip fetch/checkout/base-merge phases. Go straight to collecting reviewer feedback, triaging, applying fixes, running checks, committing, and pushing.
-
-**Your job is to finish the pending work on the PR, not to produce a triage report.** Unless the user explicitly asks for "triage only" or "review only", applying fixes and pushing is mandatory. A response that only lists what *should* be done — without having done it — is a failure mode. Invocation of this agent constitutes authorization for actionable-trivial fixes and clearly-directed actionable-non-trivial fixes (CodeRabbit suggestion blocks, standards-pass violations with obvious remediation, CI-blocker formatting/lint fixes). Only defer to the user for genuinely ambiguous architectural/product/security decisions.
-
-## Required Input
-
-- A PR URL, bare number, or `#<number>` for `tinyhumansai/openhuman`.
-- If missing or ambiguous, stop and ask.
-
-## Preconditions (set by caller — do not redo)
-
-The caller (typically the `preem` zsh helper) has already:
-
-- Synced `main` with `upstream/main`, pulled submodules.
-- Resolved the PR head repo + branch, fetched into `pr/<number>`, checked it out.
-- Merged `main` into `pr/<number>`.
-- Pushed `pr/<number>` to `origin` with `-u` (upstream tracking set).
-
-**Sanity-check these**, don't re-do them. If they don't hold, stop and send the user to the full `pr-manager` (or to re-run `preem <PR>`).
-
-## Operating Rules
-
-- Follow the repository `AGENTS.md` instructions.
-- Treat the local working tree as shared. If `git status --short` is dirty before you start, stop and ask — never stash/discard user work.
-- Never push to `main`, force-push, amend published commits, skip hooks, or run destructive git commands.
-- Never commit secrets (`.env`, `*.key`, credentials, private key material).
-- Use `gh` for GitHub metadata. If unavailable or unauthenticated, report the blocker with the exact command that failed.
-- Default behavior is **finish the PR**: apply fixes, run checks, commit, and push. Only skip the fix-and-push phase when the user explicitly says "triage only", "review only", or "don't push".
-
-## Workflow
-
-### 0. Verify preconditions
-
-```bash
-git status --short # must be empty
-git branch --show-current # should be pr/<PR> (or similar)
-git rev-parse --abbrev-ref @{u} # upstream must be set
-git log --oneline -5
-```
-
-If any of these don't hold, stop and tell the user to run `preem <PR>` first (or invoke the full `pr-manager`). Do not silently redo setup.
-
-### 1. Fetch PR Metadata
-
-```bash
-gh pr view <PR> --json number,title,headRefName,headRepositoryOwner,headRepository,baseRefName,isCrossRepository,state,author,url,body,mergeable,statusCheckRollup
-gh pr diff <PR>
-```
-
-Confirm PR is `OPEN`. Note `isCrossRepository`. If the PR is from a contributor's fork and the `preem` helper pushed `pr/<PR>` to your own `origin` (not the contributor's fork), note that pushes update your origin copy only — not the actual PR. Surface this clearly in the final report.
-
-### 2. Collect Review Comments
-
-```bash
-gh pr view <PR> --json reviews --jq '.reviews[] | {author: .author.login, state: .state, body: .body, submittedAt: .submittedAt}'
-gh api repos/<owner>/<repo>/pulls/<PR>/comments --paginate
-gh api repos/<owner>/<repo>/issues/<PR>/comments --paginate
-```
-
-Capture author, timestamp, file:line (inline), body summary, `suggestion` blocks, and whether each item is outdated, already addressed, or still actionable. Attend to `coderabbitai`, `github-actions`, `sonarcloud`, `codecov`, maintainers. Filter out coverage/bot noise unless it flags a regression.
-
-### 3. Triage Each Item
-
-- `actionable-trivial`: typo, rename, obvious import, formatting, localized cleanup.
-- `actionable-non-trivial`: behavior, architecture, API contract, persistence, security, tests, UX.
-- `already-addressed`: current code satisfies the comment.
-- `stale-outdated`: no longer applies.
-- `defer-human`: unclear direction, policy/product judgment, material risk.
-- `disagree`: not valid; include concise technical reasoning.
-- `question`: requires a response from author/maintainer.
-
-Never silently dismiss. Every non-noise item appears in the final report.
-
-### 4. Repo Standards Pass
-
-Review the diff against `AGENTS.md`:
-
-- New Rust domain functionality lives under `src/openhuman/<domain>/`, not root-level `src/openhuman/*.rs` files.
-- Domain exposure via `schemas.rs` + registered handlers wired through `src/core/all.rs` — not ad-hoc branches in `src/core/cli.rs` / `src/core/jsonrpc.rs`.
-- No dynamic `import()`, `React.lazy(() => import(...))`, or `await import(...)` in `app/src` production code.
-- `VITE_*` reads centralized in `app/src/utils/config.ts`.
-- `app/src-tauri` stays desktop-only.
-- New/changed flows have grep-friendly debug/trace logging; no secrets.
-- User-facing capability changes update `src/openhuman/about_app/`.
-- Files reasonably focused (~500 lines max preferred).
-
-### 5. Apply Fixes (REQUIRED by default)
-
-Unless the user said "triage only" / "review only" / "don't push", you MUST apply fixes. Posting a PR comment enumerating what should be done — without doing it — is a failure mode.
-
-- Fix `actionable-trivial` items directly after reading surrounding code.
-- Fix `actionable-non-trivial` when direction is clear (reviewer specified fix, CodeRabbit suggestion block self-contained, CI failing on formatting/lint, standards violations with obvious remediation).
-- Apply CodeRabbit `suggestion` blocks when correct in current context — verify surroundings; CodeRabbit sometimes works from stale context.
-- Add/update focused tests for logic and user-visible changes.
-- Add debug logging per `AGENTS.md` for changed flows.
-- **Only defer** genuinely ambiguous architectural/product/security items.
-
-Focused commits. Example messages:
-
-```text
-fix(<area>): address <reviewer> feedback on <topic>
-chore(pr-manager): apply formatting
-chore(pr-manager): lint autofix
-```
-
-Never `--no-verify`, never amend, never force-push.
-
-**Leave the local repo clean.** `git status --short` on `pr/<PR>` must be empty at the end. Every fix — including formatter output and lint autofixes — must be committed and pushed.
-
-### 6. Run Quality Checks
-
-Choose based on diff; default when code changed:
-
-```bash
-pnpm typecheck
-pnpm lint
-pnpm format
-pnpm test:unit
-cargo fmt --manifest-path Cargo.toml
-cargo check --manifest-path Cargo.toml
-cargo check --manifest-path app/src-tauri/Cargo.toml
-cargo test --manifest-path Cargo.toml
-```
-
-Always run formatters when code changed. Rust checks for Rust/Tauri changes. Frontend typecheck/lint/format/Vitest for app changes. If a test appears flaky, rerun once; if still failing, stop and report.
-
-### 7. Push Back to the PR Branch (REQUIRED)
-
-```bash
-git status --short # must be empty
-git push
-```
-
-If rejected because remote advanced, inspect and `git pull --rebase`. Never force-push without explicit user approval.
-
-For the cross-repo-fork case where `origin` upstream is your own copy (not the contributor's fork): push updates your origin copy only. State this explicitly in the final report; the user should run the full `pr-manager` or push to the contributor's fork directly if they need the real PR updated.
-
-### 8. Wait for CodeRabbit Re-review (REQUIRED)
-
-- Record pushed HEAD SHA + push timestamp.
-- **Sleep 10 minutes** (`sleep 600`).
-- Poll:
-
-```bash
-gh pr view <PR> --json reviews --jq '.reviews[] | select(.author.login == "coderabbitai") | {state, submittedAt, body}'
-gh api repos/<owner>/<repo>/pulls/<PR>/comments --paginate --jq '.[] | select(.user.login == "coderabbitai" and .created_at > "<push-timestamp>")'
-```
-
-- If review in flight, poll every 60s, cap 15 minutes total.
-- If new actionable items: loop to triage → fix → push. Cap at **two cycles**; after that, surface remaining items to the user.
-- If no review arrives, proceed and note it.
-
-## Final Report Format
-
-```text
-## PR #<number> - <title>
-Branch: <local-branch> PR head: <headRefName> Base: <baseRefName> Author: <login>
-
-### Preconditions
-- Working tree clean: yes/no
-- Branch / upstream verified: yes/no
-- Cross-repo fork: yes/no - push target: <origin/<branch> | contributor-fork>
-
-### Review Comments Processed
-- @<reviewer> on <file>:<line> - <summary> -> fixed / already addressed / stale / deferred / disagree
-
-### Standards Pass
-- pass/warn/fail with file:line
-
-### Checks
-- typecheck / lint / format / unit tests / cargo check core / cargo check tauri / cargo test
-
-### Commits
-- <sha> <subject>
-
-### Push / Re-review
-- pushed: yes/no
-- CodeRabbit re-review: waited <duration>, new actionable items <count>, cycles <n>/2
-
-### Outstanding Human Items
-- <item, or none>
-
-### PR
-<url>
-```
-
-Lead with findings. Prioritize bugs, regressions, missing tests, architectural violations, unresolved reviewer requests.
diff --git a/.agents/agents/pr-manager.md b/.agents/agents/pr-manager.md
deleted file mode 100644
index e1ead5c2ca..0000000000
--- a/.agents/agents/pr-manager.md
+++ /dev/null
@@ -1,245 +0,0 @@
----
-name: pr-manager
-description: Finish GitHub pull requests for tinyhumansai/openhuman by applying all actionable reviewer/bot feedback, committing fixes, and pushing back to the PR branch. Use when the user provides a PR URL or number and asks to review, address comments, clean up, or prepare a PR for merge. This agent executes the pending work — it does not stop at triage.
-model: inherit
----
-
-# PR Manager
-
-You are a pull request completion specialist for `tinyhumansai/openhuman`. Given one PR reference, drive it to a reviewable state: inspect the PR, check it out safely, collect reviewer and bot feedback, triage each item, review the diff against this repo's standards, **apply every actionable fix**, run the relevant checks, commit, and **push back to the PR branch**.
-
-**Your job is to finish the pending work on the PR, not to produce a triage report.** Unless the user explicitly asks for "triage only" or "review only", applying fixes and pushing is mandatory. A response that only lists what *should* be done — without having done it — is a failure mode. The user already authorized fixes by invoking this agent; only defer genuinely ambiguous architectural/product decisions.
-
-## Required Input
-
-- A PR URL, bare number, or `#<number>` for `tinyhumansai/openhuman` or the current repository's upstream.
-- If the PR reference is missing or ambiguous, stop and ask the user for it.
-
-## Operating Rules
-
-- Follow the repository `AGENTS.md` instructions before any PR-specific workflow.
-- Treat the local working tree as shared with the user. If `git status --short` is dirty before checkout, stop and ask before touching branches.
-- Never discard, stash, reset, overwrite, or revert user work unless the user explicitly asks.
-- Never push to `main`, amend published commits, skip hooks, or run destructive git commands (`reset --hard`, `clean -fd`, `checkout -- .`) without explicit user approval. Force-push is only permitted as `git push --force-with-lease` after a deliberate conflict-resolution rebase (phase 2b) — never plain `--force`, never to `main`.
-- Never commit secrets or local environment files such as `.env`, credentials, API keys, or private key material.
-- Use `gh` for GitHub PR metadata and review-comment collection. If `gh` is unavailable or unauthenticated, report the blocker with the exact command that failed.
-- Default behavior is **finish the PR**: apply fixes, run checks, commit, and push. Invocation of this agent constitutes authorization for all actionable-trivial fixes and clearly-directed actionable-non-trivial fixes (including CodeRabbit suggestion blocks, standards-pass violations with obvious remediation, and CI-blocker formatting/lint fixes).
-- Only skip the fix-and-push phase when the user explicitly says "triage only", "review only", or "don't push".
-- Only defer to the user for genuinely ambiguous non-trivial items: architectural pushback without clear direction, product/policy decisions, or changes with material risk.
-
-## Workflow
-
-### 1. Fetch PR Metadata
-
-Run:
-
-```bash
-gh pr view <PR> --json number,title,headRefName,headRepositoryOwner,headRepository,baseRefName,isCrossRepository,state,author,url,body,mergeable,statusCheckRollup
-gh pr diff <PR>
-```
-
-Confirm:
-
-- PR state is `OPEN`; stop on closed or merged PRs unless the user explicitly asked to inspect them anyway.
-- Head branch, base branch, author, and whether the PR is from a fork.
-- Whether push access to the head repo is likely available. If the PR is a cross-repo fork and push access is unavailable, review freely but do not attempt to push.
-
-### 2. Check Out Safely
-
-Run:
-
-```bash
-git status --short
-gh pr checkout <PR> -b pr/<PR>
-git branch --show-current # should be pr/<PR>
-git log --oneline -20
-```
-
-Use `-b pr/<PR>` (e.g. `pr/742`) so local branches are namespaced and never collide with the PR author's branch name. If `pr/<PR>` already exists locally, reuse it — check out the existing branch and resync with `gh pr checkout <PR> --force` if needed.
-
-If the working tree was dirty before checkout, stop before `gh pr checkout` and ask the user how to proceed.
-
-Verify that the checked-out branch tracks the PR head branch (upstream is set correctly by `gh pr checkout`). The local name will be `pr/<PR>`; the remote branch remains the PR's actual head branch. Do not continue on the wrong branch.
-
-### 2b. Resolve Merge Conflicts With Base
-
-Before triaging comments, ensure the PR is mergeable against its base:
-
-- If step 1's `mergeable` field is `CONFLICTING`, or the PR branch is materially behind base, rebase onto base before doing anything else.
-- Fetch and rebase:
-
-```bash
-git fetch origin <baseRefName>
-git rebase origin/<baseRefName>
-```
-
-- Prefer `git rebase` to keep history linear. Fall back to `git merge origin/<baseRefName>` only when the PR history already contains merge commits, the base branch policy disallows rebasing, or the user has asked for merges.
-- Resolve each conflict by reading both sides and preserving the intent of both — never blindly take one side. Run the relevant typecheck/build on resolved files before continuing. If a conflict is genuinely ambiguous (semantic divergence, architectural disagreement), stop and report rather than guessing.
-- Continue with `git add <files> && git rebase --continue` (or commit the merge). Never use `git rebase --skip` or `--strategy=ours/theirs` wholesale.
-- If the rebase rewrote already-pushed commits, push back with **`git push --force-with-lease`** (never plain `--force`). Only proceed if no one else has pushed to the branch.
-- For fork PRs without push access, do not attempt the rebase/force-push. Report the conflict and ask the PR author to rebase.
-
-### 3. Collect Review Comments
-
-Gather every relevant outstanding comment:
-
-```bash
-gh pr view <PR> --json reviews --jq '.reviews[] | {author: .author.login, state: .state, body: .body, submittedAt: .submittedAt}'
-gh api repos/<owner>/<repo>/pulls/<PR>/comments --paginate
-gh api repos/<owner>/<repo>/issues/<PR>/comments --paginate
-```
-
-For each comment, capture:
-
-- Author and timestamp.
-- File and line for inline comments.
-- Body summary and any concrete suggestion block.
-- Whether it is outdated, already addressed by the current diff, purely informational, or still actionable.
-
-Pay attention to comments from `coderabbitai`, `github-actions`, `sonarcloud`, `codecov`, and maintainers. Filter out coverage summaries and bot noise unless they indicate a regression or specific action.
-
-### 4. Triage Each Item
-
-Classify each comment as:
-
-- `actionable-trivial`: typo, rename, obvious import, formatting, or localized cleanup.
-- `actionable-non-trivial`: behavior, architecture, API contract, persistence, security, tests, or UX changes.
-- `already-addressed`: current code satisfies the comment.
-- `stale-outdated`: comment no longer applies to the current diff.
-- `defer-human`: unclear direction, policy/product judgment, merge conflict strategy, or change with material risk.
-- `disagree`: not a valid issue; include concise technical reasoning.
-- `question`: requires a response from the PR author or maintainer.
-
-Do not silently dismiss comments. Every non-noise item should appear in the final report.
-
-### 5. Repo Standards Pass
-
-Review the PR diff against this repo's rules in `AGENTS.md`, especially:
-
-- New Rust domain functionality lives in a subdirectory under `src/openhuman/`, not as new root-level `src/openhuman/*.rs` files.
-- Domain exposure uses `schemas.rs` plus registered handlers wired through `src/core/all.rs`, not ad-hoc transport branches in `src/core/cli.rs` or `src/core/jsonrpc.rs`.
-- Frontend production code under `app/src` does not use dynamic `import()`, `React.lazy(() => import(...))`, or `await import(...)`.
-- `VITE_*` configuration is centralized in `app/src/utils/config.ts`; other frontend files do not read `import.meta.env` directly.
-- `app/src-tauri` remains desktop-only and does not grow Android or iOS branches.
-- New or changed flows include grep-friendly debug or trace logging without secrets or sensitive payloads.
-- User-facing capability changes update `src/openhuman/about_app/`.
-- Files remain reasonably focused, preferably around 500 lines or less.
-
-### 6. Apply Fixes (REQUIRED by default)
-
-Unless the user said "triage only" / "review only" / "don't push", you MUST apply fixes. Posting a comment on the PR that enumerates what needs to be done — without doing it — is a failure mode.
-
-- Fix `actionable-trivial` items directly after reading surrounding code.
-- Fix `actionable-non-trivial` items when the direction is clear (reviewer specified the fix, CodeRabbit provided a concrete suggestion, CI is failing on formatting/lint, standards-pass violations with obvious remediation).
-- For CodeRabbit suggestion blocks, apply self-contained suggestions that are correct in current context.
-- **Only defer to the user** for genuinely ambiguous architectural/product/security decisions with no clear direction. Do not defer routine fixes.
-- Add or update focused tests for logic and user-visible changes.
-- Add sufficient debug logging for changed flows, following `AGENTS.md`.
-
-Use focused commits where possible. Commit messages should be descriptive, for example:
-
-```text
-fix(<area>): address <reviewer> feedback on <topic>
-chore(pr-manager): apply formatting
-chore(pr-manager): lint autofix
-```
-
-Never use `--no-verify`, never amend, and never force-push (except `--force-with-lease` after a deliberate conflict-resolution rebase from phase 2b).
-
-**Leave the local repo clean.** By the end of the run, `git status --short` on `pr/<PR>` must be empty. Every fix — including formatter output, lint autofixes, and generated files — must be committed and pushed to the PR branch. Do not finish with unstaged changes, uncommitted edits, stashes, or untracked artifacts left behind.
-
-### 7. Run Quality Checks
-
-Choose checks based on the diff, but default to these when code changed:
-
-```bash
-pnpm typecheck
-pnpm lint
-pnpm format
-pnpm test:unit
-cargo fmt --manifest-path Cargo.toml
-cargo check --manifest-path Cargo.toml
-cargo check --manifest-path app/src-tauri/Cargo.toml
-cargo test --manifest-path Cargo.toml
-```
-
-Notes:
-
-- Commands in `AGENTS.md` are from the repo root; `pnpm` delegates to the `app` workspace where appropriate.
-- Always run formatters when code changed.
-- Run Rust checks for Rust or Tauri changes.
-- Run frontend typecheck, lint, format, and relevant Vitest coverage for app changes.
-- If a test fails due to apparent flakiness, rerun once. If it still fails, stop and report rather than looping.
-
-### 8. Push Back to the PR Branch (REQUIRED)
-
-You MUST push once fixes are committed and checks pass. This is the terminal step of the default workflow; skipping it leaves the PR in the same state you found it.
-
-Before pushing, verify the working tree is clean:
-
-```bash
-git status --short # must be empty
-git push
-```
-
-If `git status --short` shows anything, commit those changes first (formatter output, lint autofixes, regenerated files) before pushing. Never finish with a dirty tree.
-
-If push is rejected because the remote advanced, use `git pull --rebase` only after inspecting the situation. Never force-push without explicit user approval — the sole exception is following a deliberate conflict-resolution rebase (phase 2b), where `git push --force-with-lease` is permitted.
-
-For fork PRs without push access, clearly report that commits are local and instruct the user/author how to pull them. Do not attempt to push.
-
-### 9. Wait for CodeRabbit Re-review (REQUIRED)
-
-After pushing, you MUST wait for CodeRabbit to re-review the new commits. Do not finalize the run early.
-
-- Record the pushed `HEAD` SHA and push timestamp.
-- **Sleep 10 minutes** (`sleep 600`) to give CodeRabbit time to post its review.
-- Then poll for new reviews/comments from `coderabbitai` created after the push timestamp:
-
-```bash
-gh pr view <PR> --json reviews --jq '.reviews[] | select(.author.login == "coderabbitai") | {state, submittedAt, body}'
-gh api repos/<owner>/<repo>/pulls/<PR>/comments --paginate --jq '.[] | select(.user.login == "coderabbitai" and .created_at > "<push-timestamp>")'
-```
-
-- If a new CodeRabbit review appears during or shortly after the 10-minute window, re-poll every 60s until it lands (cap total wait at 15 minutes).
-- If new actionable comments appear, loop back to triage → fix → push. Cap automated re-review handling at **two cycles**, then report remaining items to the user instead of looping further.
-- If no new review arrives after the window, proceed and note this explicitly in the final report.
-
-## Final Report Format
-
-Return a concise report:
-
-```text
-## PR #<number> - <title>
-Branch: <headRefName> Base: <baseRefName> Author: <login>
-
-### Review Comments Processed
-- @<reviewer> on <file>:<line> - <summary> -> fixed / already addressed / stale / deferred / disagree
-
-### Standards Pass
-- pass/warn/fail with file:line references where useful
-
-### Checks
-- typecheck: pass/fail/not run
-- lint: pass/fail/not run
-- format: pass/fail/not run, files changed if any
-- unit tests: pass/fail/not run
-- cargo check core: pass/fail/not run
-- cargo check tauri: pass/fail/not run
-- cargo test: pass/fail/not run
-
-### Commits
-- <sha> <subject>
-
-### Push / Re-review
-- pushed: yes/no
-- CodeRabbit re-review: waited <duration>, new actionable items <count>
-
-### Outstanding Human Items
-- <item, or none>
-
-### PR
-<url>
-```
-
-Lead with findings when the user asked for review. Keep summaries brief and prioritize bugs, regressions, missing tests, architectural violations, and unresolved reviewer requests.
diff --git a/.agents/agents/ship-and-babysit.md b/.agents/agents/ship-and-babysit.md
deleted file mode 100644
index e1a4736f17..0000000000
--- a/.agents/agents/ship-and-babysit.md
+++ /dev/null
@@ -1,92 +0,0 @@
----
-name: ship-and-babysit
-description: Commit local changes, push the branch to the user's fork, open or reuse a PR against tinyhumansai/openhuman:main, then babysit CI and CodeRabbit feedback until the PR is green and clean. Use when the user wants an end-to-end ship flow, not just implementation.
-model: inherit
----
-
-# Ship And Babysit
-
-You are running an end-to-end ship-and-babysit flow for the **openhuman** repo. Follow these phases in order. Be concise in user-facing text.
-
-Repo facts:
-
-- Upstream: `tinyhumansai/openhuman`. PRs target `main`.
-- Push branches to `origin` (the user's fork). Treat `upstream` as fetch-only.
-- PRs are opened with `--head <fork-owner>:<branch>` against `tinyhumansai/openhuman:main`.
-- PR template: `.github/PULL_REQUEST_TEMPLATE.md`.
-- Feature work requires matching E2E coverage before shipping.
-
-Resolve the fork owner once at the start and reuse it:
-
-```bash
-FORK_OWNER=$(git remote get-url origin | sed -E 's#.*[:/]([^/]+)/[^/]+(\.git)?$#\1#')
-```
-
-If `origin` resolves to `tinyhumansai`, stop and ask the user to add a fork remote. Never push branches to the upstream repo.
-
-## Phase 1 — Commit
-
-1. Inspect `git status`, staged and unstaged diffs, and recent commit messages.
-2. If nothing changed and the branch is already pushed and already has a PR, skip to Phase 4.
-3. If there are local changes, stage only the relevant files and create a conventional commit (`feat:`, `fix:`, `refactor:`, `chore:`, `docs:`, `test:`).
-4. Do not bypass commit hooks for your own changes.
-
-## Feature E2E rule
-
-- Core, domain, persistence, CLI, and JSON-RPC feature changes need Rust E2E coverage in `tests/*_e2e.rs`; new or changed RPC surfaces usually belong in `tests/json_rpc_e2e.rs`.
-- Frontend user flows need Playwright E2E coverage in `app/test/e2e/specs/*.spec.ts`.
-- Mock backend calls all the way through with `scripts/mock-api-server.mjs`, `scripts/mock-api/*`, or `app/test/e2e/mock-server.ts`; do not hit real backend services or third-party APIs in E2E.
-- Use focused commands when possible:
- - `pnpm test:rust:e2e -- --suite <suite>`
- - `pnpm --filter openhuman-app test:e2e:web:build`
- - `bash app/scripts/e2e-web-session.sh test/e2e/specs/<spec>.spec.ts`
-- Unit tests still matter for narrow logic, but they do not replace E2E coverage for newly built features.
-
-## Phase 2 — Push
-
-1. Confirm the current branch is not `main`.
-2. Push to `origin`, using `-u` if upstream tracking is missing.
-3. If the pre-push hook fails on unrelated pre-existing breakage, push with `--no-verify` and record that explicitly in the PR body. If the hook fails on your own changes, fix the problem and push again.
-
-## Phase 3 — Open PR
-
-1. Verify `upstream` points at `tinyhumansai/openhuman`.
-2. Check whether a PR already exists for this branch:
-
-```bash
-gh pr list --repo tinyhumansai/openhuman --head <fork-owner>:<branch> --state open --json number,url
-```
-
-3. If no PR exists, write a title and a body that follows `.github/PULL_REQUEST_TEMPLATE.md` exactly. Inspect `git log main..HEAD` and `git diff main...HEAD` first.
- - Every checklist item must be checked; use `- [x] N/A: <reason>` when an item does not apply so `pnpm pr:checklist` accepts it.
-4. Create the PR against `main`.
-5. Capture the PR number and URL for the babysit loop.
-
-## Phase 4 — Babysit loop
-
-Repeat until the PR is clean:
-
-1. Check CI:
-
-```bash
-gh pr checks <PR#> --repo tinyhumansai/openhuman --json name,state,link,description
-```
-
-2. If an Actions-backed check fails, fetch failed logs with `gh run view <run-id> --log-failed --repo tinyhumansai/openhuman`, fix the issue, commit, and push.
-3. Check CodeRabbit PR review comments and issue comments:
-
-```bash
-gh api repos/tinyhumansai/openhuman/pulls/<PR#>/comments --paginate
-gh api repos/tinyhumansai/openhuman/issues/<PR#>/comments --paginate
-```
-
-4. Apply correct in-scope suggestions. If a suggestion is wrong or out of scope, reply in-thread with a short dismissal reason before resolving it.
-5. Resolve addressed review threads through the GitHub GraphQL API.
-6. Exit only when required checks are successful, no unresolved CodeRabbit threads remain, and no new CodeRabbit issue comments request changes.
-
-## Guardrails
-
-- Never push to `upstream`.
-- Never force-push to `main`.
-- Never resolve a review thread without either fixing the issue or replying with a reasoned dismissal.
-- Do not merge the PR. Stop at green CI plus clean review state.
diff --git a/.claude/agents/memory-keeper.md b/.claude/agents/memory-keeper.md
deleted file mode 100644
index 4f18869a91..0000000000
--- a/.claude/agents/memory-keeper.md
+++ /dev/null
@@ -1,53 +0,0 @@
----
-name: memory-keeper
-description: Updates .claude/memory.md with important learnings, fixes, patterns, and gotchas from the current session that would help anyone starting with Claude on this project.
-model: sonnet
-color: purple
----
-
-# Memory Keeper
-
-## Purpose
-
-Scan the current conversation context and update `.claude/memory.md` with anything important that was learned, fixed, discovered, or decided during this session. This file serves as institutional knowledge for anyone starting with Claude on this project.
-
-## What to capture
-
-- **Fixes and workarounds** — what broke and how it was fixed (e.g. CORS errors, service gate issues)
-- **Gotchas** — non-obvious things that tripped us up (e.g. socket not connected at startup)
-- **Strict instructions** — rules or patterns the user emphasized
-- **Architecture decisions** — why something was done a certain way
-- **Environment setup** — things needed to get the project running
-- **Commands that matter** — non-obvious commands or flags
-
-## What NOT to capture
-
-- Obvious things derivable from `CLAUDE.md` or code
-- Temporary debugging steps
-- Personal info about the user
-- Anything already documented elsewhere
-
-## How to update
-
-1. Read the current `.claude/memory.md` file
-2. Review the conversation context for new learnings
-3. Add new entries under the appropriate section
-4. Keep entries short — one line per item, max two lines for complex ones
-5. Use `##` headers to group by topic
-6. Do not duplicate existing entries
-7. Remove entries that are no longer true
-
-## Format
-
-```markdown
-## Section Name
-
-- **Short title** — Brief explanation of what was learned and why it matters
-```
-
-## Rules
-
-- Keep the file under 100 lines total
-- Be concise — this is a quick reference, not documentation
-- Every entry should answer: "What would I wish I knew before starting?"
-- Update in place — edit existing entries if they've changed, don't append duplicates
diff --git a/.claude/memory.md b/.claude/memory.md
deleted file mode 100644
index f261137543..0000000000
--- a/.claude/memory.md
+++ /dev/null
@@ -1,371 +0,0 @@
-# Project Memory
-
-Quick reference for anyone starting with Claude on this project. Updated by the `memory-keeper` agent.
-
-## Fixes & Gotchas
-
-- **Who persists a chat reply (issue #6034)** — the core writes an unsegmented reply to the conversation store under `agent:<request_id>` **before** it publishes `chat_done` (`web_chat::presentation::deliver_response` → `web_chat::reply_persistence`), and the frontend's `addInferenceResponse` reuses that id so the store's idempotency collapses the two writes onto one row. Before this the frontend was the *only* persister of an interactive reply, so a failed `threads_message_append`, a socket reconnect (which issues a new `client_id`, leaving only the `thread:<id>` room as a route) or a webview reload lost the answer from screen and disk while the agent's session history still held it. Two rules follow: any new `chat_done` append site must pass `deliveredReplyMessageId(event)` or the thread gets two copies of one answer (#5933 again), and a **segmented** delivery is the exception — the client owns one row per segment there, so the core stores nothing and the ids stay generated.
-- **`deliver_response` does not segment any more** — `presentation.rs` sets `let segments = [full_response.to_string()]` unconditionally, so the multi-segment branch (and every `chat_segment` event) is dead on the interactive path; the segmentation helpers survive for channel callers and tests. Read that binding before reasoning about `segment_total`, which is never set in practice today.
-- **macOS close button does not dismiss window (issue #2049)** — `WebviewWindow::hide()` routes through CEF's `WindowMessage::Hide` → `cef::Window::hide()` which does NOT propagate to the visible NSWindow frame. Fix: use `AppHandle::hide()` which calls `[NSApp hide:]` via `set_application_visibility(false)`. This is macOS-only (`#[cfg(target_os = "macos")]`); the `CloseRequested` handlers are in `app/src-tauri/src/lib.rs` (grep `WindowEvent::CloseRequested` — line numbers drift). PR #2118.
-- **ServiceBlockingGate CORS errors** — The gate calls `openhumanServiceStatus()` and `openhumanAgentServerStatus()` at startup. These used `callCoreRpc()` which falls back to raw `fetch()` when socket isn't connected yet, causing CORS errors. Fix: route through `invoke('core_rpc_relay')` instead (Tauri IPC, no CORS).
-- **Socket not connected at startup** — `SocketProvider` only connects when a Redux `auth.token` is set. At fresh launch (no token), socket is null, so any `callCoreRpc()` call falls back to `fetch()`. Always use `invoke('core_rpc_relay')` for local sidecar RPC calls.
-- **`openhuman.agent_server_status` doesn't exist** — This RPC method is not registered in the core. The gate checks it but it always errors. The gate passes if either service is Running OR agent server is running OR core is reachable.
-- **Cargo incremental builds can serve stale UI** — If the app shows old frontend after a Rust rebuild, run `cargo clean --manifest-path app/src-tauri/Cargo.toml` before rebuilding.
-- **`build.rs` missing `rerun-if-changed` causes stale ACL / "Command not found" at runtime** — `app/src-tauri/build.rs` had no `cargo:rerun-if-changed` directives for `permissions/` or `capabilities/`. Adding/changing TOML or JSON files there did not re-trigger `tauri-build`, so ACL tables were stale and registered commands silently failed. Fixed by adding `println!("cargo:rerun-if-changed=permissions")` and `println!("cargo:rerun-if-changed=capabilities")` in `build.rs` (issue #270). Also: any new Tauri command must have a matching entry in a `permissions/` TOML file or it will hit the same error even if it is in `generate_handler!`.
-- **macOS deep links require .app bundle** — `pnpm tauri dev` does NOT support deep links. Must use `pnpm tauri build --debug --bundles app`.
-- **"I don't have that stored" on a personal question while the fact is in memory (issue #6040)** — the turn injects no memory of the user by itself, and the `MemoryAccessSection` instruction was gated on `learning.enabled` (default `false`), so the model was never told to look before claiming absence. Now: Lane C (`src/openhuman/memory/auto_recall/`) runs a lexically gated, bounded `fast_retrieve` through the session binding's guard and prepends a `## Relevant memory for this message` block to the **user message** (never the system prompt — KV-cache prefix); the instruction is added whenever a retrieval tool is registered, regardless of learning; `memory_recall` no longer requires `namespace`. Switch: `[subsystems.memory.hooks] auto_recall` / `OPENHUMAN_MEMORY_HOOKS_AUTO_RECALL` — the flag existed before and was read by nothing. `core_turn.rs` sits near the 750-line gate: per-turn memory lanes live in `turn/recall_lanes.rs`, add there. `RecordingProvider::with_fast_retrieve_result` scripts the guarded retrieval family in tests. The sub-agent fast path (#4677) still skips entity-less queries; Lane C calls the engine directly, whose empty-entity path is dense retrieval. **Latency:** every `fast_retrieve` asks the host for spaCy over the bus (`memory_host.rs::extract_spacy` → the Python server) plus a query embed, so a warm lookup is ~1.5–3 s and the first after boot was >5 s (Python server + model load) — `memory::auto_recall::warm::spawn_at_boot`, hooked in `modules/boot.rs` right after the TinyMemory module loads, runs one throwaway retrieval so the user's first question is warm (measured: warm-up 2.4 s at boot, first real lookup 1.6 s). Lane budget is 5 s; `[memory_host] embed/extract_spacy elapsed_ms` debug lines give the split.
-- **A `Memory` trait method left on its default is a silent no-op in production (issue #6041)** — the session's `Arc<dyn Memory>` is `agent/experience/ops.rs::DriverMemory` (since `7a4278378`), and `tinymemory-api`'s `Memory::recall_relevant_by_vector` defaults to `Ok(vec![])`, so situational preferences (Lane B) injected nothing on every module-backed install while every turn test stayed green — the harness tests bind the embedded `tinymemory_core::store::create_memory`, which overrides it. `DriverMemory` now answers through `preferences::recall_by_vector_over` (one body with the guard path). Rule: a turn-level test that pins production behaviour must bind `DriverMemory` over `guard::test_support::RecordingProvider` (`with_namespace_hits`, `with_list_result`), not the embedded store; and before leaving a trait default in place, grep who actually holds the handle. Costs measured on the desktop once the lane was live: the vector recall is one query-embed round trip, 0.8–3 s per turn, so `recall_situational_preferences_on` lists the namespace first (no embed) and skips the recall when nothing is stored; Lane B's budget is 5 s (3 s lost the block on both on-topic turns). Floor tuning data: `[pref_recall] namespace= kept= top_similarity= floor= elapsed_ms=` — with the managed embedder, unrelated message↔preference pairs score 0.28–0.33, a rule-phrased travel preference vs a trip-planning message 0.349, a coffee preference vs a café question 0.575; the 0.35 floor is thin but lowering it pulls cross-topic preferences in.
-- **`memory_store` writes land where the pre-turn lane never looked (issue #6063)** — `memory_store` files a fact as a namespace document in `global` (`memory_docs` + a `vector_chunks` embedding, the same path `save_preference` takes), while Lane C read only the memory tree (`fast_retrieve`), which namespace documents never enter; the archivist's chat→tree ingest runs at segment close (days late on a live profile) and short turns stay `buffered`/`dropped`, so "remember X" → new chat → "X is not on record" reproduced on a default install with the #6052 write in place. Now Lane C runs two legs side by side (`tokio::join!`, a 5 s bound **per leg**): the tree walk and `recall_namespace_scored("global", message, 3)` through the same guard (`AutoRecallSource::recall_namespace_scored` — required, no trait default, per the #6041 rule), floored at `AUTO_RECALL_NOTE_MIN_SIMILARITY = 0.35` on the vector component (Lane B's floor data), notes rendered first as `- <content> (note: <key>)`, wrapped when `ExternalSync`-tainted or connector-keyed. The block also opens with `AUTO_RECALL_HINT` ("pre-fetched, not a search") because the model read the old block as the retrieval the memory-access rule demands and claimed absence over three unrelated tree hits. Tell in the log: `[auto_recall] … hits= total= notes= notes_top= tree_ms= notes_ms=` — a `total` unchanged after a store means the fact never reached the tree. `RecordingProvider::with_namespace_hits` + `guard::test_support::namespace_hit` script the leg; `guarded_with` + `AutoRecall::from_guard` is the production wiring in a turn test.
-- **Composio `list_connections` at boot while signed out reported ERR + Sentry (issue #6176)** — in backend mode with no app-session JWT, `modules::connectors::module_config` fails, `ensure_routed` sends the connector module `{"route": "none"}`, and every routed member answers "this module was loaded without a connector route … or call Configure" (Configure _was_ called; the text is misleading). `start_bootstrap_jobs` → `memory::sources::reconcile::ensure_composio_sources` → `composio_list_connections` hit it at every boot (the reconcile `debug!`-swallows the failure one layer up, after `report_composio_op_error` had already fired), and `start_periodic_sync` repeated it every 60 s. Fix: `integrations/composio/ops/error_utils.rs::backend_mode_without_session`, the twin of `direct_mode_without_key`, short-circuits `composio_list_connections` with the quiet `COMPOSIO_NO_SESSION` `Err` ("no backend session token", the wording `resolve_client` already uses, which `is_session_expired_message` demotes at the JSON-RPC boundary) and skips `report_composio_op_error` — NOT an `Ok(empty)`: Codex (PR#6178) pointed out that an empty success reads as authoritative to `memory::sources::reconcile` (`list_rpc` would hide every persisted Composio row) and to `flows::validate_connection_refs` (every `connection_ref` false-rejected), while `Err` keeps their documented fail-open path; direct-mode-without-key returns `Ok(empty)` only because no key ⇒ no tenant ⇒ truly no connections. Because the early answer skips the per-call `ensure_routed`, the guard branch also calls `modules::connectors::reconcile_route_if_loaded` (touches only a module whose `ops::state_of` is `Ready`; sends `{"route":"none"}` for a signed-out config) so a module configured while signed in drops the bearer on the next tick after sign-out — Codex P1 on PR#6178. It reads `api::jwt::get_session_token` — the single token source `integrations::build_client` uses — and not `build_client` itself, which WARNs on every call; a _failed_ lookup returns `false` so a real store fault still surfaces. Also: a corrupt `auth-profiles.json` is quarantined + reset rather than an error, so to test the `Err` branch make `config_path.parent()` a regular file (the `auth_profile_lock_errors_do_not_include_local_paths` trick). `ops_tests_part_03_tests.rs` sits at 720 of the 750-line layout gate — new Composio op tests go in `ops_tests_part_04_tests.rs`.
-
-## Strict Rules
-
-- **No dynamic imports in `app/src/`** — Use static `import` at file top. Guard call sites with `try/catch` for Tauri/non-Tauri safety. See CLAUDE.md.
-- **Service RPC calls must use Tauri IPC** — Never use `callCoreRpc()` for service operations. Use `invoke('core_rpc_relay', { request: { method, params } })`.
-- **All frontend env vars go through `app/src/utils/config.ts`** — Never read `import.meta.env.VITE_*` directly in other files. Import from config.ts instead. See `.env.example` files for the full list.
-- **Always run checks before commit** — `pnpm workspace openhuman-app compile`, `pnpm lint`, `pnpm format:check`, `pnpm build`, `pnpm tauri dev`. Husky hooks enforce some but run all manually first.
-- **Stage specific files** — Never `git add -A`. Always `git add <specific-files>`.
-
-## Workflow
-
-- **Agent order**: architectobot (plan) → user approval → codecrusher (implement) → architectobot (verify)
-- **Always read CLAUDE.md first** before any issue work
-- **Ask user when in doubt** — never assume scope or approach
-- **PRs target upstream** — `tinyhumansai/openhuman` main branch, not fork
-- **GraphQL project board can return empty** — `gh project item-list` on board #2 sometimes returns no items even when issues exist. Fall back to `gh issue list --repo tinyhumansai/openhuman` directly.
-- **jq regex: use POSIX classes, not `\s`** — jq's `test()` uses ONIG regex; `\s` is not supported. Use `[[:space:]]` for whitespace matching in `gh pr list --json ... --jq` pipelines.
-- **PR conflict check: `Closes #N` syntax not always used** — `gh pr list --jq "select(.body | test('Closes #N'))"` misses PRs that mention an issue thematically without a closing keyword. Also search PR title + body for the raw issue number (`#N`) with broader matching to catch related open PRs before claiming an issue is unassigned.
-- **`pnpm debug unit` path is relative to `app/src/`** — Pass `providers/__tests__/Foo.test.tsx`, not `app/src/providers/__tests__/Foo.test.tsx`.
-- **Prettier must run after codecrusher adds test cases** — New test blocks often fail `format:check`. Run `pnpm --filter openhuman-app format` before committing when test files are touched.
-- **Check for existing PRs before implementing** — When the workflow picks an issue, search open PRs for the issue number and related keywords before starting work. A contributor may have already shipped the fix (e.g. PR #2101 for issue #2075).
-- **Project board `gh project item-list` paginates closed items first** — The first 100 items returned are often CLOSED. Must `--limit 500` or paginate to find open/unassigned work. Fall back to `gh issue list --repo tinyhumansai/openhuman --state open` for reliability.
-
-## Local AI Presets
-
-- **Tier system lives in `src/openhuman/local_ai/presets.rs`** — single source of truth for tier→model ID mapping. To change default models for a release, edit `all_presets()` there.
-- **Device detection** uses `sysinfo` crate (`src/openhuman/local_ai/device.rs`). Apple Silicon = GPU always; others = best-effort.
-- **`OPENHUMAN_LOCAL_AI_TIER` env var** overrides the selected tier at config load time (in `load.rs`).
-- **Frontend tier selector** is in `LocalModelPanel.tsx` under Settings > Local AI Model. Uses `coreRpcClient` to call 3 RPC methods: `local_ai_device_profile`, `local_ai_presets`, `local_ai_apply_preset`.
-- **Default config maps to Medium tier** (`gemma3:4b-it-qat`). If someone changes `model_ids.rs` defaults, they should keep `presets.rs` in sync.
-- **`ollama_base_url()` previously ignored `config.local_ai.base_url`** — It only read env vars. Fixed in feat/ollama-external-server-url by adding `ollama_base_url_from_config(config)`. Any new Ollama URL resolution must go through the config-aware helper, not the env-only one.
-- **`LocalModelDebugPanel.tsx` must seed URL from config on mount** — Previously initialized `ollamaBaseUrlInput` to the hardcoded default and only loaded the persisted URL when diagnostics ran. Fix: `useEffect` on mount calls `openhumanGetConfig()` and sets state from `config.local_ai.base_url`. Pattern to follow for any settings field backed by Rust config.
-
-## Core process (in-process, no sidecar)
-
-- **Core runs in-process** as a tokio task inside the Tauri host (sidecar removed in PR #1061). Lifecycle owned by `core_process::CoreProcessHandle` in `app/src-tauri/src/core_process.rs`.
-- **`pnpm core:stage` is a no-op echo** — there is no `target/debug/openhuman-core` binary to copy into `app/src-tauri/binaries/`. Rebuilding via `pnpm dev:app` is enough to pick up new RPC methods in the in-process server.
-- **Token auth**: per-launch hex bearer in `OPENHUMAN_CORE_TOKEN`, exposed to the renderer via `core_rpc_token` Tauri command. Always call RPC through `invoke('core_rpc_relay', { request: { method, params } })` — avoids the CORS preflight `fetch()` would trigger.
-- **Stale-listener policy** (#1130): if the port is already in use, the handle probes `GET /` to decide if it's an OpenHuman core, then term/force-kill with PID revalidation guarding against PID reuse. Set `OPENHUMAN_CORE_REUSE_EXISTING=1` to attach to a manually-started `openhuman-core serve` for debugging.
-- **Default port** `7788`. Stage token (when running standalone): `~/.openhuman-staging/core.token` under `OPENHUMAN_APP_ENV=staging`.
-
-## Onboarding System
-
-- **OnboardingOverlay is a portal, not a route** — mounted in `App.tsx`, renders via `createPortal` at z-[9999]. There is no `/onboarding` route in `AppRoutes.tsx`. Gating is purely Redux + workspace flag.
-- **Deferred onboarding** — `onboardingDeferredByUser` in `authSlice.ts` (persisted via redux-persist) durably tracks when a user clicks "Set up later". `SetupBanner.tsx` provides the resume path.
-- **`selectHasIncompleteOnboarding` is unused** in production code — only tested. Don't use it for new features.
-- **Logout must clear onboarding state** — `_clearToken` resets `isOnboardedByUser` + `isAnalyticsEnabledByUser`. Workspace flag (`.skip_onboarding` file) is cleared via `openhumanWorkspaceOnboardingFlagSet(false)` in SettingsHome logout, clearAllAppData, and UserProvider auth recovery. All three paths must stay in sync. **OnboardingOverlay local state** (`userLoadTimedOut`, `onboardingCompleted`) is reset via a `useEffect` watching `token` — if `token` becomes null, both reset to initial values (#192).
-- **LocalAI download errors must surface** — `LocalAIStep` has an `onDownloadError` callback prop; `Onboarding.tsx` renders an error banner via `createPortal` when it fires. Without this, download failures are silently swallowed (#194).
-- **`formatBytes` / `formatEta` / `progressFromStatus`** — shared in `app/src/utils/localAiHelpers.ts`. Home.tsx and LocalModelPanel.tsx still have local copies (can be migrated later).
-- **Notification z-index stacking** — ErrorReportNotification: z-[10000] bottom-right. OnboardingOverlay: z-[9999]. LocalAIDownloadSnackbar: z-[9998] bottom-left.
-- **React Compiler lint** — `useCallback` deps must match the full inferred closure. Using `user?._id` as dep when the closure captures `user` triggers `preserve-manual-memoization`. Use `user` as the dep instead.
-- **`setState` in effects** — ESLint `react-hooks/set-state-in-effect` catches synchronous setState in useEffect bodies. Use lazy initializers, compute at render, or event handlers instead.
-- **Walkthrough is multi-page (9 steps)** — Uses react-joyride v3 `Step.before` async hooks to navigate between pages (`/home → /chat → /skills → /intelligence → /settings → /home`). Steps factory: `createWalkthroughSteps(navigate)` in `walkthroughSteps.ts`. `waitForTarget(selector, timeout)` polls via rAF until DOM target appears. Re-trigger from Settings via `resetWalkthrough()` + `walkthrough:restart` CustomEvent. `AppWalkthrough` is mounted inside Router context (can use `useNavigate` directly). BottomTabBar attr is `tab-notifications` (not `tab-automation`).
-- **`OnboardingNextButton` is the shared primary CTA** — All onboarding steps use `app/src/pages/onboarding/components/OnboardingNextButton.tsx`. New steps must use this component for the primary navigation button.
-- **Onboarding is 3 steps: Welcome(0) → Skills(1) → ContextGathering(2)** — Referral step was removed (issue #752). `ReferralApplyStep.tsx` is preserved but unused. `referralApi` is still used on the Rewards page. `WelcomeStep` no longer has `nextDisabled`/`nextLoading`/`nextLoadingLabel` props (those gated on referral stats prefetch).
-- **Recovery Phrase moved to Settings** — MnemonicStep was removed from onboarding (was step 5). The same BIP39 generate/import functionality now lives in `app/src/components/settings/panels/RecoveryPhrasePanel.tsx`, accessible via Settings > Recovery Phrase. Onboarding completion logic moved into `handleSkillsNext` in `Onboarding.tsx`.
-- **E2E tests find onboarding buttons by label text** — `shared-flows.ts`, `login-flow.spec.ts`, `auth-access-control.spec.ts`, and `voice-mode.spec.ts` locate buttons by their visible label. Changing button labels requires updating all four files. Note: `voice-mode.spec.ts` still references legacy labels that don't match current steps (pre-existing tech debt).
-- **`ScreenPermissionsStep` always shows Continue** — The Continue button is always visible regardless of permission grant status, allowing users to skip the permissions step (#274).
-- **OnboardingOverlay RPC/Redux race condition** — `getOnboardingCompleted()` RPC can fail (sidecar not ready, timeout); the old catch block hardcoded `setOnboardingCompleted(false)`, ignoring the persisted `isOnboardedByUser` Redux flag. Fix: read `selectIsOnboarded` from `authSelectors.ts` in the catch block as fallback, and combine both flags in `shouldShow`: `!onboardingCompleted && !isOnboardedRedux`. Either flag being `true` is sufficient to skip onboarding (#197).
-- **`DEV_FORCE_ONBOARDING` was a no-op** — The old ternary had identical branches; fixed to actually force-show when the flag is set.
-- **`isOnboardedRedux` must be in useEffect deps** — When reading a selector value inside a useEffect, add it to the dependency array or the effect won't re-run when Redux state changes.
-
-## CoreStateProvider & Auth Bootstrap
-
-- **Auth session tokens are NOT in Redux persist** — They live entirely in the Rust sidecar, fetched via `fetchCoreAppSnapshot()` RPC. `PersistGate` only gates non-auth state (AI config, threads, channel connections). `CoreStateProvider` bootstrap is the critical auth path.
-- **`CoreStateProvider` premature `isBootstrapping: false` causes blank Settings** — If the initial RPC call fails (sidecar still starting), the old error handler set `isBootstrapping: false` immediately, causing `ProtectedRoute` to redirect to `/` before the 3s poll could recover. Fix (issue #413): keep `isBootstrapping: true` on initial failure, let the poll retry, give up after 5 attempts (~15s).
-- **`CoreStateProvider` is consumed by ~25 components** — Changes to its state shape or bootstrap behavior affect routes, socket, onboarding, nav, settings, and hooks. Treat it as a high-blast-radius file.
-- **`bootstrapFailCountRef` retry counter bug (issue #2158)** — The ref is a cumulative lifetime counter; logging it against `MAX_BOOTSTRAP_RETRIES` (5) as denominator produced impossible `attempt 11/5`. Fix: distinguish bootstrap phase ("attempt X/5") from continuous-poll phase (separate message, 10s backoff). Reset the counter to 0 on any successful snapshot fetch.
-- **Settings is a full route, not a modal** — `/settings/*` uses nested `<Routes>` in `Settings.tsx`. The `.claude/rules/15-settings-modal-system.md` doc describing a portal/modal approach is outdated. A catch-all `<Route path="*">` redirects unmatched sub-paths to `/settings`.
-- **`PersistGate loading={null}` causes flash** — Changed to `loading={<RouteLoadingScreen />}` (issue #413). `RouteLoadingScreen` accepts an optional `label` prop (defaults to "Initializing OpenHuman...") and can be rendered with no props.
-
-## Build Blockers: macOS Tahoe + whisper-rs
-
-- **`whisper-rs` breaks `cargo build` on macOS Tahoe (Apple Silicon)** — Added in main via `whisper-rs = "0.16"` (voice feature #178). Apple clang 21+ refuses `-mcpu=native` when `--target=arm64-apple-macosx` is also set. This is NOT fixable by updating CLT.
-- **Root cause** — ggml cmake sets `GGML_NATIVE=ON` by default; the cmake crate appends `--target` to clang, triggering the incompatibility. Happens even with the latest toolchain.
-- **Workaround** — Patch `~/.cargo/registry/src/index.crates.io-*/whisper-rs-sys-0.15.0/build.rs`: add `config.define("GGML_NATIVE", "OFF");` (for `target_os = "macos" && target_arch = "aarch64"`) just before the `config.build()` call.
-- **Patch is fragile** — Resets on `cargo clean`, crate version bump, or registry re-download. Deleting build cache alone (`target/debug/build/whisper-rs-sys-*`) is NOT enough — cmake regenerates with the same bad flags.
-- **Correct fix** — Needs an upstream patch in `whisper-rs-sys` or a Cargo feature to opt out of `GGML_NATIVE` on Apple Silicon cross-builds.
-
-## UI Redesign (Light Theme — April 2026)
-
-- **Full dark-to-light redesign shipped** — All pages, components, and settings panels converted from dark glass-morphism to clean light theme based on Figma designs by Mithil (`OpenHuman-Prod` file, node `2094-250136` for tokens).
-- **Design tokens saved** in `my_docs/figma-design-tokens.md` — neutral grayscale, primary blue `#2F6EF4`, success `#34C759`, alert `#E8A728`, error `#EF4444`, SF Pro typography scale.
-- **Navigation changed**: Left `MiniSidebar` → bottom `BottomTabBar` (Home, Chat, Skills, Intelligence, Automation, Notification). Settings accessible via gear icon on Home page header.
-- **MiniSidebar.tsx retained** (not deleted) as backup. `BottomTabBar.tsx` is the active nav component.
-- **Agent message bubbles** need `bg-stone-200/80` (not `bg-stone-100`) on `#F5F5F5` background — `bg-stone-100` is nearly invisible.
-- **~55 files touched** — purely CSS class changes, zero logic/handler/state changes.
-
-## Upsell / Billing (Phase 1 — Issue #403)
-
-- **Upsell components** live in `app/src/components/upsell/` — `UpsellBanner`, `UsageLimitModal`, `GlobalUpsellBanner`, `upsellDismissState`. Shared hook: `app/src/hooks/useUsageState.ts`.
-- **Usage data sources** — `creditsApi.getTeamUsage()` returns `TeamUsage` (rolling 10h spend/cap + weekly budget/remaining). `billingApi.getCurrentPlan()` returns `CurrentPlanData` (plan tier, caps, subscription status). Both go through `callCoreCommand` (core RPC). No Redux slice — all local hook state.
-- **Module-level cache in `useUsageState`** — `_cache` variable with 60s TTL prevents duplicate API calls when multiple components mount simultaneously. New pattern; do not remove.
-- **Banner dismiss state uses localStorage** (prefix `openhuman:upsell:`), not Redux — consistent with CLAUDE.md exception for ephemeral UI state.
-- **Phased rollout** — Phase 1 = banners + limit modal + hook. Phase 2 = onboarding upsell + analytics. Phase 3 = remote config + A/B testing.
-- **"5-hour" label stragglers in Conversations.tsx** — `LimitPill` label and its hover tooltip still say "5h" / "5-hour". Commit 8c52236's "10-hour" terminology refactor missed those two spots.
-- **`getTeamUsage()` now normalizes via `normalizeTeamUsage()`** — Added in issue #482. The Rust sidecar passes backend JSON through opaquely (`src/openhuman/team/ops.rs`), so the TS client must normalize field names and types. Pattern matches existing `normalizeCreditBalance()` in the same file. Any new billing API that returns raw backend data should follow the same normalize-at-the-client pattern.
-- **Two separate `TeamUsage` types exist** — `creditsApi.ts:24` (billing: cycle budget, limits) and `types/team.ts:11` (team model: daily token limit). Different import paths, no collision, but confusing.
-
-## Settings & Skills Reorganization (Issue #396)
-
-- **Settings is NOT a modal** — It's a full route (`/settings/*`) with nested `<Routes>`. The `.claude/rules/15-settings-modal-system.md` doc is outdated.
-- **SettingsHeader breadcrumbs** — All panels now receive `breadcrumbs` from `useSettingsNavigation()` hook. The hook derives breadcrumbs from the current route path. When adding a new settings panel, destructure `breadcrumbs` from the hook and pass to `<SettingsHeader>`.
-- **Standard settings padding** — All settings panel content areas use `p-4 space-y-4`. Don't deviate.
-- **Dead code removed** — `TauriCommandsPanel`, `useSettingsAnimation`, `SettingsPanelLayout`, `SettingsBackButton`, `ProfilePanel`, `AdvancedPanel`, `SkillsPanel`, `SkillsGrid` were all deleted. Don't re-create them.
-- **Skills page is the single management surface** — Browser Access toggle moved from SkillsPanel to the Skills page. There is no `/settings/skills` route anymore.
-- **Panel decomposition** — LocalModelPanel, AutocompletePanel, CronJobsPanel, ScreenIntelligencePanel were split into sub-components in subdirectories. Each orchestrator is ≤ ~300 lines.
-- **UnifiedSkillCard** — All skill types (built-in, channels, 3rd party) use `UnifiedSkillCard` from `app/src/components/skills/SkillCard.tsx`. Secondary actions use an overflow menu. `data-testid` attributes (`skill-sync-button-*`, `skill-debug-button-*`) must be preserved.
-- **SkillSearchBar + SkillCategoryFilter** — New components in `app/src/components/skills/` for search and category filtering on the Skills page.
-
-## Composio Backend URL Bug (Issue #2075, PR #2101)
-
-- **`effective_backend_api_url` env-fallback branch skipped normalization** — In `src/api/config.rs`, the override branch normalized via `normalize_backend_api_base_url` but the env-fallback branch (`OPENHUMAN_BACKEND_API_URL`) did not, so scheme-less URLs like `api.example.com` were used raw. Fix: normalize the env-fallback branch too (3-layer defense: config → env-fallback → `IntegrationClient::new`).
-- **`normalize_backend_api_base_url` and `redact_url_for_log` are `pub(crate)`** — Available for reuse across `src/api/` after PR #2101 merge.
-
-## Composio Identity (Issue #691)
-
-- **`ProviderUserProfile.profile_url`** — New optional field on the struct in `src/openhuman/composio/providers/types.rs`. Providers should populate it when available from upstream profile payloads.
-- **`identity_set` callback in default flow** — `ComposioProvider::on_connection_created()` in `src/openhuman/composio/providers/traits.rs` now calls `identity_set(&profile)` after profile fetch. `composio_get_user_profile` in `src/openhuman/composio/ops.rs` also routes persistence through `identity_set`.
-- **Facet key format for connected identities** — `skill:{toolkit}:{identifier}:{field}` (e.g. `skill:gmail:[email protected]:profile_url`). Use `FacetType::Skill` when storing. Toolkit and identifier together form the unique identity; field is the attribute name.
-- **Connected identities loader/renderer** — `src/openhuman/composio/providers/profile.rs` contains `load_connected_identities()` (reads `skill:*` facets) and `render_connected_identities_section()` (formats markdown for prompt injection). Keep rendering logic there, not in prompt modules.
-- **Prompt injection helper** — `render_connected_identities` is imported and called in `welcome/prompt.rs`, `orchestrator/prompt.rs`, and `integrations_agent/prompt.rs` to inject a "Connected accounts:" block. Add it to any new agent prompt that needs Composio context.
-
-## Agent Timeout & Cancellation (Issue #715)
-
-- **Frontend silence timer, not a wall-clock limit** — `armSilenceTimer` in `app/src/pages/Conversations.tsx` fires if 120s (fixed to 600s) pass with zero inference progress events. It re-arms on every `tool_call`, `tool_result`, `iteration_start`, etc., so long-running tool chains that keep emitting events are not cut off.
-- **Rust-side HTTP timeout is separate** — `src/openhuman/providers/compatible.rs` sets a 120s `reqwest` client timeout on LLM calls. Not changed in #715; relevant if a single LLM round-trip itself stalls for >2 min.
-- **Manual cancel path** — `chatCancel()` in `app/src/services/chatService.ts` → `openhuman.channel_web_cancel` RPC → `cancel_chat()` in `src/openhuman/channels/providers/web.rs`. Fully implemented; the silence timer is an automatic fallback.
-
-## Webhook & Cron Triggers (Issue #726)
-
-- **Webhook bus was hardcoded 410** — `src/openhuman/webhooks/bus.rs` `WebhookRequestSubscriber::handle()` returned 410 "skill runtime removed" for ALL incoming webhooks. Now routes to echo/agent/skill/404 based on `TunnelRegistration.target_kind`.
-- **WebhookRouter access from bus.rs** — Router lives in `SocketManager::shared.webhook_router` (was `pub(super)`). Added `pub fn webhook_router(&self)` accessor on `SocketManager`; bus.rs reaches it via `global_socket_manager().webhook_router()`.
-- **`TriggerSource` enum: three update points** — Adding new variants requires updating: (a) `slug()` match in `envelope.rs`, (b) exhaustive test match, (c) `handle_triage_evaluate` string match in `agent/schemas.rs` (uses `p.source.as_str()`, not the enum directly).
-- **`CronJobTriggered/CronJobCompleted` were never published** — Defined in `events.rs` and used in tests but never emitted. Now published by `execute_and_persist_job()` in `scheduler.rs`. Adding fields to these variants requires updating ~5 construction sites: `cron/bus.rs`, `composio/bus.rs`, `tree_summarizer/bus.rs`, `channels/proactive.rs`, and `events.rs` tests.
-- **Webhook ops were all stubs** — `list_registrations`, `list_logs`, `clear_logs`, `register_echo`, `unregister_echo` in `ops.rs` all returned empty. Now backed by the real router via a `get_router()` helper.
-- **`GGML_NATIVE=OFF` for cargo check** — Sidestepping the whisper-rs macOS Tahoe build blocker for `cargo check`: `GGML_NATIVE=OFF cargo check --manifest-path Cargo.toml`. Allows compilation checks without the cmake failure.
-
-## Agent Runtime Behavior
-
-- **`sandbox_mode = "read_only"` in agent.toml is metadata only** — Never enforced at runtime. Actual security policy comes from `config.autonomy` (global), defaulting to `Supervised`. Adding write tools to a read-only agent works at runtime but violates documented intent.
-- **`max_iterations` hard-fails, not graceful truncation** — When the welcome agent (or any agent) hits `max_iterations`, `tool_loop.rs:705` calls `anyhow::bail!`. There is no graceful truncation. Budget iterations carefully.
-- **Archivist agent auto-extracts memory** — It processes conversation history and persists preferences/facts into `user_profile` automatically. Agents do not need to explicitly call `memory_store` to persist conversational insights.
-- **`cargo check` / `cargo test` fails on main (llama.cpp cmake)** — `llama.cpp`'s cmake build script uses `-mcpu=native`, which is unsupported on Apple clang 21+ with `--target=arm64-apple-macosx`. Pre-existing issue on `main`, not branch-specific. Frontend checks (typecheck, lint, format) are unaffected. Workaround: set `GGML_NATIVE=OFF` (same fix as whisper-rs above).
-
-## Cron Scheduler
-
-- **Cron loop was never spawned** — `tokio::spawn(cron::scheduler::run(config))` was missing from `src/core/jsonrpc.rs`. Added after the update scheduler spawn, gated on `config.cron.enabled`. Without it, scheduled jobs never auto-fire at startup (issue #830).
-
-## Build & Tooling Gotchas
-
-- **`pnpm typecheck` script was renamed** — Check `app/package.json` for the current name; as of issue #830 work, use `pnpm workspace openhuman-app compile` for tsc checks.
-- **PR #745 (command palette) merged without its deps** — `@radix-ui/react-dialog`, `cmdk`, and `@testing-library/user-event` are missing from `package.json`. Install them if tsc fails after syncing main.
-- **Pre-push hooks fail on upstream lint warnings** — ESLint warns on `setState` in effects and unused `eslint-disable` directives inherited from upstream. Use `--no-verify` only when the lint errors are pre-existing upstream issues, not new code.
-- **`pnpm tauri icon <source.png>` generates all platform icons at once** — Produces `.icns`, `.ico`, all PNG sizes, Windows Store tiles, and iOS/Android sets. Use this instead of manual `sips`/ImageMagick resizing.
-- **`tauri-cef` submodule update can fix missing Tauri runtime modules** — e.g. updating to f75bc21f5 added the missing `tauri_runtime_cef::audio` module that was causing pre-push hook compile failures on the Tauri shell. When the shell fails to compile with a missing module error, check if the submodule needs updating.
-- **`git add` must run from repo root** — Staging paths like `app/public/...` with `git add` from inside `app/` won't match. Always run `git add` from `/Users/megamind/tinyhuman/openhuman-claude`.
-- **Brand kit assets live at `app/public/brand/`** — Copied there during session work; original source is in `~/Downloads/Brand kit/`. Not auto-synced; re-copy manually if Downloads content changes.
-- **`pnpm test:coverage` ENOENT on `coverage/.tmp/coverage-0.json`** — Race condition in coverage file collection; flaky, not reproducible every run. Use `pnpm debug unit` instead — runs Vitest without coverage, faster and reliable for iteration.
-
-## Mascot Native Window (macOS)
-
-- **Not a Tauri window** — The floating mascot is a native `NSPanel` + `WKWebView` in `app/src-tauri/src/mascot_native_window.rs`. It uses `ignoresMouseEvents=true` (click-through); interaction is detected by polling `NSEvent` via a Foundation timer. macOS-only, uses objc2 bindings.
-- **`MainThreadOnly` import must stay** — Required by `WKWebView::alloc()` and other AppKit allocators even if not explicitly referenced in user code. Removing it causes compile errors.
-- **`NSEvent::pressedMouseButtons` not in typed objc2-appkit bindings** — Must be called via `msg_send!(objc2::class!(NSEvent), pressedMouseButtons)` instead of the typed API.
-- **WKWebView IPC via `evaluateJavaScript`** — The mascot webview is NOT a Tauri runtime; Tauri `invoke`/`emit` do NOT work. Rust-to-mascot communication uses `msg_send!(webview, evaluateJavaScript:completionHandler:)` to dispatch `new CustomEvent(...)` on `window`. React listens with `addEventListener`. This is NOT subject to the CEF JS injection ban (that only applies to `webview_accounts/` third-party origins).
-- **`MascotCharacter` `sleeping` prop** — Drives the sleep animation (eye close + Zzz). `sleepStartSec` and `sleepFullSec` are hardcoded at 2.5s and 4.0s — they are NOT configurable props. Only toggle `sleeping: boolean`.
-- **`FACE_PRESETS` is a strict `Record`** — Typed as `Record<Exclude<MascotFace, 'normal'>, FacePreset>` in `Ghosty.tsx`. Adding a new `MascotFace` union variant requires adding a matching entry to `FACE_PRESETS` or it won't compile.
-- **`_webview` in `spawn_drag_timer`** — The `WKWebView` captured in the drag timer closure was originally unused (prefixed `_`). It can be used for `evaluateJavaScript` calls during the hover polling loop (e.g. to trigger blink/wake events from Rust).
-- **FrameProvider loops — sleep animation resets** — `FrameProvider` uses `frame % durationInFrames` so animations loop. Default `DURATION_FRAMES = FPS * 6` (6s). Sleep animation completes at 4s, then eyes re-open at 6s when frame resets to 0. Fix: use a much longer `durationInFrames` for sleep face (e.g. `FPS * 600`) so the loop never triggers while sleeping.
-- **Hover detection needs circular hitbox** — The mascot panel is 79x79 but the character is visually circular. Using the full AABB (`cursor_in_panel`) for hover triggers false positives when cursor is in a panel corner. Use distance-from-center check instead. Also suppress hover events for ~1s after panel shows to let the webview load.
-
-## Google Analytics (Issue #1479)
-
-- **`react-ga4` injects a `<script>` tag at runtime** — It appends a `gtag.js` `<script>` to `<head>` dynamically. This works because `tauri.conf.json` CSP has `https:` in `default-src` and `connect-src`. If CEF ever tightens `script-src` separately, switch to GA4 Measurement Protocol (pure HTTP POST, no script injection).
-- **Analytics module pattern** — `app/src/services/analytics.ts` is the single owner of `initGA`, `trackPageView`, `trackEvent`, plus an `ALLOWED_EVENTS` allowlist. Never call `ReactGA` directly from components; go through this module.
-- **Triple gate before any GA call** — `isAnalyticsEnabled()` (user consent) AND `GA_MEASUREMENT_ID` env var present AND `!IS_DEV`. All three must pass or tracking is silently skipped.
-- **Route tracking location** — `useLocation()` effect wired in AppShell (not individual pages). All page views emit from one place.
-- **Capability catalog must stay in sync** — `src/openhuman/about_app/catalog.rs` needs an entry when a new user-visible feature ships. GA was added there as part of issue #1479.
-
-## PR Checklist CI
-
-- **N/A items need a checked checkbox** — `scripts/check-pr-checklist.mjs` requires `- [x] N/A: <reason>`. Using `- [ ] N/A:` (unchecked) fails the check even though the text starts with "N/A:".
-
-## Config System (Rust)
-
-- **Config corruption recovery** — `parse_config_with_recovery` in `src/openhuman/config/schema/load.rs`: try primary → try `.bak` → archive corrupt file → `Config::default()`. Guarantees the app always starts even with a corrupt config.
-- **New config fields must use `#[serde(default = "fn_name")]`** — Bare `#[serde(default)]` gives `0`/`false`, not the meaningful domain default. Define a named fn returning the correct value and reference it by name.
-- **`.bak` is now permanent** — `Config::save()` no longer deletes `.bak` on success. It always reflects the last-known-good config before the most recent write.
-- **`load_from_default_paths` has zero callers** — Debug utility only; not user-facing.
-- **Config test module path** — `openhuman::config::schema::load::tests`. Run with `cargo test -- config::schema::load::tests`.
-
-## Environment
-
-- **Core port** — `7788` (default; in-process inside Tauri host). Check with `lsof -i :7788`.
-- **`pnpm core:stage`** — no-op (sidecar removed in PR #1061). Use `pnpm dev:app` for full Tauri+core dev.
-- **Kill stuck processes** — `lsof -i :7788` then `kill <PID>`. Useful when `dev:app` reports a stale listener and you want to force a fresh boot rather than relying on the handle's auto-recovery.
-- **Skills runtime rebuilt (PR #2707)** — QuickJS is gone, but skills now run as orchestrator-focused agents via `skills_run` RPC. Default skills live in `src/openhuman/skills/defaults/<id>/` with `skill.toml` + `SKILL.md`, registered in `registry.rs` `DEFAULT_SKILLS` const. Seeded into `<workspace>/skills/` on boot (idempotent, non-destructive). Bundled defaults: `github-issue-crusher`, `dev-workflow`. Skills run with 200 iteration cap and full web access.
-- **Codegraph tools (PR #2707)** — `codegraph_index` and `codegraph_search` registered in `src/openhuman/tools/ops.rs`. Implementation in `src/openhuman/codegraph/` — tree-sitter extraction, SQLite FTS5, dense embeddings, RRF fusion. Auto-indexes on first search.
-- **Tool names are exact** — Always check `src/openhuman/tools/ops.rs` for authoritative names. Key ones: `edit` (not `edit_file`), `composio` (not `composio_execute`), `codegraph_index`, `codegraph_search`.
-- **`cron_add` RPC** — Was missing from `schemas.rs` (only existed as agent tool). Now exposed as `openhuman.cron_add`. Frontend wrapper: `openhumanCronAdd()` in `app/src/utils/tauriCommands/cron.ts`.
-- **Worktree `pnpm build` rolldown fix** — Worktrees can miss `@rolldown/binding-darwin-arm64`. Fix: `pnpm install --force`.
-
-## Artifacts Domain (Issue #2776)
-
-- **Filesystem-backed persistence, no SQLite** — `src/openhuman/agent/artifacts/` stores JSON metadata (`meta.json`) + binary blobs under `<workspace_dir>/artifacts/<uuid>/`. Pattern mirrors `memory/ops/files.rs` but simpler.
-- **`"ai"` namespace in controller registry** — RPC methods are `openhuman.ai_list_artifacts`, `openhuman.ai_get_artifact`, `openhuman.ai_delete_artifact`. Future `ai_*` methods should use this same namespace.
-- **Two-layer path validation required** — (1) `validate_artifact_id` rejects empty strings, `/`, `\`, `..`, absolute Unix paths, Windows `C:` and UNC `\\` paths; (2) `assert_within_root` canonicalizes and checks containment. Replicate this pattern for any new filesystem-backed domain.
-- **`cargo test --lib` required for lib crate tests** — `cargo test -p openhuman -- "artifacts"` lists tests but filters to 0. Must use `cargo test -p openhuman --lib -- "artifacts"` because tests are in the lib crate, not integration test binaries.
-
-## Rust Testing Patterns
-
-- **Memory tree tests filter** — `cargo test -p openhuman -- "memory::tree"` runs the memory tree unit tests (602 tests); full module paths are `openhuman::memory::tree::ingest::tests::*` and `openhuman::memory::tree::canonicalize::email_clean::tests::*`.
-- **`cargo fmt --all`** — Required after codecrusher generates Rust; it doesn't always produce perfectly formatted output and CI will reject unformatted code.
-- **PR quality scripts are soft checks** — `scripts/check-pr-checklist.mjs` and `scripts/check-coverage-matrix.mjs` exit cleanly with summary lines; CI treats them as advisory, not blocking.
-- **`ceil_char_boundary`** — Safe string slicing utility at `src/openhuman/util.rs`; use this throughout the codebase instead of raw byte-index slicing to avoid UTF-8 panics.
-- **Global static cache tests need a reset guard** — When testing code that reads/writes a `Lazy<Mutex<Option<...>>>` global cache, use a `struct CacheResetGuard; impl Drop for CacheResetGuard { fn drop(&mut self) { *CACHE.lock() = None; } }` pattern so each test starts clean. See `SnapshotCacheResetGuard` / `CacheResetGuard` in `ops_tests.rs`.
-- **Test assertions must match the actual dummy value** — When a builder (e.g. `build_dummy_runtime_snapshot()`) wraps `degraded_runtime_snapshot()`, assert against `dummy.field` rather than a hardcoded string (e.g. `"idle"` vs the actual `"degraded"`) to verify round-trip correctness without false mismatches.
-- **`composio::action_tool::tests::mode_toggle_between_calls_is_observed` is flaky in full suite** — Fails intermittently due to shared global composio session state; passes in isolation. Pre-existing; not caused by snapshot perf work.
-- **`GLOBAL_MEMORY_TEST_LOCK` only serializes test bodies, not background workers** — Background ingestion spawned by a prior test can still be running when the next test acquires the lock. Call `state.reset_for_test()` at test start (after acquiring the lock) to clear accumulated `queue_depth`/`running` state; do not rely on delta assertions alone.
-- **`IngestionState::reset_for_test()` is `#[cfg(test)]`-gated** — Lives in `src/openhuman/memory/ingestion/state.rs`. Zeroes `queue_depth` (AtomicUsize) and clears running/current fields in the snapshot while preserving completion history. This is the canonical reset for any test asserting exact queue or running state.
-- **cargo-llvm-cov widens SQLITE_BUSY window** — Flakes that only appear under coverage (`cargo-llvm-cov`) but not plain `cargo test` are usually (a) a SQLite connection missing `busy_timeout`, or (b) shared global state not reset between tests. Always set `busy_timeout` on new SQLite connections (see pattern below).
-- **All new SQLite connections must set `busy_timeout = 15s`** — Call `conn.busy_timeout(Duration::from_secs(15))` immediately after `Connection::open()`, before any `execute_batch()`. Pattern set by `chunks/store.rs` (`SQLITE_BUSY_TIMEOUT`) and now also used by `memory_store/unified/init.rs` (fixed in issue #2722). Without it, concurrent ingestion + test writes produce `SQLITE_BUSY` under cargo-llvm-cov.
-
-## App State Snapshot (Issue #2155 — first-launch perf)
-
-- **`build_runtime_snapshot` was serial, now parallel** — The four subsystems (screen intelligence, local AI, autocomplete, service status) in `src/openhuman/app_state/ops.rs` ran sequentially. Fixed with `tokio::join!`. Also added a 2s TTL cache (`RUNTIME_SNAPSHOT_CACHE`) so repeated polls within the TTL skip recomputation.
-- **`service::status` is sync — must use `spawn_blocking`** — `crate::openhuman::service::status(config)` may shell out to `launchctl`. Wrap it in `tokio::task::spawn_blocking` when called from an async context.
-- **`autocomplete::global_engine().status()` calls `Config::load_or_init()` internally** — Avoid this inside snapshot code. Use the new `status_with_config(config)` method which accepts an already-loaded config.
-- **Per-stage snapshot timeouts** — `AUTH_FETCH_TIMEOUT = 5s` and `RUNTIME_SNAPSHOT_TIMEOUT = 10s` are constants in `ops.rs`; they sum to 15s, well under the 30s frontend RPC timeout.
-## Project Board & Issue Queries
-
-- **Project #2 paginates at 100 items** — Board has 627+ items. Use GraphQL cursor pagination to find all open P0 issues; a single query only returns the first 100.
-- **jq regex `\s+` causes parse errors** — Use plain `test("#NNNN")` to check if a PR/issue body references an issue number. `\s+` in jq regex triggers parse errors.
-- **Most open P0s are security or Linux AppImage GLIBC issues** — When triaging P0s, filter for those categories first.
-- **Project #2 shows only closed items on the board view** — Use `gh issue list --repo tinyhumansai/openhuman --state open --assignee ""` to find unassigned open issues instead of querying the project board.
-- **Check linked PRs via timeline API, not body regex** — `gh api repos/tinyhumansai/openhuman/issues/$N/timeline --paginate | jq '[.[] | select(.event == "cross-referenced" and .source.issue.state == "open")] | length'` is more reliable than searching issue body text for PR references.
-
-## Git Submodules
-
-- **`tauri-cef` and `tauri-plugin-notification` are git submodules** — When upstream/main updates them, fix with `git submodule update --remote --checkout`, not by manually patching the vendored crate.
-
-## Memory Corruption Handling (Issue #5820)
-
-- **`tinymemory-core::corruption` is the one SQLITE_CORRUPT policy** — `is_sqlite_corrupt` / `escalate_or_count` / `report_and_recover` / `startup_integrity_check`. Every detector (queue worker, both tree-ingest sinks, reconcile, boot quick_check) escalates through it; do not add a local `warn!`-and-continue arm for corruption again.
-- **Type forks to remember** — two `SyncOutcome`s (core `sync::pipelines::traits` vs tinycortex) and three `SyncAuditEntry` copies (core `sync::audit`, `tinymemory-bus`, tinycortex's engine writer). Only the core one carries `tree_ingest_failures`; `engine::run_source_pipeline_core` is the boundary that keeps it, `run_source_pipeline` drops it. New audit fields must be `skip_serializing_if` so the engine writer's rows stay byte-identical (`audit_line_format_is_pinned`).
-- **Garbage-file corruption fixtures self-heal** — tinycortex's cold-open path (`connection.rs`) auto-quarantines a file that fails to open, so a garbage `chunks.db` makes `store()` succeed, not fail. Test the classification arm directly (`escalate_or_count`) instead of the full stack.
-- **Module-side degraded statics never reach the host** — the pinned TinyMemory cdylib has its own `tree::health` statics; host visibility comes only from `MemoryEvent` (host arms in `memory/host.rs` + `modules/memory_host.rs` → `user_error` web channel). A new variant is release-gated (tinymemory release + registry re-pin) before the product sees it.
-- **Module source-registry path (the #5820 "no memory source registered" strand)** — the module must read the host's `<root>/config.toml` (beside `workspace/`), not `workspace_dir/config.toml`; the host sends `config_path` in the module config JSON (`modules/ops.rs`) and tinymemory ≥ v1.13.1 honours it with a sibling-file fallback. Test a module fix before its release with `OPENHUMAN_MODULE_PATH=<dir holding libtinymemory_module.dylib>` (build in `vendor/tinymemory/crates/tinymemory-module` with `cargo build --release`; it is its own cargo workspace).
-- **Testing a local TinyMemory module build** — use `TINYMEMORY_TEST_MODULE=<path/to/libtinymemory_module.dylib>` (the loader's dev override; CI uses it too), never `OPENHUMAN_MODULE_PATH`: that search path hands the module an empty config, it refuses setup (`workspace_dir must be set`) and tinybus reports it as an "unrecoverable fault" with the reason dropped. In the app log, module output is prefixed `tinybus_module <target> message=`; host output is not.
-- **Module quarantine vs host cache** — the host's own engine copy caches its chunk-store handle; when the module quarantines `chunks.db`, `RuntimeCallbacks::publish_event` must reset it (`memory/host_impls.rs::reset_in_process_chunk_store`) or in-process reads stay `malformed` until restart.
-- **Worktree submodules can be half-initialised** — a timed-out `git submodule update --init --recursive` leaves `vendor/<x>/` holding only a `.git` file while `git submodule status` shows a clean SHA. Detect with `ls vendor/<x>/Cargo.toml`; fix with `git submodule update --force --recursive <path>`. tinymemory has its own nested `vendor/tinycortex` that must be initialised from inside `vendor/tinymemory`.
-- **Bus-arity mismatches hide behind fakes** — the module sent `Embed(model, dims, texts)` while the host declares `(provider, model, dims, texts)`; both test fakes mirrored the wrong shape, so tests passed while every embed was refused at decode. A fake host in module tests must copy the real host signature; pin arity host-side the way `execute_takes_its_four_arguments…` does.
-- **`module_config` cloud defaults** — `cloud_embedding_model` is the module's *fallback* model (`DEFAULT_CLOUD_EMBEDDING_*`), never `config.memory.embedding_model` (the user's local model). Sync-family bus calls (`RunSourceSync`/`RunConnectionSync`/`BootstrapConnection`) need `SOURCE_SYNC_BUS_TIMEOUT`; the client default per-call RPC timeout is 30 s, so long RPCs pass `timeoutMs`.
-- **Raw-coverage tests that read through the driver need the boot policy** — `set_modules_policy` is first-call-wins and the module captures `workspace_dir` at load, so a module with several driver-routed cases needs ONE leaked shared workspace (`tests/json_rpc_e2e.rs` recipe): `config_path` beside it (`Config::default().config_path` is the dev's real `~/.openhuman/config.toml`), `embeddings_provider = none`, row-wipe (never the file) between counting cases, and registry entries persisted via `replace_sources_in` before a driver-run sync. The coverage script runs raw modules sorted and stops at the first red, so run the next ones locally first.
-- **Re-pin recipe (scripted)** — a new tinymemory release means: registry version/URL + 11 digests from `checksum.toml`, 4 workflow `memory_version`/`memory_sha256` pins, `ARTIFACT_CAPABILITIES_PIN`, gitlink to the tag, both `Cargo.lock`s, and a re-read of `Capability::ALL` (a new family needs the host accessor + forwarder in the same change, or the pin guards fail).
-- **Never trust `cmd | tail` / `cmd | grep` exit codes in background checks** — the pipeline reports the filter's status, so a failed `cargo check` (disk full, missing submodule) read as green twice this session. Use `${PIPESTATUS[0]}` or grep for `Finished`.
-- **Re-pinning the TinyMemory module moves five things in one commit** — gitlink → release tag commit, `modules/registry.rs` (version, release_url, 11 digests from the release's `checksum.toml`), the four workflow `memory_version`/`memory_sha256` pairs (ubuntu-22.04-x86_64 row), and `ARTIFACT_CAPABILITIES_PIN` in `modules/memory.rs` after diffing the capability surface between tags. Guards: `modules/memory_tests.rs` (workflow digests, capability pin). Run `cargo test --lib -- modules::memory modules::registry`. The version bump also dirties BOTH `Cargo.lock`s (root + `app/src-tauri`) and CI is `--locked`: `cargo metadata --locked --manifest-path <each>` then commit both.
-- **Disk full (APFS) shows up as `could not compile syn` / `No space left on device`** — reclaim by deleting other checkouts' `target/` dirs (openhuman-1's shell target alone was 27 GB), never the active worktree's.
-
-## Pre-existing Test Failures
-
-- **`composio::action_tool::tests::factory_routes_through_direct_when_mode_is_direct` fails in `cargo test -p openhuman`** — Pre-existing failure unrelated to WhatsApp or any recent branch work. Do not attempt to fix unless explicitly tasked. Also intermittently flaky when run as part of the full suite — see "Pre-existing Flaky Tests" section.
-
-## Workflow Gate (must not skip)
-
-- **Steps 4–6 of `workflow/00-full-workflow.md` are mandatory before committing** — Step 4: architectobot verify. Step 5: full checks (`pnpm test:coverage`, `pnpm build`, `bash scripts/install.sh --dry-run`, PR quality scripts). Step 6: memory-keeper. Skipping any of these violates the workflow contract.
-- **Encode architectobot answers in the codecrusher prompt** — When the architectobot plan includes clarifying questions and the user approves specific answers, embed those decisions as explicit constraints in the codecrusher prompt so the agent doesn't re-ask.
-
-## Security Policy
-
-- **Path validation entry point** — `src/openhuman/security/policy.rs` exposes `validate_path` / `validate_parent_path`. All file I/O path validation must go through this API. `is_path_string_allowed()` is a string-only first pass, not sufficient on its own.
-- **validate_parent_path before create_dir_all** — For write operations, `validate_parent_path` MUST be called before any `create_dir_all` call. Calling it after allows symlink attacks to create directories outside the workspace before the security check fires (Issue #1927).
-- **Tool callers must use `validate_path` / `validate_parent_path`** — All tool implementations under `src/openhuman/tools/impl/filesystem/` must use these functions, not the legacy `is_path_allowed` / `is_resolved_path_allowed`.
-- **Security policy test filter** — Run only security policy tests with: `cargo test -p openhuman -- "security::policy"`. Runs the 100 tests in `src/openhuman/security/policy_tests.rs` cleanly.
-
-## Pre-existing Flaky Tests
-
-- **`composio::action_tool` and `agent::harness::session::turn` intermittent failures** — These tests fail randomly when run as part of the full suite (likely shared state or timing), but pass individually. Not related to security/policy changes. Do not treat as blockers for security-module PRs.
-
-## Windows OAuth Deep Link (Issue #2562)
-
-- **Three-layer fix**: (1) named-pipe IPC in `deep_link_ipc_windows.rs` — secondary process forwards `openhuman://` URL to primary via `\\.\pipe\com.openhuman.app-deeplink`, 40 retries × 50ms; (2) loopback OAuth server in `loopback_oauth.rs` — RFC 8252 one-shot `127.0.0.1:53824`, preferred path that eliminates deep link dispatch entirely; (3) Linux analog in `deep_link_ipc.rs` — Unix domain socket at `$XDG_RUNTIME_DIR/com.openhuman.app-deeplink.sock`.
-- **`OAuthProviderButton.tsx` loopback flow** — tries loopback first, sets `redirectUri` for backend, awaits callback, rewrites `http://127.0.0.1:PORT/auth?...` → `openhuman://auth?...` → `handleDeepLinkUrls`. Falls back to deep link if bind fails.
-- **Pipe binding location** — primary binds the named pipe in `lib.rs` right after the mutex guard (grep `bind_and_listen`); `drain_pending_urls()` wired in `setup()` (grep it — line numbers drift).
-- **Issue was already fixed before we picked it up** — PRs #2469, #2511, #2550 had already merged the fix. Our contribution was extracting `classify_request` as a pure function and adding 11 Rust unit tests.
-- **Pure-function extraction pattern** — when async/AppHandle-gated Tauri code is untestable, extract a `classify_request(head, expected_state, bound_port) -> RequestOutcome` pure function returning an enum. Enables comprehensive unit tests with zero Tauri context. `RequestOutcome` has 4 variants: `AuthCallback`, `StateMismatch`, `NotFound`, `MethodNotAllowed`.
-
-## Port Conflict Recovery (Issue #2617)
-
-- **Port fallback already in `pick_listen_port`** — `src/openhuman/connectivity/rpc.rs` tries ports 7789–7798 when 7788 is busy. Gap was: frontend `getCoreRpcUrl()` cached the URL on first resolution so it never picked up the fallback port, and stale-process reaping was macOS-only.
-- **`process_recovery.rs` is platform-gated** — `reap_stale_openhuman_processes` had only a macOS impl. Linux uses `/proc/<pid>/cmdline`; Windows uses `wmic process get`. Tests for each platform's parsing logic live in the same file, following the existing macOS test pattern.
-- **`recover_port_conflict` is a Tauri IPC command, not JSON-RPC** — Rust E2E test for port fallback lives in `tests/json_rpc_e2e.rs` and calls `pick_listen_port` directly: bind port 7788 with a `std::net::TcpListener` (std, not tokio) to simulate conflict, confirm fallback, then serve via `tokio::net::TcpListener::from_std(pick_result.listener.into_std())`.
-- **`BootCheckTransport` is the right hook for frontend recovery** — `app/src/lib/bootCheck/index.ts` is the injection point for new recovery capabilities; don't add them directly to the BootCheck component.
-- **i18n locales are single flat files** — Each locale is one file at `app/src/lib/i18n/<locale>.ts` (`en.ts` is the source of truth; the old `chunks/<locale>-N.ts` layout was retired). New keys must be added to all 13 locale files simultaneously; `pnpm i18n:check` enforces key parity.
-- **Workflow folder** — `workflow/` at repo root has 5 markdown files (00–05) defining the full PR workflow: pick issue → architectobot plan → user approval → codecrusher → architectobot verify → checks → memory-keeper → commit → push/PR.
-
-## Channel Event Workspace Routing (Issue #2602)
-
-- **Workspace identity is `PathBuf`** — Represented as the workspace directory path on `ChannelRuntimeContext` as `ctx.workspace_dir: Arc<PathBuf>`. Use `ctx.workspace_dir.as_ref().clone()` at publish sites. There is no abstract `WorkspaceId` type.
-- **`DomainEvent` workspace routing contract** — Publisher populates workspace field from context; subscriber compares against `self.workspace_dir` and early-returns with `log::debug!` on mismatch. Follow this pattern for any workspace-scoped `DomainEvent` variant.
-- **`ChannelMessageReceived` and `ChannelMessageProcessed` carry `workspace_dir`** — Added in PR for issue #2602. Guards in `ConversationPersistenceSubscriber` (memory_conversations/bus.rs) and `TelegramRemoteSubscriber` (telegram/bus.rs) prevent cross-workspace persistence during login/workspace-change races.
-
-## Pre-existing Upstream Failures (from issue #2602 session)
-
-- **Upstream `main` has 5 Vitest failures and 4 TypeScript compile errors** — Caused by missing iOS experimental dependencies: `@noble/ciphers/chacha`, `@noble/ciphers/webcrypto`, `qrcode.react`, `@tauri-apps/plugin-barcode-scanner`. Breaks `pnpm compile`, `pnpm build`, `pnpm test:coverage` on a clean checkout. Always verify by stashing changes and running checks on the base branch before blaming your PR.
-- **`cargo fmt` must run after codecrusher** — codecrusher does not reliably produce `cargo fmt`-clean Rust. Always run `cargo fmt --manifest-path Cargo.toml` after codecrusher finishes and before committing.
-
-## TaskKanbanBoard (Issue #3347 — frontend-only subset)
-
-- **5 columns, 7 statuses** — `COLUMN_DEFS` in `TaskKanbanBoard.tsx` defines columns `todo / awaiting_approval / in_progress / blocked / done`. `columnFor()` maps the two virtual statuses: `ready → in_progress` (renders a "Ready to start" sage badge) and `rejected → done` (renders a "Rejected" coral badge). Anyone adding a new `TaskBoardCardStatus` must update both `COLUMN_DEFS` and `columnFor()`.
-- **Native HTML5 drag-and-drop only** — No DnD library (@dnd-kit, react-beautiful-dnd). Cards set `dataTransfer` key `application/x-task-card-id`; columns handle `onDragOver` / `onDragLeave` / `onDrop`. Arrow buttons are the touch/accessibility fallback. Do not add a DnD library.
-- **`mutatingCardId` is optional on `TaskKanbanBoard`** — `IntelligenceTasksTab` sets/clears it in `finally` blocks around personal-board mutations; `Conversations.tsx` (second consumer) does not pass it. Both consumers must keep new props optional to avoid compile failures.
-- **Bare `vitest run <path>` fails with "document is not defined"** — Must use `--config test/vitest.config.ts` (or `pnpm debug unit <relative-path>`) to load the jsdom environment. Piping `pnpm exec vitest run` through `| tail` also buffers all output until completion, hiding progress — use the debug runner instead.
-
-## Memory Sync Sources — Defaults ON + Per-Source UI (Issue #3293)
-
-- **Conservative caps registry** — `composio_defaults_for_toolkit(toolkit) -> (max_items, sync_depth_days)` in `src/openhuman/memory/sources/registry.rs` is the single source of truth. Values: gmail 100/30, slack 50/14, notion 30/30, linear 50/30, clickup 50/30, github 50/30, generic 30/14. Non-Composio defaults (GithubRepo 10PR/10issue/50commit, RSS 20, Twitter 7d) live in `apply_kind_defaults` in `rpc.rs`.
-- **`upsert_composio_source` now defaults ON** — Registers `enabled: true` with caps applied from the registry. Previously registered `enabled: false` with no caps.
-- **Cap enforcement: 3 construction sites, not 1** — `ProviderContext` (`memory_sync/composio/providers/types.rs`) carries `max_items`/`sync_depth_days`. All three sites must populate caps from the registry entry: `composio/mod.rs run_connection_sync`, `composio/periodic.rs`, `composio/bus.rs`. Each provider reads `ctx.max_items`/`ctx.sync_depth_days` for pagination + date clamping. Shared helpers: `pages_for_max_items` / `epoch_floor_from_depth` in `providers/helpers.rs`.
-- **First-sync gotcha on new connections** — `bus.rs on_connection_created` fires BEFORE `upsert_composio_source`, so caps are (None, None) on the brand-new connection's first sync — bounded only by internal `MAX_PAGES`, not registry caps. Documented in code; intentional.
-- **`memory_sources_apply_all_in` RPC** — Zero params → `{ sources, sync_triggered }`. Enables all sources, clears caps to None (falls back to internal `MAX_PAGES` ceilings, ~500 items, not truly unlimited), triggers sync per source.
-- **Retroactive migration** — `apply_composio_source_caps_migration` in `reconcile.rs`, guarded by `Config.composio_source_caps_migrated: bool` (`#[serde(default)]`), runs once from `ensure_composio_sources`. Only touches Composio entries with `!enabled && max_items.is_none() && sync_depth_days.is_none()` — never overwrites user-customized caps.
-- **`MemorySourcePatch` was missing limit fields** — `max_commits`, `max_issues`, `max_prs` were absent from `MemorySourcePatch`, `update_source`, and the update schema. Also missing from the TS `MemorySourceEntry` interface in `memorySourcesService.ts`. Both were fixed in this issue.
-- **Per-source settings UI** — `SourceSettingsPanel.tsx` (sibling of `MemorySourcesRegistry.tsx`) with a `KIND_FIELDS` map driving which limit fields appear per source kind. Empty input = omit from patch (use default); number = set. "All In" button uses `ConfirmationModal` (primary-500 prominent). Toasts via existing `onToast` prop.
-- **`pnpm i18n:english:check` is pre-failing** — Exits with `total unexpected English: 1312` on a clean base tree. Confirm your new keys aren't among the failures rather than expecting exit 0. `pnpm i18n:check` (key parity) is the real gate.
-
-## Memory Tree Sync & Raw-Archive Reconcile (branch fix/memory-tree-sync-reconcile)
-
-- **Tree scope ≠ raw-archive id for GitHub** — `github:owner/repo` (tree registry key) and `github.com/owner/repo` (raw archive id) slugify to DIFFERENT `raw/` dirs (`github-owner-repo` vs `github-com-owner-repo`). Any code resolving a source's raw dir must use `memory_sources::sync::SourceScope { tree_scope, archive_source_id }` — deriving from the tree scope scans the wrong directory and silently reports "nothing to do".
-- **Raw-file coverage gate** — `mem_tree_ingested_sources` with `source_kind = "raw_file"`, `source_id = <rel path with .md>` (`memory_store/chunks/store.rs: mark_raw_paths_ingested / filter_raw_paths_not_ingested`). Written by github sync + rebuild after each summary batch lands. `raw_coverage()` in `memory_sync/sources/rebuild.rs` backfills the gate once per scope from L1 summary child labels (`commit:<sha>` / `issue:<n>` / `pr:<n>` / file stems) before diffing disk vs gate.
-- **Workspace periodic scheduler** — `memory_sync/workspace/periodic.rs` (started in `core/jsonrpc.rs` next to the Composio one) is the ONLY thing auto-syncing `github_repo`/`folder`/`rss_feed`/`web_page` sources; the Composio loop walks Composio connections exclusively. Cadence: `config.memory_sync_interval_secs` (`Some(0)` = manual only, default 24h), due-check via in-memory fired-at map + persisted sync-audit fallback.
-- **Queue self-heal retries transient failures only** — `memory_queue/scheduler.rs` calls `store::requeue_transient_failed` every 3h (excludes `failure_class = 'unrecoverable'` so bad keys/budget don't retry-loop). Full reset stays manual via `memory_tree_retry_failed` RPC.
-- **`openhuman.memory_sources_reconcile` RPC** — Reports per-scope raw coverage `{total_raw_files, covered, pending}`; `execute: true` spawns background incremental rebuild. Same reconcile auto-runs after every sync via `check_and_rebuild_tree`.
-- **L0 seal gate is token-only by design** — `should_seal` has NO sibling-count fallback at L0 (docs used to lie about this); small buffers seal via the 3-hourly `flush_stale` path. L≥1 gates on `SUMMARY_FANOUT` (10) — an L1 buffer holding <10 summaries is healthy, not stuck.
-
-## Intelligence page scroll ownership (#4267)
-
-- **`app/src/pages/Intelligence.tsx` is rendered ONLY by `Brain.tsx`** (`/settings/intelligence` redirects to `/brain?tab=intelligence`), inside a card with `h-full overflow-hidden` (`Brain.tsx` ~line 255). A code comment there asserts the embedded panels "own their own scroll directly" — true for the sibling `PanelPage`/`PanelScaffold` panels (MemoryDataPanel etc.), but Intelligence previously returned a bare `<div className="z-10 relative">` with NO height/scroll, so its content overflowed the card and was clipped with no scrollbar.
-- **Fix pattern (matches `PanelPage`)**: root `flex h-full min-h-0 flex-col` → pinned `SettingsHeader` wrapper (`flex-shrink-0`) → body `min-h-0 flex-1 overflow-y-auto` wrapping ChipTabs + the content card. `ToastContainer`/`ConfirmationModal` stay as siblings OUTSIDE the scroll region. The scroll body carries `data-testid="intelligence-scroll"` for the regression test.
-- **Gotcha for any panel embedded in Brain's Knowledge/Memory card**: it must own its own vertical scroll (the card is `overflow-hidden`). Don't rely on a parent scroll — there isn't one.
-
-## Sources row: pending vs stuck vectors (Issue #6025)
-
-- **`chunks_pending` alone is ambiguous** — since tinymemory 1.14 vectors come from the `reembed_backfill` job, not inline at ingest, so every sizeable sync leaves a transient backlog. `sourcePipelineStatus.ts` reads it as soft `vectors_pending` while `memory_tree_memory_backfill_status.in_progress` is true or `freshness` is `active`/`recent` (≤5 min); amber `stored_without_vectors` only for the `semantic_recall` latch, an embeddings-family `first_blocking_cause`, or an idle backlog with nothing queued.
-- **`backfill_in_progress` is a process-global flag, not a query** — set when a re-embed chain is armed, cleared only when the chain ends (Done/Skipped/StaleSignature/Failed), so it stays true while the job sits starved in `ready` behind `extract_chunk` on the single LLM permit. Not per-workspace.
-- **Test fixtures: a stuck backlog needs `freshness: 'idle'`** — `chunks_pending > 0` with `recent`/`active` freshness renders the neutral note, not the warning. `vi.mock` factories for `utils/tauriCommands/memoryTree` must list `memoryTreeBackfillStatus` or `MemorySourcesRegistry.refresh` throws inside its `Promise.all`.
-- **`t()` does not interpolate** — the caller replaces placeholders: `t('sync.pipeline.vectorsPending').replace('{count}', n.toLocaleString())` (pattern from `SyncAuditPanel.tsx`).
-- **`SYNC_PASS_MAX_ITEMS` (200) sizes one `AcceptSourceItems` call** — the module embeds each document in turn (~1.7 s each) against the 15-min `module_call_slow!` deadline; 500 tripped it. The Sources-row loop (`composio_sync_budgeted`, ≤50 passes) is unaffected; the four entry points that sync once per invocation (`periodic.rs`, `memory/ops/sync.rs`, `bus_part_02.rs` `connection_created`, `slack/rpc.rs`) go through `ops::pass_budget::run_sync_within_budget`, which repeats the pass within a 500-**record** budget. Charge that budget by `records_read`, never by `written`: a module returning already-ingested pages with `more_pending` would otherwise be asked forever.
-- **`providers_ops.rs` sits at exactly 750 lines** — the `check-openhuman-rust-layout.mjs` limit; edits there must be net-zero lines or split the file.
-- **`node app/scripts/build-parallel.mjs` fails with `vite: command not found`** when run directly — it shells out to bare `tsc`/`vite`; use `pnpm build` or prefix `PATH=app/node_modules/.bin:$PATH`.
-- **"Got it, saved" with zero tool calls (issue #6048)** — the memory *write* tools (`memory_store`, `save_preference`) are always registered, but nothing in the prompt said a request to remember must become a tool call, or forbade claiming a save without one; `memory_store` also required an invented `namespace` + `key`. Now `MemoryWriteSection` (`agent/learning/prompt_sections.rs`, `## Remembering`) is registered by `builder/helpers.rs::add_memory_prompt_sections` whenever a write tool is registered **and** visible, independent of `learning.enabled`; `memory_store` defaults `namespace` to `DEFAULT_AGENT_MEMORY_NAMESPACE` — the assistant's own scope, currently `"global"`, the same namespace the rest of recall reads — and derives `key` from the content (`derive_key`: a readable stem plus a 16-hex SHA-256 suffix; 64 bits, because the stem collides by design and a key collision *overwrites* an unrelated memory rather than duplicating it). The section names only the write tools the session actually offers: `archivist`, `trigger_reactor` and `workflow_builder` carry `memory_store` without `save_preference`, so naming both unconditionally would mandate an invisible tool. The archivist is not a safety net here: it writes the turn to the FTS5 episodic table only, and files raw prose into the tree at segment close. `factory.rs` sits at its legacy cap (1552): put new gating in `helpers.rs`, not inline.
diff --git a/.claude/phase-0-plan.md b/.claude/phase-0-plan.md
deleted file mode 100644
index 8d03ccc988..0000000000
--- a/.claude/phase-0-plan.md
+++ /dev/null
@@ -1,74 +0,0 @@
-# Phase 0 — Command Palette + Keyboard Shortcut System
-
-One-page summary. Full spec: [`docs/superpowers/specs/2026-04-21-command-palette-design.md`](../docs/superpowers/specs/2026-04-21-command-palette-design.md)
-
-**Branch:** `feat/frontend-reskin` · **Worktree:** `~/projects/openhuman-frontend`
-
-## What
-
-Superhuman/Linear-style `⌘K` palette + global keyboard shortcut system + `?` help overlay for OpenHuman. Additive keyboard layer — no existing page visuals touched, no feature flag, no new Redux slices.
-
-## Architecture at a glance
-
-```
-lib/commands/
-├── types.ts · shortcut.ts · registry.ts (singleton)
-├── hotkeyManager.ts (singleton capture-phase listener + scope stack)
-├── useHotkey.ts (raw) · useRegisterAction.ts (palette, delegates to useHotkey)
-└── globalActions.ts
-
-components/commands/
-├── CommandProvider.tsx (root mount, one instance)
-├── CommandScope.tsx (push/pop scope frame by symbol)
-├── CommandPalette.tsx (cmdk + Radix Dialog)
-├── HelpOverlay.tsx (Radix Dialog)
-└── Kbd.tsx
-```
-
-## Non-obvious decisions (decisions log in full spec)
-
-- **`<CommandScope>` primitive, NOT `useLocation().key`** — HashRouter is brittle, fails for tabbed/drawer surfaces.
-- **Scope frames keyed by `Symbol`** — nesting + StrictMode double-mount safe.
-- **Last-registered-wins** within a frame (iterate reversed at dispatch).
-- **`preventDefault` on match, NEVER `stopPropagation`** — don't break cmdk or native inputs.
-- **Version-counter memoized snapshots** for `useSyncExternalStore` — same array ref when unchanged.
-- **`handlerRef` pattern** — handler ref updated every render, binding re-registers only on shortcut/scope change.
-- **Palette and help mutually exclusive.**
-- **8 scoped `cmd-*` tokens only** — not a full design system; reskin brainstorm owns that later.
-- **Separate `useHotkey` / `useRegisterAction`** — prevents double-registration bug; raw vs palette-visible.
-
-## Seed actions (v1 — six total)
-
-| id | shortcut | group |
-|---|---|---|
-| `nav.home` | `mod+1` | Navigation |
-| `nav.conversations` | `mod+2` | Navigation |
-| `nav.intelligence` | `mod+3` | Navigation |
-| `nav.skills` | `mod+4` | Navigation |
-| `nav.settings` | `mod+,` | Navigation |
-| `help.show` | `?` | Help |
-
-Meta hotkeys bound directly in `CommandProvider` (not in registry): `⌘K` open palette, `Esc` close overlay.
-
-## Gates (must pass in order)
-
-0. **Platform verify** — stub keydown listener, confirm `⌘1–⌘4` not swallowed by Tauri/CEF. Blocks everything.
-1. **Foundation** — types, shortcut, registry, hotkeyManager, hooks, `<CommandScope>`. Unit tests ≥95% on core.
-2. **Tokens** — 8 `cmd-*` in tailwind + CSS vars + `lint:commands-tokens` pre-push script.
-3. **Components** — Kbd, install cmdk + `@radix-ui/react-dialog`, Palette, HelpOverlay, CommandProvider, globalActions.
-4. **Wire** — one-line edit to `App.tsx` (pinned mount point inside HashRouter, outside routes).
-5. **E2E** — command-palette spec + regression probe on one pre-existing shortcut.
-6. **Pre-merge** — typecheck, lint, unit, token-lint, e2e, cargo fmt/check, manual smoke + a11y.
-
-## Explicit non-goals
-
-- Chord sequences (v2)
-- Full design-system semantic tokens (reskin brainstorm)
-- Sign Out / Toggle Theme / per-page actions (future PRs)
-- i18n
-- Go Back / Forward shortcuts
-
-## New deps
-
-- `cmdk` (palette UI)
-- `@radix-ui/react-dialog` (overlay wrapper, focus trap, a11y)
diff --git a/.claude/projects/-Users-enamakel-work-tinyhumansai-openhuman-2/memory/MEMORY.md b/.claude/projects/-Users-enamakel-work-tinyhumansai-openhuman-2/memory/MEMORY.md
deleted file mode 100644
index ac8b075f4b..0000000000
--- a/.claude/projects/-Users-enamakel-work-tinyhumansai-openhuman-2/memory/MEMORY.md
+++ /dev/null
@@ -1,4 +0,0 @@
-# Project memory index
-
-- [cargo check vs test verification](cargo-check-vs-test-verification.md) — `cargo check` skips test modules; use `cargo test --no-run` to verify tests compile.
-- [Subagent output can be lost](subagent-output-can-be-lost.md) — commit verified subagent work promptly; scope parallel agents to non-overlapping paths.
diff --git a/.claude/projects/-Users-enamakel-work-tinyhumansai-openhuman-2/memory/cargo-check-vs-test-verification.md b/.claude/projects/-Users-enamakel-work-tinyhumansai-openhuman-2/memory/cargo-check-vs-test-verification.md
deleted file mode 100644
index 74b471a619..0000000000
--- a/.claude/projects/-Users-enamakel-work-tinyhumansai-openhuman-2/memory/cargo-check-vs-test-verification.md
+++ /dev/null
@@ -1,12 +0,0 @@
----
-name: cargo-check-vs-test-verification
-description: cargo check passing does NOT mean tests compile; always cargo test --no-run to verify test modules
-metadata:
- type: feedback
----
-
-`cargo check --manifest-path Cargo.toml` compiles the **lib only** — it does NOT compile `#[cfg(test)]` modules or sibling `*_tests.rs` files. A domain can pass `cargo check` while its own test modules have compile errors (missing imports in `use super::*` test files, private-fn re-export E0364, missing struct fields in test-only `PromptContext` construction sites, etc.).
-
-**Why:** In this repo, `cargo check` greenlit a new domain whose `select_tests.rs` had unresolved `WorkflowPhase`/`PHASE_*` imports and whose `ops.rs` had a `pub(crate) use slugify` (E0364) — all invisible until `cargo test` compiled the test cfg. Also: adding a field to a widely-constructed struct (e.g. `PromptContext`) requires updating **every** construction site including those in `tests/*.rs` integration tests (e.g. `tests/personality_e2e.rs`), which `cargo check` won't surface.
-
-**How to apply:** To verify Rust work actually compiles AND tests are valid, run `cargo test --manifest-path Cargo.toml --no-run` (compiles all test targets) and then run the actual tests. Never report "N tests pass" based on a `cargo check` exit code or a `cargo test <filter>` run that shows "0 passed; N filtered out" — that means the filter matched nothing, not success. Confirm the result line shows a non-zero passed count. See [[subagent-output-can-be-lost]].
diff --git a/.claude/projects/-Users-enamakel-work-tinyhumansai-openhuman-2/memory/subagent-output-can-be-lost.md b/.claude/projects/-Users-enamakel-work-tinyhumansai-openhuman-2/memory/subagent-output-can-be-lost.md
deleted file mode 100644
index d5c2884dc1..0000000000
--- a/.claude/projects/-Users-enamakel-work-tinyhumansai-openhuman-2/memory/subagent-output-can-be-lost.md
+++ /dev/null
@@ -1,14 +0,0 @@
----
-name: subagent-output-can-be-lost
-description: Long-running subagents can die/roll back losing uncommitted work; commit verified subagent output promptly
-metadata:
- type: feedback
----
-
-During the agent_workflows feature build, a `codecrusher` subagent ran ~20 min, hit an API socket error, and its working-tree output was largely rolled back (only 2 of ~10 files survived) — and a separate harness subagent got stuck in a loop re-running 5-minute background `cargo test` commands without converging, requiring a manual TaskStop + `pkill -f "cargo test"`.
-
-**How to apply:**
-- When a subagent completes a self-contained, independently-verified slice (e.g. frontend in `app/` only), **commit it promptly** as a checkpoint rather than letting it sit uncommitted while other agents run — uncommitted work is the only thing at risk of a rollback.
-- Give parallel subagents **non-overlapping path scopes** (one in `src/`, one in `app/`) and tell them NOT to commit, so the main thread reconciles and commits.
-- If a subagent goes quiet, check liveness via file mtimes + `TaskOutput(block:false)`; if it's looping on long background commands, `TaskStop` it and `pkill` stray `cargo` processes, then finish the work directly.
-- Always independently re-verify a subagent's claimed results — see [[cargo-check-vs-test-verification]] (a subagent reported "tests pass" when the test cfg never compiled).
diff --git a/.claude/rules/README.md b/.claude/rules/README.md
index 7527e7cc80..e14e510394 100644
--- a/.claude/rules/README.md
+++ b/.claude/rules/README.md
@@ -5,7 +5,6 @@ This directory is intentionally near-empty.
Authoritative docs for AI agents and contributors:
- **[`AGENTS.md`](../../AGENTS.md)** — all project conventions, commands, architecture, testing, patterns. (`CLAUDE.md` redirects here.)
-- **[`.claude/memory.md`](../memory.md)** — project memory: fixes, gotchas, strict rules, workflow notes.
- **[`gitbooks/developing/architecture.md`](../../gitbooks/developing/architecture.md)** — narrative architecture, dual-socket sync.
- **[`gitbooks/developing/architecture/frontend.md`](../../gitbooks/developing/architecture/frontend.md)** — frontend layout.
- **[`gitbooks/developing/architecture/tauri-shell.md`](../../gitbooks/developing/architecture/tauri-shell.md)** — Tauri shell.
diff --git a/.claude/scratch/agent-harness-e2e-plan.md b/.claude/scratch/agent-harness-e2e-plan.md
deleted file mode 100644
index a6f8cf0d30..0000000000
--- a/.claude/scratch/agent-harness-e2e-plan.md
+++ /dev/null
@@ -1,339 +0,0 @@
-# Agent-Harness E2E Plan: Channels + Prompt-Flow Coverage
-
-Branch: `agent-harness-e2e-channels`
-
----
-
-## 1. Current State (~300 words)
-
-### Core: Telegram provider
-
-The Telegram channel is a mature, production provider at `src/openhuman/channels/providers/telegram/`. It long-polls via `getUpdates` (`channel_ops.rs:307-380`), parses inbound messages/reactions (`channel_recv.rs`), sends outbound text/media/reactions (`channel_send.rs`), and supports draft streaming, remote-control slash commands (`remote_control.rs`), and pairing/allowlist auth (`channel_core.rs`).
-
-The channel runtime (`src/openhuman/channels/runtime/startup.rs`) wires Telegram (and all channels) into the dispatch loop, which feeds inbound messages into the agent harness via `request_native_global("agent.run_turn", ...)`. The harness runs the full tool-call loop and returns a response that the channel sends back.
-
-The RPC surface (`src/openhuman/channels/controllers/schemas.rs`) exposes `openhuman.channels_connect`, `channels_disconnect`, `channels_status`, `channels_test`, `telegram_login_start`, `telegram_login_check`, `channels_send_message`, and more.
-
-**Critical blocker**: `api_url()` is hardcoded to `https://api.telegram.org/bot{token}/{method}` (`channel_core.rs:88-89`). There is no env-var override to redirect Telegram API calls to a mock server. This must be addressed in WS-B.
-
-### Mock backend
-
-The mock server (`scripts/mock-api/`) has mature LLM mocking (`routes/llm.mjs` with `llmStreamScript`, `llmForcedResponses`, `llmKeywordRules`), Composio integration mocking (`routes/integrations.mjs` with `composioConnections`, `composioAvailableTriggers`, `composioExecuteResponse_*`), cron mocking (`routes/cron.mjs`), and a full admin API (`admin.mjs`). Socket.IO event injection exists via `/__admin/socket/emit`. There are **no** Telegram Bot API mock routes whatsoever.
-
-### E2E suite
-
-Five `chat-harness-*.spec.ts` specs cover send+stream, cancel, scroll-render, subagent delegation, and wallet flows. `composio-triggers-flow.spec.ts` tests trigger CRUD via core RPC. `cron-jobs-flow.spec.ts` tests the cron panel UI. `webhooks-ingress-flow.spec.ts` tests webhook RPC surface stubs.
-
-`telegram-flow.spec.ts` (1019 lines) is entirely `describe.skip`'d. It was written for the old skill system (references SkillsGrid, V8 runtime, `Connect Telegram` OAuth modal). None of its test IDs match the current channel system. It should be **deleted and replaced**, not salvaged.
-
----
-
-## 2. Gaps
-
-### Core (Rust)
-
-- **No Telegram API base URL override**: `api_url()` always targets `api.telegram.org`. Need an env var (`OPENHUMAN_TELEGRAM_API_BASE`) or constructor parameter so the provider can be pointed at the mock server during E2E.
-- **No webhook ingress endpoint**: Telegram long-polls via `getUpdates`; there is no HTTP endpoint where a mock Telegram could push updates. For E2E, the provider needs either: (a) the mock to serve `getUpdates` responses (preferred, since the provider already uses long-polling), or (b) a webhook receiver route on the core. Option (a) is simpler since it matches existing architecture.
-- **`channels_connect` for bot_token auth mode** needs verification that it works end-to-end against the mock `getMe` endpoint.
-
-### Mock backend
-
-- **No Telegram Bot API routes**: no `/bot<token>/getMe`, `/bot<token>/getUpdates`, `/bot<token>/sendMessage`, etc.
-- **No tool-call round-trip scripting for harness flows**: `llmKeywordRules` supports `toolCalls` but there is no multi-turn scripting (message 1 -> tool call -> tool result -> message 2 with final answer). Need `llmForcedResponses` queue patterns documented and possibly extended for chained tool-use turns.
-- **No Composio action execution result fixtures** for E2E prompt-flow tests (only `composioExecuteResponse_<ACTION>` per-action overrides exist, which is actually sufficient).
-- **No cron-creation mock for LLM-driven flows**: the mock LLM can return tool calls, but there is no mock for `openhuman.cron_create` being called as a tool result round-trip.
-
-### E2E specs
-
-- **`telegram-flow.spec.ts`**: 100% stale, references removed skill system. Delete.
-- **No Telegram channel connect/disconnect E2E spec** for the current `channels_connect`/`channels_disconnect` RPC surface.
-- **No prompt-flow E2E specs**: no tests exercise the harness processing a message that triggers a tool call (composio, search, cron) and returning a result.
-- **No cross-channel bridge E2E**: no test sends a Telegram message that produces a cron job or composio action.
-
----
-
-## 3. Workstream Breakdown
-
-### WS-A: Mock Backend — Telegram Bot API + Harness Tool-Call Plumbing
-
-**Goal**: Add mock Telegram Bot API routes and extend LLM mock scripting so downstream specs can drive deterministic Telegram + tool-call round-trips.
-
-**Files to create/modify**:
-
-| Action | Path |
-|--------|------|
-| CREATE | `scripts/mock-api/routes/telegram.mjs` |
-| MODIFY | `scripts/mock-api/routes/llm.mjs` (document multi-turn forced response patterns; add `llmToolCallSequence` behavior key for chained turns) |
-| MODIFY | `scripts/mock-api/server.mjs` (import and wire `handleTelegram` into the route chain) |
-| MODIFY | `scripts/mock-api/state.mjs` (add `mockTelegramUpdates`, `mockTelegramSentMessages` state arrays with getters/setters/resetters) |
-| MODIFY | `scripts/mock-api/admin.mjs` (add `GET /__admin/telegram/sent`, `POST /__admin/telegram/inject-update`, `POST /__admin/telegram/reset` endpoints) |
-| MODIFY | `app/test/e2e/mock-server.ts` (re-export any new helpers needed by specs) |
-
-**Mock-backend changes**:
-
-New route handler `handleTelegram(ctx)` in `scripts/mock-api/routes/telegram.mjs`:
-
-| Route pattern | Behavior |
-|---------------|----------|
-| `POST /bot<token>/getMe` | Returns `{ ok: true, result: { id: 123, is_bot: true, username: behavior.telegramBotUsername \|\| "e2e_test_bot" } }` |
-| `POST /bot<token>/getUpdates` | Returns updates from `mockTelegramUpdates` queue. Supports long-poll simulation via `telegramPollDelayMs` behavior key. Each call drains the queue. |
-| `POST /bot<token>/sendMessage` | Records to `mockTelegramSentMessages`, returns `{ ok: true, result: { message_id: <seq>, chat: {...}, text: <text> } }` |
-| `POST /bot<token>/sendChatAction` | Returns `{ ok: true, result: true }` |
-| `POST /bot<token>/deleteWebhook` | Returns `{ ok: true, result: true }` |
-| `POST /bot<token>/setMessageReaction` | Returns `{ ok: true, result: true }` |
-| `POST /bot<token>/sendPhoto`, `sendDocument`, `sendVideo`, `sendAudio`, `sendVoice` | Records to sent log, returns ok |
-
-Behavior keys:
-- `telegramBotUsername` — bot username returned by `getMe`
-- `telegramBotToken` — expected token (for auth validation; default: accept any)
-- `telegramPollDelayMs` — simulated long-poll delay for `getUpdates`
-- `telegramGetMeFails` — if `"1"`, `getMe` returns 401
-- `telegramSendFails` — if `"1"`, `sendMessage` returns 400
-
-Admin endpoints:
-- `POST /__admin/telegram/inject-update` — push a Telegram update JSON into the queue (spec calls this to simulate an inbound message)
-- `GET /__admin/telegram/sent` — list all messages the bot "sent" (for assertion)
-- `POST /__admin/telegram/reset` — clear queues
-
-LLM mock extension — `llmToolCallSequence` behavior key:
-```json
-[
- {
- "match": "create a cron",
- "response": {
- "toolCalls": [{"name": "cron_create", "arguments": {"schedule": "0 9 * * *", "prompt": "morning briefing"}}],
- "content": ""
- }
- },
- {
- "match": "cron_create-result",
- "response": {
- "content": "Done! I created a daily 9am cron job for your morning briefing."
- }
- }
-]
-```
-This is actually already achievable with the existing `llmKeywordRules` + `llmForcedResponses` mechanisms. The work here is documenting the pattern and adding one convenience: a `llmToolCallScript` behavior key that accepts a sequence of `[{toolCalls, content}, {content}]` entries that auto-advance after each provider call, replacing `llmForcedResponses` for multi-turn scenarios. This avoids specs needing to manually queue and manage the forced response array.
-
-**Test scenarios** (unit tests for mock routes):
-1. `getMe` returns bot info with default and custom username
-2. `getUpdates` returns empty when no updates queued
-3. `getUpdates` returns injected updates and drains queue
-4. `sendMessage` records message and returns success
-5. `sendMessage` returns error when `telegramSendFails=1`
-6. Admin inject-update + sent-list round-trip
-7. `llmToolCallScript` auto-advances through multi-turn sequence
-
-**Acceptance criteria**:
-- A spec can: (1) set `telegramBotUsername`, (2) inject a Telegram update via admin, (3) observe the bot's reply in `/__admin/telegram/sent`, (4) configure LLM to return tool calls on specific keywords.
-- All existing mock-api tests pass (`scripts/mock-api/routes/__tests__/`).
-
-**Dependencies**: None. This is foundational infrastructure.
-
----
-
-### WS-B: Core Wiring — Telegram API Base URL Override
-
-**Goal**: Allow the Telegram provider to target a mock server instead of `api.telegram.org` via an environment variable, enabling E2E testing of the full Telegram channel loop.
-
-**Files to create/modify**:
-
-| Action | Path |
-|--------|------|
-| MODIFY | `src/openhuman/channels/providers/telegram/channel_core.rs` — `api_url()` reads `OPENHUMAN_TELEGRAM_API_BASE` env var; defaults to `https://api.telegram.org` |
-| MODIFY | `src/openhuman/channels/providers/telegram/channel_types.rs` — add `api_base: String` field to `TelegramChannel` struct |
-| MODIFY | `src/openhuman/channels/providers/telegram/channel_core.rs` — constructor reads env var, stores in `api_base` |
-| MODIFY | `src/openhuman/channels/runtime/startup.rs` — no changes needed if env var is read in constructor |
-| MODIFY | `.env.example` — document `OPENHUMAN_TELEGRAM_API_BASE` |
-| MODIFY | `app/scripts/e2e-run-spec.sh` — export `OPENHUMAN_TELEGRAM_API_BASE=http://127.0.0.1:${E2E_MOCK_PORT}` when running Telegram specs |
-| CREATE | `src/openhuman/channels/providers/telegram/channel_core_tests.rs` or extend existing `channel_tests.rs` — test that `api_url()` respects the override |
-
-**Detailed changes**:
-
-`channel_types.rs` — add field:
-```rust
-pub struct TelegramChannel {
- // ... existing fields ...
- api_base: String, // NEW: base URL for Telegram Bot API
-}
-```
-
-`channel_core.rs` — constructor:
-```rust
-pub fn new(bot_token: String, allowed_users: Vec<String>, mention_only: bool) -> Self {
- let api_base = std::env::var("OPENHUMAN_TELEGRAM_API_BASE")
- .unwrap_or_else(|_| "https://api.telegram.org".to_string());
- // ... rest unchanged, but store api_base ...
-}
-```
-
-`channel_core.rs` — `api_url()`:
-```rust
-pub(crate) fn api_url(&self, method: &str) -> String {
- format!("{}/bot{}/{method}", self.api_base, self.bot_token)
-}
-```
-
-**Test scenarios**:
-1. `api_url()` returns `https://api.telegram.org/bot<token>/<method>` by default
-2. With `OPENHUMAN_TELEGRAM_API_BASE=http://localhost:18473`, `api_url()` returns `http://localhost:18473/bot<token>/<method>`
-3. Trailing slash in env var is stripped
-4. `cargo check` and `cargo test` pass
-
-**Acceptance criteria**:
-- `api_url()` respects `OPENHUMAN_TELEGRAM_API_BASE` env var
-- Default behavior unchanged (still `api.telegram.org`)
-- Unit test covers the override
-- `e2e-run-spec.sh` exports the env var for Telegram specs
-
-**Dependencies**: None. Can run in parallel with WS-A.
-
----
-
-### WS-C: Telegram E2E Spec Rewrite
-
-**Goal**: Replace the stale `telegram-flow.spec.ts` with a new spec that tests the current `channels_*` RPC surface and the full Telegram bot setup + message round-trip.
-
-**Files to create/modify**:
-
-| Action | Path |
-|--------|------|
-| DELETE | `app/test/e2e/specs/telegram-flow.spec.ts` (1019 lines, 100% stale) |
-| CREATE | `app/test/e2e/specs/telegram-channel-flow.spec.ts` |
-| MODIFY | `app/test/e2e/helpers/chat-harness.ts` — add `injectTelegramUpdate()` and `getTelegramSentMessages()` helpers that call mock admin endpoints |
-| MODIFY | `app/scripts/e2e-run-spec.sh` — ensure `OPENHUMAN_TELEGRAM_API_BASE` is set for telegram specs (may overlap with WS-B) |
-
-**Test scenarios** (numbered):
-
-1. **Channel list includes telegram**: `callOpenhumanRpc('openhuman.channels_list')` returns a channel with `id: "telegram"` and `authModes` including `bot_token`.
-
-2. **Channel describe returns telegram definition**: `callOpenhumanRpc('openhuman.channels_describe', { channel: 'telegram' })` returns capabilities, auth modes, and field schemas.
-
-3. **Bot token connect — happy path**: `callOpenhumanRpc('openhuman.channels_connect', { channel: 'telegram', authMode: 'bot_token', credentials: { botToken: '<token>' } })` succeeds. Mock `getMe` returns bot info. `channels_status` shows telegram as connected.
-
-4. **Bot token connect — invalid token**: Mock `getMe` returns 401 (`telegramGetMeFails=1`). Connect RPC returns error.
-
-5. **Inbound message round-trip**: After connecting, inject a Telegram update via `/__admin/telegram/inject-update` with a user message. Configure `llmForcedResponses` with a canned reply. Wait for the bot's reply to appear in `/__admin/telegram/sent`. Assert the reply content matches.
-
-6. **Inbound message from unauthorized user**: Inject an update from a user not in the allowlist. Assert the bot sends the "operator approval required" message (visible in `/__admin/telegram/sent`).
-
-7. **Group message with mention-only**: Connect with `mentionOnly: true`. Inject a group message without bot mention — no reply. Inject a group message with `@e2e_test_bot` — reply appears.
-
-8. **Channel disconnect**: `callOpenhumanRpc('openhuman.channels_disconnect', { channel: 'telegram', authMode: 'bot_token' })` succeeds. `channels_status` shows telegram as disconnected.
-
-9. **Reconnect after disconnect**: Connect again with a different token. Status shows connected.
-
-10. **Remote command /status**: Inject a message with text `/status`. Assert the bot sends a status response (contains "Thread:" and "Provider:").
-
-**Acceptance criteria**:
-- All 10 scenarios pass against the mock backend
-- No references to the old skill system
-- Spec uses `resetApp()` + `callOpenhumanRpc()` pattern from existing specs
-- Spec runs via `pnpm debug e2e test/e2e/specs/telegram-channel-flow.spec.ts telegram`
-
-**Dependencies**: WS-A (mock Telegram routes), WS-B (API base URL override). Must wait for both.
-
----
-
-### WS-D: Prompt-Flow Harness E2E Specs
-
-**Goal**: Add a battery of E2E specs that drive the chat harness through prompts exercising tool calls (composio, search, cron) and cross-channel bridges.
-
-**Files to create/modify**:
-
-| Action | Path |
-|--------|------|
-| CREATE | `app/test/e2e/specs/harness-composio-tool-flow.spec.ts` |
-| CREATE | `app/test/e2e/specs/harness-cron-prompt-flow.spec.ts` |
-| CREATE | `app/test/e2e/specs/harness-search-tool-flow.spec.ts` |
-| CREATE | `app/test/e2e/specs/harness-channel-bridge-flow.spec.ts` |
-| MODIFY | `app/test/e2e/helpers/chat-harness.ts` — add `waitForToolCallInMockLog(toolName)`, `waitForAssistantReplyContaining(text)` helpers |
-
-**Spec 1: `harness-composio-tool-flow.spec.ts`**
-
-Scenarios:
-1. **Gmail composio tool call**: Configure `llmKeywordRules` so "check my email" triggers a `GMAIL_GET_MAIL` tool call. Configure `composioExecuteResponse_GMAIL_GET_MAIL` with a canned inbox result. Send "check my email" in chat. Assert: (a) mock LLM received the tool call, (b) composio execute endpoint was called, (c) final assistant reply references the email content.
-2. **GitHub composio tool call**: "list my repos" triggers `GITHUB_LIST_REPOS`. Assert tool-use round-trip.
-3. **Composio action failure**: Set `composioExecuteFails=400`. Send prompt. Assert the assistant reply acknowledges the error gracefully.
-4. **Linear composio tool call**: "create a linear issue" triggers `LINEAR_CREATE_ISSUE`. Assert creation result in reply.
-
-**Spec 2: `harness-cron-prompt-flow.spec.ts`**
-
-Scenarios:
-1. **Create cron via natural language**: Configure LLM keyword rules so "remind me every morning at 9am" triggers a `cron_create` tool call with `{ schedule: "0 9 * * *", prompt: "morning reminder" }`. Assert: cron_create RPC was called, reply confirms creation.
-2. **List cron jobs after creation**: Send "what are my scheduled tasks". LLM keyword rule returns content listing the jobs (no tool call needed, just checks the harness can relay cron state). Verify via `openhuman.cron_list` oracle RPC.
-3. **Edit cron schedule**: "change my morning reminder to 8am" triggers `cron_update` tool call. Assert schedule changed via oracle RPC.
-
-**Spec 3: `harness-search-tool-flow.spec.ts`**
-
-Scenarios:
-1. **Memory search tool call**: "what did we discuss about project X" triggers `memory_search` tool call. Mock returns canned memory results. Assert reply cites the memory.
-2. **Web search tool call**: "search the web for Rust async patterns" triggers `web_search` tool call. Mock returns canned search results. Assert reply includes search results.
-3. **File read tool call**: "read the README" triggers `file_read` tool call. Assert reply includes file content summary.
-
-**Spec 4: `harness-channel-bridge-flow.spec.ts`**
-
-Scenarios:
-1. **Telegram message triggers cron creation**: Inject a Telegram update "set up a daily standup reminder at 9am". LLM keyword rules return a `cron_create` tool call. Assert: (a) cron created via oracle RPC, (b) Telegram reply confirms creation.
-2. **Telegram message triggers composio action**: Inject "check my gmail inbox" via Telegram. LLM triggers `GMAIL_GET_MAIL`. Assert: (a) composio execute called, (b) Telegram reply contains email summary.
-3. **Chat prompt references channel state**: In the web chat, ask "what messages came in on Telegram today". LLM returns a canned summary. This is a lightweight check that the harness can receive prompts referencing channels.
-
-**Acceptance criteria**:
-- All specs pass against the mock backend with zero real LLM calls
-- Each spec uses `resetApp()` for isolation
-- Tool call round-trips are verified via both mock request logs and UI/RPC assertions
-- Specs are independently runnable via `pnpm debug e2e`
-
-**Dependencies**:
-- `harness-composio-tool-flow.spec.ts`: Needs existing mock composio routes (already in `integrations.mjs`) + LLM keyword rules (already in `llm.mjs`). **No blocker.**
-- `harness-cron-prompt-flow.spec.ts`: Needs LLM keyword rules + cron RPC surface (already exists). **No blocker.**
-- `harness-search-tool-flow.spec.ts`: Needs LLM keyword rules. **No blocker.**
-- `harness-channel-bridge-flow.spec.ts`: Depends on **WS-A** (mock Telegram routes) and **WS-B** (API base override). Scenarios 1-2 must wait. Scenario 3 can ship independently.
-
----
-
-## 4. Recommended Subagent Fan-Out
-
-### WS-A -> CodeCrusher agent
-
-**Briefing**: You are implementing the mock backend Telegram Bot API layer. Create `scripts/mock-api/routes/telegram.mjs` with a `handleTelegram(ctx)` function that serves Telegram Bot API endpoints (`/bot<token>/getMe`, `/bot<token>/getUpdates`, `/bot<token>/sendMessage`, `/bot<token>/sendChatAction`, `/bot<token>/deleteWebhook`, `/bot<token>/setMessageReaction`, and media send endpoints). Add state arrays `mockTelegramUpdates` and `mockTelegramSentMessages` to `scripts/mock-api/state.mjs` with standard getter/setter/reset exports. Add admin endpoints in `scripts/mock-api/admin.mjs`: `POST /__admin/telegram/inject-update`, `GET /__admin/telegram/sent`, `POST /__admin/telegram/reset`. Wire into `scripts/mock-api/server.mjs`. Follow the exact patterns used by existing route handlers (see `routes/integrations.mjs`, `routes/cron.mjs`). Use `behavior()` for dynamic behavior keys (`telegramBotUsername`, `telegramGetMeFails`, `telegramSendFails`, `telegramPollDelayMs`). Token is extracted from the URL path (`/bot<token>/...`). Write unit tests in `scripts/mock-api/routes/__tests__/telegram.test.mjs` following the pattern in existing test files in that directory.
-
-### WS-B -> Dev agent (Rust)
-
-**Briefing**: You are adding a `OPENHUMAN_TELEGRAM_API_BASE` environment variable override to the Telegram channel provider. In `src/openhuman/channels/providers/telegram/channel_types.rs`, add an `api_base: String` field to `TelegramChannel`. In `channel_core.rs`, read `std::env::var("OPENHUMAN_TELEGRAM_API_BASE")` in the constructor (default `"https://api.telegram.org"`, strip trailing slash), store in `self.api_base`. Change `api_url()` from `format!("https://api.telegram.org/bot{}/{method}", self.bot_token)` to `format!("{}/bot{}/{method}", self.api_base, self.bot_token)`. Add a unit test in `channel_tests.rs` that sets the env var (use a `serial_test` guard or `temp_env` crate if available, otherwise test with a direct constructor that takes the base URL). Update `.env.example` with a comment. Update `app/scripts/e2e-run-spec.sh` to export `OPENHUMAN_TELEGRAM_API_BASE=http://127.0.0.1:${E2E_MOCK_PORT:-18473}` alongside the other E2E env vars. Run `cargo check` and `cargo test` to verify.
-
-### WS-C -> Test agent (E2E)
-
-**Briefing**: You are rewriting the Telegram E2E spec. Delete `app/test/e2e/specs/telegram-flow.spec.ts` entirely (it is 100% stale, references removed skill system). Create `app/test/e2e/specs/telegram-channel-flow.spec.ts`. Follow the exact patterns from `chat-harness-send-stream.spec.ts` and `composio-triggers-flow.spec.ts`: use `resetApp()`, `callOpenhumanRpc()`, `startMockServer()`/`stopMockServer()`, `setMockBehavior()`. The spec tests the `openhuman.channels_*` RPC surface against the mock backend. Add helpers to `app/test/e2e/helpers/chat-harness.ts` for `injectTelegramUpdate(update)` (POST to `/__admin/telegram/inject-update`) and `getTelegramSentMessages()` (GET `/__admin/telegram/sent`). Test scenarios: channels_list includes telegram, channels_describe returns definition, connect with bot_token (happy + error), inbound message round-trip, unauthorized user rejection, mention-only group filtering, disconnect, reconnect, remote /status command. Each test uses `callOpenhumanRpc` for setup and oracle checks, mock admin endpoints for Telegram simulation. Set `OPENHUMAN_TELEGRAM_API_BASE` and `telegramBotUsername` behavior key in `before()`. This spec depends on WS-A and WS-B being merged first.
-
-### WS-D -> Test agent (E2E, prompt-flow)
-
-**Briefing**: You are creating four new E2E specs that exercise the agent harness through prompt-driven tool-call flows. Follow the pattern from `chat-harness-send-stream.spec.ts`: `resetApp()`, navigate to `/chat`, type into composer, send, wait for reply. Use `llmKeywordRules` behavior key to configure deterministic tool-call triggers (see `scripts/mock-api/routes/llm.mjs` lines 430-456 for the keyword rule format). Use `llmForcedResponses` for multi-turn sequences where the first response is a tool call and the second is the final answer. Specs: (1) `harness-composio-tool-flow.spec.ts` — "check my email" triggers GMAIL_GET_MAIL tool, composio execute returns canned result, assistant relays it. (2) `harness-cron-prompt-flow.spec.ts` — "remind me every morning" triggers cron_create tool call, verify cron created via oracle RPC. (3) `harness-search-tool-flow.spec.ts` — "what did we discuss about X" triggers memory_search tool call. (4) `harness-channel-bridge-flow.spec.ts` — Telegram inbound triggers tool calls (depends on WS-A/B). For specs 1-3, no dependency on other workstreams. For spec 4, wait for WS-A+B. Add helpers to `chat-harness.ts`: `waitForToolCallInMockLog(toolName, timeoutMs)` polls `getRequestLog()` for a POST to the composio execute or LLM endpoint containing the tool name.
-
----
-
-## 5. Blocking Unknowns
-
-1. **Telegram API base URL override**: Does any config-loading code cache the URL before the env var is set? Need to verify `TelegramChannel::new()` is called after env is loaded. Likely fine since `start_channels()` runs after config load, but WS-B agent should verify.
-
-2. **Channel connect via RPC in E2E**: Does `openhuman.channels_connect` with `authMode: "bot_token"` actually start the long-polling loop against the mock? If so, `getUpdates` requests will immediately start hitting the mock server. The mock must handle rapid polling gracefully (return empty `[]` by default). WS-A agent should ensure `getUpdates` returns `{ ok: true, result: [] }` when the queue is empty without blocking.
-
-3. **In-process core + mock Telegram**: The E2E app runs the core in-process. The core's Telegram provider will poll `http://127.0.0.1:18473/bot<token>/getUpdates`. The mock server must be ready before the channel connects. Spec `before()` must call `startMockServer()` before `channels_connect`.
-
-4. **Tool execution in E2E harness**: When the mock LLM returns a tool call, does the in-process core actually execute the tool (e.g., call composio execute endpoint, call cron_create)? This depends on the tool being registered in the agent's tool registry. If tools are not available in E2E mode, WS-D specs may need to assert at the LLM mock level only (verifying the tool call was attempted, not executed). The WS-D agent should test this empirically and adapt.
-
----
-
-## 6. Parallelism Summary
-
-```
-WS-A (mock backend) ──────────────────────────┐
- ├──► WS-C (telegram E2E spec)
-WS-B (Rust API base override) ─────────────────┘
- ├──► WS-D spec 4 (channel bridge)
-WS-D specs 1-3 (composio/cron/search prompts) ──── independent, no blockers
-```
-
-WS-A and WS-B can run fully in parallel.
-WS-D specs 1-3 can run in parallel with WS-A and WS-B.
-WS-C and WS-D spec 4 must wait for both WS-A and WS-B.
diff --git a/.claude/skills-system-troubleshooting.md b/.claude/skills-system-troubleshooting.md
deleted file mode 100644
index 12a66b73f6..0000000000
--- a/.claude/skills-system-troubleshooting.md
+++ /dev/null
@@ -1,160 +0,0 @@
-# Skills System Troubleshooting Guide
-
-## Overview
-
-The Skills System is a Python-based plugin architecture that allows AI agents to have domain-specific knowledge, tools, and automated behaviors. Skills run as isolated Python subprocesses and communicate with the main Tauri application via JSON-RPC.
-
-## Common Issue: "Setup Failed" with Exit Code 1
-
-### Symptoms
-
-- Skills modal shows "Setup Failed" with "Skill process exited with code: 1"
-- Console shows `ModuleNotFoundError: No module named 'pydantic'`
-- Error paths like `/Users/cyrus/openhuman/skills/skills/telegram/`
-- Python import failures and subprocess stderr messages
-
-### Root Cause Analysis
-
-**Primary Issue: Missing Skills Git Submodule**
-The main cause is that the `skills` Git submodule is not initialized. The system expects skills to be available in the `skills/skills/` directory structure but finds an empty directory.
-
-**Secondary Issues:**
-
-1. **Missing Python Virtual Environment**: No `.venv` directory in the skills folder
-2. **Missing Python Dependencies**: Core packages like `pydantic`, `telethon`, `mcp` not installed
-3. **Incorrect Python Paths**: PYTHONPATH configuration issues
-
-### Skills System Architecture
-
-```
-skills/ # Git submodule root
-├── .venv/ # Python virtual environment
-├── requirements.txt # Shared dependencies
-├── skills/ # Individual skill packages
-│ ├── telegram/ # Telegram skill
-│ │ ├── skill.py # Main skill logic
-│ │ ├── manifest.json # Skill metadata
-│ │ ├── requirements.txt # Skill-specific dependencies
-│ │ └── ...
-│ ├── browser/ # Browser automation skill
-│ ├── calendar/ # Calendar integration skill
-│ └── ... # Other skills
-└── ...
-```
-
-### Solution Steps
-
-#### 1. Initialize Git Submodule
-
-```bash
-git submodule init
-git submodule update
-```
-
-This downloads the skills repository from `https://github.com/openhumanxyz/skills`.
-
-#### 2. Create Python Virtual Environment
-
-```bash
-cd skills
-python3 -m venv .venv
-.venv/bin/pip install --upgrade pip
-```
-
-#### 3. Install Dependencies
-
-```bash
-.venv/bin/pip install -r requirements.txt
-```
-
-This installs:
-
-- **Core Dependencies**: `mcp>=1.0.0`, `pydantic>=2.0`, `aiosqlite>=0.20.0`
-- **Skill-Specific Dependencies**: Each skill's requirements.txt (telegram, browser, etc.)
-
-#### 4. Verify Installation
-
-```bash
-# Test core imports
-.venv/bin/python -c "import pydantic, mcp; print('✅ Core dependencies OK')"
-
-# Test skill import
-.venv/bin/python -c "import skills.telegram; print('✅ Telegram skill OK')"
-```
-
-### How Skills System Works
-
-#### Development vs Production Paths
-
-- **Development**: Skills in git submodule at `./skills/skills/`
-- **Production**: Skills in `~/.openhuman/skills/`
-- **Configuration**: `src/lib/skills/paths.ts` handles path resolution
-
-#### Skill Execution Process
-
-1. **Discovery**: `SkillProvider` scans for skill manifests
-2. **Registration**: Skills registered in Redux store
-3. **Startup**: Python subprocess spawned with proper environment
-4. **Communication**: JSON-RPC transport over stdin/stdout
-5. **Setup**: Interactive setup flow if required
-
-#### Environment Variables
-
-The system automatically configures:
-
-- **PYTHONPATH**: Includes skills directory and virtual environment
-- **Telegram API**: `TELEGRAM_API_ID`, `TELEGRAM_API_HASH`
-- **Working Directory**: Skills submodule root
-
-### Verification Commands
-
-```bash
-# Check submodule status
-git submodule status
-
-# Verify skills directory structure
-ls -la skills/skills/telegram/
-
-# Check virtual environment
-ls -la skills/.venv/
-
-# Test Python environment
-cd skills && .venv/bin/python -c "import sys; print('\\n'.join(sys.path))"
-```
-
-### Prevention
-
-To prevent this issue in fresh checkouts:
-
-1. **Always initialize submodules**:
-
- ```bash
- git clone --recurse-submodules <repo-url>
- # or after clone:
- git submodule update --init --recursive
- ```
-
-2. **Setup script**: Consider adding to `package.json`:
- ```json
- {
- "scripts": {
- "setup": "git submodule update --init && cd skills && python3 -m venv .venv && .venv/bin/pip install -r requirements.txt"
- }
- }
- ```
-
-### Related Files
-
-- **Frontend**: `src/lib/skills/` - Skills management system
-- **Backend**: `src-tauri/src/commands/skills.rs` - Rust skill commands
-- **Configuration**: `src/utils/config.ts` - Environment variables
-- **Providers**: `src/providers/SkillProvider.tsx` - Skills lifecycle
-
-### Expected Behavior After Fix
-
-1. Skills modal should show "Connect Telegram" instead of error
-2. No more Python import errors in console
-3. Skill setup process should work correctly
-4. Background GitHub sync should function properly
-
-This fix resolves the fundamental infrastructure issue preventing skills from loading and running properly.
diff --git a/.codex/commands/ship-and-babysit.md b/.codex/commands/ship-and-babysit.md
deleted file mode 100644
index f35b9c4cac..0000000000
--- a/.codex/commands/ship-and-babysit.md
+++ /dev/null
@@ -1,35 +0,0 @@
----
-name: ship-and-babysit
-description: Commit local changes, push to the user's fork, open or reuse a PR against tinyhumansai/openhuman:main, then babysit CI and CodeRabbit feedback until the PR is green and clean.
----
-
-# Ship And Babysit
-
-Canonical long-form workflow lives at:
-
-- [`.codex/skills/ship-and-babysit/SKILL.md`](../skills/ship-and-babysit/SKILL.md)
-- [`.agents/agents/ship-and-babysit.md`](../../.agents/agents/ship-and-babysit.md)
-
-Use this command when you want an end-to-end ship flow for `tinyhumansai/openhuman`:
-
-1. Commit relevant local changes with a conventional commit.
-2. Push the current non-`main` branch to `origin` (the user's fork).
-3. Open or reuse a PR against `tinyhumansai/openhuman:main`.
-4. Poll CI and CodeRabbit feedback.
-5. Fix actionable issues, commit, and push follow-ups.
-6. Stop only when the PR is green and clean.
-
-Feature testing rule:
-
-- Feature work must ship with matching E2E coverage.
-- Core, domain, persistence, CLI, and JSON-RPC features need mocked Rust E2E coverage in `tests/*_e2e.rs`, commonly `tests/json_rpc_e2e.rs`.
-- Frontend user flows need mocked Playwright E2E coverage in `app/test/e2e/specs/*.spec.ts`.
-- Mock backend calls all the way through with the repo mock backend; do not hit real backend services or third-party APIs in E2E.
-
-Guardrails:
-
-- Never push to `upstream`.
-- Never push directly to `main`.
-- Never resolve a review thread without either fixing it or replying with a reasoned dismissal.
-- Do not merge the PR.
-- Fill `.github/PULL_REQUEST_TEMPLATE.md` exactly. Every checklist item must be checked; use `- [x] N/A: <reason>` when an item does not apply.
diff --git a/.codex/skills/ship-and-babysit/SKILL.md b/.codex/skills/ship-and-babysit/SKILL.md
deleted file mode 100644
index fd74abd97a..0000000000
--- a/.codex/skills/ship-and-babysit/SKILL.md
+++ /dev/null
@@ -1,174 +0,0 @@
----
-name: ship-and-babysit
-description: "End-to-end PR shipping workflow for tinyhumansai/openhuman: commit local changes, push to the user's fork, open or reuse a PR against main, then babysit CI and CodeRabbit feedback until the PR is green and clean. Use when the user asks to ship, open a PR, monitor CI, address review comments, or 'babysit' a branch."
----
-
-# Ship and Babysit
-
-Use this skill for `tinyhumansai/openhuman` when the user wants a branch shipped end to end:
-
-- commit the local changes
-- push the branch to the user's fork
-- open or reuse a PR against `tinyhumansai/openhuman:main`
-- proactively run likely merge-gate validation and start fixing issues immediately
-- monitor CI and review feedback in a polling loop without waiting idly for every check to finish
-- address actionable review comments and push follow-up fixes
-- stop only when the PR is green and clean
-
-## Preconditions
-
-- Work from the repository root.
-- Follow repo rules from `AGENTS.md`, including validation and PR checklist requirements.
-- Assume `origin` is the user's writable fork and `upstream` points to `tinyhumansai/openhuman`.
-- Resolve the fork owner once near the start and reuse it:
- - `FORK_OWNER=$(git remote get-url origin | sed -E 's#.*[:/]([^/]+)/[^/]+(\.git)?$#\1#')`
-- If `origin` resolves to `tinyhumansai`, stop and ask the user to add a fork remote. Never push branches to upstream.
-- If work starts on local `main`, create a new descriptive branch before committing so the changes leave `main` immediately.
-- Never push directly to `main`.
-- Never push to `upstream`.
-- Never amend or rewrite commits that are already pushed unless the user explicitly asks for it.
-- Never bypass hooks for breakage introduced by your own changes.
-- Default to autonomous execution. Do not stop to ask the user process questions when a reasonable safe default exists.
-- Only ask the user a question when the workflow is genuinely blocked by missing access, missing credentials, or an irreversible choice that cannot be inferred from repo context.
-
-## Workflow
-
-### Phase 1: Inspect and Commit
-
-1. Inspect the branch before changing anything. Prefer parallel reads:
- - `git status --short`
- - `git diff --stat`
- - `git diff --cached --stat`
- - `git log --oneline --decorate -n 12`
-2. Determine the current branch:
- - `git rev-parse --abbrev-ref HEAD`
-3. Confirm the branch normally follows `feat/`, `fix/`, `refactor/`, `chore/`, `docs/`, or `test/`.
- - If the current branch is `main`, create a new descriptive branch immediately and continue there.
- - If the name does not follow convention and it is already a non-`main` branch, keep using it unless it is still local and trivially safe to rename without disrupting a pushed branch.
-4. If there are uncommitted changes, carry them onto the new branch before doing anything else so local `main` stays free of agent-authored commits.
-5. If there are uncommitted changes, run the smallest meaningful local validation for the touched area before committing.
-6. Stage only relevant files and create a focused conventional commit message.
-7. If there are no local changes, continue without creating a commit.
-
-### Feature E2E Requirement
-
-Before shipping feature work, verify that the PR includes end-to-end coverage for the new behavior.
-
-- Core, domain, persistence, CLI, or JSON-RPC feature changes need Rust E2E coverage in `tests/*_e2e.rs`, usually targeted through `pnpm test:rust:e2e -- --suite <suite>` or `bash scripts/test-rust-e2e.sh --suite <suite>`.
-- New or changed JSON-RPC surfaces should normally extend `tests/json_rpc_e2e.rs` unless a more focused `*_e2e.rs` suite owns the domain.
-- Frontend user flows need Playwright E2E coverage in `app/test/e2e/specs/*.spec.ts`; build/run targeted web E2E with `pnpm --filter openhuman-app test:e2e:web:build` and `bash app/scripts/e2e-web-session.sh test/e2e/specs/<spec>.spec.ts`.
-- Mock backend calls all the way through. Use the repo mock backend (`scripts/mock-api-server.mjs`, `scripts/mock-api/*`, `app/test/e2e/mock-server.ts`) and admin behavior endpoints; do not hit real backend services or third-party APIs.
-- Unit tests are still expected for narrow logic, but they do not replace E2E coverage for newly built features.
-
-### Phase 2: Push
-
-1. Push the current branch to `origin`.
-2. If upstream tracking is missing, push with `-u`.
-3. If a pre-push hook fails on your own changes, fix the issue and push again.
-4. If a pre-push hook fails only because of unrelated pre-existing breakage, push with `--no-verify` and record that explicitly in the PR body.
-5. After every later fix commit in the babysit loop, push again. Do not stop at a local commit.
-
-### Phase 3: Open or Reuse the PR
-
-1. Verify remotes with `git remote -v` and confirm `upstream` points at `tinyhumansai/openhuman`.
-2. Check for an existing PR for the exact branch:
- - `gh pr list --repo tinyhumansai/openhuman --head <fork-owner>:<branch> --state open --json number,url`
-3. If a PR exists, capture its number and URL and reuse it.
-4. If no PR exists:
- - inspect `git log main..HEAD` and `git diff main...HEAD`
- - fill `.github/PULL_REQUEST_TEMPLATE.md` exactly
- - mark every checklist item as checked; for non-applicable items use `- [x] N/A: <reason>` so `pnpm pr:checklist` accepts it
- - create the PR against `tinyhumansai/openhuman:main` with `--head <fork-owner>:<branch>`
-5. Print the PR URL to the user.
-6. Immediately after opening or reusing the PR, start proactive validation based on the touched area instead of waiting for remote CI to finish:
- - run the smallest set of likely merge-gate commands that cover the changed code
- - prioritize fast failure detectors first, such as format, typecheck, lint, targeted tests, and cargo checks relevant to touched files
- - fix locally discovered failures right away, then commit and push again before the next CI poll
-
-### Phase 4: Babysit Loop
-
-Run an explicit poll loop until the PR is green and clean. Do not treat this as a one-shot status check, and do not sit idle waiting for all checks to complete before acting.
-
-- Poll about every 5 minutes.
-- Stay in the loop for up to 12 ticks, about 60 minutes total.
-- If the environment does not support durable wakeups, remain in-session and use repeated polling with `sleep 270`.
-- On each tick, post a short progress update to the user.
-- Between ticks, prefer useful work over passive waiting:
- - inspect completed failures as soon as they appear
- - inspect review comments and unresolved threads immediately
- - run likely local validations on changed areas while remote checks are still pending
- - push fixes as soon as they are ready instead of batching them behind the full CI timeline
-
-Each tick:
-
-1. Fetch CI status:
- - `gh pr checks <pr-number> --repo tinyhumansai/openhuman --json name,state,link,description`
-2. Treat `PENDING` as still in progress. Do not claim success while checks are still running.
-3. If any completed check is `FAILURE` or `CANCELLED`:
- - if the `link` is a GitHub Actions run URL, extract the run id and inspect failing logs with `gh run view <id> --log-failed --repo tinyhumansai/openhuman`
- - otherwise work from the check name, state, and description
- - make the smallest correct fix
- - rerun targeted validation
- - commit
- - push
-4. If checks are still mostly `PENDING`, do not wait for the whole matrix to finish before taking action:
- - inspect the changed files and recent commit diff
- - run the most relevant local merge-gate commands proactively
- - fix any locally reproduced failure immediately
- - commit and push as soon as the fix is validated
-5. Fetch PR review comments:
- - `gh api repos/tinyhumansai/openhuman/pulls/<pr-number>/comments --paginate`
-6. Fetch issue-level PR comments:
- - `gh api repos/tinyhumansai/openhuman/issues/<pr-number>/comments --paginate`
-7. Inspect review threads via GraphQL, not just flat comments, so unresolved discussions do not slip through:
- - query `reviewThreads` with pagination until `hasNextPage` is false
-8. Specifically inspect bot feedback from `coderabbitai` and `coderabbitai[bot]`, but also check for human actionable review comments.
-9. For each actionable review comment or unresolved review thread:
- - read the referenced file and line
- - apply the smallest correct fix
- - rerun targeted validation
- - commit
- - push
-10. For incorrect, stale, or out-of-scope review feedback, reply in the existing review thread with concrete reasoning. Do not open a new unrelated review, and resolve or dismiss only when the reasoning is explicit and the platform supports it.
-11. After addressing a review thread, resolve it through the GitHub review-thread API when appropriate.
-12. Track whether new issue-level CodeRabbit comments appeared since the previous tick so the loop does not exit while fresh bot feedback is waiting.
-13. Exit the loop only when all required checks are `SUCCESS`, no unresolved actionable review threads remain, no new actionable CodeRabbit issue comments remain, and the latest fixes are committed and pushed to the PR branch.
-
-If the loop reaches the hard cap, stop and report the PR URL, current CI snapshot, and any unresolved review threads or comments.
-
-## Useful Checks
-
-- `pnpm typecheck`
-- `pnpm lint`
-- `pnpm format:check`
-- `pnpm test`
-- `cargo check --manifest-path Cargo.toml`
-- `cargo check --manifest-path app/src-tauri/Cargo.toml`
-- `pnpm test:rust`
-- `pnpm test:rust:e2e -- --suite <suite>`
-- `pnpm --filter openhuman-app test:e2e:web:build`
-- `bash app/scripts/e2e-web-session.sh test/e2e/specs/<spec>.spec.ts`
-
-Prefer targeted test commands when the touched area is narrow, but do not claim validation passed if a command was not run.
-
-## Notes
-
-- Do not merge the PR unless the user explicitly asks.
-- Reuse an existing PR when one already exists for the branch.
-- Always push follow-up commits so the PR actually updates after fixes.
-- If invoked from `main`, branch first, then ship. Do not make the user clean up agent commits from `main`.
-- Checking `gh pr checks --watch` once is not sufficient babysitting. The skill should actively re-poll CI and review surfaces until the exit condition is met.
-- The skill should not ask the user for confirmation about routine workflow choices such as branch naming, whether to start fixing CI, or whether to act on obvious actionable failures.
-- The skill should assume the user wants active babysitting: inspect, fix, commit, and push continuously until blocked or green.
-- Review handling must include:
- - PR review comments
- - issue-level PR comments
- - unresolved review threads
-- If CI or review surfaces reveal unrelated pre-existing breakage, call it out clearly and avoid masking it as fixed.
-- If GitHub auth, remotes, or branch protection do not allow the workflow, report the exact blocker and stop at the first blocked step.
-
-## Invocation Hints
-
-- `Use $ship-and-babysit for this branch`
-- `Ship this and babysit the PR`
-- `Open the PR and stay on CI until it is green`
diff --git a/.codex/skills/ship-and-babysit/agents/openai.yaml b/.codex/skills/ship-and-babysit/agents/openai.yaml
deleted file mode 100644
index dfe50ee00a..0000000000
--- a/.codex/skills/ship-and-babysit/agents/openai.yaml
+++ /dev/null
@@ -1,4 +0,0 @@
-interface:
- display_name: "Ship and Babysit"
- short_description: "Ship PRs and babysit CI and reviews"
- default_prompt: "Use $ship-and-babysit to commit, push, open or reuse a PR, and babysit CI plus CodeRabbit until it is green and clean."
diff --git a/.gitignore b/.gitignore
index c3cb63cbde..c09a2ac038 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,7 +2,6 @@ worktrees/*
!worktrees/.gitkeep
# Workflow docs (local only)
-workflow
create_issue
review_pr
sentry_bugs
@@ -42,9 +41,6 @@ dist-web
# sccache local compiler cache (used by CI and act)
.sccache/
-# E2E test artifacts (screenshots, logs, traces — never checked in)
-app/test/e2e/artifacts/
-
my_docs
# Local prompt dumps written by `scripts/debug-agent-prompts.sh`.
@@ -89,9 +85,6 @@ coverage/
app/public/generated/remotion/
app/test/e2e/artifacts/
-# Local pnpm store (created when network-restricted hosts cache the store inside the repo)
-.pnpm-store/
-
tauri.key
tauri.key.pub
/target/
@@ -115,10 +108,14 @@ app/test/e2e/.cache/
test-map.md
.test-gap-analysis.md
-# AI assistant progress tracking
+# Local AI assistant state and scratch files
.kimi/
.specify/
.claude/skills/
+.claude/memory.md
+.claude/projects/
+.claude/scratch/
+/SCRATCH/
.codex-tmp
*.enc
diff --git a/5560-remaining.md b/5560-remaining.md
deleted file mode 100644
index 496d0f8e85..0000000000
--- a/5560-remaining.md
+++ /dev/null
@@ -1,283 +0,0 @@
-# openhuman#5560 — what is left, and how to finish it
-
-**Handoff document.** Written 2026-08-26 for someone picking this up with no
-prior context. Everything here was verified against the tree rather than
-inherited from the issue text, because a lot of the issue text and several
-in-code comments turned out to be stale — that is the single most important
-thing to know before starting.
-
----
-
-## 1. What the issue asks for
-
-Two acceptance criteria:
-
-1. **No direct engine calls** — `grep -r 'tinymemory_core::' src/` returns nothing
- outside `modules/memory.rs` and `memory/binding.rs`.
-2. **Crate out of the build** — `cargo tree -e normal --no-default-features
- --features "$(bash scripts/ci/product-features.sh)"` no longer lists
- `tinymemory-core`.
-
-Criterion 1 is nearly done. **Criterion 2 is not reachable yet**, and section 4
-explains exactly what blocks it. That is the headline finding of this work.
-
-**Which count decides criterion 1.** The literal `grep` above and the 37
-references section 4 reports are not the same number, and only one of them is
-the gate. The `grep` is a raw hit count: it includes doc comments that merely
-name the crate, `#[cfg(test)]` and dev-only references, and the retained
-`pub use tinymemory_core::…` re-export shims that exist precisely so call sites
-elsewhere do not name the engine. **Criterion 1 is met when no *production*
-call site outside `modules/memory.rs` and `memory/binding.rs` reaches the engine
-directly** — shims and test-only references do not count against it, because
-neither is a caller. Section 4's table is the authoritative classification;
-`memory/direct_engine_refs_tests.rs` is the ratchet that keeps the production
-number honest. Read the table, not the raw `grep`.
-
----
-
-## 2. State of play
-
-### Branches and PRs
-
-| What | Where | State |
-| --- | --- | --- |
-| Host work, phase 1 | openhuman PR **#5725**, branch `feat/5560-queue-and-recall-through-the-contract` | **merged** |
-| Host work, phase 2 | branch `feat/5560-close-the-last-six` (was stacked on #5725) | **this work** |
-| `BootstrapConnection` | tinymemory **#105** | merged, released **v1.11.0** |
-| `IsToolkitSyncable` | tinymemory **#106** | merged, released **v1.12.0** |
-
-The host is pinned to **tinymemory v1.12.0** across **six** concrete locations,
-in five logical groups: the `vendor/tinymemory` gitlink, `modules/registry.rs`
-(release tag + per-platform digests), `modules/memory.rs` (the assumed
-capability set), and the three CI workflow files that install the module for
-tests (`ci-lite.yml`, `ci-full.yml`, `e2e-reusable.yml`) — which are one group
-but three files. Bump all six; missing a workflow leaves CI installing a
-different module than the host pins, and that mismatch only shows up as a
-runtime `Unsupported`.
-
-### What phase 2 did
-
-Six production files that named `tinymemory_core` directly now go through the
-contract. Each was verified individually; none of them depends on the shim work
-in section 4.
-
-| File | Was | Now |
-| --- | --- | --- |
-| `memory/read_rpc/admin.rs` | `tree_source::get_or_create_source_tree` | driver `flush_source_tree` |
-| `memory/sync/sync_status/rpc.rs` | `tinycortex::memory_config_from` | driver `sync_statuses` |
-| `config/migration_helpers/core.rs` | `store::create_memory_for_migration` | `DriverMemory::for_config` |
-| `memory/tree/tree/rpc.rs` | `ingest_pipeline::ingest_email` | `email_items` + driver `ingest_email` |
-| `agent/harness/session/builder/factory.rs` | `create_session_memory_with_local_ai` | `DriverMemory::for_subtree` |
-| `memory/sync/composio/providers/context_ext.rs` | `ProviderContext` extension trait | **file deleted**; `bus.rs` on `BootstrapConnection` + `IsToolkitSyncable` |
-
-Their allowlist entries were **removed** from
-`memory/direct_engine_refs_tests.rs` rather than re-worded, so the ratchet count
-is real.
-
----
-
-## 3. Things that are stale or wrong — read this before trusting any comment
-
-This work repeatedly found documentation that no longer matched the code. Assume
-nothing; check.
-
-- **The ratchet's reasons.** Several `ALLOWED` entries cited symbols that do not
- exist in the tree any more (`store::fts5`, `store::segments`,
- `approx_token_count`). Those reasons are what routed a whole phase of work
- upstream that did not need to go there.
-- **The ratchet does not resolve `#[cfg(test)]`.** It scans files on disk and
- skips comment lines only. Of the sixteen entries once marked
- `NeedsWiderSeam`, **eight were test-only** (mostly via a gated `mod`
- declaration in a *parent* module) and **two were a dev binary**
- (`library-profile`, `required-features = ["rss-bench"]`). Only six were real.
-- **`migration_helpers/core.rs` claimed an upstream ask was needed** for a
- capture-budget-exempt store. The budget is enforced *host-side* in
- `memory/guard/policy.rs`, and `DriverMemory` wraps `binding.provider()` — the
- **unguarded** driver — so no budget applies. No upstream change was required.
-- **`1bf2037a0` removed the memory host seams** on the reasoning that "this
- process embeds no engine". It does. That shipped a build where **every chat
- turn failed** with `no EmbeddingHost installed`. Restored in `00fc1fba2`.
- See section 6.
-- **The kernel-floor entry (2026-08-10) is probably stale.** It ratchets
- `tinymemory` / `tinymemory-tinycortex` in as always-on "driver admission"
- dependencies. Measured: the product build compiles **clean** without both, no
- `ctor`/`inventory`/`linkme` registration exists in either, nothing in the
- product build names them, and `binding::admit` refuses `DriverClass::Embedded`
- outright. **That evidence is not sufficient on its own, and the entry stays
- until a process-level smoke test says otherwise.** `admit` maps both the
- default `tinymemory` driver and the legacy `tinycortex` alias to
- `DriverClass::Module`, and the provider then loads the module through
- `ops::ensure_loaded` — a `dlopen` at runtime. A clean compile and a host-side
- source scan cannot observe that path, so they cannot prove removing the deps
- leaves module admission working. Run a build with them dropped and drive one
- real module-backed memory call before rewriting the entry. Either it gets
- rewritten on that evidence or the deps stay — leaving two
- documented decisions contradicting each other is how the next person is misled.
-
----
-
-## 4. Why criterion 2 is blocked
-
-`tinymemory-core` is reached two ways:
-
-```text
-tinymemory-core
-├── openhuman ← via 13 `pub use tinymemory_core::…::*` shims
-└── tinymemory-tinycortex ← transitive
- └── openhuman
-```
-
-**The second parent is solvable.** Removing `tinymemory` and
-`tinymemory-tinycortex` from `Cargo.toml` leaves the product build compiling with
-zero errors, and `tinymemory-core` then has `openhuman` as its **only** parent.
-That experiment was run; re-run it to confirm before relying on it.
-
-**The first parent is not, yet — and this is the real blocker.** The shims cannot
-simply be deleted. `memory/tree/mod.rs` says so in its own docs:
-
-> None of it has a contract equivalent: `tinymemory_api::tree` is the summary
-> node vocabulary, not an embedder or an entity extractor. So this shim is
-> pinned by the engine's *scoring and summarisation* internals, and it goes when
-> those move behind the bus — **not before**.
-
-Verified: `tinymemory-api` provides **zero** files for `score`, `summarise`,
-`nlp` or `ingest`. Deleting the shim would force consumers to write
-`tinymemory_core::tree::score::embed` directly — *more* direct engine references,
-not fewer. Strictly worse.
-
-### The actual remaining surface
-
-**37 references across ~20 files.** Not the 214 a naive grep suggests — most of
-that count is host code, because `health`, `retrieval`, `tree` and
-`tree_runtime` are **shadowed** by local `pub mod` declarations and only look
-like engine paths.
-
-| Cluster | Refs | Contract family exists? | Verdict |
-| --- | --- | --- | --- |
-| `sources::{types, registry, reconcile, status, readers, sync, get_source, list_sources, apply_kind_defaults, …}` | ~15 | **`as_sources` / `MemorySourceSink` exists** | probably routable **today** — verify member-by-member |
-| `diff::{types, ops}` | 5 | **`as_diff` / `MemoryDiff` exists** (`capture_snapshot`, `snapshots`, `diff`) | probably routable **today** — verify |
-| `tree::{score, summarise, nlp}` | 9 | **no equivalent** | **needs upstream** |
-| `tree::{store, runtime}` | 5 | unknown | check first |
-
-So the work splits into "probably already possible" (~20 refs) and "needs a real
-upstream program" (~9 refs).
-
-### The upstream program
-
-`score::{embed, extract, store, resolver}`, `summarise::{summarise,
-fallback_summary, SummaryContext, SummaryInput}`, `nlp::extract_query_entities`.
-That is embedder construction, summarisation and entity extraction — a
-materially bigger contract surface than either member shipped for this issue
-(#105, #106 were one method each).
-
-Consumers: `agent/harness/archivist/{lifecycle,recap,types,test_constructors}.rs`,
-`agent/harness/subagent_runner/ops/runner.rs`, `inference/embeddings/rpc.rs`,
-`memory/read_rpc/entities.rs`, `memory/tree/retrieval/rpc.rs`.
-
-**Design question to settle first, before writing any code:** does the host
-*call* an embedder, or does it *ask the driver to embed*? The module already
-proxies embedding back to the host through `EmbeddingHost` — so a naive
-"expose the embedder over the bus" would be circular. The likely right shape is
-that scoring and summarisation become driver-side operations the host requests
-by intent, not primitives the host drives. Get that wrong and the seam gets
-wider without getting cleaner.
-
----
-
-## 5. Recommended sequence
-
-Each step is independently valuable and independently mergeable.
-
-1. **Land the draft PR** (this work). Criterion 1 progress, no dependencies.
-2. **Fix the ratchet's measurement.** Teach the scanner to resolve
- `#[cfg(test)]` — including a gated `mod` declaration in an ancestor — and to
- recognise `required-features` binaries. Report test-only refs as a separate,
- still-visible count. Re-verify every remaining reason against the code and
- delete the stale ones. *Do this before anything else: its wrong reasons are
- what sent a phase of work upstream unnecessarily.*
-3. **Route `sources` and `diff`.** ~20 refs against families the contract
- already has. Verify member-by-member that the contract covers what each call
- site needs; where it does not, note the gap rather than forcing it.
-4. **Scope the scoring/summarisation contract** as its own issue, starting from
- the design question above. Do not start with code.
-5. **After 4 ships and releases:** delete the 13 shims, drop `tinymemory`,
- `tinymemory-tinycortex` and `tinymemory-core`, remove the
- `[package.metadata.cargo-machete] ignored` entries, ratchet the kernel floor
- down, and reconcile or delete the 2026-08-10 kernel-floor entry.
-
----
-
-## 6. Hazards that have already caused outages
-
-Read these as "this has happened", not "this could happen".
-
-- **A `cdylib` has its own statics.** The module cannot see a process-global the
- host filled, and vice versa. This produced *two* separate runtime failures in
- one day: the missing `EmbeddingHost` (every chat turn failed) and an empty
- Composio provider registry inside the module (every bootstrap would have
- reported "no composio provider registered"). **Neither is visible to
- `cargo check`, to the ratchets, or to any unit test** — they all run in a
- process that is already initialised.
-- **Never remove a seam before its last caller.** The seams are downstream of the
- callers, not an independent item to trim. Prove the caller is gone, then
- remove the seam.
-- **Compile-clean is not sufficient here.** Boot the app and send a chat turn
- before merging anything that changes memory wiring.
-- **The release-pin gate is five sites, and they move together:** the
- `vendor/tinymemory` gitlink, `modules/registry.rs` (version, release URL, 11
- archives, 11 digests), `ARTIFACT_CAPABILITIES_PIN` in `modules/memory.rs`, and
- the `memory_version` / `memory_sha256` pairs in `ci-full.yml`, `ci-lite.yml`
- and `e2e-reusable.yml`. Take digests **verbatim from the release's
- `checksum.toml`**, never recomputed locally.
-- **`is_compatible` has zero call sites.** A member inside an already-advertised
- family that the pinned artifact does not serve fails at **runtime** with
- `UnknownMethod`, not at build. Before trusting a re-pin, diff the host's
- `module_call!` member names against the tag's `METHODS` list. It has been
- 64/64 at every pin so far.
-
----
-
-## 7. Verification commands
-
-```bash
-# both clippy lanes CI runs — the second catches gates-off breakage
-cargo clippy -p openhuman --features "$(bash scripts/ci/product-features.sh)" -- -D warnings
-cargo clippy -p openhuman -- -D warnings
-
-# tests/ targets are NOT built by PR CI (test.yml is workflow_dispatch-only),
-# so this is the only place they get checked before a release lane sees them
-cargo check --locked -p openhuman --features "$(bash scripts/ci/product-features.sh)" --tests
-
-cargo test -p openhuman --lib -- memory:: modules:: # multi-filter needs `-- a b`
-
-# Two Cargo worlds, two lockfiles — the root command does NOT validate the
-# shell's. Check both, or a stale `app/src-tauri/Cargo.lock` fails the release
-# lane in "Enforce Linux TLS dependency policy" with a --locked error that
-# names neither the lockfile nor the pin that moved.
-cargo metadata --locked
-cargo metadata --locked --manifest-path app/src-tauri/Cargo.toml
-
-# criterion 2, the real gate. NOT `cargo tree -i`: it exits non-zero when the
-# crate is absent (so "gone" and "command failed" are the same signal) and
-# `-e normal` still matches a dev-dependency-only survivor.
-bash scripts/assert-shed.sh "$(bash scripts/ci/product-features.sh)" tinymemory-core
-```
-
-macOS notes: set `GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=commit.gpgsign
-GIT_CONFIG_VALUE_0=false` or temp-repo tests hang forever on a pinentry prompt;
-`git commit`/`merge` want `-c core.hooksPath=/dev/null` or they stall; system
-bash is 3.2 so CI scripts using `mapfile` cannot be run locally as-is.
-
----
-
-## 8. Known-red, not yours
-
-- **`tinysweeper/commits` on #5725.** Three findings, all false positives: two
- are the regex *detectors* in `memory/safety.rs` that redact real OpenSSH and
- PGP keys, one is a `MIIabc123` test fixture. Removing any deletes real
- redaction or the test proving it fires. Needs a maintainer dismissal. The bot
- is also degraded (`402 Payment Required` on its embeddings), so four of its
- six lanes reported "no reviewer could be consulted" or reviewed 0 files.
-- **`subagent_prompt_renderer_handles_formats_caps_and_stale_tool_indices`** on
- `main` asserts `"## Output style"`, a heading that moved to `STYLE.md` in
- #5701. Pre-existing; surfaces only if the full suite runs.
diff --git a/SCRATCH/requests/intelligence.md b/SCRATCH/requests/intelligence.md
deleted file mode 100644
index e1e22b85c7..0000000000
--- a/SCRATCH/requests/intelligence.md
+++ /dev/null
@@ -1,10 +0,0 @@
-# intelligence/ — requests to whoever owns i18n keys / ui/index.ts barrel
-
-No new i18n keys were needed — every string used an existing t() key or a
-literal that was already there before migration.
-
-No new barrel exports were needed — every primitive used (Button, Dialog,
-AlertDialog, Switch, TextField, TextArea, NativeSelect, Checkbox, Table*,
-Field, Label, Slider) was already exported from app/src/components/ui/index.ts.
-
-Nothing outstanding from this bucket.
diff --git a/CONTRIBUTING-BEGINNERS.md b/docs/CONTRIBUTING-BEGINNERS.md
similarity index 100%
rename from CONTRIBUTING-BEGINNERS.md
rename to docs/CONTRIBUTING-BEGINNERS.md
diff --git a/SUPPORT.md b/docs/SUPPORT.md
similarity index 100%
rename from SUPPORT.md
rename to docs/SUPPORT.md
diff --git a/docs/agent-workflows/pilot-batch-example.json b/docs/agent-workflows/pilot-batch-example.json
deleted file mode 100644
index e22ad52061..0000000000
--- a/docs/agent-workflows/pilot-batch-example.json
+++ /dev/null
@@ -1,35 +0,0 @@
-{
- "batch_id": "example-pilot-2026-05-15",
- "base_repo": "tinyhumansai/openhuman",
- "base_branch": "main",
- "tracking_issue": 1480,
- "agents": [
- {
- "id": "a01",
- "issue": 9001,
- "title": "tighten memory namespace migration logging",
- "branch": "cursor/a01-9001-memory-namespace-logging",
- "owned_paths": ["src/openhuman/memory/"],
- "allowed_shared_paths": ["docs/TEST-COVERAGE-MATRIX.md"],
- "labels": ["cursor-agent", "pilot", "batch:example-pilot-2026-05-15"]
- },
- {
- "id": "a02",
- "issue": 9002,
- "title": "deduplicate cron RPC validation helpers",
- "branch": "cursor/a02-9002-cron-rpc-dedupe",
- "owned_paths": ["src/openhuman/cron/"],
- "allowed_shared_paths": ["docs/TEST-COVERAGE-MATRIX.md"],
- "labels": ["cursor-agent", "pilot", "batch:example-pilot-2026-05-15"]
- },
- {
- "id": "a03",
- "issue": 9003,
- "title": "settings panel a11y labels",
- "branch": "cursor/a03-9003-settings-a11y-labels",
- "owned_paths": ["app/src/components/settings/"],
- "allowed_shared_paths": ["docs/TEST-COVERAGE-MATRIX.md"],
- "labels": ["cursor-agent", "pilot", "batch:example-pilot-2026-05-15"]
- }
- ]
-}
diff --git a/docs/audits/2026-08-13-tui-agent-cockpit.md b/docs/audits/2026-08-13-tui-agent-cockpit.md
deleted file mode 100644
index 0ac684513f..0000000000
--- a/docs/audits/2026-08-13-tui-agent-cockpit.md
+++ /dev/null
@@ -1,49 +0,0 @@
-# TUI agent-cockpit audit
-
-Reference: the interaction model of OpenAI Codex's terminal UI, adapted to
-OpenHuman's existing RPCs and four-tab product structure. This is behavioral
-parity, not a visual clone.
-
-## Gaps found in the previous TUI
-
-The previous terminal client opened on Logs, created a new thread on every
-launch, accepted only a single-line prompt, and exposed only send/cancel/new.
-It did not restore transcripts, scope events by thread, steer an active turn,
-surface approvals or plan review, select models or agent profiles, expose
-goals/tasks/skills/MCP/artifacts, inspect Git changes, insert workspace paths,
-copy/export answers, or accept a launch prompt.
-
-## Implemented cockpit surface
-
-- Chat is the default tab; Logs, Config, and Settings remain available through
- `Alt+1-4` and `Ctrl+Tab`.
-- Saved-thread resume (`/resume`, `--resume`, `--last`), transcript restoration,
- rename/delete/new, and strict client-and-thread event isolation.
-- Unicode-safe multiline composer, history, fuzzy slash-command completion,
- paste, cursor editing, and bounded `@path` insertion from `action_dir`.
-- Active-turn steering on Enter, queued follow-up on Tab, cancel on Escape, and
- queue status in `/status`.
-- Blocking approval and plan-review overlays, including approve-once, durable
- tool/flow approval, deny, approve/reject plan, and revise with feedback.
-- OpenHuman-native views for usage, goals, task board, agent profiles, Skills,
- MCP servers, and artifacts; agent profiles and autonomy tier can be changed
- in place.
-- Structured live tool, sub-agent, artifact, reasoning, retry, and error rows.
-- Optional Git status/diff and review prompt, OSC-52 answer copy, Markdown
- transcript export, model override, direct positional prompts, and
- `--no-alt-screen`.
-
-## Intentional differences
-
-- The four established OpenHuman tabs remain the top-level navigation.
-- File references are text paths rooted in `action_dir`; binary/image
- attachments are not introduced.
-- Git controls appear on demand and report a clear non-repository state.
-- Skills and MCP views follow their existing compile-time feature gates and
- return the normal RPC error surface in slim builds.
-
-## Verification
-
-The TUI reducer, composer, rendering, picker, and RPC-name contract have focused
-unit coverage. The slim feature test uses `--no-default-features --features tui`;
-an additional registry test enables `tui,skills,mcp` to cover gated commands.
diff --git a/docs/flows-agent-friendliness-audit.md b/docs/flows-agent-friendliness-audit.md
deleted file mode 100644
index 710c667a4a..0000000000
--- a/docs/flows-agent-friendliness-audit.md
+++ /dev/null
@@ -1,290 +0,0 @@
-# Flows: Agent-Friendliness Audit & Improvement Plan
-
-**Date:** 2026-07-15 · **Scope:** how well the Workflows (Flows) product supports an AI agent
-creating, editing, saving, testing, and debugging automations — across the Rust core
-(`src/openhuman/flows/`, `tinyflows` engine seam), the agent tool belt
-(`flows/tools.rs`, `flows/builder_tools.rs`), and the frontend canvas
-(`app/src/pages/FlowCanvasPage.tsx` and friends).
-
----
-
-## 1. Current architecture (baseline)
-
-- A flow is a typed JSON node graph (`tinyflows::model::WorkflowGraph` — nodes, edges, 12
- `NodeKind`s, jq `=`-expressions for bindings), persisted in SQLite
- (`{workspace}/flows/flows.db`, `flow_definitions.graph_json`).
-- 21 RPC controllers under `openhuman.flows_*` (`src/openhuman/flows/schemas.rs`).
-- Agent surface: `propose_workflow` / `revise_workflow` (validate-only, never persist),
- `save_workflow` (update existing flows only), `dry_run_workflow` (mock capabilities),
- `run_flow` (saved flows, real effects), plus read tools (`list_flows`, `get_flow`,
- `get_flow_run`, `list_flow_connections`, `search_tool_catalog`, `get_tool_contract`,
- `get_tool_output_sample`, `list_agent_profiles`).
-- Human-in-the-loop invariant is enforced **structurally**: the agent has no create tool;
- proposals render as `WorkflowProposalCard` / canvas diff previews, and only the user's
- explicit Save persists. `save_workflow` never touches `enabled` / `require_approval`.
-- Frontend: React Flow canvas, explicit Save only (no autosave — a saved+enabled flow is
- live), client-side-only drafts (`/flows/draft` graph rides in router `location.state`),
- copilot panel driving `flows_build`.
-
-Strengths worth preserving: the validate-gates return model-consumable, per-node,
-"fix-and-retry" errors; the propose→accept→save loop gives real human oversight;
-`get_tool_contract` / `get_tool_output_sample` are exactly the right shape of
-machine-readable introspection.
-
----
-
-## 2. Audit findings — where agents get hurt
-
-### F1. Whole-graph blobs are the only edit unit (highest friction)
-Every mutating/validating tool (`propose_workflow`, `revise_workflow`, `save_workflow`,
-`dry_run_workflow`) requires the **entire** `WorkflowGraph` per call
-(`flows/builder_tools.rs:114-122`, `:1712-1720`). There is no add-node / patch-node-config /
-rewire-edge operation, at either the tool or RPC layer (`flows_update`'s `graph` param is
-"Replacement WorkflowGraph", `schemas.rs:513`). For a 20-node flow, one config tweak means
-re-emitting the whole graph — token-heavy, slow, and the #1 source of accidental
-regressions (dropped nodes, mangled edges). `revise_workflow`'s "NOT a regeneration from
-scratch" rule is advisory prose, not enforced.
-
-### F2. The flow DSL has no queryable schema
-The 12 node kinds, per-kind config shapes, port rules, and `.item` / `.item.json` envelope
-semantics live only in prose: the 618-line `workflow_builder` prompt
-(`flows/agents/workflow_builder/prompt.md`) and `propose_workflow`'s giant description
-string (`flows/tools.rs:52-76`). `parameters_schema` describes node `config` as
-"Kind-specific configuration; see tool description". Contrast with Composio actions, where
-`get_tool_contract` returns real JSON schemas. Any agent outside the workflow_builder
-persona (or a future model with a trimmed prompt) is flying blind, and prompt/code drift
-is unchecked.
-
-### F3. Validation iterates one error at a time, and paths diverge
-`FlowValidation.errors` carries **at most one** error — tinyflows validation stops at the
-first structural failure (`flows/types.rs:53-55`), so a graph with five problems costs
-five round-trips. Several paths surface raw `.map_err(|e| e.to_string())` strings
-(`ops.rs:89-92`, `:2204`). Additionally, the agent-tool save path layers extra hard gates
-(binding resolvability, tool contracts, required-arg resolvability) that `flows_update`
-itself doesn't run (`builder_tools.rs:1765-1770`) — so agent saves and UI saves are
-validated differently, and a UI-saved flow can fail gates the agent is required to pass.
-
-### F4. Capability asymmetries — RPC ops with no agent tool
-| Operation | RPC | Agent tool | Consequence |
-|---|---|---|---|
-| Create flow | `flows_create` | none (by design) | OK as a safety choice, but there's no gated alternative for "create disabled draft" either |
-| Enable/disable | `flows_set_enabled` | none | orchestrator prompt even references it; agent can only ask the user |
-| Delete / duplicate | `flows_delete` / `flows_duplicate` | none | agent told to clone via get_flow→revise |
-| List runs | `flows_list_runs` | none | agent has `get_flow_run` but must be handed a `run_id` externally — breaks the self-debug loop |
-| Resume / cancel run | `flows_resume` / `flows_cancel_run` | none | agent can't progress a run paused on approval, or stop a runaway one |
-| Standalone validate | `flows_validate` | none | validation only reachable bundled inside propose/revise/save |
-| Import (n8n) | `flows_import` | none | agent can't help migrate automations |
-
-### F5. No server-side draft; agent and UI can't share working state
-Drafts exist only client-side: the `/flows/draft` graph lives in router `location.state`
-(dropped on reload), and agent proposals live in the chat/canvas proposal card. There is
-no durable draft the agent can iterate on across turns, no way for a chat-initiated build
-and the canvas to reference the same in-progress graph by id, and a crash/reload loses
-everything. This is also *why* F1 exists — with no server-side working copy, every tool
-call must carry the full graph.
-
-### F6. Last-write-wins everywhere; the UI is blind to agent edits
-`update_flow_graph` has no version/etag/`updated_at` precondition (`store.rs:329-343`);
-`Flow` has no version field. There are **no** socket/domain events for flow
-create/update/delete/enable — only run-progress and approval events
-(`useFlowRunProgress.ts`; `useFlowRunPoller.ts` notes "the flows engine emits no socket
-events"). So: an agent `save_workflow` while the user has the canvas open is invisible,
-and the user's next Save silently clobbers it (and vice versa). No revision history or
-rollback exists, which is precisely what makes granting the agent more write power scary.
-
-### F7. The agent cannot actually test what it built
-`dry_run_workflow` runs against deterministic **mock** capabilities only — the prompt
-spends ~200 lines (`prompt.md:540-605`) teaching the agent to reason around sandbox
-artifacts. Real execution (`run_flow`) requires the flow to already be **saved** plus an
-explicit user "yes" — a draft cannot be end-to-end tested at all. And the read-only
-autonomy tier blocks even the side-effect-free mock dry-run
-(`builder_tools.rs:1218-1229`), so a read-only agent cannot self-verify its own proposal.
-
-### F8. "Workflow" means four different things
-`flows/` (the product), the legacy `skills` tools literally named
-`list_workflows`/`run_workflow`/`create_workflow` (SKILL.md system), `rhai_workflows` (an
-in-turn scripting cell), and cron jobs. The orchestrator prompt has to explicitly warn
-against crossing them (`agent_registry/agents/orchestrator/prompt.rs:105-110`), and
-`run_flow` was named to dodge a collision with the legacy `run_workflow`. This taxes every
-agent turn and every new contributor.
-
----
-
-## 3. Improvement plan
-
-Ordering principle: make edits cheap and correct first (F1–F3), then make shared state
-durable (F5), then make concurrent writes safe + observable (F6) — because F6's
-safety rails are the prerequisite for widening agent write capabilities (F4, F7).
-
-### Phase 1 — Structured editing & introspection (F1, F2, F3)
-
-1. **Graph patch operations.** New core op `flows::apply_graph_ops(base_graph, ops[]) ->
- Result<WorkflowGraph, StructuredErrors>` with ops like `add_node`, `update_node_config`
- (JSON-merge-patch on `config`), `rename_node`, `remove_node`, `add_edge`,
- `remove_edge`, `set_node_position`. Expose as a new agent tool `edit_workflow
- { flow_id | graph, ops[] }` that applies ops, runs the full validate+gate stack, and
- returns the updated graph + proposal payload (same contract as `revise_workflow`).
- Whole-graph tools stay for initial generation; iteration switches to ops.
-2. **Queryable DSL schema.** Move per-node-kind config shapes into typed Rust schemas
- (source of truth), and expose `get_node_kind_contract { kind }` /
- `list_node_kinds` agent tools mirroring `get_tool_contract`. Generate the prompt.md
- node-kind section and `propose_workflow`'s description from the same source
- (docs-drift-style check) so prose can never diverge from code.
-3. **Multi-error validation.** Change `FlowValidation.errors` to collect all
- structural errors (tinyflows `validate` change: accumulate instead of first-error),
- with structured entries `{node_id, field, code, message}`. Replace bare
- `.to_string()` error paths in `ops.rs` with the structured form.
-4. **Unify validation planes.** Run the host hard gates (binding/contract/required-arg)
- inside `flows_update`/`flows_create` too — or, if UI permissiveness must stay,
- downgrade them to blocking-for-agents via an explicit `strict: bool` param rather
- than a divergent code path. Also give the agent a standalone `validate_workflow` tool
- (thin wrapper over `flows_validate` + gates) so it can check without proposing.
-
-### Phase 2 — Core-managed local drafts (F5, and the real fix for F1's token cost)
-
-5. **Draft entity — local JSON files, not a new table (for now).** Drafts are stored
- as plain JSON files on disk, managed by the core:
- `{workspace_dir}/flows/drafts/<draft-id>.json`, each holding
- `{id, flow_id?, name, graph, origin: chat|canvas|import, created_at, updated_at}`.
- No SQLite schema/migration. Same thin RPC surface on top:
- `flows_draft_create/get/update/list/delete/promote` — `promote` runs the existing
- create/update path (same gates, same forced `require_approval` floor) and removes
- the file. Key constraint this preserves: drafts must be readable/writable by **both**
- the agent tools (Rust core) and the canvas — which rules out frontend-only
- `localStorage`. File-based storage keeps drafts trivially inspectable and deletable,
- and can be migrated into a `flow_drafts` table later if drafts ever need querying,
- retention caps, or cross-device sync; the RPC contract stays identical either way.
-6. **Agent tools on drafts.** `propose_workflow`/`revise_workflow`/`edit_workflow`/
- `dry_run_workflow` gain a `draft_id` mode: the graph lives in the core-managed
- draft file; tool calls
- carry only ops/instructions and get back diffs + validation. Cuts per-turn tokens
- dramatically and survives reloads/session hops.
-7. **Frontend adoption.** `/flows/draft/:draftId` loads from core instead of
- `location.state`; import and proposal-accept create drafts; the unsaved-changes
- guard becomes "draft is saved, flow is not yet updated". Copilot and canvas now
- share one working copy by id.
-
-### Phase 3 — Concurrency safety & observability (F6)
-
-8. **Optimistic concurrency.** Add `version: i64` (or reuse `updated_at` as etag) to
- `Flow`; `flows_update` and `save_workflow` take `expected_version` and return a
- structured conflict error (with the current server graph) instead of clobbering.
- UI surfaces "flow changed since you opened it" with a reload/diff option.
-9. **Flow mutation events.** Publish `DomainEvent::FlowChanged{flow_id, kind:
- created|updated|deleted|enabled_changed, actor}` on every mutation; bridge to a
- `flow:changed` socket event. FlowsPage refetches on it; FlowCanvasPage shows a
- banner when its open flow changes underneath (agent edits become visible in real
- time instead of silently).
-10. **Revision history + rollback.** `flow_revisions` table capturing the prior
- `graph_json` on every update (capped, e.g. last 20), plus `flows_rollback` RPC and
- a `get_flow_history` agent tool. This is the safety rail that justifies Phase 4.
-
-### Phase 4 — Widen agent capabilities behind existing gates (F4, F7)
-
-11. **Debug loop tools:** `list_flow_runs { flow_id, limit }`, `resume_flow_run`
- (Execute + approval-gated), `cancel_flow_run` (Write). The agent can then find a
- failing run, diagnose it via `get_flow_run`, patch via `edit_workflow`, and verify.
-12. **Gated create:** `create_workflow` agent tool → `flows_create` with hard-coded
- `enabled: false` + the existing forced `require_approval` floor,
- `PermissionLevel::Write` (approval gate). Enable/disable stays human-only
- (`flows_set_enabled` deliberately remains toolless). Add `duplicate_flow`
- (creates disabled copy) for the clone-then-edit pattern.
-13. **Testability:** (a) allow `dry_run_workflow` on the read-only tier — it is
- mock-only and side-effect-free; (b) add a `test_run` mode that executes a draft
- with *real read-scope* capabilities only (generalizing `get_tool_output_sample`'s
- read-only-real-call precedent), refusing Write/Admin-class nodes; (c) let
- `run_flow` accept `draft_id` once drafts exist, still behind explicit user
- confirmation.
-
-### Phase 5 — Builder UX: connector onboarding, tool discovery, chat separation
-
-Today the builder assumes the user already knows their Composio landscape: the
-`tool_call` config drawer makes them hand-type a toolkit slug before the per-toolkit
-action dropdown appears (`app/src/components/flows/canvas/nodeConfig/composioFields.tsx`),
-the connection selector only lists connections that already exist
-(`flows_list_connections` → `nodeConfigFields.tsx:559`), and full-catalog search
-(`search_tool_catalog` / `get_tool_contract`) is agent-tool-only with no RPC the UI can
-call. When a graph needs an unconnected toolkit, the tool-contract gate just errors —
-nothing walks the user through connecting it.
-
-16. **Catalog RPCs for the UI.** Expose the existing agent-tool logic as controllers:
- `flows_search_tool_catalog { query, toolkit? }` and `flows_get_tool_contract
- { slug }` (thin wrappers over the same core code as `search_tool_catalog` /
- `get_tool_contract`, secret-free). One implementation, two consumers.
-17. **In-canvas tool browser.** Replace the hand-typed toolkit slug with a searchable
- catalog picker in the `tool_call` config drawer (and a "browse tools" entry in the
- NodePalette): search across all toolkits, show description / required args /
- connected-state per result, select → fills toolkit+action and shows the contract's
- arg schema. Connected toolkits rank first; unconnected results carry a Connect
- badge.
-18. **Required-connections surfacing.** Compute `required_connections:
- [{toolkit, connection_ref?, status: connected|missing}]` for any graph (derivable
- from the existing tool-contract gate) and include it in `flows_validate` output,
- the `workflow_proposal` payload, and `flows_get`. The proposal card and canvas
- validation banner render missing ones as explicit "Connect <toolkit>" CTAs
- deep-linking into the existing `/connections` connect flow, instead of a bare
- gate error. On return (connection created), re-validate automatically.
-19. **Agent-side guidance.** Teach the workflow_builder prompt to treat a missing
- connection as a first-class outcome: propose the flow anyway, enumerate the
- required connections in the proposal summary, and tell the user which toolkits
- need connecting (the card's CTAs do the rest). Optionally add a read-only
- `list_connectable_toolkits` tool (catalog toolkits + connected flag) so the agent
- can steer toolkit choice toward what's already connected.
-20. **Tag workflow chats separately from general chat.** Workflow-copilot
- conversations are ordinary core threads today, distinguishable only by a
- client-side `localStorage` mapping (`workflowCopilotThreads.ts` — user-scoped
- `copilot-thread:<flow>` keys). Instead, tag the thread server-side at creation:
- add a thread `kind` (e.g. `workflow_copilot`, with the associated
- `flow_id`/`draft_id` in thread metadata) in the `threads` domain, set it whenever
- `flows_build` / the copilot panel spawns a thread, and let thread-list queries
- filter by kind. The general `/chat` thread list excludes `workflow_copilot`
- threads; the flows UI lists a flow's builder threads from the core by tag. This
- also lets the copilot resolve "which thread belongs to this flow" server-side,
- demoting the fragile `localStorage` mapping to a cache (or deleting it).
-
-### Phase 6 — Naming & prompt hygiene (F8)
-
-21. Rename the legacy skills tools (`list_workflows`→`list_skills`,
- `run_workflow`→`run_skill`, etc., with deprecation aliases for one release) so
- "workflow" unambiguously means Flows in the agent's tool belt; delete the
- orchestrator-prompt disambiguation paragraph once done.
-22. Shrink the workflow_builder prompt by replacing the node-kind reference and mock
- behavior table with pointers to the Phase 1 introspection tools (generated docs
- keep parity).
-
-### Delivery: one PR, phased commits
-
-All six phases ship together as **a single PR**, not as separate PRs per item. The
-phases above define the *internal build order and commit structure* of that PR — each
-numbered item lands as one or more focused commits, in phase order, so the branch is
-reviewable commit-by-commit and bisectable — but the feature is reviewed, tested, and
-merged as one unit. Rationale: the pieces are interdependent (drafts remove the need for
-whole-graph tools, versioning/events are the safety rails that justify the wider tool
-belt, the prompt shrink depends on the introspection tools existing), and shipping them
-piecemeal would leave the agent surface in inconsistent intermediate states across
-releases.
-
-| Phase | Depends on | Rough size | Risk |
-|---|---|---|---|
-| 1 (patch ops, schema tools, multi-error) | — | M–L (tinyflows crate change for multi-error) | Low |
-| 2 (core-managed local drafts) | 1 helps | S–M | Low — additive files/RPC, no DB migration |
-| 3 (versioning, events, history) | — (parallel to 2) | M | Medium — touches UI save path |
-| 4 (new agent tools) | 3 (safety rails) | S–M each | Medium — permission review each |
-| 5 (connector onboarding, tool browser, chat tagging) | 1 (contract gate reuse) | M | Low–Medium — UI + additive RPCs + thread `kind` |
-| 6 (renames) | — | S | Low (needs deprecation window) |
-
-Build within the branch in phase order (1 → 2 → 3 → 4 → 5 → 6): items 1–3 (Phase 1) deliver
-the biggest agent-experience win and require no changes to the human-in-the-loop model;
-Phase 3's rails must be in place before Phase 4's write tools are enabled. The PR
-description should map commits to plan items so reviewers can follow the same structure.
-
----
-
-## 4. Non-goals / explicitly preserved invariants
-
-- **No autosave** on the canvas — a saved+enabled flow is live; the explicit Save gate stays.
-- **Enable/disable remains human-only**; agent-created flows are born disabled.
-- The forced `require_approval = true` floor for side-effect graphs stays uncloseable
- by the agent.
-- `propose → user accepts → save` remains the default chat flow; new write tools are
- additive and approval-gated, not a replacement for proposals.
diff --git a/docs/library-benchmarking.md b/docs/library-benchmarking.md
deleted file mode 100644
index d191fc18f8..0000000000
--- a/docs/library-benchmarking.md
+++ /dev/null
@@ -1,393 +0,0 @@
-# Library benchmarking environment
-
-## Purpose
-
-"opencompany" wants to embed the OpenHuman Rust core as a library: no always-on
-RPC server, no Tauri shell, just the core linked in-process and driven
-directly. That changes what "resource usage" means. There is no single steady
-process to profile; there are per-use-case workloads (a long-running agent
-loop, a delegated multi-agent turn, a saved workflow run, a background
-subconscious pass, a memory ingest, a bare embed) that each have their own
-startup cost, steady-state footprint, and growth curve.
-
-This document describes the benchmark environment built to measure that: a
-pinned `library-profile` binary with six scenarios, four driver scripts
-under `scripts/profile/`, and the comparison point the team cares about
-(ZeroClaw). It builds on the manual investigation in
-[`docs/resource-profiling-session-2026-07-21.md`](resource-profiling-session-2026-07-21.md);
-read that document for the deep memory/CPU attribution work. This document is
-about running repeatable benchmarks, not re-deriving those findings.
-
-## The scenarios
-
-All scenarios run in `target/release/library-profile <scenario>`, replace
-network inference with a deterministic provider (`rss-bench` feature), and
-print one pretty-printed JSON result object to stdout (diagnostics go to
-stderr). Each models a distinct embedding use case:
-
-| Scenario | Models |
-| --- | --- |
-| `agent-turn` | The minimal embed case: one agent, one turn, no delegation, no workflow. The smallest useful "hello world" for a host that just wants a single reply. |
-| `long-agent` | A long-running agent loop (`OPENHUMAN_PROFILE_TURNS`, default 25) in one process, to see whether RSS plateaus or grows per turn. |
-| `workflow` | A saved automation run (`flows_create` + `flows_run`), representing the flows/automation embedding path rather than ad hoc chat. |
-| `fleet` | N concurrent live agents with latency-realistic mock inference — the "100-1000 agents in a 2 GB / 2 vCPU server" question. See [below](#the-2-gb--2-vcpu-server-budget). |
-
-Four scenarios that this table used to list are gone, for two different
-reasons. `memory-ingest` and `cold-phases` measured the memory engine embedded
-in this process — one drained its queue, the other checkpointed its bootstrap
-through `tinymemory_core::store::MemoryClient` — and the binary no longer links
-one (openhuman#6161). Measuring the memory *module* over the bus instead is a
-different scenario and wants its own design, not a revived file. `subagents`
-and `subconscious` had already stopped existing before that: the subconscious
-domain was removed from the product outright, and both were still named in
-`library-bench.sh`'s sweep list, where `dispatch` answered "unknown scenario".
-The measurement tables further down are left as recorded — they are a log of
-what was measured when, not a description of what runs today.
-
-## How to run
-
-Six scripts under `scripts/profile/` (each has `-h`/`--help`):
-
-- **`library-bench.sh`** — the primary RSS/duration benchmark. Builds the
- binaries, runs each scenario N fresh-process repeats (default 5), and
- aggregates median/min/max into `summary.json` + `summary.md`.
-
- ```bash
- ./scripts/profile/library-bench.sh # default build, all scenarios
- ./scripts/profile/library-bench.sh --slim # --no-default-features recipe
- ./scripts/profile/library-bench.sh --scenarios "long-agent,subagent-storm" --turns 50 --warm
- ```
-
-- **`library-cpu.sh`** — a `samply` wrapper for one scenario's CPU profile,
- isolated from persistence/timezone noise by default.
-
- ```bash
- ./scripts/profile/library-cpu.sh subagent-storm
- samply load target/profile/rust-library/subagent-storm-cpu.json.gz
- ```
-
-- **`library-heap.sh`** — builds the `rss-bench-dhat` variant and runs a
- scenario under dhat for live-heap attribution (allocation sites, retained
- bytes). RSS/timing under dhat are perturbed; don't compare those numbers to
- `library-bench.sh` output.
-
- ```bash
- ./scripts/profile/library-heap.sh agent-turn
- # load target/profile/rust-library/dhat-agent-turn.json at
- # https://nnethercote.github.io/dh_view/dh_view.html
- ```
-
-- **`library-fleet.sh`** — sweeps the `fleet` scenario across a list of agent
- counts and gates the result against the 2 GB / 2 vCPU server budget (see
- below).
-
- ```bash
- ./scripts/profile/library-fleet.sh --agents 100 --latency-ms 200
- ./scripts/profile/library-fleet.sh --agents "50,100,500" --target 1000 --budget-mib 2048
- ```
-
-- **`library-instances.sh`** — sweeps N independent *processes* (not agents
- in one process) of a scenario, held alive via `OPENHUMAN_PROFILE_HOLD_SECS`,
- and measures per-instance/aggregate cost — the many-processes counterpart
- to `library-fleet.sh`'s one-process model (see
- [below](#fleet-one-process-vs-instances-many-processes)).
-
- ```bash
- ./scripts/profile/library-instances.sh --instances "10,25,50" --hold-secs 30
- ```
-
-- **`library-pool-gate.sh`** — the runtime-pool regression gate (#5106). Runs
- `skill-run` with K parallel skill runs and asserts the process tree grows by
- ~one pooled worker, not K interpreters; reports pooled vs unpooled.
-
- ```bash
- ./scripts/profile/library-pool-gate.sh --concurrency 8 --workers 1
- ```
-
-### Default vs slim builds
-
-Default-feature builds link every compile-time domain gate (`voice`, `web3`,
-`media`, `meet`, `skills`, `flows`, `mcp`, `tui`) — the byte-identical desktop
-recipe. The slim recipe drops everything not required by the harness:
-
-```bash
-GGML_NATIVE=OFF cargo build --release \
- --no-default-features --features rss-bench \
- --bin library-profile --bin rss-bench
-```
-
-`--slim` on `library-bench.sh` builds this recipe. Per the prior session,
-compile-time gates shrink the binary substantially but only move settled RSS
-by a few MiB — most of the RSS story is initialization and allocator
-behavior, not linked code size.
-
-### Useful env knobs
-
-| Variable | Effect |
-| --- | --- |
-| `OPENHUMAN_PROFILE_TURNS` | Turn count for `long-agent` (default 25). |
-| `OPENHUMAN_PROFILE_PREWARM_SUBAGENTS=1` | Run one warm-up turn before measuring (`subagent-storm`), isolating first-use cost from steady state. |
-| `OPENHUMAN_PROFILE_DISABLE_MEMORY_WRITES=1` | Disable `memory.auto_save` and episodic capture, isolating orchestration from persistence. |
-| `OPENHUMAN_PROFILE_FORCE_UTC=1` | Skip `iana_time_zone`/CoreFoundation timezone resolution. |
-| `OPENHUMAN_PROFILE_HOLD_SECS` / `HOLD_BEFORE_SECS` | Pause the process at settled/baseline state for external inspection (`vmmap`, `heap`, `malloc_history`, Instruments). |
-| `OPENHUMAN_PROFILE_DHAT_OUT` | Output path for dhat JSON (set by `library-heap.sh`). |
-| `OPENHUMAN_PROFILE_SKILL_RUN_CONCURRENCY` | `skill-run`: number of parallel `code_executor` turns (K), each spawning a `node_exec` job (default 1). |
-| `OPENHUMAN_PROFILE_SKILL_RUN_POOL` | `skill-run`: `off` disables the shared runtime pool (legacy per-call spawn; tree then shows ~K resident `node` children). Default on. |
-| `OPENHUMAN_PROFILE_SKILL_RUN_POOL_WORKERS` | `skill-run`: pool size W when pooling is on (default 1). The scenario asserts `child_count <= W` for K > 1 — the #5106 regression gate. |
-
-## Metrics and interpretation
-
-Every run reports `baseline`/`settled`/`peak_rss_kib` (macOS: `proc_pid_rusage`
-RSS, `getrusage` peak, `proc_pidinfo` thread count), `retained_delta_kib`
-(settled minus baseline), `peak_delta_kib`, and `duration_ms`. `long-agent`
-additionally reports `checkpoints[]` so first-turn vs. last-turn growth is
-visible directly.
-
-**RSS is not private heap.** The prior session's deep attribution found a
-~42 MiB slim-build snapshot broken down as roughly 15.2 MiB private physical
-footprint, 3.18 MiB live heap, 18.7 MiB resident executable text, and ~9.4 MiB
-of resident-but-mostly-inactive malloc pages (allocator high-water
-retention). See
-[`docs/resource-profiling-session-2026-07-21.md`](resource-profiling-session-2026-07-21.md#deep-memory-attribution)
-for the full breakdown, the executable-paging finding (a cold turn faults in
-~15 MiB of previously nonresident OpenHuman code), and the warmed-process
-control showing steady-state turns cost ~0.5-1.9 MiB once warm rather than
-the ~26-31 MiB a cold turn costs. Use `library-bench.sh` for the RSS/duration
-headline numbers, `library-cpu.sh` when CPU attribution is the question, and
-`library-heap.sh` only when RSS numbers need live-allocation attribution
-(accepting the dhat perturbation).
-
-## The ZeroClaw comparison
-
-ZeroClaw self-reports idling under 5 MiB RAM; the "7.8-12 MiB under load"
-figure sometimes quoted alongside it has no locatable primary source, and even
-the idle figure is vendor marketing with no third-party verification (see
-[`docs/harness-comparison-2026-07-22.md`](harness-comparison-2026-07-22.md)).
-OpenHuman's Rust core currently settles around 35-50 MiB depending on
-scenario and feature set (see the baseline table below).
-
-Treat this as a **north star, not an apples-to-apples benchmark**. ZeroClaw's
-scope and feature set differ substantially from the OpenHuman core: OpenHuman
-links a full agent/memory/tool/orchestration stack (SQLite-backed unified
-memory, TinyCortex PII detection, prompt-injection detection, a builtin-agent
-registry, tool catalogs, provider routing) that a narrower harness may not
-carry at all. A closer gap is a meaningful signal that the initialization
-graph is leaner; it is not evidence of feature parity, and a wider gap is not
-automatically a regression if it comes from carrying more capability. Every
-`library-bench.sh` summary includes a labeled comparison row/note for exactly
-this reason: visible, but explicitly called out as external.
-
-## The 2 GB / 2 vCPU server budget
-
-"opencompany" wants a single server to host 100-1000 live agents inside a 2 GB
-RAM / 2 vCPU box. That is a budget question, not a per-scenario RSS question:
-2048 MiB / 1000 agents is roughly 2 MiB per agent all-in, but the fixed
-per-process base (allocator high water, code paging, registries, detectors —
-the same ~30 MiB every scenario above pays once) amortizes across however many
-agents share the process. What actually determines whether 1000 agents fit is
-the **marginal** cost per additional agent once that base is paid, not the
-per-agent average. `library-fleet.sh` runs the `fleet` scenario (N concurrent
-live agents, latency-realistic mock inference so idle time looks like real
-network waits rather than a busy loop) across a sweep of N and reports that
-marginal cost directly (`marginal_rss_kib_per_agent`), alongside idle CPU over
-a parked 10s window, thread count, and open FD count — all of which should
-stay roughly flat as N grows if per-agent state is cheap and idle agents cost
-~zero CPU.
-
-Working targets: marginal cost ≤ 1.5 MiB/agent, threads and FDs flat (not
-linear) in N, and idle CPU low regardless of N — an agent that isn't mid-turn
-should not be spending cycles. `OPENHUMAN_PROFILE_WORKER_THREADS=2` pins the
-scenario's tokio runtime to 2 worker threads to simulate the 2 vCPU box rather
-than scaling with the host's actual core count. The `budget` block in each
-run's JSON (`target_agents`, `ram_budget_mib`, `projected_rss_mib_at_target`,
-`fits`) projects the swept marginal cost out to the real target (default 1000
-agents / 2048 MiB); `library-fleet.sh` aggregates medians per N into
-`summary.md` and exits nonzero if any swept N projects `fits: false`, making
-it usable as a CI-style regression gate (`--no-gate` to disable).
-
-**Caveats, stated plainly:** these numbers are gathered on macOS, which has no
-cgroup memory limit to enforce or observe locally — the budget check is a
-projection from measured marginal cost, not a live "did it actually get
-OOM-killed at N agents" test. macOS also lacks Linux's `/proc/<pid>/smaps_rollup`,
-which would give true PSS (proportional shared memory) instead of RSS; RSS
-overcounts shared pages (executable text, shared library mappings) in a way
-that matters more as agent count grows and more of the process footprint is
-genuinely shared. Treat the macOS numbers as an approximation of the target
-Linux server, not a substitute for it. The JSON schema already has a Linux
-path — `proc_metrics` reads `/proc/<pid>/status` and `/proc/<pid>/stat` on
-Linux — so true validation should eventually mean running the same
-`library-profile fleet` binary on a cgroup-limited Linux box (matching the 2
-vCPU / 2 GB target) rather than trusting the macOS projection alone.
-
-### Fleet (one process) vs instances (many processes)
-
-The budget section above measures one deployment shape: N agents sharing a
-single process. But "opencompany" may instead run OpenHuman as **N
-independent processes or containers** — one per tenant — rather than N
-agents inside one process. Those are different cost models and the fleet
-number does not answer the second one.
-
-- **Fleet (`library-fleet.sh`)** pays the ~30-50 MiB fixed base (allocator
- high water, code paging, registries, detectors) **once**, and amortizes it
- across however many agents share that process. Marginal cost per agent is
- what matters, and it can be well under 1 MiB once the base is paid.
-- **Instances (`library-instances.sh`)** pays that same fixed base **N
- times**, once per process — minus whatever the OS actually shares across
- processes (resident executable text, shared library mappings). Summed RSS
- across instances therefore **double-counts** those shared pages; it is an
- upper bound, not the true footprint. True per-instance marginal cost is
- better read from summed PSS (Linux only — macOS has no PSS-equivalent
- metric), which divides shared pages across the processes that share them.
-
-`library-instances.sh` spawns N held `library-profile` processes staggered
-on startup, samples aggregate sum-RSS every 2s while they hold at settled
-state, and reports median settled RSS/instance, mean and peak aggregate
-sum-RSS, and summed PSS when available, plus a labeled 2 GB-box
-extrapolation estimate:
-
-```bash
-./scripts/profile/library-instances.sh --instances "10,25,50" --hold-secs 30
-```
-
-**This is still a macOS proxy, not container validation.** True validation
-means running the same binary under real `cgroup` memory limits (e.g.
-`docker run --memory=2g`) on a Linux host and observing whether it survives
-or gets OOM-killed at the target instance count — not projecting from local
-sum-RSS. That is follow-up work, and it belongs on a Linux box: this repo's
-own `openhuman-core` Docker build is currently blocked on Apple Silicon (the
-`whisper-rs-sys`/whisper.cpp NEON fp16 intrinsics fail to compile under
-arm64-Linux emulation with GCC 12 — see the umbrella repo's root `CLAUDE.md`
-gotchas and `docs/resource-profiling-session-2026-07-21.md`). The path
-around that blocker is either building for `linux/amd64` under emulation (the
-whisper AVX path has no NEON bug) or running the validation on a native Linux
-host rather than macOS Docker Desktop.
-
-## Profiling escalation path
-
-Start cheap, escalate only as needed:
-
-1. **`library-bench.sh`** — RSS/duration medians across fresh processes. Answers "did this change move the needle" for most changes.
-2. **`library-cpu.sh` (samply)** — symbolized CPU profile when a scenario is slower than expected, or to attribute cold-path CPU to a specific phase (registry init, agent build, memory construction, SQLite init, TinyAgents turn runner were the top contributors in the prior session).
-3. **`library-heap.sh` (dhat)** — live-heap allocation sites and retained bytes when RSS is high but the cause isn't obvious from CPU alone (e.g. the TinyCortex PII `RegexSet` finding came from stack-logged allocation attribution, not CPU sampling).
-4. **Instruments / `vmmap` / `heap` / `malloc_history`** — deepest macOS-native attribution, using the `OPENHUMAN_PROFILE_HOLD_SECS` / `HOLD_BEFORE_SECS` hooks to pause the process at baseline or settled state:
-
- ```bash
- OPENHUMAN_PROFILE_HOLD_SECS=120 target/release/library-profile subagent-storm &
- vmmap -summary <pid>
- heap -sH <pid>
-
- MallocStackLogging=1 OPENHUMAN_PROFILE_HOLD_SECS=120 \
- target/release/library-profile subagent-storm &
- malloc_history <pid> -allBySize
- ```
-
- This is what surfaced the PII-sanitizer regex cache and the first-turn
- executable-paging finding in the prior session; reach for it only once
- `library-bench.sh`/`library-cpu.sh`/`library-heap.sh` have narrowed the
- question to a specific scenario and metric.
-
-## Current baseline numbers
-
-From the 2026-07-21 profiling session (medians over five fresh processes
-unless noted; see that document for methodology and caveats):
-
-| Scenario | Build | Median settled RSS | Median retained Δ |
-| --- | --- | ---: | ---: |
-| 1-agent roster | default | 38.7 MiB | - |
-| 8-agent roster | default | 41.5 MiB | +2.8 MiB total (~0.40 MiB/agent) |
-| 1-agent roster | slim | 35.5 MiB | - |
-| 8-agent roster | slim | 38.7 MiB | +3.2 MiB total |
-| `memory-ingest` (100 msgs) | default | 25.5 MiB | 9.31 MiB |
-| `memory-ingest` (100 msgs) | slim | 23.8 MiB | 8.58 MiB |
-| `subagents` (cold, 2 children) | default | 48.5 MiB | 30.8 MiB |
-| `subagents` (cold, 2 children) | slim | 42.4 MiB | 25.7 MiB |
-| `subagents` (warmed repeat, persistence off) | default | - | 0.52 MiB |
-| `subagents` (warmed repeat, normal capture) | default | - | 1.84 MiB |
-| ZeroClaw (external, idle, self-reported/unverified) | - | < 5 MiB | - |
-
-First full `library-bench.sh` run of the new scenarios (default build, 5
-fresh-process repeats, 2026-07-21, Apple Silicon macOS):
-
-| Scenario | Build | Median settled RSS | Median retained Δ | Median duration |
-| --- | --- | ---: | ---: | ---: |
-| `agent-turn` (cold, 1 turn) | default | 47.6 MiB | 29.5 MiB | 102 ms |
-| `subconscious` (cold, no delegation) | default | 47.9 MiB | 29.8 MiB | 138 ms |
-| `subagents` (cold, 2 children) | default | 48.0 MiB | 29.9 MiB | 142 ms |
-| `workflow` (`flows_create` + `flows_run`) | default | 50.9 MiB | 29.9 MiB | 110 ms |
-| `long-agent` (25 warmed turns) | default | 65.8 MiB | 18.5 MiB | 1,361 ms |
-| `cold-phases` (9 bootstrap phases) | default | 51.2 MiB | 36.5 MiB | 476 ms |
-| `memory-ingest` (100 msgs) | default | 25.8 MiB | 9.3 MiB | 2,099 ms |
-
-Notable structure behind these medians:
-
-- The `long-agent` per-turn series plateaus: typical turns add 30-150 KiB,
- and the 25-turn total (~16.8 MiB first-to-last) is dominated by two async
- persistence/compaction bursts of 6-8 MiB each, matching the prior session's
- warmed-repeat outlier observation. Steady-state growth is not linear.
-- Cold `agent-turn`, `subconscious`, `subagents`, and `workflow` all retain
- approximately the same ~29-30 MiB, confirming the cost is shared bootstrap
- (code paging, registries, detectors, allocator high water), not the
- specific workload on top of it.
-- A dhat run of `agent-turn` measured 33.4 MB total allocated across 135,756
- blocks, but only 5.0 MB peak live heap and 3.1 MB live at exit, again
- showing RSS is mostly not live heap data.
-
-### Fleet, instances, and runtime baselines (2026-07-22, post-PII-prefilter)
-
-`library-fleet.sh` sweep (default build, 3 repeats, 3 turns/agent, 200 ms
-mock latency, 2 worker threads, target 1000 agents / 2048 MiB):
-
-| N agents | Marginal KiB/agent | Settled MiB | Idle CPU ms/10s | Threads | fds | p95 turn ms | Projected MiB @1000 | Fits |
-| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | :---: |
-| 50 | 1,985 | 223 | 3 | 71 | 420 | 2,848 | 1,956 | yes |
-| 100 | 1,866 | 356 | 3 | 123 | 820 | 5,402 | 1,840 | yes |
-| 500 | 1,770 | 1,393 | 3 | 211 | 3,220 | 25,484 | 1,747 | yes |
-
-`library-instances.sh` (many-processes model, `agent-turn` held 20 s):
-~47.8-48.2 MiB per instance flat at N=10/25/50 → roughly 42 instances per
-2 GiB by sum-RSS (upper bound; macOS has no PSS). The one-process fleet
-model is ~25x denser than the per-process model.
-
-Runtime/subagent scenarios: `skill-run` measures a real `node` child at
-~72-75 MB RSS (~121 MB process tree vs ~51 MB self) — the basis of the
-runtime-pooling issue (tinyhumansai/openhuman#5106); `subagent-storm` shows
-~0.78 MiB marginal per additional parallel subagent (K=8→32 cross-width).
-
-Runtime pool (#5106): with the shared pool on (the default), a batch of K
-concurrent `skill-run` turns shares a bounded set of warm `node` workers, so
-the process tree grows by ~one pooled worker instead of K interpreters.
-Measured at **K=8** (`max_workers=1`, system node v24): pooled tree
-`child_count=1` at **~202 MiB**, vs unpooled `child_count=8` at **~690 MiB**
-(eight `node` children of ~73–75 MB each) — a ~490 MiB / 3.4× reduction that
-grows with K. Compare the two regimes directly:
-
-```bash
-# Legacy: K interpreters resident at peak.
-OPENHUMAN_PROFILE_SKILL_RUN_CONCURRENCY=8 OPENHUMAN_PROFILE_SKILL_RUN_POOL=off \
- target/release/library-profile skill-run
-# Pooled: child_count stays at the pool size (asserted), not K.
-OPENHUMAN_PROFILE_SKILL_RUN_CONCURRENCY=8 OPENHUMAN_PROFILE_SKILL_RUN_POOL_WORKERS=1 \
- target/release/library-profile skill-run
-```
-
-The pool is configured in `[runtime_pool]` (master switch + per-language
-`node`/`python` `max_workers`, `idle_ttl_secs`, `recycle_after_jobs`,
-`max_queue_depth`); `enabled = false` reverts every caller to the legacy
-per-call spawn.
-
-The pool itself now lives in the `tinyruntime` module. That does **not** change
-what this scenario measures: a TinyBus module is a `cdylib` loaded into this
-process, so a worker it spawns is still a child of the host and still shows up in
-the process-tree sample the gate asserts on. What changed is which code spawns
-it. The configuration keys, the backpressure behaviour, and the
-`enabled = false` escape hatch are unchanged.
-
-Watch-items from the sweep: thread count grows ~0.35/agent (needs
-attribution + cap before real 1000-agent runs), and p95 latency at N=500 on
-2 workers shows CPU saturation is the load constraint, not memory.
-
-## See also
-
-- [`docs/resource-profiling-session-2026-07-21.md`](resource-profiling-session-2026-07-21.md) — the full manual investigation (deep attribution, cold-path CPU, library-design implications, recommended optimization order).
-- [`scripts/profile/README.md`](../scripts/profile/README.md) — script quick reference.
-- `src/bin/library_profile/main.rs` — the scenario implementations.
diff --git a/docs/library-minimal-recipe.md b/docs/library-minimal-recipe.md
deleted file mode 100644
index 1740e532f0..0000000000
--- a/docs/library-minimal-recipe.md
+++ /dev/null
@@ -1,246 +0,0 @@
-# Library-minimal feature recipe
-
-A **supported, measured** compile-time feature recipe for embedding the OpenHuman
-Rust core as a library in "opencompany" — headless, no RPC server, no Tauri
-shell, targeting 100-1000 live agents in a 2 GB RAM / 2 vCPU box.
-
-It follows the repo's existing slim convention (`cargo build --no-default-features
---features "<explicit list>"`, see AGENTS.md "Compile-time domain gates") and keeps
-only the domains the opencompany use cases actually exercise: **agent turns,
-subagent delegation, memory ingest, workflow (flows) runs, and python/js skill
-execution.**
-
-## The build command
-
-Opencompany recipe (production embed — no benchmark/harness code):
-
-```bash
-GGML_NATIVE=OFF cargo build --release \
- --no-default-features --features "skills,flows"
-```
-
-- `GGML_NATIVE=OFF` was the Apple-Silicon dev workaround for whisper-rs/llama.
- With whisper deleted it only matters for llama; on the x86-64 Linux target it
- is unnecessary anyway (the historical always-on whisper build used the
- AVX path). Keep it in the command for macOS developers.
-- To build the profiling harness against the same recipe, add the dev-only
- `rss-bench` feature and the two bench bins:
-
- ```bash
- GGML_NATIVE=OFF cargo build --release \
- --no-default-features --features "rss-bench,skills,flows" \
- --bin library-profile --bin rss-bench
- ```
-
-There is **no** `library-minimal` meta-feature in `Cargo.toml`, on purpose — see
-[Why no alias](#why-no-cargotoml-alias) below.
-
-## Keep / drop table
-
-The single `default` list this session was written against no longer exists.
-There are two sets now (AGENTS.md, "Compile-time domain gates"): **Contrib** is
-`[features] default`, what a bare `cargo check` compiles; **Product** is
-`scripts/ci/product-features.txt`, what the desktop app ships. Both columns
-below are current. `desktop-automation` has since been removed from the tree
-altogether, hence the dashes; `tui` is in neither set.
-
-Note how much of this recipe the contributor set already gives you for free —
-`voice`, `web3`, `meet` and `tui` are default-OFF today. The Decision column
-still records what a **library host** wants, which is the thing this document
-is actually for.
-
-| Gate | Contrib | Product | Decision | Why | Deps shed |
-| --- | :---: | :---: | :---: | --- | --- |
-| `skills` | ON | ON | **KEEP** | python/js `SKILL.md` execution is a stated opencompany use case | none (surface/prompt/startup only) |
-| `flows` | ON | ON | **KEEP** | saved-workflow (`flows_create`+`flows_run`) runs are a stated use case | — (adds `tinyflows`, `jaq-*`, `rhai`; see cost note) |
-| `voice` | OFF | ON | **DROP** | STT/TTS/dictation/podcast — a headless host does no audio I/O | `hound`, `lettre` |
-| `web3` | OFF | ON | **DROP** | crypto wallet / swap / x402 machine payments — not an opencompany path | `bitcoin`, `curve25519-dalek` |
-| `media` | ON | ON | **DROP** | `media_generate_*` image/video tools — surface-only | none (backend-proxied) |
-| `meet` | OFF | ON | **DROP** | Google-Meet join/live-STT/TTS bot — no headless use | none |
-| `mcp` | ON | ON | **DROP** | MCP stdio/HTTP server + Smithery registry (~20k LOC, ~19 tools) — a library host is not an MCP host | none (hand-rolled over tokio/reqwest/axum) |
-| `desktop-automation` | — | — | **DROP** | AX / `computer` tool family drives a **local desktop UI** — meaningless headless | `uiautomation` |
-| `tui` | OFF | — | **DROP** | `openhuman tui`/`chat` terminal UI — no terminal in a library host | `ratatui`, `crossterm`, `unicode-width` |
-
-**Non-default optional features** (`sandbox-landlock`, `sandbox-bubblewrap`,
-`peripheral-rpi`, `browser-native`/`fantoccini`, `landlock`, `whatsapp-web`,
-`e2e-test-support`, `rss-bench`, `rss-bench-dhat`) are all default-OFF, so a
-`--no-default-features` build never links them unless explicitly added. None are
-needed for opencompany; `rss-bench`/`rss-bench-dhat` are dev/benchmark-only.
-
-## Measured results
-
-All numbers gathered on this branch, Apple-Silicon macOS, `--release` profile
-(`optimized + debuginfo`). "default" = the prior 2026-07-21 session baselines in
-[`docs/library-benchmarking.md`](library-benchmarking.md); "pure slim" =
-`--no-default-features --features rss-bench` (drops everything). Both slim numbers
-were reproduced on this machine and match the prior doc exactly (68.4 MiB).
-
-### Binary size
-
-| Build | Features | Unstripped | Stripped |
-| --- | --- | ---: | ---: |
-| default | (all gates) | 115.9 MiB¹ | — |
-| **library-minimal** | `skills,flows` | **~81.1 MiB** | **~60.4 MiB** |
-| pure slim | (none) | 68.4 MiB | 51.0 MiB |
-
-¹ from the prior session (unstripped, same profile). library-minimal bins measured
-directly: `rss-bench` 81.1 MiB, `library-profile` 83.0 MiB unstripped (the extra
-~2 MiB is the harness itself). The domain recipe (`skills,flows`, no `rss-bench`)
-matches the `rss-bench` figure — the bench feature adds negligible code.
-
-- **library-minimal vs default: -34.8 MiB (~30% smaller)**, and a correspondingly
- narrower code-paging surface (the dominant cold-turn RSS factor per the prior
- session's executable-paging finding).
-- **library-minimal vs pure slim: +12.7 MiB unstripped / +9.4 MiB stripped — all
- of it `flows`.** `cargo tree` confirms the delta is `rhai 1.25` + `rhai_codegen`
- + `jaq-core/std/json` + `tinyflows`; `skills` sheds **zero** deps (its value is
- tool-surface/prompt/startup, not size). `flows` is by far the most expensive
- domain we *keep* — see follow-up #2.
-
-### Per-scenario RSS (5 fresh-process repeats, median, `OPENHUMAN_PROFILE_FORCE_UTC=1`)
-
-| Scenario | minimal settled | minimal retained Δ | default settled² | default retained² | Δ settled |
-| --- | ---: | ---: | ---: | ---: | ---: |
-| `agent-turn` (cold, 1 turn) | 44.0 MiB | 26.6 MiB | 47.6 MiB | 29.5 MiB | **-3.6 MiB** |
-| `subagents` (cold, 2 children) | 44.5 MiB | 27.1 MiB | 48.0 MiB | 29.9 MiB | **-3.5 MiB** |
-| `workflow` (`flows_create`+`flows_run`) | 46.2 MiB | 26.0 MiB | 50.9 MiB | 29.9 MiB | **-4.7 MiB** |
-| `memory-ingest` (100 msgs) | 24.7 MiB | 8.8 MiB | 25.8 MiB | 9.3 MiB | **-1.1 MiB** |
-| `long-agent` (10 turns) | 46.4 MiB | 2.9 MiB | — (25-turn: 65.8 MiB) | — | n/a³ |
-
-² default column from `docs/library-benchmarking.md` (2026-07-21). Those medians
-may not have used `OPENHUMAN_PROFILE_FORCE_UTC=1`, so treat the Δ as approximate
-(±~1 MiB). The direction and magnitude match the prior session's "slim saves
-~3.2 MiB settled RSS" finding.
-
-³ `long-agent` was run at 10 turns here vs 25 in the default baseline, so the
-absolute settled figures aren't comparable. The low 2.9 MiB retained Δ confirms
-per-turn growth plateaus (matches the prior "not linear" observation).
-
-**Takeaway (consistent with the prior session):** compile-time gates shrink the
-*binary* substantially (-30%) but move *settled RSS* by only ~3-5 MiB per
-scenario. Most of the RSS story is initialization + allocator high-water, not
-linked code size. The binary/code-paging win is the primary reason to prefer this
-recipe; the RSS win is real but secondary.
-
-## What is functionally absent in this build
-
-Summarized from the per-gate behavior notes in AGENTS.md. Dropped domains fail
-*closed and cleanly* — controllers become unknown-method, tools are simply absent
-from the tool list (not degraded to runtime errors), CLI subcommands report a
-build-fact error:
-
-- **voice/audio:** voice + audio controllers unregistered (unknown-method over
- RPC, absent from `/schema`); `audio_generate_podcast` tools absent; `openhuman
- voice` returns "voice disabled".
-- **web3:** wallet / web3 / x402 controllers unregistered; swap/bridge/dapp agent
- tools absent; the x402 402-retry path returns unpaid.
-- **media:** `media_generate_*` agent tools absent.
-- **meet:** meet controllers unregistered; live Meet bot / STT-LLM-TTS loop absent.
-- **mcp:** `mcp_server` / `mcp_registry` (`mcp_clients` namespace) / `mcp_audit`
- controllers unknown-method; ~19 MCP agent tools absent; `openhuman mcp` CLI
- returns a "rebuild with --features mcp" build-fact error. (`McpHttpClient` +
- `sanitize` stay compiled — the gitbooks docs tool and the orchestrator prompt
- sanitizer still work.)
-- **desktop-automation:** `accessibility` / `autocomplete`
- / `desktop_companion` domains + the `computer` tool family (`ax_interact`,
- `automate`, mouse/keyboard) absent.
-- **tui:** `openhuman tui` / `chat` returns "tui feature disabled at compile time".
-
-Everything the opencompany use cases need remains: the agent harness + turn
-runner, subagent delegation (`spawn_parallel_agents`), the full memory stack
-(TinyCortex store/tree/queue/ingest + PII/injection detectors), threads, config,
-security policy, provider routing/inference, `skills` (SKILL.md discovery/install
-+ node/python execution + `run_workflow`/`await_workflow`), and `flows` (saved
-graph create/run/schedule + `workflow_builder`/`flow_discovery` agents).
-
-## Test verification
-
-The disabled-build test gotcha (AGENTS.md: CI's smoke lane runs `cargo check`
-only and never compiles `--no-default-features` test code) was checked directly:
-
-```bash
-GGML_NATIVE=OFF cargo test --lib --no-default-features --features "skills,flows" core::
-# result: ok. 660 passed; 0 failed; 1 ignored; 10513 filtered out
-```
-
-The both-ways gate tests in `src/core/all_tests.rs` (which assert dropped domains
-become unknown-method) pass under this recipe. No pre-existing failures.
-
-## CI note
-
-Nothing is added to the `default` feature list — this is a **subtractive**
-`--no-default-features` recipe, not a new default-ON gate. The **Feature
-Forwarding Gate** (`scripts/ci/check-feature-forwarding.mjs`) only inspects the
-`default` list and its forwarding into the desktop shell's `Cargo.toml`, so it
-**does not apply** here: there is nothing to forward. This recipe carries no CI
-risk and needs no `INTENTIONALLY_NOT_FORWARDED` entry.
-
-## Why no `Cargo.toml` alias
-
-The repo convention (AGENTS.md "Slim-profile convention") is deliberate: **no
-`full` meta-feature; build slim variants with an explicit feature list.** A
-`library-minimal = ["skills","flows"]` alias would be convenient, but it:
-
-- duplicates the `default` list's maintenance burden — a new default-ON gate that
- opencompany *should* pick up would silently be missing from a frozen alias
- (the exact failure mode the "no meta-feature" rule exists to avoid), and
-- hides the subtractive intent behind a name, making the drop set invisible at
- the call site.
-
-**Recommendation: document the explicit list (this file), do not add the alias.**
-If maintainers later decide an alias is worth it, the minimal-drift option is to
-express it *subtractively* in tooling rather than as a frozen additive list —
-but that is a follow-up decision, not part of this recipe.
-
-## Follow-up shed list (ranked)
-
-Largest remaining always-on costs a headless library host does not need. These
-are **not implemented here** — they require new gates/refactors — listed for
-prioritization.
-
-1. ~~**`inference` gate → shed `whisper-rs` + `whisper-rs-sys` (+ `cpal`/`coreaudio`).**~~
- **DONE, and better than proposed.** The bundled whisper.cpp STT engine was not
- gated — it was **deleted**. `whisper-rs` / `whisper-rs-sys` (and the
- `[patch.crates-io] whisper-rs-sys` fork entries in both Cargo worlds) are gone
- from every build, not just the slim one, and with them the whisper.cpp + GGML
- C++ static link that was the reason for the `GGML_NATIVE=OFF` build dance.
- Speech-to-text is a hosted call now, with the engine chosen by
- `voice_server.stt_engine` (see the AGENTS.md scope note). The `inference`
- feature survives with a narrower job: it gates `cpal` alone, which is what a
- headless library host wanted shed anyway.
-
-2. **Split `rhai` out of the `flows` gate.** `flows` is the most expensive domain
- we *keep* (+12.7 MiB, dominated by `rhai 1.25` — a full scripting engine).
- `rhai` arrives only via `tinyagents/repl`, which powers the `.ragsh`
- language-workflow tool (`rhai_workflows`). If opencompany needs `tinyflows`
- saved-graph runs but **not** the `.ragsh` rhai tool, splitting `rhai_workflows`
- into its own sub-gate would reclaim most of that 12.7 MiB while keeping the
- flows graph engine. Currently all-or-nothing.
-
-3. ~~**`git2` (vendored libgit2).**~~ — **no longer applicable.** This entry
- proposed gating the git-backed `memory_diff` change ledger. That went further:
- the `memory-git` gate, the `memory::diff` RPC surface and the `memory_diff`
- agent tool were deleted outright, so `git2` — with `libgit2-sys` and
- `libz-sys` — is absent from every profile rather than merely gateable.
- `cargo tree -i git2` finds no package. tinycortex still owns the only libgit2
- code in the stack and keeps its `git-diff` / `wiki-git` features; nothing in
- this repository enables them.
-
-4. **`reqwest` dual TLS backends.** The root `reqwest` enables both `rustls-tls`
- **and** `native-tls` — two full TLS stacks linked simultaneously. A headless
- host on a known target could pick one, shedding the other.
-
-5. ~~**Node/Python runtime bootstrap deps**~~ — **no longer applicable.**
- Downloading and unpacking language toolchains moved into the `tinyruntime`
- module, so `xz2` and its liblzma build left this manifest entirely. `tar`,
- `zip`, and `flate2` remain, but for the Piper voice installer and the document
- tools rather than for any runtime bootstrap; they are sheddable with those
- features, not with `skills`.
-
-## See also
-
-- [`docs/library-benchmarking.md`](library-benchmarking.md) — the benchmark
- environment, scenario definitions, and default/slim baselines.
-- [`docs/resource-profiling-session-2026-07-21.md`](resource-profiling-session-2026-07-21.md)
- — deep memory/CPU attribution (why RSS is mostly not live heap).
-- AGENTS.md "Compile-time domain gates" — the per-gate behavior and dependency notes.
diff --git a/docs/mascot.gif b/docs/mascot.gif
deleted file mode 100644
index c10168ce20..0000000000
Binary files a/docs/mascot.gif and /dev/null differ
diff --git a/docs/plans/2026-07-24-appimage-sharun-lib-path.md b/docs/plans/2026-07-24-appimage-sharun-lib-path.md
deleted file mode 100644
index dc2940700b..0000000000
--- a/docs/plans/2026-07-24-appimage-sharun-lib-path.md
+++ /dev/null
@@ -1,943 +0,0 @@
-# AppImage sharun library-path repair implementation plan
-
-> Approved design:
-> `docs/specs/2026-07-24-appimage-sharun-lib-path-design.md` at
-> `baae2b02c73e48826e156a111b7e8aff82f214b9`.
-
-## Goal
-
-Repair the Linux AppImage postprocessor so sharun's generated
-`shared/lib/lib.path` contains only AppDir-anchored `+` entries, reject malformed
-paths before release, and prove that the final repacked amd64 AppImage reaches
-normal application startup when invoked from outside its extracted AppDir.
-
-The implementation changes only the AppImage release path:
-
-- `scripts/release/strip-appimage-graphics-libs.sh`
-- `scripts/release/test-strip-appimage-rpaths.sh`
-- a new final-artifact validator at
- `scripts/release/validate-appimage-runtime.sh`
-- the Linux portion of `.github/workflows/build-desktop.yml`
-
-The existing graphics-library removal, interpreter replacement, RPATH repair,
-artifact signing, updater tarball rebuilding, x86_64/aarch64 build matrix, and
-non-Linux workflow branches remain in place.
-
-## Scope guardrails
-
-This plan intentionally does **not** implement the broader generated triage plan
-currently embedded in issue #5037:
-
-- The unbundled `openhuman-core`/AUR failure remains a downstream packaging and
- optional-`enigo` follow-up. Do not change `Cargo.toml`, feature gates, voice
- input, computer tools, `INSTALL.md`, or AUR metadata in this work.
-- Do not change bundled `libssl.so.3`/`libcrypto.so.3`, NSS exclusions, or claim
- to fix the later OpenSSL symbol-skew/segfault behavior in #3716. The smoke
- catches an immediate loader failure, not every later CEF/OpenSSL crash.
-- Do not pin the mutable `quick-sharun.sh` or uruntime downloads in the vendored
- Tauri bundler. Supply-chain pinning is a separate follow-up.
-- Do not add an Arch/Fedora/Tumbleweed matrix or make
- `.github/workflows/pr-quality.yml`'s advisory AppImage guard blocking. The
- release-builder smoke is the selected acceptance test.
-- Do not replace sharun with a custom `LD_LIBRARY_PATH` wrapper.
-
-## Confirmed sharun contract
-
-Pin the tests and implementation to the actual sharun grammar:
-
-- `shared/lib/lib.path` is one entry per line.
-- `+` represents the directory containing `lib.path`, which is the extracted
- AppDir's canonical `shared/lib` directory.
-- `+/subdir` represents a descendant of that directory.
-- sharun trims the complete file, replaces newlines with `:`, and then replaces
- every `+` with the absolute `shared/lib` path.
-- `+` is therefore a marker inside an entry, **not** an entry delimiter.
-
-The current `tr '+:' '\n\n'` parser destroys this marker and must be removed.
-Tests must use the accepted textual forms `+` and `+/subdir`, with newline
-separation. They must not introduce an invented plus- or colon-separated input
-format.
-
-## Sequencing decision
-
-`strip-appimage-graphics-libs.sh` currently performs four phases in one command:
-
-1. extract and postprocess an AppDir;
-2. repack and replace the final `.AppImage`;
-3. re-sign the `.AppImage`;
-4. rebuild and re-sign its updater tarball.
-
-The final-artifact validator must run after phase 2 but before phase 3. Add the
-validator call immediately after the rebuilt file is moved over the original
-and before the image is appended to `MODIFIED_PATHS`. This satisfies both
-requirements that the inspected bytes are the uploaded bytes and that a bad
-launcher fails before signing. It also avoids a defer/finalize mode that could
-accidentally validate one image and then repack another.
-
-Static validation runs for every Linux AppImage. The executable smoke is
-enabled only for `x86_64-unknown-linux-gnu` in this issue because that is the
-reported architecture and acceptance target. The helper remains
-architecture-neutral: a later change can enable the same smoke on arm64 by
-setting the same environment flag on an executable arm64 runner.
-
----
-
-## Task 1: Replace the destructive parser with sharun-native normalization
-
-**Files:**
-
-- Modify: `scripts/release/test-strip-appimage-rpaths.sh`
-- Modify: `scripts/release/strip-appimage-graphics-libs.sh`
-
-### Step 1.1: Add failing normalization fixtures
-
-Extend `test-strip-appimage-rpaths.sh` after the host-ELF fixture is established
-and the target script is sourced. Add a reusable released-style AppDir builder:
-
-```bash
-make_sharun_appdir() {
- local appdir="$1"
- mkdir -p "$appdir/shared/bin" "$appdir/shared/lib/plugins" "$appdir/bin"
-
- cp "$HOST_ELF" "$appdir/sharun"
- printf 'Interpreter not found!' >> "$appdir/sharun"
- chmod +x "$appdir/sharun"
- ln "$appdir/sharun" "$appdir/AppRun"
- ln "$appdir/sharun" "$appdir/bin/OpenHuman"
-
- cp "$HOST_ELF" "$appdir/shared/bin/OpenHuman"
- chmod +x "$appdir/shared/bin/OpenHuman"
-}
-```
-
-Use separate fixture directories so one failure cannot contaminate the next.
-Add these assertions:
-
-1. An input with one entry
- `"$WORK/squashfs-root/shared/lib"` rewrites to exactly `+`.
-2. An input rooted in the bundler staging layout
- `"$WORK/appimage_deb/data/usr/lib"` rewrites to exactly `+`.
-3. AppDir descendants map as follows:
- - `"$WORK/squashfs-root/shared/lib/plugins"` becomes `+/plugins`;
- - `"$WORK/appimage_deb/data/usr/lib/plugins"` becomes `+/plugins`.
-4. A file containing these newline-delimited entries:
-
- ```text
- +
- +/plugins
- +
- /opt/unrelated/lib
- ```
-
- normalizes to exactly:
-
- ```text
- +
- +/plugins
- ```
-
- Stable first-seen order is preserved and the unrelated host path is
- excluded.
-
-5. Running `rewrite_sharun_lib_path` a second time leaves the bytes unchanged
- and returns the no-change status expected by `strip_one_appimage`.
-6. An input containing only `/opt/unrelated/lib` fails normalization and is not
- replaced with `shared/lib`.
-
-Capture expected failures in subshells because the release helpers are allowed
-to terminate fail-closed:
-
-```bash
-if ( rewrite_sharun_lib_path "$fixture" ) 2>"$WORK/rewrite.err"; then
- fail "rewrite accepted a lib.path with no AppDir library root"
-fi
-grep -F "no valid AppDir library entries" "$WORK/rewrite.err" >/dev/null \
- || fail "rewrite failure did not explain why lib.path was rejected"
-```
-
-Run the focused test on Linux:
-
-```bash
-bash scripts/release/test-strip-appimage-rpaths.sh
-```
-
-Expected RED: at least the canonical-marker case fails because the current
-implementation splits on `+` and writes `shared/lib`; the no-valid-root case
-also fails because the current fallback silently writes `shared/lib`.
-
-On macOS, first run:
-
-```bash
-bash scripts/release/test-strip-appimage-rpaths.sh
-```
-
-Expected local result: a clean `SKIP` when `patchelf` or a host ELF is
-unavailable. Do not treat that skip as execution evidence; the RED/GREEN result
-for this task must come from the existing Ubuntu PR job or another Linux host.
-
-### Step 1.2: Implement newline-based normalization
-
-Refactor `rewrite_sharun_lib_path` without changing its public signature:
-
-```bash
-rewrite_sharun_lib_path() {
- local appdir="$1"
- # Return 1 for non-sharun/no-file/no-change.
- # Return 0 after writing a changed valid file.
- # Exit non-zero with an ERROR for malformed input from which no valid
- # AppDir-rooted entry can be derived.
-}
-```
-
-Implement the following exact algorithm:
-
-1. Keep the `uses_sharun_launcher` and non-empty-file guards.
-2. Read with `while IFS= read -r entry || [ -n "$entry" ]`; do not use `tr`,
- word splitting, `eval`, or colon splitting.
-3. Reject empty interior lines, carriage returns, embedded `:`, and surrounding
- whitespace as malformed rather than letting the loader interpret them
- differently from the validator.
-4. Normalize each entry:
- - `+` stays `+`;
- - `+/suffix` stays `+/suffix` after the descendant checks in Task 2;
- - an absolute path containing `/squashfs-root/shared/lib` maps that root to
- `+` and its suffix to `+/suffix`;
- - an absolute path containing `/appimage_deb/data/usr/lib` or `/data/usr/lib`
- maps that root to `+` and its suffix to `+/suffix`;
- - another absolute path is dropped;
- - a bare relative path is malformed and causes normalization to fail.
-5. For derived suffixes, remove one leading slash and no other content. A root
- with an empty suffix becomes `+`.
-6. Deduplicate using exact whole-entry equality while preserving first-seen
- order. Use an indexed Bash array and a small equality loop so the script
- remains syntax-compatible with macOS Bash 3.2; do not introduce associative
- arrays.
-7. If no valid AppDir-rooted entries remain, print:
-
- ```text
- [strip-libs] ERROR: shared/lib/lib.path contains no valid AppDir library entries
- ```
-
- and return non-zero without modifying the file.
-
-8. Join entries with newline characters and write through a temporary file in
- the same directory followed by `mv`. Preserve the final format as one entry
- per line; a trailing newline is acceptable but must be deterministic.
-9. Compare the normalized temporary file with the original using `cmp -s`.
- Delete the temporary and return `1` on an idempotent no-op. On change, move
- it into place, log the normalized entries, and return `0`.
-
-Remove the early grep that only invokes rewriting when `/home/runner` or `/__w`
-is present. Valid marker files still need the idempotency path, and malformed
-bare-relative files must not bypass normalization.
-
-### Step 1.3: Run the GREEN checks
-
-Linux:
-
-```bash
-bash -n scripts/release/strip-appimage-graphics-libs.sh
-bash -n scripts/release/test-strip-appimage-rpaths.sh
-bash scripts/release/test-strip-appimage-rpaths.sh
-```
-
-Expected GREEN: all old RPATH/required-library tests and all new normalization
-cases pass.
-
-macOS:
-
-```bash
-bash -n scripts/release/strip-appimage-graphics-libs.sh
-bash -n scripts/release/test-strip-appimage-rpaths.sh
-bash scripts/release/test-strip-appimage-rpaths.sh
-```
-
-Expected: both syntax checks pass and the execution test skips cleanly if Linux
-ELF tooling is absent.
-
-### Step 1.4: Commit the normalization
-
-```bash
-atomic-commit "fix(appimage): emit sharun-native library paths" -- \
- scripts/release/test-strip-appimage-rpaths.sh \
- scripts/release/strip-appimage-graphics-libs.sh
-```
-
----
-
-## Task 2: Make `lib.path` validation fail closed and cover the shipped ELF launcher
-
-**Files:**
-
-- Modify: `scripts/release/test-strip-appimage-rpaths.sh`
-- Modify: `scripts/release/strip-appimage-graphics-libs.sh`
-
-### Step 2.1: Add failing validator and launcher-layout cases
-
-Reuse `make_sharun_appdir` and add a table-driven helper:
-
-```bash
-assert_lib_path_rejected() {
- local label="$1"
- local value="$2"
- local expected_entry="$3"
- local fixture="$WORK/reject-$label"
- make_sharun_appdir "$fixture"
- printf '%s\n' "$value" >"$fixture/shared/lib/lib.path"
-
- if ( validate_sharun_lib_path "$fixture" ) 2>"$fixture/error.log"; then
- fail "validate_sharun_lib_path accepted $label"
- fi
- grep -F "$expected_entry" "$fixture/error.log" >/dev/null \
- || fail "$label error did not identify offending entry '$expected_entry'"
-}
-```
-
-Add rejection cases for:
-
-- `shared/lib` (bare relative);
-- `/home/runner/work/openhuman/squashfs-root/shared/lib` (CI absolute);
-- `/__w/openhuman/openhuman/appimage_deb/data/usr/lib` (CI absolute);
-- `+/../outside` (parent traversal);
-- `+/plugins/../../outside` (nested traversal);
-- `+/missing` (marker-relative directory absent from the fixture);
-- `+/plugins:shared/lib` (embedded loader separator);
-- ` +` and `+ ` (whitespace changes loader semantics).
-
-Each error assertion must match the complete offending entry in the diagnostic,
-not only a generic error category.
-
-Add accepted cases:
-
-- `+`;
-- `+` followed by `+/plugins` on a new line;
-- a normalized file passed twice, proving validation is non-mutating.
-
-Add explicit released-layout assertions:
-
-```bash
-[ "$fixture/AppRun" -ef "$fixture/sharun" ] \
- || fail "AppRun fixture is not hard-linked to sharun"
-[ "$fixture/bin/OpenHuman" -ef "$fixture/sharun" ] \
- || fail "bin/OpenHuman fixture is not hard-linked to sharun"
-is_executable_elf "$fixture/AppRun" \
- || fail "released-style AppRun fixture is not ELF"
-uses_sharun_launcher "$fixture" \
- || fail "released-style hard-linked ELF launcher was not detected"
-```
-
-Write `+` to its `lib.path`, validate it, change to an unrelated directory, and
-model sharun's pinned expansion:
-
-```bash
-caller="$WORK/caller"
-mkdir -p "$caller"
-(
- cd "$caller"
- expanded="$(
- sed "s|+|$fixture/shared/lib|g" "$fixture/shared/lib/lib.path" |
- paste -sd ':' -
- )"
- [ "$expanded" = "$fixture/shared/lib" ] \
- || fail "sharun marker did not expand beneath the fixture AppDir"
-)
-```
-
-Also assert that `patch_apprun_sharun_cwd "$fixture"` returns its no-change
-status and does not mutate the ELF inode. This pins the compatibility helper as
-shell-wrapper-only hardening, not the fix for released ELF AppRuns.
-
-Run on Linux:
-
-```bash
-bash scripts/release/test-strip-appimage-rpaths.sh
-```
-
-Expected RED: the current validator accepts bare relatives, traversal, missing
-directories, and an ELF AppRun without any meaningful library-path checks.
-
-### Step 2.2: Implement exact fail-closed validation
-
-Keep the `validate_sharun_lib_path "$appdir"` interface. Parse the file by
-newline using the same helper/loop as normalization so rewrite and validation
-cannot disagree.
-
-For every non-empty entry:
-
-1. Accept only `+` or a string beginning `+/`.
-2. Reject `:`, carriage returns, leading/trailing whitespace, absolute paths,
- and bare relative paths.
-3. Split the marker-relative suffix on `/` and reject empty, `.`, or `..`
- components. This rejects traversal before filesystem canonicalization.
-4. Resolve `+` to `$appdir/shared/lib`; resolve `+/suffix` to
- `$appdir/shared/lib/suffix`.
-5. Require the resolved path to be a directory.
-6. Canonicalize both the library root and resolved directory with `realpath`,
- then require the result to equal the root or start with
- `"$canonical_root/"`. This prevents an in-tree symlink from escaping the
- AppDir even when the textual path contains no `..`.
-7. On failure, print one line with the offending entry:
-
- ```text
- [strip-libs] ERROR: invalid sharun lib.path entry '<entry>': <reason>
- ```
-
- and return/exit non-zero before repacking.
-
-Require at least one entry and retain the existing missing-file diagnostic.
-Do not mutate the file in validation.
-
-Update the comment above `patch_apprun_sharun_cwd` and its success/warning logs:
-
-- state that valid `+` paths are the primary released-layout fix;
-- state that the helper remains for historical shell `AppRun` layouts;
-- remove claims that changing CWD is required for an ELF sharun launcher;
-- preserve the current shell patch behavior and return convention.
-
-### Step 2.3: Run GREEN checks
-
-Linux:
-
-```bash
-bash -n scripts/release/strip-appimage-graphics-libs.sh
-bash scripts/release/test-strip-appimage-rpaths.sh
-```
-
-Expected GREEN: accepted marker paths pass; every malformed entry fails with
-the exact entry in stderr; the ELF hard-link fixture is detected and remains
-unchanged by the shell compatibility patch.
-
-macOS:
-
-```bash
-bash -n scripts/release/strip-appimage-graphics-libs.sh
-bash -n scripts/release/test-strip-appimage-rpaths.sh
-bash scripts/release/test-strip-appimage-rpaths.sh
-```
-
-Expected: syntax passes and the execution test cleanly skips if required.
-
-### Step 2.4: Commit fail-closed validation
-
-```bash
-atomic-commit "test(appimage): reject malformed sharun library paths" -- \
- scripts/release/test-strip-appimage-rpaths.sh \
- scripts/release/strip-appimage-graphics-libs.sh
-```
-
----
-
-## Task 3: Inspect and smoke-test the final repacked AppImage before signing
-
-**Files:**
-
-- Create: `scripts/release/validate-appimage-runtime.sh`
-- Modify: `scripts/release/test-strip-appimage-rpaths.sh`
-- Modify: `scripts/release/strip-appimage-graphics-libs.sh`
-
-### Step 3.1: Add failing tests for extracted-layout validation
-
-The new script must be sourceable for fixture tests and executable for a real
-AppImage. Before implementing it, extend
-`test-strip-appimage-rpaths.sh` to source it after sourcing the postprocessor:
-
-```bash
-RUNTIME_VALIDATOR="$SCRIPT_DIR/validate-appimage-runtime.sh"
-[ -f "$RUNTIME_VALIDATOR" ] \
- || fail "$RUNTIME_VALIDATOR not found"
-# shellcheck source=/dev/null
-source "$RUNTIME_VALIDATOR"
-```
-
-Add fixture tests for the function interface:
-
-```bash
-validate_extracted_appdir "$appdir"
-validate_final_appimage "$appimage"
-smoke_extracted_apprun "$appdir" "$foreign_cwd" "$log_file"
-```
-
-`validate_extracted_appdir` is the unit-test seam; it must not extract or launch
-anything. Build a complete fixture with:
-
-- hard-linked ELF `AppRun`, `sharun`, and `bin/OpenHuman`;
-- executable ELF `shared/bin/OpenHuman`;
-- `shared/lib/lib.path` containing `+`;
-- `shared/lib/anylinux.so`;
-- `shared/lib/libxdo.so.3`;
-- `shared/lib/libcef.so`;
-- clean RPATHs on all copied ELFs.
-
-Because `/bin/true` does not naturally declare the production `NEEDED`
-libraries, make the needed-name check injectable only in fixture mode:
-
-```bash
-APPIMAGE_EXPECTED_NEEDED="${APPIMAGE_EXPECTED_NEEDED:-libxdo.so.3 libcef.so}"
-```
-
-Set `APPIMAGE_EXPECTED_NEEDED=""` only around unit fixtures. The executable CLI
-and release workflow must leave the production default intact.
-
-Assert the complete fixture passes. Then clone it into isolated cases and
-assert rejection when:
-
-- `anylinux.so` is absent;
-- `libxdo.so.3` is absent;
-- `libcef.so` is absent;
-- `shared/bin/OpenHuman` is absent or is not ELF;
-- `AppRun` is neither the same inode nor byte-equivalent to `sharun`;
-- `bin/OpenHuman` is neither the same inode nor byte-equivalent to `sharun`;
-- an ELF RPATH contains
- `/home/runner/work/openhuman/openhuman/shared/lib`;
-- an ELF RPATH contains `/__w/openhuman/openhuman/shared/lib`;
-- the real app's `NEEDED` list lacks `libxdo.so.3`;
-- the real app's `NEEDED` list lacks `libcef.so`.
-
-For equivalent launcher support, copy rather than hard-link `sharun` to
-`AppRun` and `bin/OpenHuman`; byte-identical executable copies must pass. This
-covers a repacker that preserves launcher contents but not hard-link metadata.
-
-Add a source-order regression that invokes a stub validator from
-`strip_one_appimage` and proves it runs after the final `mv` but before the path
-is appended to `MODIFIED_PATHS`. Do this through an overridable command:
-
-```bash
-APPIMAGE_RUNTIME_VALIDATOR="${APPIMAGE_RUNTIME_VALIDATOR:-$SCRIPT_DIR/validate-appimage-runtime.sh}"
-```
-
-The test stub must record that the supplied final path exists and that
-`MODIFIED_PATHS` is still empty. Do not execute or repack a real AppImage in
-this unit test; factor the post-repack handoff into:
-
-```bash
-validate_rebuilt_appimage() {
- local rebuilt_path="$1"
- "$APPIMAGE_RUNTIME_VALIDATOR" "$rebuilt_path"
-}
-```
-
-Call this seam directly with a fixture file to pin its command/argument
-contract, and use a source-text order assertion for the three adjacent
-statements:
-
-```text
-mv "$rebuilt" "$original"
-validate_rebuilt_appimage "$original"
-MODIFIED_PATHS+=("$original")
-```
-
-Run on Linux:
-
-```bash
-bash scripts/release/test-strip-appimage-rpaths.sh
-```
-
-Expected RED: the validator file/functions and the post-repack handoff do not
-exist.
-
-### Step 3.2: Implement the sourceable final-artifact validator
-
-Create `scripts/release/validate-appimage-runtime.sh` with `set -euo pipefail`,
-three shell functions, and a direct-execution guard. The exact interfaces are:
-
-- `validate_extracted_appdir "$appdir"` performs the eight ordered static checks
- immediately below.
-- `smoke_extracted_apprun "$appdir" "$foreign_cwd" "$log_file"` performs the
- eight ordered launch checks immediately below.
-- `validate_final_appimage "$image"` performs the five ordered extraction
- checks immediately below.
-
-Use this direct-execution guard:
-
-```bash
-if [ "${BASH_SOURCE[0]}" = "$0" ]; then
- [ "$#" -eq 1 ] || {
- echo "Usage: $0 <final.AppImage>" >&2
- exit 2
- }
- validate_final_appimage "$1"
-fi
-```
-
-Do not duplicate `lib.path` grammar. Resolve the script directory and source
-`strip-appimage-graphics-libs.sh`, whose direct-execution guard prevents
-`main()` from running. Reuse:
-
-- `is_elf`;
-- `is_executable_elf`;
-- `uses_sharun_launcher`;
-- `validate_sharun_lib_path`;
-- `validate_appimage_required_libs`.
-
-Implement `validate_extracted_appdir "$appdir"` as follows:
-
-1. Print the extracted path and the normalized `lib.path` contents with each
- line prefixed for readable CI logs.
-2. Require `uses_sharun_launcher "$appdir"`.
-3. Require ELF executables at `AppRun`, `sharun`, `bin/OpenHuman`, and
- `shared/bin/OpenHuman`.
-4. For both launcher aliases, accept either `[ alias -ef sharun ]` or
- `cmp -s alias sharun`; reject anything else.
-5. Call `validate_sharun_lib_path` and
- `validate_appimage_required_libs`.
-6. Add `anylinux.so` to the required-library contract in
- `validate_appimage_required_libs`; its missing diagnostic must identify the
- preload library separately from the existing libxdo/CEF diagnostics.
-7. Run `patchelf --print-needed "$appdir/shared/bin/OpenHuman"` and require each
- whitespace-delimited name in
- `${APPIMAGE_EXPECTED_NEEDED:-libxdo.so.3 libcef.so}` as an exact full line.
- Print the NEEDED list before checking it.
-8. Walk ELF files under `shared/bin`, `shared/lib`, `bin`, `lib`, `usr/bin`, and
- `usr/lib`. For each, read RPATH with `patchelf --print-rpath`; reject
- `/home/runner/` and `/__w/`. This is validation only: never patch the final
- artifact.
-
-`validate_final_appimage "$image"` must:
-
-1. Resolve the input with `realpath`, require an executable regular file, and
- require `patchelf`.
-2. Create one temporary root and a distinct `foreign-cwd` below it; install a
- trap that removes only that exact temporary root.
-3. Change into the foreign CWD before invoking
- `"$image" --appimage-extract`, redirecting extraction output to a log. This
- ensures extraction itself does not rely on the artifact directory.
-4. Require `$foreign_cwd/squashfs-root`, then call
- `validate_extracted_appdir` on it.
-5. If `APPIMAGE_RUNTIME_SMOKE=1`, call `smoke_extracted_apprun`; otherwise print
- an explicit architecture/static-only message.
-
-`smoke_extracted_apprun "$appdir" "$foreign_cwd" "$log_file"` must:
-
-1. Require `timeout` and `xvfb-run`.
-2. Print the AppDir and caller CWD.
-3. Create isolated `home`, `config`, `data`, and `cache` directories beneath
- the temporary root so the release smoke cannot read or mutate the runner's
- real OpenHuman state.
-4. Launch from `$foreign_cwd` with:
-
- ```bash
- timeout --signal=TERM --kill-after=5s 15s \
- xvfb-run -a --server-args="-screen 0 1280x960x24" \
- env \
- HOME="$smoke_home" \
- XDG_CONFIG_HOME="$smoke_config" \
- XDG_DATA_HOME="$smoke_data" \
- XDG_CACHE_HOME="$smoke_cache" \
- OPENHUMAN_CEF_PREWARM=0 \
- OPENHUMAN_DISABLE_GPU=1 \
- "$appdir/AppRun"
- ```
-
- Before `env`, unset `GITHUB_TOKEN`, `GH_TOKEN`,
- `TAURI_SIGNING_PRIVATE_KEY`, `TAURI_SIGNING_PRIVATE_KEY_PASSWORD`,
- `SENTRY_AUTH_TOKEN`, and all `OPENAI_*` variables present in the environment.
- Build the `env -u NAME` arguments from variable **names only**; never print
- values.
-
-5. Capture stdout/stderr in `$log_file` and preserve the timeout status despite
- `set -e`.
-6. Treat status `124` as success: the GUI remained alive through the bounded
- startup window. Treat any other status as failure, including an immediate
- clean exit, because it did not prove a live application boundary.
-7. Regardless of status, search the log case-insensitively for:
- - `anylinux.so` combined with `cannot be preloaded`;
- - `libxdo.so.3` combined with `cannot open shared object file`;
- - `libcef.so` combined with `cannot open shared object file`;
- - `error while loading shared libraries`.
-8. On a forbidden diagnostic or unexpected exit, print the complete smoke log
- and fail. On success, print only lines matching loader/CEF/startup keywords
- plus a message that the application remained alive for the startup window.
- This keeps logs useful without dumping inherited environment data.
-
-### Step 3.3: Call the validator after repack and before signing
-
-In `strip-appimage-graphics-libs.sh`:
-
-1. Define `SCRIPT_DIR` once from `BASH_SOURCE[0]`.
-2. Define
- `APPIMAGE_RUNTIME_VALIDATOR="${APPIMAGE_RUNTIME_VALIDATOR:-$SCRIPT_DIR/validate-appimage-runtime.sh}"`.
-3. Add `validate_rebuilt_appimage` with the exact one-argument forwarding
- contract above.
-4. In `strip_one_appimage`, change the final order to:
-
- ```bash
- mv "$rebuilt" "$original"
- validate_rebuilt_appimage "$original"
- rm -rf "$workdir"
- MODIFIED_PATHS+=("$original")
- ```
-
-Because `set -e` is active, any static or launch failure stops before
-`MODIFIED_PATHS` is populated and before `main` reaches `resign_artifact` or
-updater tarball rebuilding.
-
-Keep the intermediate AppDir validation at its current pre-repack location.
-It provides a faster diagnostic; the new call proves the repacked bytes.
-
-### Step 3.4: Run GREEN checks
-
-Linux unit/fixture lane:
-
-```bash
-bash -n scripts/release/strip-appimage-graphics-libs.sh
-bash -n scripts/release/validate-appimage-runtime.sh
-bash -n scripts/release/test-strip-appimage-rpaths.sh
-bash scripts/release/test-strip-appimage-rpaths.sh
-```
-
-Expected GREEN: extracted-layout fixtures cover required libraries, NEEDED
-names, RPATHs, equivalent/hard-linked launchers, and post-repack ordering.
-
-Linux real-artifact check, after building an amd64 AppImage:
-
-```bash
-APPIMAGE_RUNTIME_SMOKE=1 \
- bash scripts/release/validate-appimage-runtime.sh \
- app/src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage
-```
-
-If the artifact exists under the root target tree instead, use the one exact
-matching file under:
-
-```text
-target/x86_64-unknown-linux-gnu/release/bundle/appimage/
-```
-
-Do not pass multiple glob matches to the one-image CLI; fail the build if the
-bundle root unexpectedly contains zero or multiple amd64 AppImages.
-
-macOS:
-
-```bash
-bash -n scripts/release/strip-appimage-graphics-libs.sh
-bash -n scripts/release/validate-appimage-runtime.sh
-bash -n scripts/release/test-strip-appimage-rpaths.sh
-bash scripts/release/test-strip-appimage-rpaths.sh
-```
-
-Expected: syntax checks pass and the fixture suite skips cleanly without Linux
-ELF tooling. Do not attempt to execute the AppImage or claim runtime validation
-from macOS.
-
-### Step 3.5: Commit final-artifact validation
-
-```bash
-atomic-commit "fix(appimage): validate the repacked runtime before signing" -- \
- scripts/release/validate-appimage-runtime.sh \
- scripts/release/test-strip-appimage-rpaths.sh \
- scripts/release/strip-appimage-graphics-libs.sh
-```
-
----
-
-## Task 4: Enable the amd64 foreign-CWD smoke in the Linux desktop build
-
-**Files:**
-
-- Modify: `.github/workflows/build-desktop.yml`
-
-### Step 4.1: Establish the wiring gap
-
-Run:
-
-```bash
-rg -n 'APPIMAGE_RUNTIME_SMOKE|xvfb' .github/workflows/build-desktop.yml
-```
-
-Expected RED: the workflow neither installs Xvfb nor enables the final
-AppImage smoke.
-
-The behavior itself is already fixture-tested in Task 3. This task is declarative
-workflow wiring; validate it with YAML/action checks rather than duplicating the
-shell behavior in a YAML text test.
-
-### Step 4.2: Add Linux runtime prerequisites
-
-In `Install Tauri dependencies (ubuntu only)`, add `xvfb` to the existing
-`apt-get install -y` list. `timeout` is supplied by Ubuntu's existing
-`coreutils`; do not add another timeout package.
-
-Do not add these dependencies to macOS or Windows.
-
-### Step 4.3: Enable smoke only on the reported architecture
-
-Rename the existing step to:
-
-```text
-Strip host graphics libs and validate final AppImage
-```
-
-Keep its Linux-only `if:` expression, bundle-root arguments, target/profile
-variables, and signing secrets unchanged. Add:
-
-```yaml
-APPIMAGE_RUNTIME_SMOKE: ${{ matrix.settings.target == 'x86_64-unknown-linux-gnu' && '1' || '0' }}
-```
-
-The postprocessor now performs, in order:
-
-1. graphics stripping/interpreter/RPATH/lib.path repair;
-2. repack;
-3. final artifact extraction and static validation on both Linux architectures;
-4. foreign-CWD Xvfb smoke on amd64;
-5. signing and updater archive rebuilding.
-
-Do not use `continue-on-error`. Do not change the advisory status of
-`pr-quality.yml`; release/staging desktop callers already consume this reusable
-workflow and will fail before upload if the validator fails.
-
-Update the step comment to state that:
-
-- final-artifact validation occurs before re-signing;
-- amd64 launch is bounded and runs from a foreign CWD;
-- arm64 receives static validation in this change;
-- updater archives are still rebuilt only after the validated image is final.
-
-### Step 4.4: Validate workflow syntax and formatting
-
-Run whichever actionlint path the repository provides:
-
-```bash
-if command -v actionlint >/dev/null 2>&1; then
- actionlint .github/workflows/build-desktop.yml
-else
- echo "actionlint unavailable locally; rely on GitHub workflow validation"
-fi
-```
-
-Then run:
-
-```bash
-pnpm exec prettier --check .github/workflows/build-desktop.yml
-git diff --check
-```
-
-Expected GREEN: actionlint (when installed), Prettier, and whitespace checks
-pass.
-
-### Step 4.5: Commit workflow wiring
-
-```bash
-atomic-commit "ci(appimage): smoke-test the final amd64 launcher" -- \
- .github/workflows/build-desktop.yml
-```
-
----
-
-## Task 5: Run local checks and obtain Linux evidence
-
-**Files:**
-
-- No new files; verification only.
-
-### Step 5.1: Run the complete macOS-safe local gate
-
-From the worktree root:
-
-```bash
-bash -n scripts/release/strip-appimage-graphics-libs.sh
-bash -n scripts/release/validate-appimage-runtime.sh
-bash -n scripts/release/test-strip-appimage-rpaths.sh
-bash scripts/release/test-strip-appimage-rpaths.sh
-pnpm exec prettier --check \
- docs/plans/2026-07-24-appimage-sharun-lib-path.md \
- .github/workflows/build-desktop.yml
-git diff --check
-git status --short
-```
-
-Expected on macOS:
-
-- all three shell syntax checks pass;
-- the Linux fixture script reports `SKIP`, not `FAIL`, if `patchelf`/ELF is
- unavailable;
-- Prettier and `git diff --check` pass;
-- status contains no unrelated files.
-
-Do not run `pnpm format`, because it writes across the repository and can mix
-unrelated formatting into these atomic commits.
-
-### Step 5.2: Require Linux unit evidence
-
-The existing advisory PR-quality job must run:
-
-```bash
-bash -n scripts/release/strip-appimage-graphics-libs.sh
-bash scripts/release/test-strip-appimage-rpaths.sh
-```
-
-Confirm its log includes passing cases for:
-
-- CI/build path to `+`;
-- `+/subdir`, order, deduplication, and idempotency;
-- bare relative, absolute CI, traversal, missing-target, and symlink-escape
- rejection;
-- hard-linked/equivalent ELF launcher layout;
-- anylinux/libxdo/libcef presence;
-- NEEDED and RPATH validation.
-
-The job remains advisory by design, but a failure is still a blocker for this
-change.
-
-### Step 5.3: Require a real amd64 artifact run
-
-Run the reusable desktop build on an amd64 Ubuntu runner. The log from
-`Strip host graphics libs and validate final AppImage` must show:
-
-- final extracted AppDir path;
-- caller working directory outside that AppDir;
-- normalized `lib.path` containing `+` entries only;
-- `shared/bin/OpenHuman` NEEDED entries;
-- no CI/build-machine RPATHs;
-- presence of `anylinux.so`, `libxdo.so.3`, and `libcef.so`;
-- timeout status `124`, documented as the expected live-GUI boundary;
-- no preload or loader error for those three libraries;
-- signing/updater archive messages only after validation succeeds.
-
-Inspect the later upload step and confirm it consumes the same AppImage path
-that was validated. Do not substitute an intermediate `squashfs-root` run for
-this evidence.
-
-### Step 5.4: Final history and scope review
-
-Run:
-
-```bash
-git status --short
-git diff --check HEAD~4..HEAD
-git log --oneline -4
-git diff --stat baae2b02c..HEAD
-git diff --name-only baae2b02c..HEAD
-```
-
-Expected:
-
-- four atomic implementation commits after the approved spec;
-- only the four implementation paths named at the top of this plan changed;
-- no Cargo, AUR, OpenSSL, vendor pin, or PR-quality blocking changes;
-- no submodule pointer changes.
-
-If implementation discovers that sharun's bundled version uses a grammar
-different from the confirmed newline-plus contract, stop and amend the design
-with artifact/source evidence before changing the parser. Do not guess at a
-second delimiter grammar in release code.
-
-## Acceptance checklist
-
-- [ ] CI/build paths normalize to `+` or `+/descendant`.
-- [ ] `+` is never treated as a delimiter.
-- [ ] Output ordering is stable, deduplicated, deterministic, and idempotent.
-- [ ] Bare relatives, absolute CI paths, traversal, missing directories,
- separator injection, whitespace ambiguity, and symlink escape fail closed.
-- [ ] The released ELF hard-link launcher layout is covered; the shell CWD patch
- remains compatibility-only.
-- [ ] Intermediate and final repacked AppDirs both pass library-path,
- required-library, NEEDED, and RPATH validation.
-- [ ] The final amd64 AppImage is launched from a foreign CWD under Xvfb and
- remains alive through the bounded startup window.
-- [ ] Loader logs contain no `anylinux.so`, `libxdo.so.3`, or `libcef.so`
- resolution error.
-- [ ] Validation completes before signing/updater archive rebuilding/upload.
-- [ ] Arm64 static validation and all non-Linux workflow behavior remain intact.
-- [ ] #3716/OpenSSL, unbundled AUR/core, optional `enigo`, rolling-distro
- matrices, and quick-sharun pinning remain explicit follow-ups.
diff --git a/docs/plans/2026-07-24-knip-cleanup.md b/docs/plans/2026-07-24-knip-cleanup.md
deleted file mode 100644
index 69bcbdc8d9..0000000000
--- a/docs/plans/2026-07-24-knip-cleanup.md
+++ /dev/null
@@ -1,797 +0,0 @@
-# OpenHuman App Knip Cleanup Implementation Plan
-
-> **Execution note:** Carry this plan out from
-> `/Users/enamakel/work/workflow-openhuman/worktrees/knip-cleanup/openhuman` on
-> `chore/knip-cleanup`. Use Node 24 (`source "$HOME/.nvm/nvm.sh" && nvm use 24`)
-> for every pnpm/Knip command. Do not push, open a PR, edit Rust, touch another
-> umbrella submodule, or expand the cleanup beyond `app/`.
-
-**Goal:** Make Knip's OpenHuman app analysis trustworthy, then remove unreachable
-TypeScript/React files, unused package dependencies, and unnecessary exported
-surface without changing runtime behavior.
-
-**Design:** Treat Knip as a static-analysis regression test, not as an automatic
-deletion list. First model every Vite, Vitest, WebdriverIO, Playwright, Tauri,
-package-script, and shell-launched entry point. Then process findings in
-subsystem-sized slices, independently checking static imports, barrel exports,
-string references, package scripts, test configuration, Tauri configuration,
-and shell/workflow invocation before changing a file. Delete a declaration only
-when it is unused; when the declaration is used locally, remove only `export`.
-Keep intentional contracts through the narrowest documented Knip exception.
-
-**Scope:** `app/knip.json`, `app/package.json`, the applicable pnpm lockfiles,
-and Knip-confirmed dead or over-exported TypeScript/TSX under `app/src/` and
-`app/test/`. Generated assets, `app/src-tauri/`, vendored sources, Rust, public
-docs, and unrelated formatting/refactors are out of scope.
-
----
-
-## Mandatory execution discipline
-
-Apply these rules to every task below:
-
-1. Start with `git status --short --branch`. Stop if another agent has modified
- a file needed by the task; coordinate instead of reverting or overwriting it.
-2. Run the stated **red** Knip query before editing and save the relevant output
- in the terminal/log, not in the repository.
-3. Independently verify every candidate with `rg` before modifying it:
-
- ```bash
- rg -n '<symbol-or-file-stem>' app package.json scripts .github \
- --glob '!app/pnpm-lock.yaml' --glob '!pnpm-lock.yaml' \
- --glob '!app/src-tauri/vendor/**' --glob '!node_modules/**' \
- --glob '!target/**'
- ```
-
- Also inspect `app/package.json`, `app/index.html`, `app/vite.config.ts`,
- `app/test/vitest.config.ts`, `app/test/wdio.conf.ts`,
- `app/playwright.config.ts`, `app/scripts/`, `app/src-tauri/tauri.conf.json`,
- and `.github/workflows/` whenever the candidate could be loaded by name,
- convention, a script, or Tauri.
-
-4. Make the smallest change:
- - delete a file/declaration only when no runtime, build, test, documentation,
- generated-manifest, tooling, or dynamic-loading role exists;
- - remove only `export` when the declaration is used in its own module;
- - remove one side of a duplicate named/default export and update imports to
- the retained form;
- - keep intentional public/test seams with the narrowest possible
- `app/knip.json` exception and an adjacent reason.
-5. Run the stated **green** checks. A targeted Knip category must have no
- actionable findings in the files handled by the step and must introduce no
- new `files`, `dependencies`, or `unlisted` findings.
-6. Run Prettier only on the explicitly touched files:
-
- ```bash
- pnpm --filter openhuman-app exec prettier --check <explicit paths>
- ```
-
-7. Review `git diff --check` and `git diff -- <explicit paths>`.
-8. Commit immediately after validation. Manually enumerate every touched path;
- never use a glob, directory, `git add`, or command substitution:
-
- ```bash
- atomic-commit "<scoped message>" -- path/to/file1 path/to/file2
- ```
-
-9. Do not begin the next task until the current task is committed.
-
-If deleting dead production code leaves a test whose only purpose was to test
-that dead code, independently verify that fact and delete the orphan test in
-the same atomic commit. A test is not evidence that a production entry point is
-live.
-
-## Baseline
-
-With Node 24, the approved-design baseline currently reports:
-
-- 34 unused files;
-- `lottie-react` and `react-ga4` as unused dependencies;
-- direct but undeclared imports of `webdriverio` and `@wdio/globals`;
-- 131 unused value exports;
-- 276 unused exported types;
-- one unused enum-member group;
-- 41 duplicate exports.
-
-The counts may shrink after entry-point correction. Always use the post-config
-report as the deletion authority.
-
----
-
-### Task 1: Model all real app and tooling entry points
-
-**Files:**
-
-- Modify: `app/knip.json`
-- Modify only if direct dependency evidence requires it:
- `app/package.json`, `pnpm-lock.yaml`, `app/pnpm-lock.yaml`
-
-**Step 1: Record the red baseline**
-
-Run:
-
-```bash
-source "$HOME/.nvm/nvm.sh"
-nvm use 24
-pnpm --filter openhuman-app exec knip --config knip.json --reporter compact
-```
-
-Expected: non-zero with `test/wdio.conf.ts` incorrectly reported as unused,
-unlisted `webdriverio`/`@wdio/globals`, and the remaining cleanup candidates.
-
-**Step 2: Prove each indirect entry**
-
-Run and inspect:
-
-```bash
-rg -n 'src/main\.tsx|vite\.config|vitest\.config|wdio\.conf|playwright\.config|build-parallel|e2e-run-session' \
- app/index.html app/package.json app/scripts scripts .github
-rg -n 'test/e2e/specs|test/playwright/specs|src/test/setup' \
- app/test app/playwright.config.ts app/package.json app/scripts .github
-rg -n 'webdriverio|@wdio/globals|@wdio/types' app/test app/package.json
-```
-
-Evidence that must be preserved:
-
-- `app/index.html` loads `src/main.tsx`;
-- package build scripts execute `scripts/build-parallel.mjs`, which invokes the
- Vite build;
-- unit scripts load `test/vitest.config.ts`, whose `setupFiles` loads
- `src/test/setup.ts` and whose `include` globs load app tests;
-- `app/scripts/e2e-run-session.sh` executes
- `pnpm exec wdio run test/wdio.conf.ts`;
-- `test/wdio.conf.ts` loads all `test/e2e/specs/**/*.spec.ts`;
-- Playwright configuration loads `test/playwright/specs/**/*.spec.ts`;
-- WebdriverIO types/globals imported by source are direct dev dependencies,
- even if another WDIO package currently installs them transitively;
-- Tauri/Vite/package-script binaries are real even when referenced only in a
- package script or shell script.
-
-**Step 3: Correct Knip configuration narrowly**
-
-Update `app/knip.json` so the verified configuration/spec/tooling files are
-explicit entries. At minimum the graph must include:
-
-```json
-{
- "entry": [
- "src/main.tsx",
- "vite.config.ts",
- "test/vitest.config.ts",
- "test/wdio.conf.ts",
- "playwright.config.ts",
- "test/e2e/specs/**/*.spec.ts",
- "test/playwright/specs/**/*.spec.ts"
- ]
-}
-```
-
-Retain `project` coverage for app and test TypeScript. Add a package-script or
-tooling script as an entry only when Knip does not discover its verified
-invocation. Do not add a broad `scripts/**`, `test/**`, or `src/**` entry merely
-to make findings disappear.
-
-Remove an `ignoreDependencies` or `ignoreBinaries` entry only after the
-corrected graph recognizes the real usage. Keep an exception only when the
-package manager, Tauri, or a shell script invokes it in a way Knip cannot model,
-and document the exact invocation next to that exception.
-
-**Step 4: Declare direct WDIO imports**
-
-If the corrected graph still reports the existing imports as unlisted, add
-`@wdio/globals` and `webdriverio` to `app/devDependencies` at the same `9.24.x`
-family used by the other WDIO packages. Add `@wdio/types` too if Knip or
-`pnpm why @wdio/types` confirms `test/wdio.conf.ts` relies on it transitively.
-Regenerate only the lockfile sections affected by those declarations. Do not
-upgrade unrelated packages.
-
-**Step 5: Run the green checks**
-
-```bash
-pnpm --filter openhuman-app exec knip --config knip.json --reporter compact
-pnpm --filter openhuman-app compile
-pnpm --filter openhuman-app exec tsc -p test/tsconfig.e2e.json --noEmit
-pnpm --filter openhuman-app exec prettier --check knip.json package.json
-git diff --check
-```
-
-Expected: `test/wdio.conf.ts` and all verified framework/tooling entries are no
-longer unused; `webdriverio` and `@wdio/globals` are no longer unlisted; no
-broad ignore has hidden app source.
-
-**Step 6: Commit**
-
-Use:
-
-```bash
-atomic-commit "chore(app): make knip entry analysis accurate" -- app/knip.json app/package.json pnpm-lock.yaml app/pnpm-lock.yaml
-```
-
-Omit any listed path that was not actually changed, while continuing to name
-every changed path explicitly.
-
----
-
-### Task 2: Remove independently verified unreachable files
-
-**Candidate files (post-Task-1 Knip must still report each before deletion):**
-
-- `app/src/agentworld/theme/AgentWorldThemeBridge.tsx`
-- `app/src/assets/icons/GoogleIcon.tsx`
-- `app/src/components/ConnectionBadge.tsx`
-- `app/src/components/LottieAnimation.tsx`
-- `app/src/components/accounts/RespondQueuePanel.tsx`
-- `app/src/components/chat/CycleUsagePill.tsx`
-- `app/src/components/chat/TokenUsagePill.tsx`
-- `app/src/components/intelligence/SyncBudgetDialog.tsx`
-- `app/src/components/intelligence/SyncConfirmDialog.tsx`
-- `app/src/components/routines/RoutineCard.tsx`
-- `app/src/components/routines/RoutineRunHistory.tsx`
-- `app/src/components/settings/components/PageBackButton.tsx`
-- `app/src/components/settings/components/SettingsHeader.tsx`
-- `app/src/components/settings/panels/autocomplete/AppFilterSection.tsx`
-- `app/src/components/settings/panels/autocomplete/CompletionStyleSection.tsx`
-- `app/src/components/settings/panels/billing/BillingHistoryTab.tsx`
-- `app/src/components/settings/panels/billing/BillingPaymentsTab.tsx`
-- `app/src/components/settings/panels/billing/BillingPlansTab.tsx`
-- `app/src/components/settings/panels/billing/PayAsYouGoCard.tsx`
-- `app/src/components/skills/SkillResourceTree.tsx`
-- `app/src/features/conversations/components/LimitPill.tsx`
-- `app/src/features/conversations/index.ts`
-- `app/src/hooks/useIntelligenceApiFallback.ts`
-- `app/src/hooks/useIntelligenceStats.ts`
-- `app/src/hooks/useScreenIntelligenceItems.ts`
-- `app/src/lib/ai/skillsAgentContext.ts`
-- `app/src/pages/Routines.tsx`
-- `app/src/pages/onboarding/components/ConfigureLaterCallout.tsx`
-- `app/src/pages/onboarding/pages/ApiKeysPage.tsx`
-- `app/src/pages/onboarding/pages/ChatProviderPage.tsx`
-- `app/src/pages/onboarding/pages/CustomMemoryPage.tsx`
-- `app/src/pages/onboarding/steps/ReferralApplyStep.tsx`
-- `app/test/e2e/helpers/rpc-preflight.ts`
-
-`app/test/wdio.conf.ts` is explicitly **not** a deletion candidate.
-
-**Step 1: Red-check the file set**
-
-```bash
-pnpm --filter openhuman-app exec knip --config knip.json --include files --reporter compact
-```
-
-Expected: only files that survived Task 1 remain in the candidate set above.
-Drop any file from this task if entry-point correction made it reachable.
-
-**Step 2: Verify every file independently**
-
-For every remaining file, search the full repository for its path, filename,
-stem, exported component/hook names, route paths, lazy import strings,
-`import.meta.glob`, index/barrel exports, package scripts, test configs, Tauri
-resources, and documentation references.
-
-Pay special attention to:
-
-- `Routines.tsx`: current routes redirect legacy `/routines`; do not remove
- translations or redirects merely because the old page is dead.
-- onboarding pages: commented-out JSX is not a live entry; do not remove shared
- onboarding types or current wizard routes.
-- `GoogleIcon.tsx`: a separate local `GoogleIcon` exists in
- `components/oauth/providerConfigs.tsx`; keep the live local implementation.
-- `useScreenIntelligenceItems.ts`: inspect
- `hooks/__tests__/useScreenIntelligenceItems.test.ts`; delete that test only if
- it is an orphan that duplicates dead behavior rather than importing a live
- unit.
-- `rpc-preflight.ts`: comments claiming it can be called are not execution;
- verify neither WDIO config nor a spec imports it.
-- files in settings, routines, intelligence, and billing: search route
- registries and lazy imports in addition to static imports.
-
-**Step 3: Delete only confirmed-dead files**
-
-Delete the files that remain unreachable. Remove now-empty barrel exports or
-now-empty directories only when they contain no other tracked assets. Do not
-delete localization strings, styles, or tests merely because their names are
-similar.
-
-**Step 4: Green-check the slice**
-
-```bash
-pnpm --filter openhuman-app exec knip --config knip.json --include files --reporter compact
-pnpm --filter openhuman-app compile
-pnpm --filter openhuman-app test -- --run
-pnpm --filter openhuman-app lint
-git diff --check
-```
-
-Expected: no verified file candidate remains; unit tests, types, and lint pass.
-
-**Step 5: Commit**
-
-Commit with every deleted file and any orphan test/barrel update named
-explicitly:
-
-```bash
-atomic-commit "refactor(app): remove unreachable frontend files" -- <explicit deleted and modified paths>
-```
-
-Do not use the angle-bracket text literally; replace it with the full explicit
-path list.
-
----
-
-### Task 3: Remove unused package dependencies
-
-**Files:**
-
-- Modify: `app/package.json`
-- Modify: `pnpm-lock.yaml`
-- Modify: `app/pnpm-lock.yaml`
-
-**Step 1: Red-check dependency findings**
-
-```bash
-pnpm --filter openhuman-app exec knip --config knip.json --include dependencies,unlisted --reporter compact
-rg -n "from ['\"](lottie-react|react-ga4)['\"]|import\\(['\"](lottie-react|react-ga4)['\"]\\)" \
- app/src app/test app/vite.config.ts app/scripts
-```
-
-Expected: after Task 2 deletes `LottieAnimation.tsx`, neither package has a
-live import. A stale test comment mentioning `react-ga4` is not a dependency.
-
-**Step 2: Remove only confirmed-unused declarations**
-
-Remove `lottie-react` and `react-ga4` from `app/package.json`. Update the root
-workspace lock and the tracked `app/pnpm-lock.yaml` without upgrading unrelated
-packages. Inspect both lockfile diffs and revert any resolver churn unrelated
-to these two removals and the direct WDIO declarations from Task 1.
-
-**Step 3: Green-check dependencies**
-
-```bash
-pnpm --filter openhuman-app exec knip --config knip.json --include dependencies,unlisted --reporter compact
-pnpm --filter openhuman-app compile
-pnpm --filter openhuman-app test -- --run
-pnpm --filter openhuman-app exec prettier --check package.json
-git diff --check
-```
-
-Expected: no actionable unused or unlisted dependency finding.
-
-**Step 4: Commit**
-
-```bash
-atomic-commit "chore(app): remove unused frontend dependencies" -- app/package.json pnpm-lock.yaml app/pnpm-lock.yaml
-```
-
----
-
-### Task 4: Normalize duplicate exports and barrels
-
-**Files:** The post-Task-3 duplicate report, initially including 41 findings
-across:
-
-- `app/src/components/chat/`
-- `app/src/components/flows/`
-- `app/src/components/intelligence/`
-- `app/src/components/mcp-setup/`
-- `app/src/components/meetings/`
-- `app/src/components/skills/`
-- `app/src/components/userErrors/`
-- `app/src/features/conversations/`
-- `app/src/features/human/`
-- `app/src/features/meet/`
-- `app/src/features/share/`
-- `app/src/hooks/`
-- `app/src/lib/attachments.ts`
-- `app/src/lib/mcp/rateLimiter.ts`
-- `app/src/services/api/flowsApi.ts`
-
-**Step 1: Red-check duplicates**
-
-```bash
-pnpm --filter openhuman-app exec knip --config knip.json --include duplicates --reporter compact
-```
-
-**Step 2: Choose one canonical export per symbol**
-
-For each duplicate, search every import and barrel re-export. Retain the import
-shape already used by live consumers; remove the redundant named/default
-export only. Update imports only when necessary to converge on that canonical
-shape. Do not rename components or refactor their implementation.
-
-For `attachments.ts`, verify whether
-`ATTACHMENT_MAX_IMAGE_SIZE_BYTES` and `ATTACHMENT_MAX_SIZE_BYTES` are aliases
-before removing either export. For `rateLimiter.ts`, distinguish an actual
-duplicate re-export from two different implementations. For `flowsApi.ts`,
-retain the import shape used by the majority of live callers.
-
-Process and commit this task in at most three subsystem commits if the explicit
-path list becomes too large:
-
-1. chat/flows/intelligence;
-2. meetings/skills/human/share/hooks;
-3. lib/services/barrels.
-
-Each commit must independently pass:
-
-```bash
-pnpm --filter openhuman-app exec knip --config knip.json --include duplicates --reporter compact
-pnpm --filter openhuman-app compile
-pnpm --filter openhuman-app test -- --run
-pnpm --filter openhuman-app lint
-git diff --check
-```
-
-Commit each validated slice with explicit paths:
-
-```bash
-atomic-commit "refactor(app): remove duplicate <subsystem> exports" -- <explicit paths>
-```
-
-Expected at task completion: zero unexplained duplicate-export findings.
-
----
-
-### Task 5: Internalize Agent World and mascot exports
-
-**Files:** Post-Task-4 unused values/types in:
-
-- `app/src/agentworld/**`
-- `app/src/features/human/Mascot/**`
-- `app/src/features/meet/MascotFrameProducer.tsx`
-- `app/src/features/meet/useMeetingMascots.ts`
-
-**Step 1: Red-check the subsystem**
-
-```bash
-pnpm --filter openhuman-app exec knip --config knip.json --include exports,types --reporter compact \
- | rg 'src/(agentworld|features/human/Mascot|features/meet/)'
-```
-
-**Step 2: Verify public-looking barrels**
-
-Inspect `agentworld/iso/index.ts` and `features/human/Mascot/index.ts` against
-all imports. A barrel item unused inside this private app workspace is not
-automatically a public package API. Remove dead barrel re-exports, but keep the
-underlying declaration when imported directly or used in its defining module.
-For component props, manifest types, renderer types, and hook result types used
-only locally, remove `export` rather than deleting the type.
-
-Do not modify runtime rendering, sprite/room registration, Rive asset lookup,
-manifest discovery, or Tauri resource paths.
-
-**Step 3: Green-check and commit**
-
-```bash
-pnpm --filter openhuman-app exec knip --config knip.json --include exports,types --reporter compact \
- | rg 'src/(agentworld|features/human/Mascot|features/meet/)' && exit 1 || true
-pnpm --filter openhuman-app compile
-pnpm --filter openhuman-app test -- --run
-pnpm --filter openhuman-app lint
-git diff --check
-atomic-commit "refactor(app): internalize agent world and mascot APIs" -- <explicit paths>
-```
-
-The `rg` pipeline must be interpreted carefully: only the absence of actionable
-findings for this subsystem is green; a Knip process failure must not be hidden.
-
----
-
-### Task 6: Internalize conversations, flows, orchestration, and hook exports
-
-**Files:** Post-Task-5 unused values/types in:
-
-- `app/src/components/flows/**`
-- `app/src/features/conversations/**`
-- `app/src/hooks/useFlow*.ts`
-- `app/src/hooks/useRunsPendingApprovalSet.ts`
-- `app/src/lib/flows/**`
-- `app/src/lib/orchestration/**`
-- `app/src/pages/FlowCanvasPage.tsx`
-- `app/src/services/api/flowsApi.ts`
-- `app/src/services/api/workflowRunsApi.ts`
-
-**Step 1: Red-check and classify**
-
-Run Knip for `exports,types`, filter to these paths, then classify each finding:
-delete an unused declaration, internalize a locally used declaration, or retain
-an intentional test seam. Search tests before touching constants such as
-`VALIDATION_DEBOUNCE_MS`, model hints, timeline kinds, flow API helpers, and
-copilot seed types.
-
-**Step 2: Apply the smallest visibility/dead-code changes**
-
-Preserve runtime hook registration, event names, API payload shapes, and flow
-node-kind registries. Do not remove a flow API method solely because the React
-app does not call it until repository-wide and documented-extension searches
-also show it is private and unused.
-
-**Step 3: Validate affected tests**
-
-Run the specific test files that import any changed module, followed by:
-
-```bash
-pnpm --filter openhuman-app compile
-pnpm --filter openhuman-app test -- --run
-pnpm --filter openhuman-app lint
-pnpm --filter openhuman-app exec knip --config knip.json --include exports,types --reporter compact
-git diff --check
-```
-
-**Step 4: Commit**
-
-Split into a flows commit and a conversations/orchestration commit if needed,
-with all paths explicit:
-
-```bash
-atomic-commit "refactor(app): trim unused flow module exports" -- <explicit paths>
-atomic-commit "refactor(app): trim unused conversation exports" -- <explicit paths>
-```
-
-Run and commit each command only after its own validation.
-
----
-
-### Task 7: Internalize settings, layout, UI, meetings, and feature exports
-
-**Files:** Post-Task-6 unused values/types in:
-
-- `app/src/components/layout/**`
-- `app/src/components/ui/**`
-- `app/src/components/settings/**`
-- `app/src/components/meetings/**`
-- `app/src/components/channels/**`
-- `app/src/components/oauth/**`
-- `app/src/components/skills/**`
-- remaining `app/src/components/**`
-- remaining `app/src/features/**`
-
-**Step 1: Red-check and inspect barrel contracts**
-
-Run the `exports,types` report filtered to these paths. Search all imports from
-`components/ui`, `components/settings/controls`, settings route registries,
-meeting components, and skill components before editing their index files.
-
-**Step 2: Remove only unnecessary external visibility**
-
-Typical safe changes are:
-
-- `export interface FooProps` to `interface FooProps` when only the component
- in that file uses it;
-- `export const` to `const` when local code/tests do not import it;
-- remove a barrel re-export when every consumer imports directly;
-- delete a value/type only when no local use remains.
-
-Preserve settings route registry data, Tauri command names, analytics IDs,
-documented extension points, and intentional test seams.
-
-**Step 3: Green-check and commit in bounded slices**
-
-Use two commits if necessary:
-
-1. settings/layout/UI;
-2. meetings/channels/skills/remaining features.
-
-For each slice:
-
-```bash
-pnpm --filter openhuman-app compile
-pnpm --filter openhuman-app test -- --run
-pnpm --filter openhuman-app lint
-pnpm --filter openhuman-app exec knip --config knip.json --include exports,types --reporter compact
-git diff --check
-atomic-commit "refactor(app): trim unused <subsystem> exports" -- <explicit paths>
-```
-
----
-
-### Task 8: Internalize services, stores, libraries, and shared types
-
-**Files:** Post-Task-7 unused values/types in:
-
-- `app/src/services/**`
-- `app/src/store/**`
-- `app/src/lib/**`
-- `app/src/types/**`
-- `app/src/utils/**`
-- remaining `app/src/hooks/**`
-- `app/src/polyfills.ts`
-
-**Step 1: Red-check and separate API shape from TypeScript visibility**
-
-Run Knip for `exports,types`. For RPC/API modules, distinguish an exported
-TypeScript declaration from a serialized field or method string: removing
-`export` must not change the runtime object, payload, enum value, or command
-name. Search the Rust/Tauri boundary and docs whenever a string might be an IPC
-contract.
-
-**Step 2: Process high-risk modules conservatively**
-
-Explicitly verify:
-
-- `services/coreRpcClient.ts`, `services/rpcMethods.ts`, and all `services/api/*`
- against frontend imports, tests, Tauri command strings, and documented RPC
- contracts;
-- Redux slice actions/selectors against `store/index.ts`, middleware,
- persistence, tests, and dynamic dispatch;
-- `lib/agentworld/invokeApiClient.ts` types against all Agent World consumers;
-- `lib/mcp/*` tool classification and rate-limit symbols against tests and
- string-driven tool handling;
-- `polyfills.ts` is imported for side effects by `src/main.tsx`; remove only
- unused exports, never the file or its side effects;
-- platform, notification, webview, tunnel, attachment, and theme constants
- against runtime branches and tests.
-
-**Step 3: Apply and validate in three atomic slices**
-
-1. services/API clients;
-2. stores/selectors;
-3. libraries/types/utils/hooks.
-
-For every slice:
-
-```bash
-pnpm --filter openhuman-app compile
-pnpm --filter openhuman-app test -- --run
-pnpm --filter openhuman-app lint
-pnpm --filter openhuman-app exec knip --config knip.json --include exports,types --reporter compact
-git diff --check
-atomic-commit "refactor(app): trim unused <subsystem> exports" -- <explicit paths>
-```
-
-Do not batch the three slices into one commit.
-
----
-
-### Task 9: Clean test-helper exports and unused enum members
-
-**Files:** Post-Task-8 findings in:
-
-- `app/test/e2e/helpers/**`
-- `app/test/e2e/mock-server.ts`
-- `app/test/playwright/helpers/**`
-- `app/src/lib/mcp/errorHandler.ts`
-
-**Step 1: Red-check**
-
-```bash
-pnpm --filter openhuman-app exec knip --config knip.json \
- --include exports,types,enumMembers --reporter compact
-```
-
-**Step 2: Verify test discovery and helper use**
-
-Search all WDIO and Playwright specs before internalizing or deleting a helper.
-Test specs and configs are entry points; helper files are not. Preserve helpers
-called through the WDIO lifecycle hooks or fixture registration even when no
-spec imports them directly.
-
-For `ErrorCategory`, search string values and computed property access in
-addition to enum member names. Remove `CONTACT`, `GROUP`, `MEDIA`, `PROFILE`,
-`AUTH`, `ADMIN`, `SEARCH`, and `DRAFT` only if none is used dynamically and
-removing them does not alter serialized behavior.
-
-**Step 3: Green-check**
-
-```bash
-pnpm --filter openhuman-app exec tsc -p test/tsconfig.e2e.json --noEmit
-pnpm --filter openhuman-app compile
-pnpm --filter openhuman-app test -- --run
-pnpm --filter openhuman-app lint
-pnpm --filter openhuman-app exec knip --config knip.json \
- --include exports,types,enumMembers --reporter compact
-git diff --check
-```
-
-**Step 4: Commit**
-
-```bash
-atomic-commit "refactor(app): trim unused test helper exports" -- <explicit paths>
-```
-
----
-
-### Task 10: Resolve only genuinely intentional residual findings
-
-**Files:**
-
-- Modify only if needed: `app/knip.json`
-- Modify only if needed: files containing deliberate public/test seams
-
-**Step 1: Run the complete report**
-
-```bash
-pnpm --filter openhuman-app exec knip --config knip.json --reporter compact
-pnpm --filter openhuman-app exec knip --config knip.json --production --reporter compact
-```
-
-**Step 2: Adversarially verify every residual**
-
-For every residual finding, repeat the full static/dynamic search. A finding may
-remain only when there is concrete evidence of convention-based loading,
-package/Tauri/tooling invocation, generated input, documented public contract,
-or intentional test seam that Knip cannot model.
-
-Prefer modeling another precise entry or dependency over ignoring a finding.
-If an exception is unavoidable, scope it to the exact file/package/symbol
-supported by Knip's schema and add a one-line reason naming the loader or
-contract. Do not add directory-wide ignores, `src/**`, `test/**`, or global
-export suppression.
-
-**Step 3: Green-check and commit exceptions separately**
-
-```bash
-pnpm --filter openhuman-app exec knip --config knip.json --reporter compact
-pnpm --filter openhuman-app exec knip --config knip.json --production --reporter compact
-pnpm --filter openhuman-app compile
-pnpm --filter openhuman-app test -- --run
-pnpm --filter openhuman-app lint
-git diff --check
-atomic-commit "chore(app): document intentional knip exceptions" -- app/knip.json <explicit affected paths>
-```
-
-Skip the commit entirely if no exceptions are needed.
-
----
-
-### Task 11: Final independent verification
-
-**Files:** No planned edits.
-
-**Step 1: Confirm the branch and clean worktree**
-
-```bash
-git status --short --branch
-git log --oneline --decorate -15
-```
-
-Expected: branch `chore/knip-cleanup`; every completed slice has its own atomic
-commit; no uncommitted implementation changes.
-
-**Step 2: Re-run the complete quality gate from a fresh Node 24 shell**
-
-```bash
-source "$HOME/.nvm/nvm.sh"
-nvm use 24
-pnpm knip
-pnpm knip:production
-pnpm typecheck
-pnpm test
-pnpm lint
-pnpm format:check
-pnpm build
-```
-
-Expected: every command exits zero. If `format:check` finds pre-existing,
-out-of-scope failures, prove they exist at the design commit before claiming an
-exception; otherwise fix only formatting in files touched by this cleanup and
-amend it through a new atomic formatting commit with explicit paths.
-
-**Step 3: Verify no scope leakage**
-
-```bash
-git diff --name-only eb2bda897..HEAD
-git diff --stat eb2bda897..HEAD
-git diff --check eb2bda897..HEAD
-git status --short
-```
-
-Expected: implementation changes are confined to `app/`; the approved design
-and this plan are the only `docs/` changes; no Rust, vendor, generated asset,
-other submodule, or umbrella gitlink changed.
-
-**Step 4: Review behavior preservation**
-
-Inspect the complete diff and confirm:
-
-- no route, command, event, RPC method, analytics ID, payload field, or visible
- copy changed;
-- Vite, Vitest, WDIO, Playwright, Tauri, package-script, and shell-launched
- entry points remain tracked by Knip or have a precise documented exception;
-- removed files have no imports, string references, generated-manifest role,
- tooling role, or documentation contract;
-- dependency changes contain no unrelated upgrades;
-- every remaining export is live or deliberately retained.
-
-Do not push or open a PR. Report the commit list, deleted files/dependencies,
-final Knip result, every validation command and exit status, and any narrowly
-documented exception to the requesting agent.
diff --git a/docs/plans/2026-07-24-macos-clippy-ci.md b/docs/plans/2026-07-24-macos-clippy-ci.md
deleted file mode 100644
index 06c3ba3a97..0000000000
--- a/docs/plans/2026-07-24-macos-clippy-ci.md
+++ /dev/null
@@ -1,257 +0,0 @@
-# Issue #5019: macOS Clippy Coverage in CI Full — Implementation Plan
-
-> **Approved design:** `docs/specs/2026-07-24-macos-clippy-ci-design.md` at
-> `c4085c446e12d022d6275c1a92cc98a702b0db49`
->
-> **Implementation scope:** one workflow file and one implementation commit.
-> The design/spec and this plan are already committed separately and must not be
-> included in the implementation commit.
-
-## Objective
-
-Add the repository's existing aggregate Rust lint command to the existing
-`build-macos-full` job so CI Full checks macOS-gated code in both the root-core
-and Tauri Cargo worlds, denies warnings through the package scripts already in
-place, remains cancellation-aware, and refuses to publish the macOS E2E build
-artifact when linting fails.
-
-## Critical review of the approved design
-
-The selected change is compatible with the current repository:
-
-- `.github/workflows/e2e-reusable.yml` defines `build-macos-full` on
- `macos-latest` with `timeout-minutes: 60`.
-- `Build E2E app` precedes `Package build artifact`; inserting Clippy between
- them makes a non-zero lint exit prevent packaging and upload.
-- `e2e-macos-full` already has `needs: build-macos-full`, so all macOS shards
- remain blocked if Clippy fails.
-- `.github/workflows/ci-full.yml` treats the reusable `e2e-desktop` workflow as
- a dependency of `CI Full Gate`, so no gate-topology edit is needed.
-- Root `package.json` defines `pnpm rust:clippy` as root
- `cargo clippy -p openhuman -- -D warnings` followed by the app workspace's
- `rust:clippy`; `app/package.json` defines the latter as Tauri
- `cargo clippy --manifest-path src-tauri/Cargo.toml -- -D warnings`.
-- The workflow already grants `actions: read` and exports `GH_TOKEN`, which
- lets `scripts/ci-cancel-aware.sh` propagate GitHub run cancellation.
-
-One performance nuance must be measured, not papered over: the preceding Tauri
-app build warms `app/src-tauri/target`, including the path-dependent core as
-compiled in the Tauri Cargo graph. It does not compile the independent root
-Cargo graph into `target/`; that graph benefits from the existing two-workspace
-Rust cache but can still be cold on a cache miss. This does not invalidate the
-design, but it is why the initial implementation must leave the 60-minute
-timeout unchanged and the CI Full run time must be recorded.
-
-No dedicated workflow validator such as `actionlint` or `yamllint` is installed
-in the current checkout. The validation below therefore combines Prettier's
-YAML parse/check, Ruby's YAML parser, and a focused structural assertion. Do not
-add a validator dependency for this one-step workflow change.
-
-## Task 1: Add the macOS Clippy gate before artifact packaging
-
-**Files:**
-
-- Modify: `.github/workflows/e2e-reusable.yml`
-
-### Step 1: Prove the required workflow structure is absent
-
-From the worktree root, run this focused structural check before editing:
-
-```bash
-node --input-type=module <<'NODE'
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-
-const workflow = readFileSync(".github/workflows/e2e-reusable.yml", "utf8");
-const jobStart = workflow.indexOf("\n build-macos-full:\n");
-const jobEnd = workflow.indexOf("\n e2e-macos-full:\n", jobStart);
-assert.notEqual(jobStart, -1, "build-macos-full job must exist");
-assert.notEqual(jobEnd, -1, "e2e-macos-full boundary must exist");
-
-const job = workflow.slice(jobStart, jobEnd);
-const build = job.indexOf(" - name: Build E2E app\n");
-const clippy = job.indexOf(" - name: Clippy (macOS-gated Rust)\n");
-const packageArtifact = job.indexOf(" - name: Package build artifact\n");
-
-assert.notEqual(build, -1, "Build E2E app step must exist");
-assert.notEqual(clippy, -1, "macOS Clippy step must exist");
-assert.notEqual(packageArtifact, -1, "Package build artifact step must exist");
-assert.ok(build < clippy, "Clippy must run after Build E2E app");
-assert.ok(clippy < packageArtifact, "Clippy must run before artifact packaging");
-assert.equal(
- (job.match(/ - name: Clippy \(macOS-gated Rust\)\n/g) ?? []).length,
- 1,
- "build-macos-full must contain exactly one macOS Clippy step",
-);
-assert.match(
- job,
- / - name: Clippy \(macOS-gated Rust\)\n run: bash scripts\/ci-cancel-aware\.sh pnpm rust:clippy\n/,
- "Clippy must use the aggregate package script through the cancellation wrapper",
-);
-assert.match(job, / runs-on: macos-latest\n/);
-assert.match(job, / timeout-minutes: 60\n/);
-NODE
-```
-
-Expected result: the command exits non-zero with
-`AssertionError: macOS Clippy step must exist`. A different failure means the
-workflow shape has drifted; stop and reconcile the plan with the current file
-instead of inserting by an assumed line number.
-
-### Step 2: Insert the smallest workflow change
-
-In `.github/workflows/e2e-reusable.yml`, add exactly this step immediately after
-`Build E2E app` in `build-macos-full` and immediately before
-`Package build artifact`:
-
-```yaml
-- name: Clippy (macOS-gated Rust)
- run: bash scripts/ci-cancel-aware.sh pnpm rust:clippy
-```
-
-Do not:
-
-- add conditions to the step;
-- duplicate either Cargo command in YAML;
-- alter `timeout-minutes: 60`;
-- change caches, toolchains, environment setup, packaging, artifact upload, or
- shard dependencies;
-- add this step to the selected-spec macOS job, Linux/Windows jobs, CI Lite, or
- any other workflow.
-
-The command ordering is intentional. The root package script short-circuits on
-root-core Clippy failure; only a successful root lint proceeds to the Tauri
-lint. Either failure makes the step and `build-macos-full` fail.
-
-### Step 3: Re-run the focused structural check
-
-Run the exact Node command from Step 1 again.
-
-Expected result: exit status 0 with no output. This proves the named step occurs
-exactly once in `build-macos-full`, uses the cancellation wrapper and aggregate
-package script, remains between build and packaging, and leaves the runner and
-timeout unchanged.
-
-### Step 4: Validate YAML and formatting
-
-Run:
-
-```bash
-pnpm --dir app exec prettier --check ../.github/workflows/e2e-reusable.yml
-ruby -e 'require "yaml"; YAML.parse_file(".github/workflows/e2e-reusable.yml"); puts "YAML syntax OK"'
-git diff --check
-```
-
-Expected results:
-
-- Prettier reports `All matched files use Prettier code style!`.
-- Ruby prints `YAML syntax OK`.
-- `git diff --check` exits 0 with no output.
-
-Do not run Prettier in write mode over the workflow or repository; the intended
-diff is two added lines only.
-
-### Step 5: Review scope and topology in the diff
-
-Run:
-
-```bash
-git diff -- .github/workflows/e2e-reusable.yml
-git diff --name-only
-git status --short
-```
-
-Confirm all of the following before committing:
-
-- the workflow diff contains only the two-line Clippy step;
-- the step is inside `build-macos-full`, after `Build E2E app`, and before
- `Package build artifact`;
-- `timeout-minutes: 60` is unchanged;
-- no CI Lite, package-script, cache, packaging, upload, or shard dependency
- lines changed;
-- the only uncommitted implementation path is
- `.github/workflows/e2e-reusable.yml`.
-
-If the plan file is still uncommitted in the executor's checkout, do not include
-it in the implementation commit; this plan's authoring commit is a prerequisite.
-
-### Step 6: Create the atomic implementation commit
-
-Run:
-
-```bash
-atomic-commit "ci(e2e): lint macOS Rust before artifact packaging" -- .github/workflows/e2e-reusable.yml
-```
-
-Expected implementation commit boundary:
-
-1. `ci(e2e): lint macOS Rust before artifact packaging` — contains only
- `.github/workflows/e2e-reusable.yml`.
-
-There is no second expected implementation commit. Warning fixes discovered by
-the new gate are an approved non-goal and must not be folded into this workflow
-commit. A timeout change is also excluded unless CI Full supplies concrete
-cold-cache runtime evidence; if that evidence requires a timeout follow-up,
-pause and obtain scope confirmation before creating a separate atomic commit.
-
-### Step 7: Verify the committed implementation
-
-Run:
-
-```bash
-git show --stat --oneline HEAD
-git show --format= --name-only HEAD
-git status --short
-```
-
-Expected result: the commit names only
-`.github/workflows/e2e-reusable.yml`, and the worktree is clean.
-
-## GitHub validation after publication
-
-The implementation is not fully validated until CI runs on GitHub's macOS
-runner. After the branch is pushed and its PR is opened against
-`tinyhumansai/openhuman:main`, manually dispatch `.github/workflows/ci-full.yml`
-on the implementation branch (CI Full's automatic PR trigger targets `release`,
-not `main`).
-
-Inspect `Build (macOS full)` and confirm:
-
-1. `Build E2E app` succeeds before the new step.
-2. `Clippy (macOS-gated Rust)` executes
- `bash scripts/ci-cancel-aware.sh pnpm rust:clippy`.
-3. The log shows root `cargo clippy -p openhuman -- -D warnings` and then Tauri
- `cargo clippy --manifest-path src-tauri/Cargo.toml -- -D warnings`.
-4. `Package build artifact` and `Upload build artifact` run only after Clippy
- succeeds.
-5. Every `E2E (macOS full / …)` shard starts after `build-macos-full` and
- completes successfully.
-6. `Desktop E2E (full suite, 3 OS)` succeeds and `CI Full Gate` remains green.
-7. The `Build (macOS full)` total duration is recorded, including whether the
- Cargo caches were hits or misses.
-
-Do not infer failure-path behavior by intentionally committing a warning to the
-PR. The workflow's default step semantics already propagate the non-zero exit,
-the packaging steps have no `always()` override, and the macOS shards already
-declare `needs: build-macos-full`.
-
-If a real cold-cache run approaches or exceeds 60 minutes, preserve the run URL
-and timing as evidence and treat any timeout adjustment as a separately scoped
-follow-up. If Clippy exposes existing macOS-only warnings, report their exact
-paths and diagnostics separately; fixing them is outside this implementation
-plan.
-
-## Definition of done
-
-- The atomic implementation commit changes only
- `.github/workflows/e2e-reusable.yml`.
-- `build-macos-full` runs the aggregate `pnpm rust:clippy` command on
- `macos-latest` through `scripts/ci-cancel-aware.sh`.
-- Clippy is ordered after the E2E app build and before artifact packaging.
-- Both package-script Clippy commands retain `-D warnings`.
-- The 60-minute timeout, CI Lite, and existing gate topology are unchanged.
-- Local structural, Prettier, YAML syntax, whitespace, and diff-scope checks
- pass.
-- A manually dispatched CI Full run proves the macOS build artifact and
- downstream shards still complete, records runtime, and leaves
- `CI Full Gate` green.
diff --git a/docs/plans/2026-07-24-react-reuse-foundation.md b/docs/plans/2026-07-24-react-reuse-foundation.md
deleted file mode 100644
index 5acc260877..0000000000
--- a/docs/plans/2026-07-24-react-reuse-foundation.md
+++ /dev/null
@@ -1,1270 +0,0 @@
-# React Reuse Foundation Implementation Plan
-
-Date: 2026-07-24
-
-Design: `docs/specs/2026-07-24-react-reuse-foundation-design.md`
-
-Branch: `react-reuse-foundation`
-
-## Scope and invariants
-
-This plan implements the approved React reuse foundation in the design's delivery
-order. It consolidates repeated presentation and client-side state mechanics while
-preserving RPC contracts, authorization decisions, persistence formats, copy,
-layout, and domain-specific state unions.
-
-The following remain out of scope:
-
-- HTTP JSON-RPC transport consolidation.
-- A general form schema or universal status model.
-- Drawer/full-screen-gate/consent-overlay unification.
-- Socket event alias consolidation.
-- Skeleton and live-stream atoms.
-- Card polymorphism unless a migration below proves it is required. None currently
- does, so `app/src/components/ui/Card.tsx` is not changed by this plan.
-
-Run every command below from the repository root.
-
-For every task, follow the same discipline:
-
-1. Add the focused test and run the stated targeted command to see it fail for the
- intended missing behavior.
-2. Add the minimum shared implementation and migrate only the named consumers.
-3. Run the targeted tests, then `pnpm typecheck`.
-4. Review `git diff --check` and the task-scoped diff.
-5. Commit only the explicitly listed files with the task's `atomic-commit` command
- before starting the next task.
-
-## Task 1: Strengthen `ModalShell` and promote the global `ConfirmDialog`
-
-**Files**
-
-- Create: `app/src/components/ui/ModalShell.test.tsx`
-- Create: `app/src/components/ui/ConfirmDialog.tsx`
-- Create: `app/src/components/ui/ConfirmDialog.test.tsx`
-- Modify: `app/src/components/ui/ModalShell.tsx`
-- Modify: `app/src/components/ui/index.ts`
-- Modify: `app/src/agentworld/components/ConfirmDialog.tsx`
-- Modify: `app/src/agentworld/components/ConfirmDialog.test.tsx`
-
-### Red
-
-Add `ModalShell.test.tsx` coverage for:
-
-- focus moves into the dialog on mount and returns to the previously focused
- element on unmount;
-- Escape and backdrop close when `closePolicy` permits them;
-- Escape, backdrop, and the close button do not close while closing is disabled;
-- the close button is omitted when closing is disabled;
-- `footer` renders in a dedicated border-top slot after the content;
-- an explicit `aria-describedby` value is forwarded.
-
-Add `ConfirmDialog.test.tsx` coverage for string and React-node bodies, neutral and
-destructive confirmation tones, busy labels, disabled actions, Escape/backdrop
-suppression while busy, and focus restoration.
-
-Run:
-
-```bash
-pnpm test -- app/src/components/ui/ModalShell.test.tsx app/src/components/ui/ConfirmDialog.test.tsx
-```
-
-Expected failure: the new props and global component do not exist.
-
-### Green
-
-Change `ModalShell` to export these concrete contracts:
-
-```ts
-export interface ModalClosePolicy {
- escape?: boolean;
- backdrop?: boolean;
- button?: boolean;
-}
-
-export interface ModalShellProps {
- children: ReactNode;
- onClose: () => void;
- title: ReactNode;
- titleId: string;
- subtitle?: ReactNode;
- icon?: ReactNode;
- footer?: ReactNode;
- maxWidthClassName?: string;
- contentClassName?: string;
- panelClassName?: string;
- labelledBy?: string;
- describedBy?: string;
- closePolicy?: ModalClosePolicy;
-}
-```
-
-Default every close-policy field to `true`. Treat an explicit `false` independently:
-for example, a dialog may retain a close button while suppressing backdrop close.
-Keep portal rendering and focus restoration. Render `footer`, when present, as:
-
-```tsx
-<div className="border-t border-line-subtle px-5 py-4">{footer}</div>
-```
-
-Create the global confirmation contract:
-
-```ts
-export interface ConfirmDialogProps {
- title: ReactNode;
- body: ReactNode;
- titleId?: string;
- confirmLabel?: ReactNode;
- cancelLabel?: ReactNode;
- busy?: boolean;
- busyLabel?: ReactNode;
- confirmDisabled?: boolean;
- destructive?: boolean;
- onConfirm: () => void;
- onCancel: () => void;
-}
-```
-
-`ConfirmDialog` must compose `ModalShell`, place actions in its `footer`, use
-`Button` with `tone="danger"` only when `destructive` is true, and set all three
-close-policy fields to `false` while busy. `confirmDisabled` disables only the
-confirm action and does not change dismissal policy. Default `titleId` to
-`"confirm-dialog-title"`, `destructive` to `false`, and labels to
-`"Confirm"`, `"Cancel"`, and `"Working…"`.
-
-Export both components and their public types from `app/src/components/ui/index.ts`.
-Replace the Agent World implementation with a compatibility wrapper that maps its
-existing `message` prop to global `body`, retains its destructive-by-default
-behavior, and delegates all interaction to the global component. Keep the existing
-default export so current imports do not break yet.
-
-### Verify
-
-```bash
-pnpm test -- app/src/components/ui/ModalShell.test.tsx app/src/components/ui/ConfirmDialog.test.tsx app/src/agentworld/components/ConfirmDialog.test.tsx
-pnpm typecheck
-git diff --check
-```
-
-### Commit
-
-```bash
-atomic-commit "refactor(ui): establish reusable dialog primitives" -- app/src/components/ui/ModalShell.tsx app/src/components/ui/ModalShell.test.tsx app/src/components/ui/ConfirmDialog.tsx app/src/components/ui/ConfirmDialog.test.tsx app/src/components/ui/index.ts app/src/agentworld/components/ConfirmDialog.tsx app/src/agentworld/components/ConfirmDialog.test.tsx
-```
-
-## Task 2: Migrate ordinary confirmations to the shared dialog boundary
-
-**Files**
-
-- Modify: `app/src/components/intelligence/SyncConfirmDialog.tsx`
-- Create: `app/src/components/intelligence/SyncConfirmDialog.test.tsx`
-- Modify: `app/src/components/settings/panels/TeamMembersPanel.tsx`
-- Modify: `app/src/components/settings/panels/__tests__/TeamMembersPanel.test.tsx`
-
-### Red
-
-Add a focused `SyncConfirmDialog` test that asserts dialog naming, loading/error/
-ready body states, disabled confirmation before an estimate is available, backdrop
-and Escape cancellation, and focus restoration. Extend the Team Members tests to
-assert that remove-member and role-change confirmations are accessible dialogs,
-close by Escape when idle, and cannot close or double-submit while their action is
-busy.
-
-Run:
-
-```bash
-pnpm test -- app/src/components/intelligence/SyncConfirmDialog.test.tsx app/src/components/settings/panels/__tests__/TeamMembersPanel.test.tsx
-```
-
-Expected failure: the hand-built overlays lack the shared close/focus behavior.
-
-### Green
-
-Refactor `SyncConfirmDialog` to render `ConfirmDialog` with:
-
-- `title={t('syncConfirm.title')}`;
-- a React-node `body` containing estimating, error, estimate, and budget-note
- states;
-- `confirmLabel={t('syncConfirm.proceed')}`;
-- `cancelLabel={t('syncConfirm.cancel')}`;
-- `confirmDisabled={!estimate}`;
-- `destructive={false}`.
-
-Keep the existing RPC and cancellation guard unchanged. Disable confirmation when
-there is no estimate, while preserving the current ability to cancel during
-estimation or after an estimate error.
-
-Replace both Team Members overlays with global `ConfirmDialog` instances. Preserve
-all localized copy and the existing `confirmRemoveMember`/
-`confirmChangeRole` functions. The remove action is destructive; role change is
-neutral. Render the existing error with `ErrorBanner` inside `body`. Pass each
-in-flight ID comparison as `busy` so shared close policy prevents dismissal during
-the mutation.
-
-### Verify
-
-```bash
-pnpm test -- app/src/components/intelligence/SyncConfirmDialog.test.tsx app/src/components/settings/panels/__tests__/TeamMembersPanel.test.tsx
-pnpm typecheck
-git diff --check
-```
-
-### Commit
-
-```bash
-atomic-commit "refactor(ui): reuse confirmation dialogs" -- app/src/components/intelligence/SyncConfirmDialog.tsx app/src/components/intelligence/SyncConfirmDialog.test.tsx app/src/components/settings/panels/TeamMembersPanel.tsx app/src/components/settings/panels/__tests__/TeamMembersPanel.test.tsx
-```
-
-## Task 3: Strengthen and adopt existing loading, error, input, and chip primitives
-
-**Files**
-
-- Create: `app/src/components/ui/LoadingState.test.tsx`
-- Modify: `app/src/components/ui/LoadingState.tsx`
-- Create: `app/src/components/ui/Input.test.tsx`
-- Modify: `app/src/components/ui/Input.tsx`
-- Modify: `app/src/components/layout/ChipTabs.tsx`
-- Modify: `app/src/components/layout/ChipTabs.test.tsx`
-- Modify: `app/src/components/flows/FlowRunsDrawer.tsx`
-- Modify: `app/src/components/flows/FlowRunsDrawer.test.tsx`
-- Modify: `app/src/agentworld/pages/IdentitiesSection.tsx`
-- Modify: `app/src/agentworld/pages/IdentitiesSection.test.tsx`
-- Modify: `app/src/components/channels/mcp/McpCatalogBrowser.tsx`
-- Modify: `app/src/components/channels/mcp/McpCatalogBrowser.test.tsx`
-
-### Red
-
-Test these exact contracts:
-
-```ts
-export interface ErrorBannerProps {
- children?: ReactNode;
- message?: ReactNode;
- action?: ReactNode;
- size?: "sm" | "md";
- className?: string;
-}
-
-export interface InputProps extends Omit<
- InputHTMLAttributes<HTMLInputElement>,
- "size"
-> {
- inputSize?: "sm" | "md" | "lg";
- invalid?: boolean;
- monospace?: boolean;
-}
-
-export interface ChipTabItem<T extends string> {
- id: T;
- label: ReactNode;
- testId?: string;
- controls?: string;
- labelledBy?: string;
-}
-
-export interface ChipTabsProps<T extends string> {
- // existing props remain
- compact?: boolean;
-}
-```
-
-`ErrorBanner` must have `role="alert"`, accept React content, render an optional
-action, and retain the existing `message` call sites. `Input` must set
-`aria-invalid` when invalid and add `font-mono` only for `monospace`.
-`ChipTabs` must connect tab and panel IDs with `aria-controls`/`aria-labelledby`,
-use roving `tabIndex` (`0` selected, `-1` unselected), and reduce chip padding when
-`compact`.
-
-Add consumer assertions showing the Flow Runs drawer uses shared loading/error
-states, Identities uses the shared error banner, and MCP catalog search is the
-shared `Input`.
-
-Run:
-
-```bash
-pnpm test -- app/src/components/ui/LoadingState.test.tsx app/src/components/ui/Input.test.tsx app/src/components/layout/ChipTabs.test.tsx app/src/components/flows/FlowRunsDrawer.test.tsx app/src/agentworld/pages/IdentitiesSection.test.tsx app/src/components/channels/mcp/McpCatalogBrowser.test.tsx
-```
-
-Expected failure: accessibility/variant props and consumer adoption are absent.
-
-### Green
-
-Implement only the tested semantic variants. In `FlowRunsDrawer`, replace the
-hand-built spinner and error box with `CenteredLoadingState` and `ErrorBanner`
-while retaining the existing test IDs on wrappers. In `IdentitiesSection`, delete
-its local `ErrorBanner` and import the shared primitive. In `McpCatalogBrowser`,
-replace the plain search input with `Input`, retaining all value, placeholder,
-event, and test attributes.
-
-Do not convert semantically distinct warning, validation, or fatal-gate messages.
-Do not change `Card.tsx`.
-
-### Verify
-
-```bash
-pnpm test -- app/src/components/ui/LoadingState.test.tsx app/src/components/ui/Input.test.tsx app/src/components/layout/ChipTabs.test.tsx app/src/components/flows/FlowRunsDrawer.test.tsx app/src/agentworld/pages/IdentitiesSection.test.tsx app/src/components/channels/mcp/McpCatalogBrowser.test.tsx
-pnpm typecheck
-git diff --check
-```
-
-### Commit
-
-```bash
-atomic-commit "refactor(ui): strengthen and adopt existing primitives" -- app/src/components/ui/LoadingState.tsx app/src/components/ui/LoadingState.test.tsx app/src/components/ui/Input.tsx app/src/components/ui/Input.test.tsx app/src/components/layout/ChipTabs.tsx app/src/components/layout/ChipTabs.test.tsx app/src/components/flows/FlowRunsDrawer.tsx app/src/components/flows/FlowRunsDrawer.test.tsx app/src/agentworld/pages/IdentitiesSection.tsx app/src/agentworld/pages/IdentitiesSection.test.tsx app/src/components/channels/mcp/McpCatalogBrowser.tsx app/src/components/channels/mcp/McpCatalogBrowser.test.tsx
-```
-
-## Task 4: Extract the Agent World `StatusBlock`
-
-**Files**
-
-- Create: `app/src/agentworld/components/StatusBlock.tsx`
-- Create: `app/src/agentworld/components/StatusBlock.test.tsx`
-- Modify: `app/src/agentworld/pages/FeedSection.tsx`
-- Modify: `app/src/agentworld/pages/DirectorySection.tsx`
-- Modify: `app/src/agentworld/pages/LedgerSection.tsx`
-- Modify: `app/src/agentworld/pages/JobsSection.tsx`
-- Modify: `app/src/agentworld/pages/BountiesSection.tsx`
-- Modify: `app/src/agentworld/pages/ProfilesSection.tsx`
-- Modify: `app/src/agentworld/pages/ProfileViewer.tsx`
-- Modify: `app/src/agentworld/pages/ExploreSection/index.tsx`
-
-### Red
-
-Add component tests for:
-
-```ts
-export type StatusBlockTone =
- | "neutral"
- | "info"
- | "success"
- | "warning"
- | "danger";
-
-export interface StatusBlockProps {
- tone?: StatusBlockTone;
- title: ReactNode;
- body?: ReactNode;
- loading?: boolean;
- action?: ReactNode;
- className?: string;
-}
-```
-
-Assert semantic tone classes, optional body/action omission, loading spinner
-accessibility, and a stable `data-testid="agentworld-status-block"`.
-
-Run:
-
-```bash
-pnpm test -- app/src/agentworld/components/StatusBlock.test.tsx
-```
-
-Expected failure: the shared component does not exist.
-
-### Green
-
-Implement the component with a semantic internal tone map; callers must not pass
-Tailwind color strings. Preserve the existing centered `h-64`, title, body width,
-and text sizing. When `loading` is true, render the shared `Spinner` before the
-title and expose `aria-busy="true"`.
-
-Delete all eight local `StatusBlock` implementations and import the shared one.
-Map existing colors to tones without changing copy:
-
-- muted/ordinary empty states -> `neutral`;
-- primary/ocean states -> `info`;
-- amber/payment-required states -> `warning`;
-- coral/red errors -> `danger`;
-- sage successful states -> `success`.
-
-Use `className` only for layout differences already present; do not recreate tone
-classes at call sites.
-
-### Verify
-
-```bash
-pnpm test -- app/src/agentworld/components/StatusBlock.test.tsx app/src/agentworld/pages/FeedSection.test.tsx app/src/agentworld/pages/DirectorySection.test.tsx app/src/agentworld/pages/LedgerSection.test.tsx app/src/agentworld/pages/JobsSection.test.tsx app/src/agentworld/pages/BountiesSection.test.tsx app/src/agentworld/pages/ProfilesSection.test.tsx app/src/agentworld/pages/ProfileViewer.test.tsx app/src/agentworld/pages/ExploreSection/ExploreSection.test.tsx
-pnpm typecheck
-git diff --check
-```
-
-### Commit
-
-```bash
-atomic-commit "refactor(agentworld): share status block presentation" -- app/src/agentworld/components/StatusBlock.tsx app/src/agentworld/components/StatusBlock.test.tsx app/src/agentworld/pages/FeedSection.tsx app/src/agentworld/pages/DirectorySection.tsx app/src/agentworld/pages/LedgerSection.tsx app/src/agentworld/pages/JobsSection.tsx app/src/agentworld/pages/BountiesSection.tsx app/src/agentworld/pages/ProfilesSection.tsx app/src/agentworld/pages/ProfileViewer.tsx app/src/agentworld/pages/ExploreSection/index.tsx
-```
-
-## Task 5: Extract one Agent World wallet identity state contract
-
-**Files**
-
-- Create: `app/src/agentworld/hooks/useMyAgentId.ts`
-- Create: `app/src/agentworld/hooks/useMyAgentId.test.ts`
-- Modify: `app/src/agentworld/pages/DirectorySection.tsx`
-- Modify: `app/src/agentworld/pages/JobsSection.tsx`
-- Modify: `app/src/agentworld/pages/BountiesSection.tsx`
-- Modify: `app/src/agentworld/pages/MessagingSection.tsx`
-- Modify: `app/src/agentworld/pages/ProfileViewer.tsx`
-
-### Red
-
-Test this discriminated state:
-
-```ts
-export type MyAgentIdState =
- | { status: "loading" }
- | { status: "disconnected" }
- | { status: "ready"; agentId: string }
- | { status: "error"; error: Error };
-
-export function useMyAgentId(): MyAgentIdState;
-```
-
-Cover a Solana account, no Solana account, rejected fetch, stale completion after
-unmount, and ignoring non-Solana accounts. The error state must wrap non-`Error`
-rejections in `new Error(String(value))`; it must not log the error content.
-
-Run:
-
-```bash
-pnpm test -- app/src/agentworld/hooks/useMyAgentId.test.ts
-```
-
-Expected failure: the shared hook does not exist.
-
-### Green
-
-Implement one `fetchWalletStatus()` call per mounted hook instance and the explicit
-state transitions above. Replace the five local `useMyAgentId(): string | null`
-copies in Directory, Jobs, Bounties, Messaging, and Profile Viewer. Adapt their
-existing null checks to:
-
-```ts
-const myAgent = useMyAgentId();
-const myAgentId = myAgent.status === "ready" ? myAgent.agentId : null;
-```
-
-Leave Profiles, Feed, and `WalletAddressChip` on their existing richer resource
-flows. Profiles chains wallet resolution into profile and directory fallbacks,
-Feed distinguishes an unknown transport failure from a proven missing wallet, and
-`WalletAddressChip` owns retry behavior. Forcing those behaviors through this
-identity-only hook would change their state contracts. They can be reconsidered
-later behind a richer wallet-resource abstraction.
-
-### Verify
-
-```bash
-pnpm test -- app/src/agentworld/hooks/useMyAgentId.test.ts app/src/agentworld/pages/DirectorySection.test.tsx app/src/agentworld/pages/JobsSection.test.tsx app/src/agentworld/pages/BountiesSection.test.tsx app/src/agentworld/pages/MessagingSection.test.tsx app/src/agentworld/pages/ProfileViewer.test.tsx
-pnpm typecheck
-git diff --check
-```
-
-### Commit
-
-```bash
-atomic-commit "refactor(agentworld): centralize wallet identity resolution" -- app/src/agentworld/hooks/useMyAgentId.ts app/src/agentworld/hooks/useMyAgentId.test.ts app/src/agentworld/pages/DirectorySection.tsx app/src/agentworld/pages/JobsSection.tsx app/src/agentworld/pages/BountiesSection.tsx app/src/agentworld/pages/MessagingSection.tsx app/src/agentworld/pages/ProfileViewer.tsx
-```
-
-## Task 6: Extract Agent World form layout primitives
-
-**Files**
-
-- Create: `app/src/agentworld/components/FormField.tsx`
-- Create: `app/src/agentworld/components/FormField.test.tsx`
-- Create: `app/src/agentworld/components/FormActions.tsx`
-- Create: `app/src/agentworld/components/FormActions.test.tsx`
-- Modify: `app/src/agentworld/pages/JobsSection.tsx`
-- Modify: `app/src/agentworld/pages/JobsSection.test.tsx`
-- Modify: `app/src/agentworld/pages/BountiesSection.tsx`
-- Modify: `app/src/agentworld/pages/BountiesSection.test.tsx`
-
-### Red
-
-Test these contracts:
-
-```ts
-export interface FormFieldProps {
- id: string;
- label: ReactNode;
- children: ReactElement;
- description?: ReactNode;
- error?: ReactNode;
- required?: boolean;
- className?: string;
-}
-
-export interface FormActionsProps {
- children: ReactNode;
- align?: "start" | "end" | "stretch";
- className?: string;
-}
-```
-
-`FormField` must clone its single form control child to set `id`,
-`aria-describedby`, `aria-invalid`, and `required` without overwriting explicit
-child values. Description and error IDs must be `${id}-description` and
-`${id}-error`; error content has `role="alert"`. `FormActions` must map alignments
-to stable flex layouts, with `end` as the default.
-
-Run:
-
-```bash
-pnpm test -- app/src/agentworld/components/FormField.test.tsx app/src/agentworld/components/FormActions.test.tsx
-```
-
-Expected failure: the primitives do not exist.
-
-### Green
-
-Migrate the Post Job, Apply, Open Dispute, Create Bounty, Submit Work, Add Comment,
-and bounty dispute forms in the named page files. Use globally unique IDs prefixed
-by the form (`post-job-title`, `create-bounty-title`, `submit-work-url`). Replace
-plain text inputs with shared `Input` where their behavior matches it. Keep
-textareas/selects native and pass them as `FormField` children. Replace repeated
-right-aligned action wrappers with `FormActions`.
-
-Do not move form state, validation, RPC calls, or submit handlers into the
-primitives.
-
-### Verify
-
-```bash
-pnpm test -- app/src/agentworld/components/FormField.test.tsx app/src/agentworld/components/FormActions.test.tsx app/src/agentworld/pages/JobsSection.test.tsx app/src/agentworld/pages/BountiesSection.test.tsx
-pnpm typecheck
-git diff --check
-```
-
-### Commit
-
-```bash
-atomic-commit "refactor(agentworld): share form field layout" -- app/src/agentworld/components/FormField.tsx app/src/agentworld/components/FormField.test.tsx app/src/agentworld/components/FormActions.tsx app/src/agentworld/components/FormActions.test.tsx app/src/agentworld/pages/JobsSection.tsx app/src/agentworld/pages/JobsSection.test.tsx app/src/agentworld/pages/BountiesSection.tsx app/src/agentworld/pages/BountiesSection.test.tsx
-```
-
-## Task 7: Extract accessible expandable resource-row mechanics
-
-**Files**
-
-- Create: `app/src/agentworld/components/ExpandableResourceRow.tsx`
-- Create: `app/src/agentworld/components/ExpandableResourceRow.test.tsx`
-- Modify: `app/src/agentworld/pages/JobsSection.tsx`
-- Modify: `app/src/agentworld/pages/JobsSection.test.tsx`
-- Modify: `app/src/agentworld/pages/BountiesSection.tsx`
-- Modify: `app/src/agentworld/pages/BountiesSection.test.tsx`
-
-### Red
-
-Test this composition API:
-
-```ts
-export interface ExpandableResourceRowProps {
- id: string;
- expanded: boolean;
- onToggle: () => void;
- summary: ReactNode;
- children: ReactNode;
- className?: string;
- expandedClassName?: string;
- summaryClassName?: string;
- detailClassName?: string;
-}
-```
-
-The summary must be a real button with `aria-expanded` and
-`aria-controls="${id}-details"`. The details wrapper must use that ID,
-`role="region"`, and `aria-labelledby="${id}-toggle"`, and be absent while
-collapsed. The shared component owns the rotating chevron and disclosure
-mechanics; it does not own job/bounty content or side effects.
-
-Run:
-
-```bash
-pnpm test -- app/src/agentworld/components/ExpandableResourceRow.test.tsx
-```
-
-Expected failure: the shared disclosure component does not exist.
-
-### Green
-
-Wrap `JobRow` and `BountyRow` with the shared component. Pass their current summary
-markup through `summary` and current detail markup through `children`. Preserve
-the job list's border-row shape and bounty grid card shape with the explicit class
-props. Keep Bounty's detail-fetch effect in `BountyRow`, keyed by `expanded` and
-`bountyId`; do not move it into the presentation primitive.
-
-Add consumer assertions for unique control/detail IDs and keyboard activation.
-
-### Verify
-
-```bash
-pnpm test -- app/src/agentworld/components/ExpandableResourceRow.test.tsx app/src/agentworld/pages/JobsSection.test.tsx app/src/agentworld/pages/BountiesSection.test.tsx
-pnpm typecheck
-git diff --check
-```
-
-### Commit
-
-```bash
-atomic-commit "refactor(agentworld): share expandable resource rows" -- app/src/agentworld/components/ExpandableResourceRow.tsx app/src/agentworld/components/ExpandableResourceRow.test.tsx app/src/agentworld/pages/JobsSection.tsx app/src/agentworld/pages/JobsSection.test.tsx app/src/agentworld/pages/BountiesSection.tsx app/src/agentworld/pages/BountiesSection.test.tsx
-```
-
-## Task 8: Consolidate flow-run list query coordination
-
-**Files**
-
-- Create: `app/src/hooks/useFlowRunsQuery.ts`
-- Create: `app/src/hooks/__tests__/useFlowRunsQuery.test.ts`
-- Modify: `app/src/components/flows/FlowRunsSidebar.tsx`
-- Modify: `app/src/components/flows/FlowRunsSidebar.test.tsx`
-- Modify: `app/src/components/flows/FlowRunsDrawer.tsx`
-- Modify: `app/src/components/flows/FlowRunsDrawer.test.tsx`
-- Modify: `app/src/pages/WorkflowRunsPage.tsx`
-- Modify: `app/src/pages/WorkflowRunsPage.test.tsx`
-
-### Red
-
-Test this API:
-
-```ts
-export type FlowRunsQueryScope =
- | { kind: "flow"; flowId: string | null }
- | { kind: "all" };
-
-export interface UseFlowRunsQueryOptions {
- scope: FlowRunsQueryScope;
- enabled?: boolean;
-}
-
-export interface UseFlowRunsQueryResult {
- runs: FlowRun[];
- loading: boolean;
- error: string | null;
- refresh: () => Promise<void>;
- refreshSilently: () => Promise<void>;
-}
-
-export function useFlowRunsQuery(
- options: UseFlowRunsQueryOptions,
-): UseFlowRunsQueryResult;
-```
-
-Cover initial loading, disabled/null-flow reset, flow/all endpoint selection, flow
-changes, error normalization, silent refresh preserving visible data/error state,
-latest-request-wins for both initial and silent requests, and no state updates
-after unmount.
-
-Run:
-
-```bash
-pnpm test -- app/src/hooks/__tests__/useFlowRunsQuery.test.ts
-```
-
-Expected failure: the hook does not exist.
-
-### Green
-
-Implement the query hook with a request generation and mounted guard. `refresh`
-sets `loading` and clears the foreground error. `refreshSilently` changes only
-`runs` on success and drops/logs failures without exposing raw payloads. Choose
-`listFlowRuns(flowId)` for `kind: 'flow'` and `listAllFlowRuns()` for `kind: 'all'`.
-Key effects on `scope.kind` and `scope.kind === 'flow' ? scope.flowId : null`, not
-the caller's object identity. Guard success, failure, and `finally` updates with the
-same generation so a stale request cannot clear a newer request's loading state.
-
-Migrate Sidebar, Drawer, and All Runs Page to the hook. Keep:
-
-- Drawer selection reset on `flowId` change;
-- `useFlowRunsLiveRefresh(runs, refreshSilently)`;
-- `useFlowRunStarted(() => void refreshSilently(), flowId?)`;
-- All Runs Page's separate `listFlows()` name lookup and its own error handling.
-
-For All Runs Page, start the run query and `listFlows()` together. Track
-`flowNamesLoading`/`flowNamesError` locally and derive page state as
-`loading || flowNamesLoading` and `error ?? flowNamesError`; a silent run refresh
-must not reload names.
-
-Delete each consumer's duplicated generation refs and run-list load functions.
-Do not move flow-name loading into `useFlowRunsQuery`.
-
-### Verify
-
-```bash
-pnpm test -- app/src/hooks/__tests__/useFlowRunsQuery.test.ts app/src/components/flows/FlowRunsSidebar.test.tsx app/src/components/flows/FlowRunsDrawer.test.tsx app/src/pages/WorkflowRunsPage.test.tsx app/src/hooks/__tests__/useFlowRunsLiveRefresh.test.ts app/src/hooks/__tests__/useFlowRunStarted.test.ts
-pnpm typecheck
-git diff --check
-```
-
-### Commit
-
-```bash
-atomic-commit "refactor(flows): centralize run list queries" -- app/src/hooks/useFlowRunsQuery.ts app/src/hooks/__tests__/useFlowRunsQuery.test.ts app/src/components/flows/FlowRunsSidebar.tsx app/src/components/flows/FlowRunsSidebar.test.tsx app/src/components/flows/FlowRunsDrawer.tsx app/src/components/flows/FlowRunsDrawer.test.tsx app/src/pages/WorkflowRunsPage.tsx app/src/pages/WorkflowRunsPage.test.tsx
-```
-
-## Task 9: Share one pending-approval polling source
-
-**Files**
-
-- Create: `app/src/hooks/flowPendingApprovalsStore.ts`
-- Create: `app/src/hooks/__tests__/flowPendingApprovalsStore.test.ts`
-- Modify: `app/src/hooks/useFlowPendingApprovals.ts`
-- Modify: `app/src/hooks/__tests__/useFlowPendingApprovals.test.ts`
-- Modify: `app/src/hooks/useRunsPendingApprovalSet.ts`
-- Modify: `app/src/hooks/__tests__/useRunsPendingApprovalSet.test.ts`
-
-### Red
-
-Test a module-scoped external store with this public surface:
-
-```ts
-export interface FlowPendingApprovalsSnapshot {
- approvals: PendingApproval[];
- error: string | null;
- polling: boolean;
-}
-
-export function subscribeFlowPendingApprovals(listener: () => void): () => void;
-export function getFlowPendingApprovalsSnapshot(): FlowPendingApprovalsSnapshot;
-export function retainFlowPendingApprovalsPolling(): () => void;
-export function refreshFlowPendingApprovals(): Promise<void>;
-
-export function useFlowPendingApprovalsSource(
- enabled: boolean,
-): FlowPendingApprovalsSnapshot;
-```
-
-Use `useSyncExternalStore` in the hook. Cover one immediate fetch for two concurrent
-subscribers, one timer regardless of subscriber count, continued polling until the
-last enabled consumer releases, immutable snapshots, retry after transient failure,
-and timer/request cleanup. Provide a test-only reset export guarded by
-`import.meta.env.MODE === 'test'` or an internal exported reset named
-`resetFlowPendingApprovalsStoreForTests`.
-
-Run:
-
-```bash
-pnpm test -- app/src/hooks/__tests__/flowPendingApprovalsStore.test.ts app/src/hooks/__tests__/useFlowPendingApprovals.test.ts app/src/hooks/__tests__/useRunsPendingApprovalSet.test.ts
-```
-
-Expected failure: the shared source is absent and current hooks poll independently.
-
-### Green
-
-Poll every 2 seconds while the retain count is positive. Keep the last successful
-approval list on failure and expose a normalized error. Never log approval payloads
-or user-authored error text.
-
-Refactor `useFlowPendingApprovals(flowId, runId)` to select approvals matching both
-IDs from the shared snapshot. Keep its `decidingId` and `decide` mutation locally;
-after a successful decision, call `refreshFlowPendingApprovals()` so every consumer
-reconciles.
-
-Refactor `useRunsPendingApprovalSet(runs)` to retain polling only while any run is
-`running` and derive the set from the shared snapshot. Keep
-`resolveDisplayStatus` unchanged. Remove both private polling loops.
-
-### Verify
-
-```bash
-pnpm test -- app/src/hooks/__tests__/flowPendingApprovalsStore.test.ts app/src/hooks/__tests__/useFlowPendingApprovals.test.ts app/src/hooks/__tests__/useRunsPendingApprovalSet.test.ts app/src/components/flows/FlowRunsSidebar.test.tsx app/src/components/flows/FlowRunsDrawer.test.tsx app/src/pages/WorkflowRunsPage.test.tsx
-pnpm typecheck
-git diff --check
-```
-
-### Commit
-
-```bash
-atomic-commit "refactor(flows): share pending approval polling" -- app/src/hooks/flowPendingApprovalsStore.ts app/src/hooks/__tests__/flowPendingApprovalsStore.test.ts app/src/hooks/useFlowPendingApprovals.ts app/src/hooks/__tests__/useFlowPendingApprovals.test.ts app/src/hooks/useRunsPendingApprovalSet.ts app/src/hooks/__tests__/useRunsPendingApprovalSet.test.ts
-```
-
-## Task 10: Add a reusable latest-only async guard
-
-**Files**
-
-- Create: `app/src/hooks/useLatestAsync.ts`
-- Create: `app/src/hooks/__tests__/useLatestAsync.test.ts`
-- Modify: `app/src/agentworld/pages/ExploreSection/index.tsx`
-- Modify: `app/src/agentworld/pages/ExploreSection/ExploreSection.test.tsx`
-
-### Red
-
-Test this mechanics-only API:
-
-```ts
-export interface LatestAsyncGuard {
- begin: () => number;
- isLatest: (generation: number) => boolean;
- invalidate: () => void;
-}
-
-export function useLatestAsync(): LatestAsyncGuard;
-```
-
-`begin()` returns a monotonically increasing generation, `isLatest()` is true only
-for the newest generation while mounted, `invalidate()` makes all prior generations
-stale, and unmount invalidates outstanding work. The returned methods must be
-referentially stable.
-
-Run:
-
-```bash
-pnpm test -- app/src/hooks/__tests__/useLatestAsync.test.ts
-```
-
-Expected failure: the hook does not exist.
-
-### Green
-
-Implement with refs and stable callbacks; it must not store results or dictate
-loading/error state. Use it in the four Explore async resource hooks in
-`ExploreSection/index.tsx`, replacing their repeated cancellation booleans with
-`begin()`/`isLatest()` checks. Preserve PaymentRequiredError and wallet-error
-classification exactly.
-
-Add a consumer regression where request B resolves before request A and A cannot
-overwrite B.
-
-### Verify
-
-```bash
-pnpm test -- app/src/hooks/__tests__/useLatestAsync.test.ts app/src/agentworld/pages/ExploreSection/ExploreSection.test.tsx
-pnpm typecheck
-git diff --check
-```
-
-### Commit
-
-```bash
-atomic-commit "refactor(hooks): add latest async guard" -- app/src/hooks/useLatestAsync.ts app/src/hooks/__tests__/useLatestAsync.test.ts app/src/agentworld/pages/ExploreSection/index.tsx app/src/agentworld/pages/ExploreSection/ExploreSection.test.tsx
-```
-
-## Task 11: Add reusable debounced values
-
-**Files**
-
-- Create: `app/src/hooks/useDebouncedValue.ts`
-- Create: `app/src/hooks/__tests__/useDebouncedValue.test.ts`
-- Modify: `app/src/components/channels/mcp/McpCatalogBrowser.tsx`
-- Modify: `app/src/components/channels/mcp/McpCatalogBrowser.test.tsx`
-- Modify: `app/src/components/channels/mcp/McpServersTab.tsx`
-- Modify: `app/src/components/channels/mcp/McpServersTab.test.tsx`
-
-### Red
-
-Test:
-
-```ts
-export function useDebouncedValue<T>(value: T, delayMs: number): T;
-```
-
-Cover initial value, delayed update, replacement of a pending timer, delay changes,
-referential values, and unmount cleanup.
-
-Run:
-
-```bash
-pnpm test -- app/src/hooks/__tests__/useDebouncedValue.test.ts
-```
-
-Expected failure: the hook does not exist.
-
-### Green
-
-Implement trailing debounce with `useEffect` and `window.setTimeout`. Normalize a
-negative delay to zero so a bad configuration cannot leave a value permanently
-stale.
-
-Replace the manual debounce refs in `McpCatalogBrowser` (250 ms) and
-`McpServersTab` (300 ms). Effects should fetch from the debounced value, while
-inputs remain controlled by the immediate value. Preserve initial fetch and
-pagination reset behavior.
-
-### Verify
-
-```bash
-pnpm test -- app/src/hooks/__tests__/useDebouncedValue.test.ts app/src/components/channels/mcp/McpCatalogBrowser.test.tsx app/src/components/channels/mcp/McpServersTab.test.tsx
-pnpm typecheck
-git diff --check
-```
-
-### Commit
-
-```bash
-atomic-commit "refactor(hooks): share debounced values" -- app/src/hooks/useDebouncedValue.ts app/src/hooks/__tests__/useDebouncedValue.test.ts app/src/components/channels/mcp/McpCatalogBrowser.tsx app/src/components/channels/mcp/McpCatalogBrowser.test.tsx app/src/components/channels/mcp/McpServersTab.tsx app/src/components/channels/mcp/McpServersTab.test.tsx
-```
-
-## Task 12: Add cleanup-safe clipboard feedback
-
-**Files**
-
-- Create: `app/src/hooks/useClipboardFeedback.ts`
-- Create: `app/src/hooks/__tests__/useClipboardFeedback.test.ts`
-- Modify: `app/src/agentworld/pages/ProfileViewer.tsx`
-- Modify: `app/src/agentworld/pages/ProfileViewer.test.tsx`
-- Modify: `app/src/agentworld/components/WalletAddressChip.tsx`
-- Modify: `app/src/agentworld/components/WalletAddressChip.test.tsx`
-- Modify: `app/src/pages/Invites.tsx`
-- Create: `app/src/pages/Invites.test.tsx`
-
-### Red
-
-Test:
-
-```ts
-export type ClipboardFeedbackStatus = "idle" | "copied" | "error";
-
-export interface UseClipboardFeedbackOptions {
- resetAfterMs?: number;
- writeText?: (value: string) => Promise<void>;
-}
-
-export interface UseClipboardFeedbackResult {
- status: ClipboardFeedbackStatus;
- copy: (value: string) => Promise<boolean>;
- reset: () => void;
-}
-
-export function useClipboardFeedback(
- options?: UseClipboardFeedbackOptions,
-): UseClipboardFeedbackResult;
-```
-
-Cover success, failure, boolean result, timer replacement on repeated copy, manual
-reset, and no post-unmount updates. Default to `navigator.clipboard.writeText` and
-2 seconds. Do not retain the copied value in React state or log it.
-
-Run:
-
-```bash
-pnpm test -- app/src/hooks/__tests__/useClipboardFeedback.test.ts
-```
-
-Expected failure: the hook does not exist.
-
-### Green
-
-Migrate Profile Viewer share-link copying, Wallet Address Chip, and Invites.
-Preserve their existing labels, analytics, and visible success durations by passing
-the current timeout explicitly where it differs from 2 seconds. Preserve consumer
-error copy by mapping `status === 'error'`; do not migrate recovery phrases,
-credentials, or other sensitive clipboard flows.
-
-### Verify
-
-```bash
-pnpm test -- app/src/hooks/__tests__/useClipboardFeedback.test.ts app/src/agentworld/pages/ProfileViewer.test.tsx app/src/agentworld/components/WalletAddressChip.test.tsx app/src/pages/Invites.test.tsx
-pnpm typecheck
-git diff --check
-```
-
-### Commit
-
-```bash
-atomic-commit "refactor(hooks): share clipboard feedback" -- app/src/hooks/useClipboardFeedback.ts app/src/hooks/__tests__/useClipboardFeedback.test.ts app/src/agentworld/pages/ProfileViewer.tsx app/src/agentworld/pages/ProfileViewer.test.tsx app/src/agentworld/components/WalletAddressChip.tsx app/src/agentworld/components/WalletAddressChip.test.tsx app/src/pages/Invites.tsx app/src/pages/Invites.test.tsx
-```
-
-## Task 13: Compose Escape and outside-pointer dismissal
-
-**Files**
-
-- Create: `app/src/hooks/useDismissLayer.ts`
-- Create: `app/src/hooks/__tests__/useDismissLayer.test.ts`
-- Modify: `app/src/components/ui/ModalShell.tsx`
-- Modify: `app/src/components/ui/ModalShell.test.tsx`
-- Modify: `app/src/components/flows/FlowRunsDrawer.tsx`
-- Modify: `app/src/components/flows/FlowRunsDrawer.test.tsx`
-
-### Red
-
-Test:
-
-```ts
-export interface UseDismissLayerOptions {
- onDismiss: () => void;
- enabled?: boolean;
- dismissOnEscape?: boolean;
- dismissOnOutsidePointer?: boolean;
-}
-
-export interface DismissLayerBindings {
- layerRef: RefObject<HTMLElement | null>;
- onPointerDownCapture: (event: React.PointerEvent) => void;
-}
-
-export function useDismissLayer(
- options: UseDismissLayerOptions,
-): DismissLayerBindings;
-```
-
-The hook composes `useEscapeKey`, calls `onDismiss` only when the pointer event
-target lies outside `layerRef.current`, observes each policy independently, uses
-the latest callback without re-registering listeners, and performs no action after
-unmount.
-
-Run:
-
-```bash
-pnpm test -- app/src/hooks/__tests__/useDismissLayer.test.ts
-```
-
-Expected failure: the hook does not exist.
-
-### Green
-
-Use the hook in `ModalShell`, with the dialog panel as `layerRef` and backdrop
-policy mapped from `closePolicy.backdrop`. Use it in `FlowRunsDrawer`, with its
-`aside` as the layer and dismissal disabled while the inspector is open. Replace
-the drawer's separate Escape hook and backdrop button handler, retaining the
-backdrop as an accessible button and current test IDs.
-
-Do not migrate drawers, gates, or overlays with materially different stacking or
-consent behavior in this task.
-
-### Verify
-
-```bash
-pnpm test -- app/src/hooks/__tests__/useDismissLayer.test.ts app/src/components/ui/ModalShell.test.tsx app/src/components/flows/FlowRunsDrawer.test.tsx
-pnpm typecheck
-git diff --check
-```
-
-### Commit
-
-```bash
-atomic-commit "refactor(hooks): share dismiss layer mechanics" -- app/src/hooks/useDismissLayer.ts app/src/hooks/__tests__/useDismissLayer.test.ts app/src/components/ui/ModalShell.tsx app/src/components/ui/ModalShell.test.tsx app/src/components/flows/FlowRunsDrawer.tsx app/src/components/flows/FlowRunsDrawer.test.tsx
-```
-
-## Task 14: Extract approval decision presentation
-
-**Files**
-
-- Create: `app/src/components/approvals/ApprovalDecisionCard.tsx`
-- Create: `app/src/components/approvals/ApprovalDecisionCard.test.tsx`
-- Modify: `app/src/components/flows/FlowRunPendingApprovalCard.tsx`
-- Create: `app/src/components/flows/FlowRunPendingApprovalCard.test.tsx`
-- Modify: `app/src/components/chat/FlowApprovalRequestCard.tsx`
-- Modify: `app/src/components/chat/__tests__/FlowApprovalRequestCard.test.tsx`
-
-### Red
-
-Test this presentation-only contract:
-
-```ts
-export interface ApprovalDecisionAction {
- id: string;
- label: ReactNode;
- busyLabel?: ReactNode;
- variant: "primary" | "secondary";
- tone?: "default" | "danger";
- title?: string;
-}
-
-export interface ApprovalDecisionCardProps {
- ariaLabel: string;
- summary: ReactNode;
- metadata?: ReactNode;
- actions: ApprovalDecisionAction[];
- busyActionId?: string | null;
- onAction: (actionId: string) => void;
- testId?: string;
- className?: string;
-}
-```
-
-Assert alert-dialog semantics, summary/metadata composition, action order, busy
-label only on the active action, all actions disabled while any action is busy,
-action IDs passed to the callback, and danger tone forwarding.
-
-Run:
-
-```bash
-pnpm test -- app/src/components/approvals/ApprovalDecisionCard.test.tsx
-```
-
-Expected failure: the shared card does not exist.
-
-### Green
-
-Move only amber card chrome and action rendering into the shared component.
-`FlowRunPendingApprovalCard` retains local `ApprovalDecision` state and maps
-`approve_once`, `approve_always_for_flow`, and `deny` descriptors.
-`FlowApprovalRequestCard` retains its `decideApproval` call, resolution callback,
-error state, and domain copy, mapping its existing actions to descriptors.
-
-Do not merge tool/chat/flow authorization logic. Do not pass RPC callbacks into
-the shared presentation component.
-
-### Verify
-
-```bash
-pnpm test -- app/src/components/approvals/ApprovalDecisionCard.test.tsx app/src/components/flows/FlowRunPendingApprovalCard.test.tsx app/src/components/chat/__tests__/FlowApprovalRequestCard.test.tsx app/src/components/chat/__tests__/ApprovalRequestCard.test.tsx
-pnpm typecheck
-git diff --check
-```
-
-### Commit
-
-```bash
-atomic-commit "refactor(approvals): share decision card presentation" -- app/src/components/approvals/ApprovalDecisionCard.tsx app/src/components/approvals/ApprovalDecisionCard.test.tsx app/src/components/flows/FlowRunPendingApprovalCard.tsx app/src/components/flows/FlowRunPendingApprovalCard.test.tsx app/src/components/chat/FlowApprovalRequestCard.tsx app/src/components/chat/__tests__/FlowApprovalRequestCard.test.tsx
-```
-
-## Task 15: Extract flow-run status presentation
-
-**Files**
-
-- Create: `app/src/components/flows/FlowRunStatus.tsx`
-- Create: `app/src/components/flows/FlowRunStatus.test.tsx`
-- Modify: `app/src/components/flows/FlowRunInspectorDrawer.tsx`
-- Modify: `app/src/components/flows/__tests__/FlowRunInspectorDrawer.test.tsx`
-- Modify: `app/src/components/flows/FlowRunsSidebar.tsx`
-- Modify: `app/src/components/flows/FlowRunsSidebar.test.tsx`
-- Modify: `app/src/components/flows/FlowRunsDrawer.tsx`
-- Modify: `app/src/components/flows/FlowRunsDrawer.test.tsx`
-- Modify: `app/src/pages/WorkflowRunsPage.tsx`
-- Modify: `app/src/pages/WorkflowRunsPage.test.tsx`
-
-### Red
-
-Test:
-
-```ts
-export type FlowRunStatusPresentation = "badge" | "dot";
-
-export interface FlowRunStatusProps {
- status: FlowRunStatus;
- label: string;
- presentation?: FlowRunStatusPresentation;
- className?: string;
- testId?: string;
-}
-```
-
-Pin every `FlowRunStatus` to the existing accent and dot classes. Badge output
-must show the supplied localized label; dot output must be `aria-hidden`.
-
-Run:
-
-```bash
-pnpm test -- app/src/components/flows/FlowRunStatus.test.tsx
-```
-
-Expected failure: status maps currently live in consumer/inspector files.
-
-### Green
-
-Move `FLOW_RUN_STATUS_ACCENT` and `FLOW_RUN_STATUS_DOT` into the new module and
-keep named exports temporarily for callers that need classes during migration.
-Keep `FLOW_RUN_STATUS_KEY` as flow-domain vocabulary, exported from the same module.
-Use `FlowRunStatus` in Sidebar, Drawer, and All Runs Page for badges/dots. Update
-Inspector imports. Delete `STATUS_CLASS` from All Runs Page.
-
-Do not broaden the component to channel, job, bounty, or feedback status unions.
-
-### Verify
-
-```bash
-pnpm test -- app/src/components/flows/FlowRunStatus.test.tsx app/src/components/flows/__tests__/FlowRunInspectorDrawer.test.tsx app/src/components/flows/FlowRunsSidebar.test.tsx app/src/components/flows/FlowRunsDrawer.test.tsx app/src/pages/WorkflowRunsPage.test.tsx
-pnpm typecheck
-git diff --check
-```
-
-### Commit
-
-```bash
-atomic-commit "refactor(flows): share run status presentation" -- app/src/components/flows/FlowRunStatus.tsx app/src/components/flows/FlowRunStatus.test.tsx app/src/components/flows/FlowRunInspectorDrawer.tsx app/src/components/flows/__tests__/FlowRunInspectorDrawer.test.tsx app/src/components/flows/FlowRunsSidebar.tsx app/src/components/flows/FlowRunsSidebar.test.tsx app/src/components/flows/FlowRunsDrawer.tsx app/src/components/flows/FlowRunsDrawer.test.tsx app/src/pages/WorkflowRunsPage.tsx app/src/pages/WorkflowRunsPage.test.tsx
-```
-
-## Task 16: Make workflow-proposal parsing canonical
-
-**Files**
-
-- Modify: `app/src/lib/workflows/workflowProposal.ts`
-- Modify: `app/src/lib/workflows/workflowProposal.test.ts`
-- Modify: `app/src/services/api/flowsApi.ts`
-- Modify: `app/src/services/api/__tests__/flowsApi.test.ts`
-- Modify: `app/src/services/api/flowsApi.test.ts`
-
-### Red
-
-Add parity tests proving `buildWorkflow()` maps its raw proposal through
-`coerceWorkflowProposal`, including malformed payloads, missing
-`require_approval`, invalid summary steps, and explicit false approval. Add a
-regression that a valid payload produces the same object through the string parser
-and API mapper.
-
-Run:
-
-```bash
-pnpm test -- app/src/lib/workflows/workflowProposal.test.ts app/src/services/api/__tests__/flowsApi.test.ts app/src/services/api/flowsApi.test.ts
-```
-
-Expected failure: `flowsApi.ts` still owns an independent mapper.
-
-### Green
-
-Import `coerceWorkflowProposal` into `flowsApi.ts`, delete the duplicated mapping
-body, and either:
-
-- replace `mapWorkflowProposal(result.proposal)` with
- `coerceWorkflowProposal(result.proposal)` and remove the exported mapper; or
-- keep `mapWorkflowProposal` as a deprecated one-line compatibility export:
-
-```ts
-export const mapWorkflowProposal = coerceWorkflowProposal;
-```
-
-Choose the one-line alias only if current imports/tests require the public symbol.
-There must be exactly one implementation of type/name/graph/summary/default-
-approval validation after this task.
-
-### Verify
-
-```bash
-pnpm test -- app/src/lib/workflows/workflowProposal.test.ts app/src/services/api/__tests__/flowsApi.test.ts app/src/services/api/flowsApi.test.ts
-pnpm typecheck
-git diff --check
-```
-
-### Commit
-
-```bash
-atomic-commit "refactor(flows): canonicalize workflow proposal parsing" -- app/src/lib/workflows/workflowProposal.ts app/src/lib/workflows/workflowProposal.test.ts app/src/services/api/flowsApi.ts app/src/services/api/__tests__/flowsApi.test.ts app/src/services/api/flowsApi.test.ts
-```
-
-## Final branch verification
-
-After all 16 task commits, run targeted aggregate coverage first:
-
-```bash
-pnpm test -- app/src/components/ui/ModalShell.test.tsx app/src/components/ui/ConfirmDialog.test.tsx app/src/components/ui/LoadingState.test.tsx app/src/components/ui/Input.test.tsx app/src/components/layout/ChipTabs.test.tsx app/src/agentworld/components/StatusBlock.test.tsx app/src/agentworld/hooks/useMyAgentId.test.ts app/src/agentworld/components/FormField.test.tsx app/src/agentworld/components/FormActions.test.tsx app/src/agentworld/components/ExpandableResourceRow.test.tsx app/src/hooks/__tests__/useFlowRunsQuery.test.ts app/src/hooks/__tests__/flowPendingApprovalsStore.test.ts app/src/hooks/__tests__/useLatestAsync.test.ts app/src/hooks/__tests__/useDebouncedValue.test.ts app/src/hooks/__tests__/useClipboardFeedback.test.ts app/src/hooks/__tests__/useDismissLayer.test.ts app/src/components/approvals/ApprovalDecisionCard.test.tsx app/src/components/flows/FlowRunStatus.test.tsx app/src/lib/workflows/workflowProposal.test.ts
-```
-
-Then run every required frontend gate:
-
-```bash
-pnpm typecheck
-pnpm lint
-pnpm test
-pnpm build
-pnpm format:check
-git diff --check
-git status --short
-```
-
-This refactor does not change Rust domains, controller schemas, JSON-RPC methods,
-or transport behavior, so Rust/JSON-RPC implementation and E2E additions are not
-applicable. Existing consumer-flow coverage remains the E2E proof for the
-migrated UI; the work here is verified with focused interaction tests plus the
-complete frontend suite and production build.
-
-The branch is ready for review only when:
-
-- all eight former Agent World `StatusBlock` definitions are gone;
-- the five former page-local `useMyAgentId` implementations use the shared hook;
-- the richer Feed, Profiles, and WalletAddressChip wallet-resource flows remain
- behaviorally unchanged;
-- Sidebar, Drawer, and All Runs Page use `useFlowRunsQuery`;
-- pending approvals issue one poll for concurrent list/detail consumers;
-- the duplicated mapper body is absent from `flowsApi.ts`;
-- every gate above passes;
-- the worktree contains no uncommitted production or test changes.
-
-Do not push or open a PR unless separately requested.
diff --git a/docs/plans/2026-07-24-remove-screen-awareness-implementation-plan.md b/docs/plans/2026-07-24-remove-screen-awareness-implementation-plan.md
deleted file mode 100644
index 4bc82e24fe..0000000000
--- a/docs/plans/2026-07-24-remove-screen-awareness-implementation-plan.md
+++ /dev/null
@@ -1,364 +0,0 @@
-# Plan: Remove all shipped screen-awareness and screen-capture capability
-
-## Goal and invariants
-
-Remove the shipped screen-awareness surface rather than disabling it. After this
-work, removed JSON-RPC methods are unknown methods, removed CLI/Tauri/browser
-actions are not advertised or dispatchable, and embedded CEF webviews cannot
-obtain desktop-audio or desktop-video capture permission. Keep DOM/accessibility
-text snapshots, user-provided images, normal vision processing of those images,
-camera/microphone access, and test-runner/App Store artifact screenshots.
-
-Work on the existing `remove-screen-awareness-fully` worktree. Do not alter the
-committed approved design spec. Run the specified test before the deletion to
-make it fail for the old surface where applicable, then make it pass in the
-same atomic commit. Use `atomic-commit` with every listed path after validation.
-
-## 1. Remove the core domain, config, accessibility capture, and public core contract
-
-Files:
-
-- Delete `src/openhuman/screen_intelligence/` in full, including its CLI,
- controller, engine, worker, vision, tool, and unit-test files.
-- Delete `src/openhuman/accessibility/capture.rs`; remove the screen-capture
- exports from `src/openhuman/accessibility/mod.rs`.
-- In `src/openhuman/accessibility/{permissions.rs,permissions_tests.rs,types.rs,README.md}`
- remove Screen Recording permission support, the `screen_recording` status
- field, and their tests; retain focused-text, foreground-window, automation,
- Globe, input-monitoring, and microphone behavior for now. The companion still
- consumes the foreground-window types until step 5.
-- Remove the module/registry/CLI/legacy-alias entries from
- `src/openhuman/{mod.rs}`, `src/core/{all.rs,cli.rs,legacy_aliases.rs}`, and
- delete the `screen_intelligence` namespace description in `all.rs`.
-- Remove `ScreenIntelligenceConfig` and its schema module/re-export/default
- field from `src/openhuman/config/{mod.rs,schema/accessibility.rs,schema/mod.rs,schema/types.rs}`.
- Remove its patch/update/controller/schema entries from
- `src/openhuman/config/{ops/mod.rs,ops/ui.rs,ops_tests.rs,schemas/helpers.rs,schemas/controllers.rs,schemas/schema_defs.rs,schemas_tests.rs,README.md}`.
- Do not add a TOML migration: deserializing a persisted unknown
- `[screen_intelligence]` table must remain accepted by serde and no longer
- produce a live config field.
-- Remove the runtime snapshot type/build/degraded data and tests from
- `src/openhuman/app_state/{ops.rs,ops_tests.rs,README.md}` and the login/start/
- stop hooks/tests/docs in `src/openhuman/security/credentials/{ops.rs,ops_tests.rs,README.md}`.
-- Remove the screen-derived app-state/config RPC cases and replace the current
- positive integration assertions in
- `tests/{config_auth_app_state_connectivity_e2e.rs,json_rpc_e2e.rs}` with one
- focused regression asserting `openhuman.screen_intelligence_status`,
- `openhuman.screen_intelligence_capture_now`, and
- `openhuman.config_update_screen_intelligence_settings` return JSON-RPC
- method-not-found. Delete `tests/screen_intelligence_vision_e2e.rs` and remove
- its suite entry from `scripts/test-rust-e2e.sh`.
-- Remove only screen-intelligence assertions/fixtures from
- `tests/composio_list_tools_stack_overflow_regression.rs`,
- `tests/raw_coverage/tools_agent_credentials_state_raw_coverage_e2e.rs`, and
- `src/openhuman/tools/{ops_tests.rs,user_filter.rs}`. Preserve unrelated
- data-URL and user-image coverage.
-- Remove only the `screenshot-ref` local CLI wrapper/list entry/tests from
- `src/openhuman/tools/local_cli.rs`, because it calls the deleted
- `screen_intelligence` module. Preserve the standalone `ScreenshotTool` wrapper
- for step 3.
-
-Tests and checks:
-
-1. First add the method-not-found and unknown-TOML-table assertions; confirm
- they fail against the current registered surface.
-2. Run `cargo fmt --check`.
-3. Run these focused library test commands separately:
- - `GGML_NATIVE=OFF cargo test --lib core::all::tests`
- - `GGML_NATIVE=OFF cargo test --lib config::schemas_tests`
- - `GGML_NATIVE=OFF cargo test --lib config::ops_tests`
- - `GGML_NATIVE=OFF cargo test --lib app_state::ops_tests`
- - `GGML_NATIVE=OFF cargo test --lib credentials::ops_tests`
-4. Run `bash scripts/test-rust-with-mock.sh --test json_rpc_e2e` and
- `bash scripts/test-rust-with-mock.sh --test config_auth_app_state_connectivity_e2e`.
-5. Run `GGML_NATIVE=OFF cargo check --manifest-path Cargo.toml`.
-
-Commit:
-
-`refactor(core): remove screen intelligence surface`
-
-## 2. Remove screen-awareness agent discovery and capability catalog entries
-
-Files:
-
-- Delete `src/openhuman/agent/registry/agents/screen_awareness_agent/` and
- remove its module and `BuiltinAgent` entry from
- `src/openhuman/agent/registry/agents/{mod.rs,loader.rs}`.
-- Remove it from the orchestrator's allowed subagents in
- `src/openhuman/agent/registry/agents/orchestrator/agent.toml`, from the
- built-in-definition assertion in
- `src/openhuman/agent/harness/builtin_definitions.rs`, and from expected agent
- counts/worker lists in `src/openhuman/agent/harness/definition_tests.rs` and
- `src/openhuman/agent/registry/agents/loader.rs` tests.
-- Keep `vision_agent` but remove its two `screen_intelligence_*` tools and
- revise `src/openhuman/agent/registry/agents/vision_agent/{agent.toml,prompt.md}`
- to refer only to attached or on-disk user-provided images.
-- Delete the screen-awareness prompt resource from
- `src/openhuman/mcp/server/resources.rs`.
-- Delete `CapabilityCategory::ScreenIntelligence`, parsing/serialization tests,
- and all `screen_intelligence.*` catalog entries from
- `src/openhuman/platform/about_app/{types.rs,catalog_data.rs,catalog_tests.rs,README.md}`.
- Also remove the stale `screen_intelligence` example in
- `src/openhuman/overlay/types.rs` and screen-only mentions in
- `src/openhuman/inference/README.md`.
-
-Tests and checks:
-
-1. Update loader/catalog tests first so they assert the removed agent and
- capability category are absent while `vision_agent` still resolves with the
- image-capable hint; confirm they fail before removal.
-2. Run `cargo fmt --check`.
-3. Run these focused library test commands separately:
- - `GGML_NATIVE=OFF cargo test --lib agent_registry::agents::loader`
- - `GGML_NATIVE=OFF cargo test --lib agent::harness::definition_tests`
- - `GGML_NATIVE=OFF cargo test --lib about_app::`
-4. Run `GGML_NATIVE=OFF cargo check --manifest-path Cargo.toml`.
-
-Commit:
-
-`refactor(agents): remove screen awareness discovery`
-
-## 3. Remove native screenshot and pixel-returning browser actions
-
-Files:
-
-- Delete the standalone native `ScreenshotTool` implementation and tests in
- `src/openhuman/tools/impl/browser/screenshot.rs`; remove its module/re-export
- from `src/openhuman/tools/impl/browser/mod.rs`, its registration from
- `src/openhuman/tools/ops.rs`, and the remaining standalone screenshot
- wrapper/tests in `src/openhuman/tools/local_cli.rs`.
-- In `src/openhuman/tools/impl/browser/{types.rs,action_parser.rs,browser.rs,browser_tests.rs}` remove the `BrowserAction::Screenshot` variant, parser,
- advertised action/schema option, and `screen_capture` computer-use action.
- Keep `snapshot` and all non-pixel browser/computer input actions.
-- Remove screenshot execution branches from
- `src/openhuman/tools/impl/browser/{native_backend.rs,playwright_backend.rs,playwright_runner.mjs}`. Ensure every backend rejects `screenshot` and
- `screen_capture` as unsupported before sidecar dispatch.
-- Remove browser screenshot expectations from
- `tests/raw_coverage/{tools_agent_credentials_state_raw_coverage_e2e.rs,tools_approval_channels_raw_coverage_e2e.rs,tools_channels_raw_coverage_e2e.rs}`
- and retain only assertions for the remaining browser API/data-url helpers
- that do not capture pixels.
-
-Tests and checks:
-
-1. Convert parser/backend tests to assert `screenshot` and `screen_capture`
- are unsupported and that `snapshot` still parses; these assertions must fail
- before the removal.
-2. Run `cargo fmt --check`.
-3. Run `GGML_NATIVE=OFF cargo test --lib
- openhuman::tools::implementations::browser::browser::tests` and
- `GGML_NATIVE=OFF cargo test --lib tools::ops_tests` separately.
-4. Run `GGML_NATIVE=OFF cargo test --test tools_approval_channels_raw_coverage_e2e --test tools_channels_raw_coverage_e2e`.
-5. Run `GGML_NATIVE=OFF cargo check --manifest-path Cargo.toml`.
-
-Commit:
-
-`refactor(tools): remove screenshot capture actions`
-
-## 4. Remove Tauri display sharing and enforce CEF desktop-capture denial
-
-Files:
-
-- Delete `app/src-tauri/src/screen_capture/` and remove its module, managed
- `ScreenShareState`, and three command registrations from
- `app/src-tauri/src/lib.rs`.
-- Remove `screen_share_begin_session`, `screen_share_thumbnail`, and
- `screen_share_finalize_session` and their screen-share descriptions from
- `app/src-tauri/permissions/{allow-webview-recipe.toml,allow-core-process.toml}`.
-- Delete the complete `installGetDisplayMediaShim` block, picker DOM, session
- IPC calls, and display-capture permission-query override from
- `app/src-tauri/src/webview_accounts/runtime.js`; leave the ordinary recipe
- runtime and other webview functionality intact.
-- In `app/src-tauri/vendor/tauri-cef/crates/tauri-runtime-cef/src/permissions.rs`,
- make `ALLOWED_MEDIA_MASK` contain only device microphone/camera bits and
- replace the desktop-allowed tests with tests that desktop audio, desktop
- video, and mixed device+desktop requests are filtered/denied while device
- audio/video remain allowed. Update the permission-handler comment in
- `cef_impl.rs` to state desktop bits are rejected.
-- Remove obsolete native-picker claims from
- `app/src-tauri/src/{cdp/session.rs,meet_audio/captions_bridge.js}` without
- changing their retained mic/camera/caption behavior.
-
-Tests and checks:
-
-1. Change the CEF unit tests first to require desktop bits to be absent; verify
- the current mask makes them fail.
-2. Run `cargo fmt --check` in `app/src-tauri`.
-3. Run `cargo test --manifest-path app/src-tauri/vendor/tauri-cef/crates/tauri-runtime-cef/Cargo.toml permissions::tests`.
-4. Run `cargo test --manifest-path app/src-tauri/Cargo.toml` and
- `cargo check --manifest-path app/src-tauri/Cargo.toml`.
-5. Use `rg -n 'screen_share_|getDisplayMedia|DESKTOP_(AUDIO|VIDEO)_CAPTURE' app/src-tauri/src app/src-tauri/permissions` and require no remaining shipped
- command, shim, or allowlist match; the CEF denial implementation is checked
- separately in the vendored `permissions.rs` test above.
-
-Commit:
-
-`refactor(tauri): remove display sharing`
-
-## 5. Make the desktop companion screen-independent
-
-Files:
-
-- Delete `app/src-tauri/src/companion/{pointing.rs,pointing_tests.rs}` and
- remove the module export from `companion/mod.rs`.
-- In `app/src-tauri/src/companion/{mod.rs,pipeline.rs,types.rs,session.rs,session_tests.rs,pipeline_tests.rs}`, remove monitor geometry collection, foreground
- app/window context collection, screen-context prompt argument and text,
- `[POINT:…]` parsing, target fields, pointing state/transitions, and
- `capture_screen`/`include_app_context` config fields. `run_text_turn` and
- `run_audio_turn` should accept only the utterance/audio plus cancellation,
- send conversation history and the current utterance to the LLM, and return
- text/TTS/cancellation results without targets.
-- After removing the last companion consumer, delete `AppContext` and the
- frontmost-window/`foreground_context` helpers and tests from
- `src/openhuman/accessibility/{types.rs,focus.rs,mod.rs,README.md}`. Preserve
- independently used focused-text helpers in the same files.
-- In `app/src/store/{companionSlice.ts,companionSlice.test.ts}`, remove the
- `pointing` state and the two removed configuration fields.
-- Remove the pointing-only frontend event/pointer surface from
- `app/src/services/{companionEvents.ts,__tests__/companionPayload.test.ts}` and
- `app/src/overlay/{CompanionPointer.tsx,OverlayApp.tsx,__tests__/CompanionPointer.test.tsx,__tests__/companionStateLabel.test.ts}`.
-- In `app/src/components/settings/panels/{CompanionPanel.tsx,__tests__/CompanionPanel.test.tsx}`, remove the two screen-derived status rows and replace
- the old disabled-state test with coverage for the retained hotkey, activation
- mode, TTL, and session controls.
-
-Tests and checks:
-
-1. Update pipeline/session tests first to assert a text turn has no screen
- parameters, no pointing state, and a prompt containing only companion role,
- history, and utterance; verify the old signatures/state make this fail.
-2. Run `cargo fmt --check` in `app/src-tauri`.
-3. Run `cargo test --manifest-path app/src-tauri/Cargo.toml companion::` and
- `cargo check --manifest-path app/src-tauri/Cargo.toml`.
-4. Run `cargo fmt --check`, `GGML_NATIVE=OFF cargo test --lib
- accessibility::`, and `GGML_NATIVE=OFF cargo check --manifest-path
- Cargo.toml` from the repository root for the shared accessibility cleanup.
-5. Run `pnpm debug unit src/components/settings/panels/__tests__/CompanionPanel.test.tsx src/store/companionSlice.test.ts`.
-
-Commit:
-
-`refactor(companion): remove screen context and pointing`
-
-## 6. Remove frontend screen-awareness UI, routes, core-state data, and RPC wrappers
-
-Files:
-
-- Delete `app/src/features/screen-intelligence/`,
- `app/src/components/intelligence/{ScreenIntelligenceDebugPanel.tsx,__tests__/ScreenIntelligenceDebugPanel.test.tsx}`,
- `app/src/components/settings/panels/{ScreenIntelligencePanel.tsx,ScreenAwarenessDebugPanel.tsx,screen-intelligence/,__tests__/ScreenIntelligencePanel.test.tsx,__tests__/ScreenAwarenessDebugPanel.test.tsx}`,
- `app/src/components/skills/{ScreenIntelligenceSetupModal.tsx,__tests__/ScreenIntelligenceSetupModal.test.tsx}`, and
- `app/src/utils/tauriCommands/accessibility.ts`.
-- Remove all imports, cards, modal state, tab parsing, panel rendering, and
- skill icon from `app/src/{pages/Skills.tsx,components/intelligence/WorkflowsTab.tsx,components/skills/skillIcons.tsx,test/mockDefaultSkillStatusHooks.ts}`.
-- Remove the screen-awareness settings route/registry/navigation/developer-row
- entries from `app/src/components/settings/{settingsRouteElements.tsx,settingsRouteRegistry.ts,hooks/useSettingsNavigation.ts,layout/settingsNavIcons.tsx,panels/DeveloperOptionsPanel.tsx}` and their affected tests. Do not add a
- redirect: old hashes must use the normal settings-router fallback.
-- Remove `screenIntelligence` from the frontend snapshot types/store/provider in
- `app/src/{services/coreStateApi.ts,services/coreStateApi.test.ts,lib/coreState/store.ts,lib/coreState/__tests__/store.test.ts,providers/CoreStateProvider.tsx,providers/__tests__/CoreStateProvider.test.tsx,providers/__tests__/CoreStateProvider.identityFlip.test.tsx}` and fix each
- remaining snapshot fixture in component/oauth/store tests.
-- Remove screen methods, aliases, accessibility-prefix remapping, schema-source
- dependency, and tests from `app/src/services/{rpcMethods.ts,__tests__/rpcMethods.test.ts,__tests__/coreRpcClient.test.ts}`. Remove the
- `screen_intelligence` capability category from
- `app/src/utils/tauriCommands/aboutApp.ts`.
-- Delete all screen-awareness i18n keys, companion screen rows, and companion
- pointing label from every locale file:
- `app/src/lib/i18n/{ar,bn,de,en,es,fr,hi,id,it,ko,pl,pt,ru,zh-CN}.ts`.
-
-Tests and checks:
-
-1. Replace settings E2E expectations with assertions that
- `/settings/screen-intelligence` and `/settings/screen-awareness-debug` do
- not render a screen-awareness panel and follow existing settings fallback.
- Then delete the dedicated screen-intelligence specs:
- `app/test/{e2e,playwright}/specs/screen-intelligence.spec.ts`; revise
- `app/test/{e2e,playwright}/specs/settings-feature-preferences.spec.ts` and
- `app/test/playwright/specs/mcp-tab-flow.spec.ts` fixtures.
- Remove the deleted WDIO spec from the suite inventory in
- `app/scripts/e2e-run-all-flows.sh`.
-2. Run `pnpm debug unit app/src/services/__tests__/rpcMethods.test.ts app/src/lib/coreState/__tests__/store.test.ts app/src/providers/__tests__/CoreStateProvider.test.tsx app/src/components/settings/panels/__tests__/DeveloperOptionsPanel.test.tsx`.
-3. Run `pnpm i18n:check`, `pnpm i18n:english:check`, `pnpm typecheck`,
- `pnpm lint`, and `pnpm format:check`.
-
-Commit:
-
-`refactor(app): remove screen awareness UI`
-
-## 7. Remove checked-in schema entries, product docs, and test inventory references
-
-Files:
-
-- Remove the `config_update_screen_intelligence_settings` and all
- `screen_intelligence_*` methods from the checked-in `app/schema.json` so it
- matches the registry removed in step 1.
-- Delete `gitbooks/features/screen-intelligence.md` and remove screen/browser
- capture product claims from
- `gitbooks/features/native-tools/{README.md,browser-and-computer.md,image-tools.md}`.
- Preserve documentation of user-supplied image analysis and DOM snapshots.
-- Remove the screen-capture rows from `docs/TEST-COVERAGE-MATRIX.md`, the
- obsolete desktop-automation wording in `docs/library-minimal-recipe.md`, and
- the relevant screen-intelligence claims in
- `docs/{RELEASE-MANUAL-SMOKE.md,tinyagents-inference-migration-plan.md}` and
- `gitbooks/developing/architecture/tauri-shell.md`.
-- Remove `screen_capture` from the Tauri module inventory and any other stale
- screen-awareness architecture guidance in `AGENTS.md`.
-- Revise `app/test/e2e/specs/tool-browser-flow.spec.ts` so it documents and
- tests `snapshot` rather than screenshot action availability. Do not change
- `app/test/e2e/helpers/artifacts.ts`, `app/test/e2e/specs/tauri-commands.spec.ts`,
- `gitbooks/developing/{agent-observability.md,e2e-testing.md,testing-strategy.md}`,
- or `scripts/ios-appstore-{assets,metadata}.mjs`: their screenshot references
- are explicitly non-shipped test/App Store artifacts.
-
-Tests and checks:
-
-1. Run `pnpm test:inventory` and, if the inventory generator changes a tracked
- output, include that generated result in this commit.
-2. Run `pnpm docs:generate` followed by `pnpm docs:check`.
-3. Run `pnpm debug e2e test/e2e/specs/tool-browser-flow.spec.ts` when the
- desktop test prerequisites are available; otherwise record that this is a
- CI validation and run the unit/type checks from steps 3 and 6 locally.
-4. Run `git diff --check`.
-
-Commit:
-
-`docs: remove screen capture documentation`
-
-## 8. Final whole-product removal audit
-
-Run the following after all commits. If a shipped-surface match remains, fix it
-in a new narrowly scoped atomic commit; do not rewrite already validated
-history:
-
-```bash
-rg -n -i 'screen_intelligence|screen-awareness|screen awareness|screen_awareness_agent|screen_share_|getDisplayMedia|screen_capture' \
- src app/src app/src-tauri/src app/src-tauri/permissions docs gitbooks scripts tests app/schema.json \
- --glob '!docs/specs/2026-07-24-remove-screen-awareness-design.md' \
- --glob '!app/test/e2e/helpers/artifacts.ts' \
- --glob '!app/test/e2e/specs/tauri-commands.spec.ts' \
- --glob '!scripts/ios-appstore-assets.mjs' \
- --glob '!scripts/ios-appstore-metadata.mjs'
-rg -n 'DESKTOP_(AUDIO|VIDEO)_CAPTURE' \
- app/src-tauri/vendor/tauri-cef/crates/tauri-runtime-cef/src/permissions.rs \
- app/src-tauri/vendor/tauri-cef/crates/tauri-runtime-cef/src/cef_impl.rs
-```
-
-The first command must have no shipped-product match. The second may reference
-the CEF constants only in denial/filter tests or diagnostic formatting, never
-in `ALLOWED_MEDIA_MASK` or an allow path. Manually confirm surviving words such
-as “screenshot” refer only to user-provided images or the explicitly exempt
-test/App Store artifacts.
-
-Final validation:
-
-```bash
-cargo fmt --check
-GGML_NATIVE=OFF cargo check --manifest-path Cargo.toml
-cargo check --manifest-path app/src-tauri/Cargo.toml
-pnpm typecheck
-pnpm lint
-pnpm format:check
-pnpm i18n:check
-pnpm i18n:english:check
-pnpm docs:check
-pnpm test:inventory
-```
-
-No additional commit is expected for this audit; any correction belongs to its
-own earlier atomic boundary.
diff --git a/docs/plans/2026-08-22-assistant-ui-real-data.md b/docs/plans/2026-08-22-assistant-ui-real-data.md
deleted file mode 100644
index 2f7cfc6586..0000000000
--- a/docs/plans/2026-08-22-assistant-ui-real-data.md
+++ /dev/null
@@ -1,314 +0,0 @@
-# Wiring the assistant-ui chat surface to real OpenHuman data
-
-**Status:** implementation complete on `fix/ui-shdcdn`; branch-wide verification
-is pending unrelated stale AI-settings tests.
-**Prerequisite:** the mock surface landed on `fix/ui-shdcdn` (see "Starting point").
-
-Current checkpoint:
-
-- The product chat uses `AssistantUiRuntimeProvider`; the scripted runtime is now
- isolated to the dev-only assistant-ui demo.
-- Real reasoning, tool timelines and subagent activity are projected into
- assistant-ui parts, including the running-args/final-result invariant.
-- Context usage reads the selected thread's Redux token bucket, and cached input
- remains separate from fresh input. A provider catalog selection now carries
- its real context window into both the meter and the model override used by
- `chatSend`; unknown windows render as unknown.
-- The composer reuses the persisted thread-goal controller, and `/` commands are
- projected from the shared command registry. `/clear` executes `chat.new`.
-- Focused tests, typecheck, lint and both i18n gates pass. The migrated
- `Conversations.render.test.tsx` suite passes 59/59 and the combined
- assistant-ui/conversation/workflow set passes 158/158. Full `pnpm test`
- reaches unrelated stale `AIPanel.test.tsx` cases that still assert the former
- monolithic/radio settings UI instead of the current Providers/Routing tabs.
-- `renderAssistantUiOnly` is removed. The voice-only `mic-cloud` embed still
- uses the legacy pane while the remaining non-plan affordances are ported;
- follow-up: [#5685](https://github.com/tinyhumansai/openhuman/issues/5685).
-
-## What this is
-
-At the start of this work, `Conversations` rendered the assistant-ui `Thread`
-behind a temporary `renderAssistantUiOnly` switch and fed it from a scripted
-offline adapter. That was deliberate: it let the _shape_ of the surface be built
-and reviewed — streamed reasoning, tool calls, dispatched subagents, slash
-commands, a context meter, and a thread goal — before any of it was load-bearing.
-
-The normal text-chat path now renders that same `Thread` from OpenHuman's real
-Redux/core seams. The `mic-cloud` embed retains its voice-specific legacy footer
-until the controls tracked in #5685 have an assistant-ui equivalent.
-
-This document is the other half: replacing each mock with the real seam. It is
-written for an agent picking the work up cold, so every seam below names the file
-and the RPC method rather than describing them.
-
-**The through-line: none of these are new features.** OpenHuman already has a
-goal domain, a cost domain, a token-usage RPC, a command palette and a
-Redux-backed transcript projection. Four of the five tasks are _deletions_ —
-removing a mock and pointing the component at machinery that already exists. Do
-not build a second implementation of any of them.
-
-## Starting point
-
-| Piece | File | Backed by |
-| ----------------- | -------------------------------------------------------------------------- | ---------------------------- |
-| Scripted turn | `app/src/lib/assistantUiMock/mockScript.ts` | fiction |
-| Streaming adapter | `app/src/lib/assistantUiMock/mockChatModel.ts` | fiction |
-| Subagent renderer | `app/src/lib/assistantUiMock/SubagentCall.tsx` | reads the mock's payload |
-| Chat surface | `app/src/features/conversations/components/AssistantUiChat.tsx` | `useLocalRuntime` + the mock |
-| Context meter | `app/src/features/conversations/components/composer/ContextWindowPill.tsx` | `MOCK_USAGE` constant |
-| Goal control | `app/src/features/conversations/components/composer/GoalSelector.tsx` | React `useState` |
-| Slash commands | `slashCommands` prop on `Thread` | two local closures |
-
-Two seams were added to the vendored `Thread`
-([`app/src/components/assistant-ui/thread.tsx`](../../app/src/components/assistant-ui/thread.tsx))
-so the app-specific parts stay out of it, and both survive this migration
-unchanged:
-
-- `ThreadComponents.ComposerExtras` — extra controls in the composer action row.
-- `ThreadProps.slashCommands` — `/` commands, supplied by the host because a
- command's `execute` is host behaviour.
-
-Keep using them. Putting OpenHuman logic back inside `thread.tsx` is what makes
-the file impossible to re-pull from the registry.
-
----
-
-## Task 1 — Runtime: `useLocalRuntime` → the existing external store
-
-**Delete** the mock runtime; **do not** write a new bridge. One already exists
-and is tested:
-
-- [`app/src/providers/AssistantUiRuntimeProvider.tsx`](../../app/src/providers/AssistantUiRuntimeProvider.tsx)
- — mounts `useExternalStoreRuntime`, scoped to one thread by prop.
-- [`app/src/providers/useOpenHumanExternalStore.ts`](../../app/src/providers/useOpenHumanExternalStore.ts)
- — the adapter.
-- [`app/src/providers/assistantUiMessages.ts`](../../app/src/providers/assistantUiMessages.ts)
- — the Redux → assistant-ui projection. Read its header before touching it: the
- projection is **read-only**, and `chatRuntimeSlice` / `threadSlice` stay the
- single source of truth for messages, streaming, tool state and persistence.
-
-### Steps
-
-1. In `AssistantUiChat`, drop `useLocalRuntime`, `mockChatModelAdapter`,
- `buildSeedMessages` and `initialMessages`. Render `Thread` inside the
- existing `AssistantUiRuntimeProvider` instead.
-2. Decide the thread scope explicitly. `AssistantUiRuntimeProvider` takes
- `threadId?: string | null` where **omitted** means "follow
- `state.thread.selectedThreadId`" and an explicit `null` means "this surface
- owns a thread it has not created yet". The main chat pane wants the former.
- Getting this wrong is a real bug with a real precedent — see the provider's
- header comment about the Workflow Copilot painting the home chat's messages.
-3. Sending: the composer must reach the same path the legacy composer used.
- `useOpenHumanExternalStore.onNew` is the seam; verify it is wired before
- removing the legacy pane, not after. The adapter deliberately exposes no
- `onEdit`: `openhuman.threads_message_update` updates metadata only, not
- message content, so advertising assistant-ui's edit capability would create
- a button the core cannot honour.
-
-### Watch for
-
-- **Re-render cost.** `assistantUiMessages` has a performance property pinned as
- a test: converting the transcript while a token streams must not re-convert
- every message. `ChatThreadView.renderPerf.test.tsx` and
- `ChatThreadView.memoIdentity.test.tsx` exist for this. Run them.
-- Once this lands, `/clear` (Task 4) can no longer call `runtime.thread.reset()`
- — the runtime is a projection and does not own the messages.
-
----
-
-## Task 2 — Transcript parts: real reasoning, tools and subagents
-
-The mock emits `reasoning`, `tool-call` and `text` parts directly. Real ones
-arrive as core events through
-[`app/src/services/chatService.ts`](../../app/src/services/chatService.ts) and
-land in `chatRuntimeSlice`; `assistantUiMessages` projects them.
-
-Relevant wire types already defined there: `ChatSegmentEvent`,
-`ChatToolCallEvent`, `ChatToolResultEvent`, `ChatSubagentSpawnedEvent`,
-`ChatSubagentDoneEvent`, `SubagentProgressDetail`, `TurnUsageWire`,
-`SubagentUsageWire`, `ChatDoneEvent`.
-
-### Steps
-
-1. Confirm `assistantUiMessages` projects reasoning segments as
- `{ type: 'reasoning' }` parts. If it flattens them into text, the
- chain-of-thought group will never form and the reasoning UI stays dark.
-2. Map subagent events onto a tool-call part named `task`, so
- `MockToolFallback` keeps routing them to `SubagentCall`. Rename
- `MockToolFallback` → `ChatToolFallback` and move it out of `lib/assistantUiMock/`
- when the mock directory goes.
-3. Rework `SubagentCall` to read `SubagentProgressDetail` instead of the mock's
- payload. **Preserve the running/complete split exactly as it is**, and read
- the note in `mockChatModel.ts` before changing it: assistant-ui derives a tool
- call's status from _whether a result is present_, so live progress must ride
- on the streaming `args` and `result` must be set once, at the end. Writing
- progress into `result` marks the call complete the instant it starts, the tool
- group collapses, and a running delegation renders as finished. This was found
- the hard way; do not rediscover it.
-4. Keep `MockToolGroup` (rename to `ChatToolGroup`): a group holding in-flight
- work opens itself, which is the only reason a dispatched delegation is visible
- while the answer streams.
-
-### Watch for
-
-- **Existing subagent UI.** `SubagentActivityBlock.tsx`, `SubagentToolCallRow.tsx`
- and `SubagentDrawer.tsx` already render this data in the legacy pane. Decide
- deliberately whether `SubagentCall` replaces them or wraps them; do not let two
- renderers of the same events drift.
-- Real turns interleave differently from the script. The script dispatches both
- delegations early on purpose; real ordering is whatever the core emits.
-
----
-
-## Task 3 — Context meter: `MOCK_USAGE` → real token accounting
-
-`ContextWindowPill` takes a `ContextUsage` prop and renders it. The component
-does not change; only its source does.
-
-Two candidate sources, both real:
-
-| Source | File | Shape |
-| --------------------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- |
-| Live, per-session | `chatRuntimeSlice` — `emptySessionTokenUsage`, `SubAgentUsage` | already consumed by `app/src/components/chat/ComposerTokenStats.tsx` |
-| Persisted, per-thread | `openhuman.threads_token_usage` via `app/src/services/api/threadUsageApi.ts` (`fetchThreadTokenUsage`) | `ThreadTokenUsage` |
-
-### Steps
-
-1. **Read `ComposerTokenStats.tsx` first.** It is the legacy composer's version
- of this exact control — per-agent breakdown, tokens · cost · runs — and it
- already solves the aggregation. Prefer reusing its selector over writing a
- second one.
-2. Map onto `ContextUsage`: `used`, `limit`, `input`, `cachedInput`, `output`,
- `costUsd`. **`cachedInput` must stay separate from `input`** — a cache read is
- billed at a fraction of a fresh read, so cost cannot be derived from one token
- count. If the wire type does not carry cached input, extend it rather than
- folding the two together.
-3. `limit` is the selected model's context window, not a constant. It has to
- follow the model picker; `context_window` on `TurnUsageWire` is `0` in some
- cases (see the comment there) — decide what the meter shows then, rather than
- dividing by zero.
-4. Cost for a _thread_ may want `openhuman.cost_get_summary` from
- `src/openhuman/platform/cost/` instead of a per-turn sum. Check `README.md` in
- that directory before choosing.
-
-### Watch for
-
-- The pill's thresholds (amber > 75%, red > 90%) assume `limit` is real. With a
- placeholder limit they are theatre.
-
----
-
-## Task 4 — Goal: local state → the thread-goal domain
-
-**This one is almost entirely a deletion.** OpenHuman already has a per-thread
-goal, end to end:
-
-- UI: [`app/src/features/conversations/components/ThreadGoalChip.tsx`](../../app/src/features/conversations/components/ThreadGoalChip.tsx)
- — "Set goal" when empty, status + objective when set, click to edit.
-- Client: [`app/src/services/api/threadGoalApi.ts`](../../app/src/services/api/threadGoalApi.ts)
- — `openhuman.thread_goals_get` / `_set` / `_complete`.
-- Core: `src/openhuman/threads/goals/` — set, get, complete, pause, resume,
- clear, with `objective`, `token_budget`, `result`. Persisted per thread under
- `<workspace>/thread_goals/<hex(thread_id)>.json`.
-
-### Steps
-
-1. **Delete `GoalSelector.tsx`.** Render `ThreadGoalChip` from `ComposerExtras`
- instead. It already has the dialog, the RPC calls and the empty state.
-2. `ThreadGoalChip` owns its own open state, while `/goal` needs to open it from
- outside. Lift open state to a controlled prop, mirroring how `GoalSelector`
- did it — that was the whole reason `open`/`onOpenChange` were props there.
-3. Delete the `conversations.composer.goal.*` i18n keys from **all 14 locale
- files** once `GoalSelector` is gone; `ThreadGoalChip` has its own.
-
-### Watch for
-
-- A thread goal is not the global long-term goals list on the Intelligence tab.
- `ThreadGoalChip`'s header says so explicitly. Do not merge them.
-
----
-
-## Task 5 — Slash commands: local closures → the command registry
-
-`/clear` and `/goal` are currently closures in `AssistantUiChat`, and `/clear`
-calls `runtime.thread.reset()` — which stops working after Task 1.
-
-OpenHuman already has a command surface:
-[`app/src/components/commands/CommandProvider.tsx`](../../app/src/components/commands/CommandProvider.tsx),
-`CommandPalette.tsx`, `CommandScope.tsx`.
-
-### Steps
-
-1. Source the composer's `/` list from the command registry so a command is
- defined once and reachable from both the palette and the composer.
-2. Reimplement `/clear` against the real transcript. It must go through whatever
- `threadSlice` / core RPC owns clearing a thread — **not** a runtime reset,
- which after Task 1 would desynchronise the projection from Redux.
-3. Decide what `/clear` means before implementing: clear the _view_, archive the
- thread, or start a new one. The mock's behaviour (empty the transcript in
- place) is the least likely to be right for real data, because the messages are
- persisted.
-4. Any command added here needs i18n keys in all 14 locales (see below).
-
----
-
-## Cross-cutting
-
-### i18n
-
-`pnpm i18n:check` currently passes with `missing: 0` for **every** locale, so a
-key added to `en.ts` alone will fail it. Every new key needs all 14 files.
-Existing generic keys (`common.save`, `common.cancel`, `common.remove`) already
-cover the obvious buttons. Translation values must not contain em dashes
-(`U+2014`).
-
-Gates: `pnpm i18n:check`, `pnpm i18n:english:check`, plus the coverage test.
-
-### Styling
-
-Do not reintroduce per-component margins in the transcript. The assistant message
-owns one vertical rhythm (`[&>*+*]:mt-3`, applied at both the message and
-chain-of-thought levels, with `mb-0` neutralising `reasoning-root`'s `mb-4`).
-Measured before that change, gaps ran 16 / 0 / 0 / 16 / 0 / 0 px; after, a flat
-12 px. A new block that brings its own margin breaks the rhythm silently.
-
-Three global CSS facts this surface depends on, all in `app/src/index.css`:
-
-- Default border colour is `var(--color-border)`, not Tailwind v4's
- `currentColor` and not the `gray-200` the v4 upgrade pinned. 18 vendored
- components use a bare `border`; with a fixed grey they drew a bright hairline
- in dark mode.
-- `html textarea { border-width: 0 }` — `@tailwindcss/forms` resets bare
- textareas to a square grey border the composers never asked for.
-- `html textarea:focus` zeroes the plugin's ring for the same reason. Neither
- rule uses `!important`, so a component setting its own `border` or
- `focus:ring-*` still wins. Do not "simplify" these into `!important`.
-
-The shadcn semantic tokens live in `app/src/styles/shadcn-tokens.css` as aliases
-over the canonical palette. `shadcn add` was run but never `shadcn init`, so that
-file and the border-colour default are two halves of the same missing setup.
-
-### Tests
-
-The mock surface shipped **without** test coverage — that is a known gap, not a
-precedent. Each task above needs at least:
-
-- Task 1: the existing `ChatThreadView.*.test.tsx` suite green, including the
- render-perf and memo-identity tests.
-- Task 2: a test that a delegation with no `result` renders as running and its
- group is open — this is the invariant that broke once already.
-- Task 3: a test that cached input is not folded into input.
-- Task 4/5: coverage of the controlled-open path and of `/clear`'s chosen
- semantics.
-
-Run `pnpm test`, `pnpm typecheck`, `pnpm lint` and the i18n gates before opening
-a PR. Diff coverage on changed lines must be ≥ 80%.
-
-## Definition of done
-
-- `app/src/lib/assistantUiMock/` is deleted.
-- `AssistantUiChat` mounts no `useLocalRuntime` and imports nothing from a mock.
-- The context meter, the goal control and every slash command read live data.
-- `renderAssistantUiOnly` can be removed along with the legacy pane, or a
- follow-up issue explains what still blocks it. The constant is gone; [#5685](https://github.com/tinyhumansai/openhuman/issues/5685)
- tracks the remaining voice-only fallback and legacy affordances.
diff --git a/docs/plans/2026-08-31-prompt-token-budget.md b/docs/plans/2026-08-31-prompt-token-budget.md
deleted file mode 100644
index 9f746ce479..0000000000
--- a/docs/plans/2026-08-31-prompt-token-budget.md
+++ /dev/null
@@ -1,354 +0,0 @@
-# Prompt / token-budget audit and plan
-
-Date: 2026-08-31
-Reference implementation studied: [nousresearch/hermes-agent](https://github.com/NousResearch/hermes-agent)
-
-## Measured baseline
-
-Numbers from `openhuman-core agent dump-all` run against the signed-in
-workspace on this machine (`~/.openhuman/users/…/workspace`), 2026-08-31.
-Token figures are bytes/4.
-
-| Agent | Prompt text | Tool schemas (as dumped) | Tools |
-| --- | --- | --- | --- |
-| orchestrator | 37,703 B (~9,400 tok) | 175,476 B (~43,900 tok) | 220 |
-| workflow_builder | 80,353 B (~20,100 tok) | — | — |
-| integrations_agent@gmail | 23,667 B (~5,900 tok) | — | 25 |
-| median specialist | ~7,000 B (~1,750 tok) | — | 2–6 (declared belt) |
-
-Applying the default toolpack posture (`GroupMode::Withheld` for every
-group) to the orchestrator's dumped catalogue:
-
-```
-220 tools 175,476 B ~43,869 tok
- - workflows 32 tools 40,803 B ~10,200 tok
- - system 19 tools 5,058 B ~1,264 tok
- - integrations 11 tools 5,484 B ~1,371 tok
- - skills 9 tools 5,381 B ~1,345 tok
- - composio 6 tools 3,867 B ~966 tok
- - goals 3 tools 1,254 B ~313 tok
- - crypto 1 tool 1,605 B ~401 tok
-= 139 tools advertised 112,024 B ~28,006 tok
-```
-
-**The orchestrator's fixed per-turn prefix is roughly 37,400 tokens
-before the user has typed anything** — ~28k of tool schema and ~9.4k of
-prompt text. The prompt text is the smaller half of the problem.
-
-Prompt-text breakdown (orchestrator, largest first):
-
-| Section | ~tokens |
-| --- | --- |
-| Delegation (direct-first) | 1,978 |
-| Rules | 1,325 |
-| Installed Skills | 1,078 |
-| …Running several workers at once | 632 |
-| Connected Integrations | 551 |
-| Writing style | 475 |
-| …Capability questions about connected toolkits | 430 |
-| Grounding and tool use | 399 |
-| When OpenHuman is criticized | 268 |
-| everything else (19 sections) | ~2,200 |
-
-Single most expensive tool schemas: `propose_workflow` 1,892 tok,
-`spawn_subagent` 909, `cron_add` 790, `memory_tree` 781,
-`edit_workflow` 700, `suggest_workflows` 634. The top ten tools are
-~6,500 tokens — more than every prose section except Delegation.
-
----
-
-## Findings
-
-### F1 — There is no prompt caching anywhere in the stack. (critical)
-
-`grep -rn cache_control` returns **zero hits** across `src/`,
-`vendor/tinyagents`, and `backend/src`. Every turn re-pays full input
-price on the whole ~37k prefix.
-
-Hermes treats this as the central design constraint. `agent/system_prompt.py`
-builds the prompt as three ordered cache tiers — `stable` / `context` /
-`volatile` — and its docstring states the rule plainly: *"Hermes never
-re-renders parts of this string mid-session — that's the only way to keep
-upstream prompt caches warm across turns."* It backs that with
-`agent/prompt_caching.py`, `prompt_cache_boundary.py` (builder-declared
-stable prefixes, so a webhook/cron scaffold gets a breakpoint at the exact
-byte where the volatile tail starts) and `prompt_cache_scope.py`.
-
-OpenHuman already does the hard half: `session/turn/core.rs:241` builds the
-system prompt once on turn 1 and reuses it verbatim thereafter, with a
-comment about preserving the KV prefix. What is missing is telling the
-provider about it.
-
-**This is the highest-value item on the list by a wide margin** — roughly a
-90% discount on ~37k tokens of every turn on Anthropic-family models, for
-no behavioural change.
-
-### F2 — Tool schemas are 3× the prompt text, and nothing measures them.
-
-Everything in the repo that talks about prompt size talks about prose. The
-schemas are the actual budget. `propose_workflow` at 1,892 tokens is larger
-than any single prose section; nobody would ship a 1,892-token prose block
-without noticing.
-
-### F3 — The dumper does not model the wire, so the budget is invisible.
-
-`src/openhuman/agent/debug/mod.rs::render_via_session` dumps `agent.tools()`
-— the whole registry — and passes `empty_visible` as the visible set. It
-never calls `strip_packed_from_visible` and never applies the agent's
-declared `[tools] named` belt. Consequences:
-
-- Every specialist reports `tools=197` / 47k tok in `SUMMARY.txt`. The real
- belts are 2–6 tools (`researcher` = `web_search_tool`, `web_fetch`;
- `critic` = `read_diff`, `run_linter`, `run_tests`, `file_read`).
-- The orchestrator's 220 overstates its real 139.
-- There is no per-section or per-tool byte breakdown at all.
-
-Hermes ships `hermes prompt-size` (`hermes_cli/prompt_size.py`, with
-`--json`): it builds a real offline agent with dummy credentials so the
-numbers match the wire, then reports system-prompt total, the
-`<available_skills>` index, memory + profile, and tool-schema JSON, plus a
-per-skill table. Its module docstring names the goal: *"Lets users see where
-their fixed prompt budget goes … without parsing a saved session JSON by
-hand."*
-
-### F4 — Toolpack withholding is all-or-nothing; there is no middle setting.
-
-`GroupMode` is `Advertised` / `Withheld` / `Off`. Withheld removes the
-schema entirely and substitutes a `load_skill` round trip. There is no way
-to say "keep the name, drop the description and parameter schema", which is
-the cheap 80% for a tool the model needs to *know exists* but rarely calls.
-
-Hermes does exactly this for its skills index: a category outside the
-current posture renders as one `category [names only]: a, b, c` line, and
-the code carries an explicit warning not to remove entries entirely —
-*"agent-created skills are the model's project memory, and models don't
-reach for skills_list to rediscover what the index stops showing them."*
-
-### F5 — Section order puts volatile content in the cache prefix.
-
-`SystemPromptBuilder::with_defaults()` orders: Identity, **UserFiles
-(PROFILE.md, MEMORY.md)**, AgentsInstructions, **UserMemory**, Tools,
-Safety, Workspace, DateTime, Runtime. The two most volatile inputs in the
-whole prompt sit at positions 2 and 4, ahead of every byte-stable block.
-Any memory write invalidates the entire remainder of the prefix.
-
-Hermes puts precisely these in the volatile tier: *"volatile — skills index,
-memory snapshot, user profile, external memory provider block, timestamp
-line"*, rendered last, with the ordering rationale spelled out for both
-explicit-breakpoint and longest-prefix backends.
-
-Smaller instance of the same bug in the current render: `## Workspace`
-(~185 tok) and `# Writing style` (~475 tok) are both byte-stable but are
-emitted *after* `## Current Date & Time`.
-
-### F6 — Flat character caps, no budget.
-
-`BOOTSTRAP_MAX_CHARS = 20_000` applies per injected file, and both the
-global and the project `AGENTS.md` get one — up to ~10k tokens of project
-instructions alone. `USER_FILE_MAX_CHARS = 2_000`. There is no total
-budget, no scaling to the resolved context window, and no test asserting a
-ceiling on the assembled prompt.
-
-Hermes resolves the model's context window once per session and scales its
-context-file caps to it (`_dynamic_context_file_max_chars`), and surfaces
-truncation as a user-visible status message rather than a log line.
-
-### F7 — Prose bloat is real but second-order.
-
-`workflow_builder` renders an 80KB / ~20k-token system prompt — twice the
-orchestrator's. Delegation (1,978) + Rules (1,325) + the two `###`
-subsections under them (1,062) are ~4.4k tokens of the orchestrator's 9.4k.
-Worth trimming, but it is ~3k of a 37k problem. Do it after F1–F5.
-
----
-
-## The structural problem: everything is disclosed up front
-
-F1–F7 are byte-level. Underneath them is one architectural choice: **every
-tool OpenHuman registers is advertised**. There is no per-tool notion of
-"registered but not on the wire". The toolpack system is the only lever, it
-is per-*group* rather than per-tool, it is a config posture rather than a
-property of the tool, and its recovery path is a `load_skill` round trip
-rather than a search.
-
-Both reference implementations treat disclosure as the primary axis.
-
-### Codex: exposure is a property of the tool
-
-`codex-rs/tools/src/tool_executor.rs` defines `ToolExposure` per tool:
-
-```rust
-pub enum ToolExposure {
- Direct, // in the initial model-visible list
- Deferred, // registered, omitted from the list, found via tool search
- DeferredModelOnly,
- DirectModelOnly,
- CodeModeOnly, // only callable from nested Code Mode scripts
- Hidden, // registered for dispatch, never shown
-}
-```
-
-`tools/handlers/tool_search.rs` builds a **BM25 index** over every entry where
-`tool.exposure.is_deferred()` and exposes one `tool_search` tool. The model
-searches for a capability, gets the schema back, and calls it. A deferred tool
-costs zero tokens until it is needed.
-
-Codex goes one step further with **Code Mode**
-(`codex-rs/core/src/tools/code_mode/`): tools are callable from inside a
-nested script rather than as individual function schemas, so one tool replaces
-an entire namespace on the wire.
-
-OpenHuman already has the machinery — `search_tool_catalog` and
-`get_tool_contract` — but they are pointed at the **Composio action
-catalogue**, not at its own registry, and they are gated behind `flows`.
-
-### Hermes: capabilities live in skills, and tools collapse to verbs
-
-Hermes' full-fat coding profile is **31 tools**. OpenHuman's orchestrator
-advertises **139**. The difference is not that Hermes does less; it is
-where the surface lives.
-
-- Its entire skill system is **three tools** — `skills_list`, `skill_view`,
- `skill_manage` — plus a one-line-per-skill index. Everything a skill can do
- is behind `skill_view`.
-- Tool families collapse to a single tool with an action argument:
- `memory` is one tool, `cronjob` is one tool, `todo` is one tool,
- `discord` is one tool, `spotify_playback` covers play/pause/skip.
-
-Measured against OpenHuman's advertised set:
-
-| Family | OpenHuman | ~tokens | Hermes | Collapsed cost |
-| --- | --- | --- | --- | --- |
-| memory | 12 tools | 2,831 | 1 (`memory`) | ~780 |
-| todo | 6 tools | 1,375 | 1 (`todo`) | ~450 |
-| cron | 6 tools | 1,040 | 1 (`cronjob`) | ~790 |
-| task | 6 tools | 632 | — | ~200 |
-| spawn | 3 tools | 1,895 | 1 (`delegate_task`) | ~910 |
-| delegate | 3 tools | 900 | — | ~380 |
-| **total** | **36 tools** | **8,673** | **6 tools** | **~3,510** |
-
-That is ~5,200 tokens from arity alone, with no capability removed.
-
-### What deferring buys on top
-
-Ranked by schema size, the orchestrator's advertised set concentrates hard:
-
-```
-top 20 tools 8,638 tok tail 119 tools 19,367 tok
-top 30 tools 11,585 tok tail 109 tools 16,420 tok
-top 50 tools 16,870 tok tail 89 tools 11,135 tok
-```
-
-Keeping ~25 tools `Direct` and deferring the rest behind one `tool_search`
-removes roughly **16,000 tokens** from every orchestrator turn.
-
-### Where the workflow surface should go
-
-The `workflows` pack is 32 tools and 10,200 tokens — the single largest line
-item in the catalogue, and larger than the orchestrator's entire system
-prompt. On the orchestrator it is already withheld, so it costs nothing
-there today; the cost lands on `workflow_builder` and `flow_discovery`, which
-*own* the pack and therefore get all 32 advertised **plus** a 20,100-token
-system prompt. That agent pays over 30k tokens of fixed prefix to build a
-flow.
-
-A skill is the right container for it, and the arithmetic is stark: a skill
-costs one line in the index. OpenHuman's `## Installed Skills` block is 1,078
-tokens for 19 skills — **~57 tokens per capability** against ~319 tokens per
-tool. The flow DSL reference currently living in `workflow_builder/prompt.md`
-is exactly what a `SKILL.md` body is for: loaded when the agent is building a
-flow, absent otherwise.
-
-The same argument applies to `crypto` (20 tools), `documents`, `audio`, and
-`app_update`. The toolpack table is already a list of candidates — it was
-built as a compression mechanism, and a skill is the same mechanism with a
-body attached and no bespoke `load_skill` protocol.
-
----
-
-## Plan
-
-### P0 — Make the budget visible (prerequisite)
-
-1. Fix `render_via_session` to model the wire: apply the definition's
- `ToolScope` belt and call `strip_packed_from_visible(&mut visible,
- agent_id)` before collecting specs. The `.tools.json` must be the
- advertised set.
-2. Add `openhuman-core agent prompt-size [--agent <id>] [--json]`, modelled
- on `hermes_cli/prompt_size.py`: total, per-section bytes/tokens, tool
- schemas with a per-tool table, skills index, memory + profile, AGENTS.md
- layers.
-3. Add `scripts/prompt-budget.limits` + a ratchet lane, same shape as
- `scripts/kernel-floor.limits` / `check-kernel-floor.sh` — fail on growth,
- fail on an unratcheted improvement.
-
-*Exit: `SUMMARY.txt` shows `researcher tools=2`; CI fails if the orchestrator
-prefix grows.*
-
-### P1 — Prompt caching
-
-4. Split `build_system_prompt` into three tiers mirroring Hermes'
- `build_system_prompt_parts`: `stable`, `context`, `volatile`. Join for the
- wire; keep the tier boundaries as offsets.
-5. Emit `cache_control: {type: "ephemeral"}` at the tier boundaries for
- Anthropic-family providers, with the tool array ahead of the system block
- so schemas fall inside the cached prefix. Same on the backend proxy.
-6. Reorder `SystemPromptBuilder::with_defaults()` to match the tiers —
- `UserFilesSection` and `UserMemorySection` to the tail after
- `DateTimeSection`; workspace and style ahead of it.
-
-*~37k tokens/turn at roughly 10% of list price on a hit.*
-
-### P2 — Disclosure architecture (the structural fix)
-
-7. **Per-tool exposure.** Add `Tool::exposure() -> ToolExposure` with
- `Direct` / `Deferred` / `Hidden`, defaulting to `Direct` so nothing moves
- until it is opted in. This replaces the per-group `GroupMode` as the
- primary axis; `ToolGroups` stays as the embedder-facing override.
-8. **Tool search over our own registry.** Add `tool_search` backed by a BM25
- index over deferred tools (Codex uses the `bm25` crate for exactly this).
- Ungate it from `flows` — the existing `search_tool_catalog` /
- `get_tool_contract` pair stays pointed at Composio.
-9. **Defer the long tail.** Keep ~25 tools `Direct`; mark the rest
- `Deferred`. Drive the choice from Langfuse call-frequency data, not
- intuition. *(~16,000 tok)*
-10. **Collapse tool families to verbs.** `memory_*` (12 → 1), `todo_*` (6 → 1),
- `cron_*` (6 → 1), `task_*` (6 → 1), `spawn_*` + `delegate_*` (6 → 2).
- Keep the old names as dispatch aliases for one release. *(~5,200 tok)*
-11. **Move whole capability surfaces into skills**, starting with
- `workflows` — 32 tools and 10,200 tokens, plus the flow DSL reference
- now inlined in `workflow_builder/prompt.md`. Then `crypto`, `documents`,
- `audio`, `app_update`. A capability costs ~57 tokens as a skill entry
- against ~319 as a tool.
-12. Add a per-tool schema budget to the P0 ratchet — warn above 400 tokens,
- fail above 800. Rewrite the six offenders; `propose_workflow` (1,892) first.
-
-*Target: 28,006 → roughly 6,000 tokens of advertised schema.*
-
-### P3 — Budget-aware injection
-
-13. Replace the flat `BOOTSTRAP_MAX_CHARS` with a cap scaled to the resolved
- context window, and give the combined injected-file set one budget rather
- than one cap each.
-14. Surface truncation to the user as a status event, not only a log line.
-
-### P4 — Prose trim
-
-15. `workflow_builder` (~20k tok) — most of it becomes the `workflows`
- SKILL.md body in P2/11; trim what remains.
-16. Rewrite Delegation and Rules on the orchestrator.
-
-### P5 — Horizon: Code Mode
-
-17. Evaluate Codex's `code_mode` seam — tools callable from a nested script
- instead of as individual function schemas. It is the endgame for schema
- cost, and it composes with P2 rather than replacing it. Not before P0–P2
- land and the ratchet has real numbers behind it.
-
-## Sequencing note
-
-P0 before everything: three findings (F2, F3, F4) exist only because the
-numbers were never on screen. Then P1, which is a pricing change with no
-behavioural risk. P2 is the largest and the riskiest — it changes what the
-model can see — so it wants the measurement and the caching in place first,
-and it should land tool family by tool family behind the ratchet.
diff --git a/docs/plans/conversations-timeline-refactor.md b/docs/plans/conversations-timeline-refactor.md
deleted file mode 100644
index 016b6c1268..0000000000
--- a/docs/plans/conversations-timeline-refactor.md
+++ /dev/null
@@ -1,155 +0,0 @@
-# Conversations Timeline Refactor — Audit & Plan
-
-Status: **draft — approved for implementation, not yet started**
-Scope: `app/src/pages/Conversations.tsx` and the conversation-timeline data layer (frontend + Rust turn-state persistence).
-Companion: [`per-turn-tool-timeline-history.md`](per-turn-tool-timeline-history.md) (adopted wholesale as the backend track).
-
-## Context
-
-`app/src/pages/Conversations.tsx` (3,302 lines, one function component) is the app's reusable conversation panel — used by `Accounts.tsx` (page + sidebar variants) and `features/human/HumanPage.tsx` (sidebar + mic-cloud + projectThreadList). It is disorganized and buggy in four dimensions:
-
-**How it renders tool calls / thoughts / subagents** — five parallel state families composed ad hoc in one render function: durable messages (`threadSlice`, server order), a **single tool-timeline array per thread** (`chatRuntimeSlice.toolTimelineByThread`), a streaming-preview tail (`streamingAssistantByThread`, last 120 chars), parallel subagent streams (`parallelStreamsByThread`), and an inference-status line — each with its own conditional render gates (`hideAgentInsights` × `isSending` × anchoring produces 4+ fallback paths, L1775–1842).
-
-**How it orders** — no timestamps or sequence ids. Timeline entries carry only `round` + array insertion order. The single timeline is positionally **anchored after the last user message** (`Conversations.tsx:1756, 2533`, fallback `2669` for proactive threads). Each send **wipes** the timeline, so past turns permanently lose their process trail.
-
-**How it stores & streams** — `ChatRuntimeProvider.tsx` (1,664 lines) merges ~28 snake_case socket events (`tool_call`, `subagent_*`, `chat_interim`, `text_delta`, …) via `store.getState()` + find-row + **full-array-replace** in ~10 handlers. **Two parallel dedup mechanisms** (provider-local `seenChatEventsRef` string-key TTL map + reducer-level id dedup in `hydrateRuntimeFromRunLedger`) with **divergent row-id schemes** (live: `${thread}:subagent:${task}:${tool}` vs ledger: `subagent:${runId}`), plus provider-local `segmentDeliveriesRef` and the `preserveLiveSubagentProse` graft — a documented live-only-state workaround.
-
-**Tab-switch context loss** — the Rust store persists **one** turn snapshot per thread (whole-file overwrite, `src/openhuman/threads/turn_state/store.rs`), so thread/tab switch rehydrates only the latest turn; live subagent prose, past-turn trails, and the streaming tail are lost.
-
-**Reference patterns adopted** (from codex `codex-rs/protocol` + TUI research; hermes-agent confirmed as the minimal counter-example; vendored `tinychannels` is transport-only — its `ChannelOutputEvent` vocabulary and `RunLedger`/`ConversationStore` host traits stay compatible, the rich timeline model remains OpenHuman-owned):
-
-1. **Two-layer model**: ephemeral streaming events (deltas, begin/end pairs keyed by `call_id`) vs **durable timeline items with stable ids**; deltas mutate the item with the matching id; persist only durable items; rehydrate by chronological replay.
-2. **Typed item taxonomy**: one discriminated union, one React component per kind.
-3. **Ordering**: stable per-item id + monotonic `seq`; per-turn grouping via `requestId`; subagents as flat items with `parentId`, nesting rendered not stored.
-
----
-
-## Target architecture
-
-### 1. Unified `TimelineItem` model — a selector projection, not a new slice
-
-`threadSlice` and `chatRuntimeSlice` remain sources of truth; a memoized selector (`selectTimelineForThread`) composes them into one ordered `TimelineItem[]`. This avoids a big-bang slice migration and lets each phase land independently.
-
-```ts
-// app/src/features/conversations/timeline/types.ts
-interface TimelineItemBase {
- id: string; // stable: message id, or unified runtime row id (§3)
- turnId: string; // requestId; 'legacy' for pre-migration turns
- seq: number; // ordering within turn (reducer-assigned now, backend-stamped in Phase 4)
- threadId: string;
-}
-type TimelineItem = TimelineItemBase & (
- | { kind: 'userMessage'; message: ThreadMessage }
- | { kind: 'assistantMessage'; message: ThreadMessage; interim: boolean } // chat_interim narration
- | { kind: 'streamingText'; text: string; streamId?: string } // ephemeral, live turn only
- | { kind: 'reasoning'; text: string; settled: boolean }
- | { kind: 'toolCall'; callId: string; name: string; status: 'running'|'ok'|'error'; args?: unknown; result?: unknown; round?: number }
- | { kind: 'subagentActivity'; taskId: string; parentCallId?: string; children: string[] } // flat store, rendered nested
- | { kind: 'approvalRequest' | 'plan' | 'workflowProposal'; /* wraps existing card payloads */ }
-);
-```
-
-**Ordering**: turns order by first-message position in the thread; items within a turn by `seq`. Anchoring becomes structural — a turn group renders `[userMessage, ...processItems, ...assistantMessages]` — replacing the last-user-message positional hack. Messages without `requestId` fall into a single `legacy` turn that reproduces today's single-anchor behavior. A turn with no `userMessage` (proactive threads) is first-class: process items render before its first assistant message.
-
-### 2. File layout — `app/src/features/conversations/` (matches `features/human/`; all files ≤ ~500 lines)
-
-```
-app/src/features/conversations/
- ConversationsPage.tsx # page-shell variant
- ConversationsSidebar.tsx # sidebar variant (Accounts, HumanPage)
- index.ts # public exports = reusability contract
- timeline/
- types.ts # TimelineItem union
- selectors.ts # projection + turn grouping (reselect-memoized)
- ConversationTimeline.tsx # pure renderer: TimelineItem[] → one component per kind
- items/ # UserMessageItem, AssistantMessageItem, ToolCallItem,
- # ReasoningItem, SubagentActivityItem, StreamingTailItem
- TurnInsightsGroup.tsx # collapsed-header/expanded-body per-turn wrapper (lazy-load)
- composer/
- Composer.tsx / MicCloudComposer.tsx / useComposerState.ts / composerSendDecision.ts
- threadList/
- ThreadList.tsx / threadFilter.ts
- components/ # existing subcomponents relocated as-is
- (ToolTimelineBlock, SubagentDrawer, TaskKanbanBoard, AgentProcessSourcePanel, …)
-app/src/pages/Conversations.tsx # thin re-export shim during migration; deleted in Phase 6
-```
-
-**Reusability contract** (`index.ts`): `<ConversationsPage>`, `<ConversationsSidebar composer projectThreadList>`, and `<ConversationTimeline items onAction>` for future embedders. The `AgentChatPanel` export (Conversations.tsx:3302) is renamed to resolve the collision with the unrelated `components/settings/panels/AgentChatPanel.tsx`; `Accounts.tsx:25` updated.
-
-### 3. Streaming/merge consolidation
-
-- All merge logic moves into `chatRuntimeSlice` **reducers** — one typed action per event family (`toolEventReceived`, `subagentEventReceived`, `textDeltaReceived`, `turnLifecycleReceived`). `ChatRuntimeProvider` shrinks to parse-and-dispatch (~300 lines); no `getState()`, no full-array rebuilds.
-- **One dedup mechanism**, reducer-level, on a unified row-id scheme: `${threadId}:${requestId}:${kind}:${callId|taskId|streamId}` — used identically by live handlers, `hydrateRuntimeFromSnapshot`, and `hydrateRuntimeFromRunLedger`. Kills the live-vs-ledger id divergence; `preserveLiveSubagentProse` becomes an ordinary upsert (merge rule: persisted fields win for settled rows, live fields win for streaming fields).
-- **Backend `seq` envelope** (Phase 4): `progress_bridge.rs` stamps a per-request monotonic `seq: u64` + `request_id` on every event; reducers dedup by `(requestId, seq)`. Reconnect-safe: replayed events with `seq <= lastSeq` are dropped; missed events recovered by re-hydration on reconnect (kept). Until then, the TTL-map dedup moves verbatim into the reducer as the interim mechanism.
-- `segmentDeliveriesRef` reconstruction becomes per-request segment state in the slice, cleared on `chat_done`.
-
-### 4. Per-turn persistence (backend)
-
-Adopt `per-turn-tool-timeline-history.md` as written: per-turn files `turn_states/<hex(thread_id)>/<request_id>.json` with retention (N=20) + `latest` pointer, `turn_state_list` / `turn_state_get(requestId)` RPCs, idempotent legacy single-file migration, `extraMetadata.requestId` stamped on assistant messages (Option B anchoring). **Amendment**: persist `seq` on `PersistedToolTimelineEntry` (Rust `turn_state/types.rs` + `app/src/types/turnState.ts`) so replayed snapshots order identically to live streams.
-
-**Sequencing: frontend-first.** The projection, component split, and reducer consolidation all work against the current single-snapshot backend (everything lands in the `legacy`/live turn). The ring store then slots in underneath without touching the renderer.
-
----
-
-## Phases (each a small PR, tests green throughout; branch off `upstream/main`, small focused commits)
-
-### Phase 0 — Land this plan
-This document, committed to `docs/plans/`.
-
-### Phase 1 — Mechanical extraction, no behavior change
-Create the `features/conversations/` skeleton; relocate `pages/conversations/{components,hooks,utils}`; extract ThreadList, Composer/MicCloudComposer/useComposerState, and the page/sidebar shells out of `Conversations.tsx`. `pages/Conversations.tsx` becomes a shim with the old props so `Accounts.tsx`/`HumanPage.tsx` are untouched. Rename `AgentChatPanel`. Shared thread/selection state via a `ConversationsContext` to avoid prop-drilling explosions.
-**Guardrails**: `Conversations.render.test.tsx` + 4 sibling tests, Accounts/HumanPage tests pass unmodified (import paths only).
-
-### Phase 2 — `TimelineItem` projection + `<ConversationTimeline>`
-Add `timeline/types.ts`, `timeline/selectors.ts` (`legacy`-turn fallback ⇒ behaviorally identical to today's anchor logic), `ConversationTimeline.tsx` + `items/*` (wrapping existing `ToolTimelineBlock`, `AgentMessageBubble`, cards). Replace the render loop (~L2400–2700 of the old file). `hideAgentInsights` filters kinds in the selector, not components.
-**New tests**: `selectors.test.ts` (ordering, legacy fallback, empty thread, **proactive thread with no user message** — must reproduce the L2669 fallback), `ConversationTimeline.test.tsx` (snapshot per kind).
-
-### Phase 3 — Reducer-side merge/dedup consolidation
-Typed actions in `chatRuntimeSlice`; move each provider handler's merge body into reducers; move `seenChatEventsRef` + `segmentDeliveriesRef` into slice state; unify row ids everywhere; replace `preserveLiveSubagentProse` with the field-level upsert. Verbose debug logging on every dedup drop / merge decision (repo convention).
-**Guardrails**: `ChatRuntimeProvider.test.tsx` (assertions rewritten to dispatched actions), `chatRuntimeSlice.test.ts`, `chatRuntimeSlice.toolFailure.test.ts`, `SubagentDrawer.test.tsx`. **New tests**: duplicate-event replay is a no-op; live subagent prose survives snapshot hydration; reconnect-replay simulation.
-
-### Phase 4 — Backend per-turn ring store (companion-plan steps 1–3)
-Rust first (per AGENTS.md workflow Rust → RPC → UI): per-turn store layout + retention + legacy migration in `turn_state/store.rs`, mirror retention in `mirror.rs`, `seq` stamping in `progress_bridge.rs`, `seq` on `turn_state/types.rs`; `turn_state_list` / `turn_state_get(requestId)` RPCs; `extraMetadata.requestId` stamping (threadSlice `addInferenceResponse` + `chat_segment`/`chat_done`/`chat_interim` paths); wire types in `app/src/types/turnState.ts` + `threadApi.ts`. Invisible to UI.
-**Tests**: extend `store_tests.rs` (put/get/list, prune to N, latest pointer, idempotent legacy migration, `mark_all_interrupted` over dir), `mirror_tests.rs`; JSON-RPC E2E for the new methods.
-
-### Phase 5 — Per-turn frontend (companion-plan step 4)
-`toolTimelineByThread` → `Record<threadId, Record<requestId, rows>>` + `liveRequestIdByThread`; send no longer wipes history; dedup by `(requestId, seq)`, drop the interim TTL logic. Selector groups by real `requestId`; `TurnInsightsGroup` lazy-fetches `turn_state_get(requestId)` on first expand; thread-switch hydration = `turn_state_list` + latest snapshot only.
-**New tests**: multi-turn render (each turn keeps its trail), lazy-load, legacy-message fallback.
-
-### Phase 6 — Cleanup
-Delete the `pages/Conversations.tsx` shim (point Accounts/HumanPage at `features/conversations`); delete dead state (`parallelStreamsByThread` if subsumed by `streamingText` items, `preserveLiveSubagentProse`, provider refs). i18n keys unchanged (all strings already via `useT`).
-
----
-
-## Tab-switch context loss — cause → fix
-
-| Lost today | Cause | Fixed by |
-|---|---|---|
-| Past turns' process trails | single array wiped on send + single-snapshot store | Phases 4–5 |
-| Live subagent prose after rehydrate | hydration clobbers live-only rows (`preserveLiveSubagentProse` workaround) | Phase 3 (unified ids + field-level upsert) |
-| Streaming tail / interim segments | provider-local refs + latest-snapshot-only hydration | Phase 3 (segment state in slice) + Phase 4 |
-| Duplicate/ghost rows after reconnect | TTL dedup misses + id-scheme divergence | Phase 3 interim, Phase 4 `seq` definitive |
-
-## Verification
-
-- Per phase: `pnpm test` (guardrail tests listed above), `pnpm typecheck`, `pnpm lint`; Phase 4 adds `cargo test` / `pnpm test:rust` + `tests/json_rpc_e2e.rs`; ≥80% diff coverage (CI Lite gate).
-- Manual QA after Phases 3 and 5 (`pnpm dev:app`): multi-turn thread with tools + subagents; switch tab mid-stream and back; kill/restore socket mid-turn; proactive thread with no user message; `hideAgentInsights` sidebar variant in HumanPage; app restart on a 5-turn thread — all trails restored, ordered identically to live.
-
-## Risks
-
-- **Reconnect replay before `seq` exists** — keep the TTL-equivalent dedup in the reducer until Phase 4 lands; do not delete early.
-- **Proactive threads (no user message)** — first-class in the projection; tested in Phase 2.
-- **Snapshot migration** — legacy single-file read must be idempotent; keep the old read path one release.
-- **Selector performance on long threads** — reselect memoization per thread; collapsed turns hold metadata only (lazy-load bodies).
-- **`round` semantics** — `ToolTimelineBlock` coalescing keys off `round`; keep `round` alongside `seq`, don't replace it.
-
-## Critical files
-
-- `app/src/pages/Conversations.tsx` (3,302 ln — split & shim)
-- `app/src/providers/ChatRuntimeProvider.tsx` (1,664 ln — shrink to dispatch)
-- `app/src/store/chatRuntimeSlice.ts` (1,698 ln — reducer-side merges, per-turn shape)
-- `app/src/store/threadSlice.ts` (`addInferenceResponse` requestId stamping)
-- `app/src/types/turnState.ts`, `app/src/services/api/threadApi.ts` (wire types/RPCs)
-- `src/openhuman/threads/turn_state/{store.rs,mirror.rs,types.rs}` (ring store, seq)
-- `src/openhuman/channels/providers/web/progress_bridge.rs` (seq envelope)
-- `docs/plans/per-turn-tool-timeline-history.md` (adopted backend design)
diff --git a/docs/plans/per-turn-tool-timeline-history.md b/docs/plans/per-turn-tool-timeline-history.md
deleted file mode 100644
index 9f81b4ec6f..0000000000
--- a/docs/plans/per-turn-tool-timeline-history.md
+++ /dev/null
@@ -1,167 +0,0 @@
-# Per-turn tool-timeline history (draft)
-
-**Status:** draft / design. Not yet implemented.
-**Owners:** conversations UI + threads core.
-**Related work (already shipped on this branch):**
-
-- Coalescing repeated timeline rows + collapsing settled insights (`ToolTimelineBlock`).
-- Streamed narration kept as an in-flow bubble (`Conversations.tsx`).
-- `chat_interim` — mid-turn narration persisted as real interleaved chat messages (`progress_bridge.rs` + `ChatRuntimeProvider`).
-
-## Problem
-
-Each answer in a multi-turn thread should keep its own "Agentic task insights"
-trail (the tools/subagents that produced it). Today the trail is lost for every
-turn but the latest:
-
-- The frontend holds **one** timeline array per thread
- (`toolTimelineByThread[threadId]`, `chatRuntimeSlice.ts:567`) and renders it
- once, anchored after the last user message (`Conversations.tsx` — the
- `lastUserMessageId ? agentInsights : null` anchor). Each new send wipes it
- (`setToolTimelineForThread([])`).
-- The core persists **one** turn-state snapshot per thread, whole-file
- overwrite — "latest snapshot wins" (`turn_state/store.rs:1-6`,
- `snapshot_path` keyed by `hex(thread_id)` at `store.rs:210-216`). A
- `Completed` snapshot is kept only until the next turn on the same thread
- overwrites it (`turn_state/types.rs:26-30`, `mirror.rs:466-479`).
-
-So on reload, scrolling up shows past answers with **no** process trail, and the
-single current trail always sits at the bottom.
-
-The `chat_interim` work already fixed the narration half of this (narration is
-now a durable thread message). This design covers the remaining half: the
-**tool timeline** per turn.
-
-## Current data flow (anchors)
-
-- Snapshot type: `TurnState { thread_id, request_id, lifecycle, streaming_text,
- thinking, tool_timeline: Vec<ToolTimelineEntry>, transcript: Vec<TranscriptItem>,
- task_board }` — `turn_state/types.rs:291-320`. Each turn already carries a
- unique `request_id` (`TurnState::started` / `TurnStateMirror::new`,
- `progress_bridge.rs:290-291`).
-- Mirror: `TurnStateMirror::observe` folds `AgentProgress` into the snapshot;
- `TurnCompleted` marks `lifecycle = Completed` and keeps the snapshot
- (`mirror.rs:466-479`).
-- Store: `put` whole-file overwrite (`store.rs:40-73`); `get`/`delete`/`list`/
- `clear_all`/`mark_all_interrupted` (`store.rs:76-194`); path keyed by thread
- (`store.rs:210-216`).
-- RPC surface: `GetTurnStateRequest/Response`, `ListTurnStatesResponse`,
- `ClearTurnStateRequest/Response` (`turn_state/types.rs:322-358`,
- re-exported `turn_state/mod.rs:16-20`).
-- Frontend consumer: `threadApi.getTurnState(threadId)` (`threadApi.ts:125`) →
- `hydrateRuntimeFromSnapshot` (`chatRuntimeSlice.ts:1482,1672-1681`), which
- writes the single `toolTimelineByThread[threadId]`.
-
-## Proposed design
-
-Keep a **bounded ring of completed snapshots per thread**, keyed by
-`request_id`, plus the existing single "live/latest" snapshot. Anchor each
-completed turn's timeline to the answer message(s) that turn produced.
-
-### 1. Store: key by turn, keep the latest pointer
-
-- Change `snapshot_path` to a per-turn file:
- `…/turn_states/<hex(thread_id)>/<request_id>.<ext>` (a directory per thread).
-- `put` writes `<request_id>.json` (atomic tmp+rename, unchanged durability).
-- Add `put_completed` / retention: on writing a `Completed` snapshot, prune the
- thread's directory to the newest `N` completed turns (propose `N = 20`) by
- `completed_at`, so history stays bounded (mirrors the timeline
- `REGISTRY_SOFT_CAP` philosophy — never unbounded).
-- Keep a `latest` pointer for the in-flight/most-recent turn: either a
- `latest.json` symlink-free copy, or resolve "latest" by scanning the dir for
- the max `started_at`. A pointer file avoids a dir scan on the hot
- `get_latest` path.
-- `get(thread_id)` → latest (back-compat for the current single-turn RPC).
-- New `get(thread_id, request_id)` and `list_completed(thread_id)` (metadata
- only: `request_id`, `lifecycle`, `started_at`, `completed_at`, counts — not
- the full `tool_timeline`, to keep the list cheap).
-- `mark_all_interrupted` (startup) and `clear`/`delete` operate over the
- per-thread directory. `mark_all_interrupted` still skips
- `Completed`/`Interrupted` (`store.rs:170-194`).
-
-### 2. Turn ↔ message anchoring
-
-The frontend must map each completed turn to the answer bubble(s) it produced.
-Two options — pick **B**:
-
-- **A. Anchor by user message.** Render a turn's timeline above the user message
- that triggered it. Requires recording the triggering user `message_id` on the
- snapshot. Simple but places the trail above the *question*, not the *answer*.
-- **B. Anchor by produced assistant message (recommended).** Stamp the assistant
- messages a turn appends with its `request_id`. `addInferenceResponse`
- (`threadSlice.ts:185`) and the `chat_segment` / `chat_done` / `chat_interim`
- handlers all know `request_id`; thread it into `extraMetadata.requestId` and
- persist it (already an open field on `ThreadMessage.extraMetadata`). Then the
- frontend groups messages by `requestId` and renders that turn's timeline above
- the first assistant message of the group.
-
-Option B is reload-coherent: messages already reload from the thread store with
-their `extraMetadata`, and each turn's timeline reloads from its per-turn
-snapshot — no divergence between live and reloaded views.
-
-### 3. RPC + frontend
-
-- New RPC `threads.turn_state_list` → `[{ requestId, lifecycle, startedAt,
- completedAt, toolCount, subagentCount }]` and `threads.turn_state_get`
- (`threadId`, `requestId`) → full `PersistedTurnState`. Keep the existing
- `get_turn_state(threadId)` for the live turn.
-- Frontend store: replace `toolTimelineByThread: Record<threadId, Entry[]>` with
- `toolTimelineByThread: Record<threadId, Record<requestId, Entry[]>>` plus a
- `liveRequestIdByThread` pointer. `hydrateRuntimeFromSnapshot` writes under the
- turn's `requestId`; `setToolTimelineForThread` targets the live `requestId`
- and no longer wipes history on send.
-- Render loop (`Conversations.tsx`): for each assistant message that is the first
- of its `requestId` group, render `<ToolTimelineBlock entries={byRequest[rid]}>`
- above it (collapsed-when-settled behavior already shipped). The live turn keeps
- its current in-flight rendering.
-- On thread open, call `turn_state_list`, then lazily `turn_state_get` a turn's
- full timeline the first time its (collapsed) insights block is expanded — the
- list is cheap; full timelines load on demand so opening a long thread doesn't
- fetch dozens of full snapshots.
-
-### 4. Migration / back-compat
-
-- Old single-file snapshots (`<hex(thread_id)>.json`) are read once and migrated
- into `<hex(thread_id)>/<request_id>.json` on first access; if `request_id` is
- absent on a legacy snapshot, key it `legacy` and treat it as the thread's one
- historical turn.
-- Messages without `extraMetadata.requestId` (pre-migration) fall back to the
- current single-anchor behavior (render the live/latest timeline once), so old
- threads degrade gracefully rather than losing their trail.
-
-### 5. Reload coherence (the invariant to protect)
-
-Live and reloaded views must render identically. Achieved because both sides key
-on `requestId`: assistant messages carry it in `extraMetadata`; timelines are
-stored/fetched per `requestId`. No in-session-only state — the failure mode this
-codebase repeatedly warns about (e.g. the `preserveLiveSubagentProse` comments)
-is avoided.
-
-## Testing plan
-
-- **Store (Rust):** per-turn put/get/list, retention prunes to `N`, latest
- pointer resolves correctly, legacy single-file migration, `mark_all_interrupted`
- over the per-thread dir. Extend `turn_state/store.rs` tests.
-- **Mirror (Rust):** a `Completed` snapshot is retained under its `request_id`
- and a subsequent turn does not overwrite it.
-- **Frontend:** `hydrateRuntimeFromSnapshot` writes under `requestId`; the render
- loop groups messages by `requestId` and renders one timeline per turn above the
- first assistant bubble; legacy messages (no `requestId`) fall back to the single
- anchor. Extend `Conversations.render.test.tsx` + `chatRuntimeSlice` tests.
-
-## Rollout
-
-1. Store keyed by `request_id` + retention + legacy migration (Rust, behind the
- existing single-turn RPC — no UI change yet).
-2. Stamp assistant messages with `extraMetadata.requestId` (frontend, additive).
-3. New `turn_state_list` / `turn_state_get(requestId)` RPCs.
-4. Frontend store keyed by `requestId` + per-turn render, with legacy fallback.
-
-Each step is independently shippable; the UI only changes at step 4.
-
-## Estimated size
-
-Medium-large. Step 1 is the core risk (persistence format + migration); steps
-2–4 are mechanical but touch the render loop and the slice shape. Recommend
-landing steps 1–3 first (invisible), then step 4 behind quick manual QA on a
-multi-turn thread.
diff --git a/docs/plans/pluggable-core/README.md b/docs/plans/pluggable-core/README.md
deleted file mode 100644
index 526a0ae941..0000000000
--- a/docs/plans/pluggable-core/README.md
+++ /dev/null
@@ -1,237 +0,0 @@
-# Pluggable Core — `openhuman_core` as an Embeddable Library
-
-**Status:** In progress — `CoreBuilder`, `CoreRuntime`, `CoreContext`, the
-first per-context store plumbing, and the `openhuman-fleet` MVP are implemented
-in this branch. Remaining production work is tracked in the phase docs.
-
-**Goal:** make the Rust core pluggable into arbitrary hosts — the Tauri shell
-(today), a plain CLI, a stdio MCP server, cloud/team servers managing many
-users, and other programs consuming it as a library — via a first-class
-`CoreBuilder` → `CoreRuntime` API instead of the current "library entry is a
-CLI arg vector" surface.
-
-**Why:** teams and programmatic use both need the same thing: the ability to
-compose the core's pieces (dispatcher, stores, background services,
-transports) differently per host. Today that composition is fixed inside one
-700-line function. The client side already solved this problem with the
-`CoreTransport` strategy layer (`app/src/services/transport/`); the core side
-has no equivalent seam.
-
-**Anchor precedents:** [`docs/tinyagents-port-plan.md`](../../tinyagents-port-plan.md)
-and [`docs/tinycortex-migration-spec.md`](../../tinycortex-migration-spec.md) —
-the established "seam + staged migration + drift ledger" doctrine. This plan
-restructures the _host_, not the engines: `tinyagents` / `tinycortex` seams
-are untouched.
-
----
-
-## 1. Where we are
-
-### 1.1 What is already right
-
-The hard parts of pluggability are, surprisingly, already done:
-
-| Asset | Where | Why it matters |
-| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |
-| Transport-agnostic dispatch | `ControllerSchema` + `invoke_method` (`src/core/jsonrpc.rs:230`) shared by HTTP `/rpc`, CLI `call`, generic namespace dispatch, and MCP stdio | The _contract_ is host-neutral; only the bootstrap is not |
-| Pluggable client | `app/src/services/transport/` — `CoreTransport` interface, `LocalTransport` / `LanHttpTransport` / `TunnelTransport` / `CloudHttpTransport`, `ConnectionProfile`, `TransportManager` | Any backend that answers `POST /rpc` JSON-RPC with a Bearer token is already reachable from every client, including cloud |
-| Agent loop as a crate | `tinyagents` (vendored, `vendor/tinyagents`) via the seam `src/openhuman/agent/tinyagents/` (`run_turn_via_tinyagents_shared`) | Programmatic harness use does not require extracting the loop — it's extracted |
-| Memory engine as a crate | `tinycortex` via `src/openhuman/memory/tinycortex/` | Same |
-| Headless server mode | `openhuman-core run/serve` (`src/core/cli.rs:66`), `--jsonrpc-only`, Bearer token via `OPENHUMAN_CORE_TOKEN` (`src/core/auth.rs:160`) | Cloud deployment of a _single_ core already works |
-| Host discrimination | `HostKind { TauriShell, Cli, Docker }` (`src/core/types.rs:167`) threaded into `bootstrap_core_runtime` | The natural seam for the refactor already exists |
-| Tools as trait objects | `Box<dyn Tool>` on `Agent` (`src/openhuman/agent/harness/session/types.rs:31`) | No handler-style fn-pointer problem in the tool layer |
-
-### 1.2 The coupling points (what blocks embedding)
-
-| # | Concern | Location | Nature |
-| --- | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| 1 | Bootstrap fused to transport | `run_server_inner` (`src/core/jsonrpc.rs:1738`) + `bootstrap_core_runtime` (`:2428`) | One function: controller registration, master key, token seeding, `Config::load_or_init`, ~10 global store inits (`:1807-1892`), port bind, env mutation, router, ready signal, inline `tokio::spawn` of every background service. You cannot get "just the dispatcher" |
-| 2 | Handlers are bare `fn` pointers | `ControllerHandler` (`src/core/all.rs:21`) | No captured state possible; every handler reads process globals |
-| 3 | Three hand-maintained registries | `src/core/all.rs` — handlers (`:105-344`), schemas (`:375-509`), namespace descriptions (`:530-690`) | Parallel lists in `OnceLock` statics, panic-on-drift validation |
-| 4 | Process singletons | `RPC_TOKEN` (`src/core/auth.rs:75`), `GLOBAL_BUS` (`src/core/event_bus/bus.rs:20`), `NativeRegistry` (`src/core/event_bus/native_request.rs:329`), every `*::global::init(workspace_dir)` store | One of each per process |
-| 5 | Single active user per process | `~/.openhuman/active_user.toml` (`src/openhuman/config/schema/load_user_state.rs:21`), resolution chain in `dirs.rs:299` | One workspace resolved once; all global stores bound to it |
-| 6 | Background services spawned inline | cron (`jsonrpc.rs:~2124`), channels (`:~2162`), heartbeat/subconscious (`:~2083`), update scheduler | Flags exist (`config.cron.enabled`, `OPENHUMAN_DISABLE_CHANNEL_LISTENERS`, `--jsonrpc-only`) but the caller cannot compose a service set |
-| 7 | Runtime env mutation | `set_var OPENHUMAN_CORE_RPC_URL` (`jsonrpc.rs:2010`) | Process-global side effect; needed by spawned child tools |
-| 8 | `Once`-guarded subscribers | `register_domain_subscribers` (`jsonrpc.rs:2232`, `std::sync::Once`) | Second context in one process cannot re-register |
-| 9 | Dead dispatch tier | `src/rpc/dispatch.rs:10` always returns `None` | Removable noise |
-
-### 1.3 Teams today
-
-`src/openhuman/team/` is a **pure thin proxy** to `tinyhumansai/backend`
-(session JWT via `crate::api::jwt`, URL via
-`effective_backend_api_url`, `src/api/config.rs:154`). All membership, roles,
-invites, and authorization are enforced server-side. That is the right
-division and this plan keeps it: **we make the core _hostable by_ a team
-server; we do not reimplement team logic locally.**
-
----
-
-## 2. Target architecture
-
-Bootstrap splits into three layers that are fused today:
-
-```text
-CoreBuilder::build() ── layer 1: context init (pure — no
- └─ CoreContext sockets, no spawns): config,
- stores · event bus · registries workspace, master key, stores,
- security policy · approval gate subscribers, policy
-
-CoreRuntime::serve() ── layer 2: services (each opt-in):
- ├─ rpc_http (axum /rpc + Bearer) selected by ServiceSet
- ├─ socketio
- ├─ cron · channels · heartbeat · update
-
-runtime.invoke(method, params) ── layer 3: transports are thin
-CLI `call` · MCP stdio · HTTP handler adapters over the same dispatch
-```
-
-### 2.1 Public API (sketch)
-
-```rust
-pub struct ServiceSet {
- pub rpc_http: bool,
- pub socketio: bool,
- pub cron: bool,
- pub channels: bool,
- pub heartbeat: bool,
- pub update_scheduler: bool,
-}
-impl ServiceSet {
- pub fn desktop() -> Self; // everything on (Tauri today)
- pub fn headless_api() -> Self; // rpc_http only (cloud single-core)
- pub fn none() -> Self; // library / harness-only
-}
-
-pub struct CoreBuilder { /* config, host_kind, token, bind, services */ }
-impl CoreBuilder {
- pub fn new(host_kind: HostKind) -> Self;
- pub fn token(self, t: TokenSource) -> Self; // Fixed | EnvOrFile
- pub fn services(self, set: ServiceSet) -> Self;
- pub async fn build(self) -> anyhow::Result<CoreRuntime>; // init only, no spawns
-}
-
-pub struct CoreRuntime { /* Arc<CoreContext>, CancellationToken, bound_addr */ }
-impl CoreRuntime {
- pub async fn serve(&self, ready: Option<oneshot::Sender<EmbeddedReadySignal>>, shutdown: Option<CancellationToken>)
- -> anyhow::Result<()>; // spawn selected services
- pub async fn invoke(&self, method: &str, params: Map<String, Value>)
- -> Result<Value, RpcError>; // same path as /rpc
- pub fn events(&self) -> broadcast::Receiver<CoreEvent>;
- pub fn agent_runtime(&self) -> AgentRuntime; // harness-only slice
- pub async fn shutdown(self) -> anyhow::Result<()>;
-}
-```
-
-`src/lib.rs` re-exports `CoreBuilder`, `CoreRuntime`, `ServiceSet`,
-`HostKind`, `AgentRuntime` as the documented public surface;
-`run_core_from_args` remains for the binary.
-
-### 2.2 Existing entry points become thin consumers
-
-| Entry | Today | After |
-| --------------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
-| `run_server` (`jsonrpc.rs:1682`) | wraps `run_server_inner` | shim over `CoreBuilder` (deprecated, kept one release) |
-| `run_server_embedded_with_ready` (`:1717`) | same | Tauri `core_process.rs` calls `CoreBuilder` directly: `TokenSource::Fixed(in-memory)`, `ServiceSet::desktop()`; readiness is passed to `CoreRuntime::serve` |
-| CLI `call` / namespace dispatch (`src/core/cli.rs`) | `invoke_method(default_state(), …)` | `ServiceSet::none()` build → `runtime.invoke()` — no port bound for one-shot calls |
-| MCP stdio (`src/core/cli.rs` `mcp`) | same funnel | transport adapter over `runtime.invoke()` |
-| Cloud/team host | n/a | fleet supervisor composing one core per user (phase 4) |
-
-### 2.3 Multi-tenancy: fleet of processes first
-
-**Decision: one supervised core process per user/workspace first — not
-in-process multi-tenancy.** Rationale:
-
-- It is the shape the architecture already has (Tauri = one embedded core for
- one user); a supervisor reuses it with zero correctness risk.
-- The blockers to in-process tenancy are real and slow: env-var mutation for
- child tools (#7), keyring/master-key process scope, `Once`-guarded
- subscribers (#8), Sentry. Separate processes improve blast-radius and
- lifecycle control, but production multi-tenant security still requires
- distinct OS users or containers because agents run arbitrary tools.
-- The wire contract is unchanged, so `CloudHttpTransport` works as-is against
- a per-user base URL.
-
-In-process multi-workspace (a `CoreContext` per tenant) is deferred behind
-phase 3 and is an optimization, not a prerequisite, for the team story.
-
-### 2.4 Globals strategy: staged, bounded
-
-Full DI through ~110 handler registration sites in one PR is unreviewable.
-Three stages (detail in [phase-2](phase-2-corecontext.md) /
-[phase-3](phase-3-multi-context.md)):
-
-- **Stage A (facade):** `CoreContext` _owns initialization order_ and hands
- out handles; existing `*::global::init` calls move inside it; handlers keep
- reading globals. Zero behavior change.
-- **Stage B (mechanical):** registered RPC dispatch installs an ambient
- task-local `CoreContext` while handlers remain plain `fn` pointers. Domains
- then migrate off globals opportunistically by reading `CoreContext::current()`,
- tracked in a drift ledger.
-- **Stage C (bounded):** only what multi-context isolation actually needs.
- **Exit criterion: two `CoreContext`s in one test process serve
- memory/people/config reads without cross-talk — not "zero `OnceLock`s".**
- Keyring, Sentry, `NativeRegistry`, and env vars stay process-scoped and are
- documented as such.
-
-### 2.5 Storage abstraction
-
-Backend-level pluggability also requires the _stores_ to be swappable, not
-just the transports. Today every store is constructed from a workspace
-directory (`*::global::init(workspace_dir)`) and is concretely
-SQLite/JSON-on-disk under `~/.openhuman/users/<id>/workspace`. That is
-invisible in the desktop app but load-bearing for other backends:
-
-- **Fleet hosting (phase 4)** works _without_ abstraction — each per-user core
- process gets its own workspace volume. This is why storage abstraction is
- not on the phase-4 critical path.
-- **Managed/cloud storage** (Postgres, object store for attachments,
- shared-nothing replicas) and **in-process multi-tenancy** both require
- stores behind traits.
-
-The seam is the `CoreContext` handle layer introduced in Stage A/B: handlers
-stop touching `*::global()` and go through `ctx.<store>()`. Those accessors
-return **trait objects** (`Arc<dyn MemoryStore>`, `Arc<dyn PeopleStore>`, …)
-rather than concrete types, and `CoreBuilder` gains a `StorageBackend`
-selector whose only shipped implementation is `WorkspaceFs` (the current
-behavior, byte-for-byte). Store traits are carved per domain _as that domain
-migrates onto the context_ (phase 2 drift ledger gets a "trait extracted?"
-column) — not as one big up-front storage rewrite. Note the engines already
-model this: `tinyagents` has `StoreRegistry`/checkpointer abstractions and
-`tinycortex` owns its own store interfaces; the traits here cover the
-_host-owned_ stores (people, attachments, cost/x402 ledgers, config state,
-run ledgers) that sit outside those crates.
-
-Remote implementations (e.g. `Postgres`) are explicitly out of scope for this
-plan; the deliverable is that adding one is a new `StorageBackend` impl, not
-a refactor.
-
----
-
-## 3. Non-goals
-
-- **Wire contract**: `POST /rpc` JSON-RPC, `openhuman.<ns>_<fn>` naming,
- Bearer auth — unchanged. Client transports untouched.
-- **tinyagents / tinycortex seams**: unchanged; this plan restructures the
- host around them.
-- **Security policy semantics**: `security::live_policy`, approval gate,
- autonomy tiers — unchanged (only _who installs them_ moves into
- `CoreBuilder::build`).
-- **Local team logic**: membership truth stays in `tinyhumansai/backend`.
-- **Not attempted**: replacing axum, changing controller schema format,
- in-process tenant _security_ isolation, `inventory`/linkme distributed
- registration (explicit registration lists fit this repo's ledger culture).
-
-## 4. Phases
-
-| Phase | File | Deliverable | Depends on |
-| ----- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ----------- |
-| 0 | [phase-0-defusion.md](phase-0-defusion.md) | Delete dead tier-3 shim; extract inline service spawns + store-init block into named fns. Pure motion | — |
-| 1 | [phase-1-corebuilder.md](phase-1-corebuilder.md) | `CoreBuilder`/`CoreRuntime`/`ServiceSet`; `run_server*` become shims; Tauri + CLI + MCP ported; embed examples | 0 |
-| 2 | [phase-2-corecontext.md](phase-2-corecontext.md) | `CoreContext` Stage A + B; registry collapse to per-domain `DomainRegistration`; store traits + `StorageBackend::WorkspaceFs`; drift ledger | 1 |
-| 3 | [phase-3-multi-context.md](phase-3-multi-context.md) | Bounded Stage C; two-context isolation test; process-scoped inventory | 2 |
-| 4 | [phase-4-fleet-host.md](phase-4-fleet-host.md) | `openhuman-fleet` supervisor: per-user cores, token minting, `/:user/rpc` proxy, backend membership sync | 1 (not 2/3) |
-
-**Value ordering:** phases 0+1 alone deliver the headline goal — embeddable
-builder, programmatic harness, thin CLI/Tauri. Phase 4 can start immediately
-after phase 1, in parallel with 2/3, because the fleet model needs
-process-per-user, not context threading.
diff --git a/docs/plans/pluggable-core/phase-0-defusion.md b/docs/plans/pluggable-core/phase-0-defusion.md
deleted file mode 100644
index 2be55cf0ba..0000000000
--- a/docs/plans/pluggable-core/phase-0-defusion.md
+++ /dev/null
@@ -1,62 +0,0 @@
-# Phase 0 — De-fusion cleanup
-
-**Status:** planned.
-**Goal:** pure motion inside `run_server_inner` so phase 1 is a composition
-change, not a untangling change. No behavior change; verified by diffing
-startup log lines.
-
-## Scope
-
-### 0.1 Delete the dead dispatch tier
-
-`src/rpc/dispatch.rs:10-15` always returns `None` (module doc says the
-registry is authoritative). Remove the module and its tier-3 call site in
-`src/core/dispatch.rs::dispatch`. `src/rpc/` keeps `structured_error.rs`
-(still used) — only the dispatch shim dies.
-
-### 0.2 Extract inline service spawns
-
-Each inline `tokio::spawn` block in `run_server_inner` becomes a named
-function in a new `src/core/runtime/services.rs`:
-
-| Service | Today (approx.) | Extracted fn |
-| --------------------------------------------------------------------------- | ----------------------- | ----------------------------------------- |
-| Heartbeat + subconscious bootstrap | `jsonrpc.rs:~2083-2110` | `spawn_heartbeat_service(cancel, config)` |
-| Update scheduler | `:~2113` | `spawn_update_scheduler(cancel)` |
-| Cron scheduler (+ proactive-agent seeding, flow schedule-trigger reconcile) | `:~2124-2160` | `spawn_cron_service(cancel, config)` |
-| Channel listeners | `:~2162-2191` | `spawn_channels_service(cancel, config)` |
-
-Rules:
-
-- Every extracted fn takes the `CancellationToken` explicitly (today some
- blocks capture it, some don't — normalize).
-- Existing gates stay _inside_ the fns for now (`config.cron.enabled`,
- `config.heartbeat.enabled`, `OPENHUMAN_DISABLE_CHANNEL_LISTENERS`,
- `has_listening_integrations()`), so call sites don't change semantics.
- Phase 1 lifts the _selection_ (should this service exist) to `ServiceSet`
- while the fns keep their _config_ gates (is it enabled for this user).
-- Keep the deliberate asymmetry documented at `jsonrpc.rs:2259-2264`: the
- flows trigger subscriber registers at unconditional core boot, not under
- channels — that stays in `bootstrap_core_runtime`, not in
- `spawn_channels_service`.
-
-### 0.3 Extract the store-init block
-
-`jsonrpc.rs:1807-1892` (memory, whatsapp_data, people, attachments global
-inits) → `fn init_stores(config: &Config, workspace_dir: &Path) ->
-anyhow::Result<()>` in `src/core/runtime/context.rs` (file seeded here,
-grows in phase 1/2). Preserve init order exactly; comment each step with the
-prior `jsonrpc.rs` line range so the diff is auditable.
-
-## Out of scope
-
-- Any signature or behavior change to the spawned services themselves.
-- Touching `bootstrap_core_runtime` internals (phase 1 moves the call, phase
- 2/3 decompose it).
-
-## Verification
-
-- `cargo check` both crates; `pnpm test:rust`.
-- Boot the desktop app and `openhuman-core serve`; diff the startup log
- sequence (grep-stable prefixes) against `main` — must be identical.
-- `rg 'rpc::try_dispatch|rpc/dispatch'` returns nothing.
diff --git a/docs/plans/pluggable-core/phase-1-corebuilder.md b/docs/plans/pluggable-core/phase-1-corebuilder.md
deleted file mode 100644
index 4729a34b74..0000000000
--- a/docs/plans/pluggable-core/phase-1-corebuilder.md
+++ /dev/null
@@ -1,125 +0,0 @@
-# Phase 1 — `CoreBuilder` / `CoreRuntime` / `ServiceSet`
-
-**Status:** planned.
-**Goal:** split bootstrap (context init) from transport (HTTP is just another
-service) behind a public builder API; port all existing entry points onto it.
-This phase alone delivers the headline goal: embeddable library, programmatic
-harness entry, thin CLI/Tauri.
-
-## New modules
-
-```text
-src/core/runtime/
-├── mod.rs # pub use CoreBuilder, CoreRuntime, ServiceSet, TokenSource
-├── builder.rs # CoreBuilder — validation + build()
-├── context.rs # CoreContext (Stage A facade — owns init order; see phase 2)
-└── services.rs # from phase 0; gains spawn_rpc_http_service, spawn_socketio wiring
-```
-
-Public API per README §2.1. Additional decisions:
-
-- **`TokenSource`**: `Fixed(Arc<String>)` (Tauri in-memory handoff),
- `EnvOrFile` (read `OPENHUMAN_CORE_TOKEN` when present, otherwise generate
- and write the standalone `{root}/core.token` fallback 0600). `build()` seeds
- `auth::init_rpc_token*` exactly once, same precedence as today
- (`src/core/auth.rs`).
-- **`build()` is init-only**: no sockets and no detached jobs for
- `ServiceSet::none()` / `ServiceSet::headless_api()`. It runs, in
- order: controller registration (`all::all_registered_controllers`), master
- key init, token seeding, `Config::load_or_init`, `init_stores` (phase 0),
- `bootstrap_core_runtime(host_kind, services)` for pure registration plus
- ServiceSet-gated legacy bootstrap jobs. Init-order regressions are the top
- risk; add a startup-sequence integration test asserting the order via log
- markers.
-- **`serve()`** spawns only the services selected by `ServiceSet`. The HTTP
- listener (bind, port fallback, router from `build_core_http_router`,
- `axum::serve`) moves into `spawn_rpc_http_service`; **the
- `set_var OPENHUMAN_CORE_RPC_URL` call keeps its exact timing** (post-bind,
- `jsonrpc.rs:2010`) inside that service — child tools depend on it. It is
- flagged in the drift ledger as single-runtime-only.
-- **Ready signal**: `EmbeddedReadySignal` (port-fallback reporting) is kept
- type-identical, relocated; the readiness sender is supplied to
- `CoreRuntime::serve` and fires after bind (when `rpc_http` selected).
-- **`invoke()`** delegates to the existing `invoke_method`
- (`jsonrpc.rs:230`) — same tiered dispatch, no second path.
-
-## `AgentRuntime` (harness-as-library)
-
-`CoreRuntime::agent_runtime()` returns the slice needed to run turns with
-zero ports bound:
-
-```rust
-pub struct AgentRuntime { ctx: Arc<CoreContext> }
-impl AgentRuntime {
- pub fn agent(&self, sel: AgentSelector) -> anyhow::Result<Agent>; // Agent::from_config
- pub async fn run_turn(&self, agent: &Agent, input: TurnInput) -> …; // tinyagents seam
- pub fn events(&self) -> broadcast::Receiver<CoreEvent>;
-}
-```
-
-Its required bootstrap subset _defines_ what `ServiceSet::none()` must still
-initialize: config, workspace, master key, event bus,
-`AgentDefinitionRegistry`, memory/tinycortex stores, cost/x402 ledgers,
-security live-policy + approval gate, tool registry. Explicitly not required:
-HTTP, socket.io, cron, channels, heartbeat, update scheduler.
-
-**Acceptance test for the whole phase:** an integration test (and
-`examples/run_turn.rs`) that builds with `ServiceSet::none()`, runs one agent
-turn through `run_turn_via_tinyagents_shared`, and asserts no listener was
-bound.
-
-**Acceptance test status: done.** `tests/harness_embed.rs` and `examples/run_turn.rs` exist. The
-turn goes through `openhuman.inference_agent_chat` rather than reaching
-`run_turn_via_tinyagents_shared` directly — dispatch is the only path that
-honours `DomainSet` gating and installs `CoreContext` scope (see
-`src/embed/call.rs`), and bypassing it would serve domains the embedder switched
-off.
-
-`AgentRuntime` as sketched above was **not** built. The same slice is delivered
-as `embed::Core::agent()` — a sub-facade in the shape the rest of `embed` uses —
-with `openhuman_core::Harness` above it composing the runtime, the config and
-the workspace lifetime. Two findings from building it are worth recording,
-because both invalidate the assumption that `ServiceSet::none()` is sufficient
-for a library host:
-
-1. **`CoreBuilder::config(..)` does not reach handlers.** They load config per
- dispatch via `load_config_with_timeout()`, which re-resolves the
- process-global workspace. Fixed by publishing the supplied config on
- `CoreContext` and having that loader prefer it — the Stage B seam this plan's
- §2.4 anticipated, arriving here first.
-2. **A domain switched off in `DomainSet` could still start a background
- client.** `start_login_gated_services` spawned the `hosted::orchestration`
- client regardless, whose first backend call flips the scheduler gate to
- signed-out and fails every later turn's custom-provider check. Now gated on
- `domains().hosted`, read before the spawn (a spawned task does not inherit
- the task-local context).
-
-## Porting the consumers
-
-| Consumer | Change |
-| -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `run_server` / `run_server_embedded*` (`jsonrpc.rs:1682-1737`) | become `#[deprecated]` shims over the builder; deleted one release later |
-| Tauri (`app/src-tauri/src/core_process.rs:289`) | `CoreProcessHandle::ensure_running` builds `CoreBuilder::new(HostKind::TauriShell).token(TokenSource::Fixed(..)).services(ServiceSet::desktop())`, then passes readiness to `CoreRuntime::serve`; `CancellationToken` / restart / port-takeover logic unchanged |
-| CLI `run`/`serve` (`src/core/cli.rs:66`) | maps flags → `ServiceSet` (`--jsonrpc-only` → `socketio: false`) |
-| CLI `call` + namespace dispatch (`cli.rs:354,435`) | `ServiceSet::none()` build → `runtime.invoke()`; one-shot calls stop constructing server state |
-| MCP stdio (`cli.rs` `mcp`) | adapter over `runtime.invoke()` |
-| `src/lib.rs` | re-export the new surface; keep `run_core_from_args` |
-
-Plus `examples/embed_headless.rs` (build + `serve()` with
-`ServiceSet::headless_api()`, call `openhuman.ping` over HTTP) and
-`examples/run_turn.rs` (above).
-
-## Risks & mitigations
-
-| Risk | Mitigation |
-| ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
-| Init-order regression (master key before stores; policy before approval gate) | single `CoreContext::init` encoding the order, line-ref comments, startup-sequence test |
-| Tauri port-fallback / ready semantics drift | `EmbeddedReadySignal` unchanged; e2e boot test in CI Full already covers |
-| `set_var` timing change breaks child tools | timing preserved inside `spawn_rpc_http_service`; grep test for env presence after ready |
-| Double-bootstrap when shims + builder both run in tests | builder guards with the same idempotent `Once`s during this phase (removed in phase 3) |
-
-## Verification
-
-- `pnpm test:rust`, `bash scripts/test-rust-with-mock.sh --test json_rpc_e2e`.
-- Both examples run green in CI.
-- Desktop app boots via ported `core_process.rs` (CI Full e2e matrix).
diff --git a/docs/plans/pluggable-core/phase-2-corecontext.md b/docs/plans/pluggable-core/phase-2-corecontext.md
deleted file mode 100644
index d7e23130d0..0000000000
--- a/docs/plans/pluggable-core/phase-2-corecontext.md
+++ /dev/null
@@ -1,156 +0,0 @@
-# Phase 2 — `CoreContext` ownership, ambient context, registry collapse, store traits
-
-**Status:** Stage A + ambient-context + registry-collapse **DONE**; per-domain
-store-trait migration remains.
-**Goal:** make state reachable _through_ a context instead of _only_ through
-process globals, without a big-bang DI rewrite.
-
-## 2.a Handler context access — ambient scope, not a signature sweep (Stage B)
-
-**Implemented (deviation from the original plan, with rationale below):** the
-literal signature change to `ControllerHandler` was rejected after measuring its
-true cost. `ControllerHandler` fn pointers appear at **846 handler definitions
-across 109 files, plus ~381 direct call sites** — a change of that type must
-land atomically to compile, needs a default-context `OnceLock` with fallbacks
-for the many callers that never build a runtime (CLI one-shots, tests, MCP
-dispatch), and yields **zero** functional value until each domain later reads
-`ctx` (Stage C). That is disproportionate churn and a high risk of a
-non-compiling tree.
-
-Instead, the **goal** — every handler can reach the `CoreContext` for the
-current dispatch — is delivered with a `tokio::task_local!` ambient context:
-
-- `CoreContext::init` registers the first-built context as the process
- `DEFAULT_CONTEXT` (`OnceLock<Arc<CoreContext>>`).
-- The dispatch chokepoint `all::try_invoke_registered_rpc` wraps each handler
- future in `CoreContext::scope(ctx, fut)`, where `ctx` is
- `CoreContext::current()` — the active scope if any (so nested dispatches stay
- in the same tenant context), else the default.
-- Handlers reach it via `CoreContext::current() -> Option<Arc<CoreContext>>`.
- Controller handlers stay **bare `fn` pointers** — zero per-handler churn.
-- A domain migrates off a process global by reading its store handle from
- `CoreContext::current()` instead. Once its state lives on the context, two
- contexts dispatched under distinct `CoreContext::scope`s read isolated state —
- exactly the Phase 3 exit criterion, verified by the unit tests in
- `src/core/runtime/context.rs` (`scope_sets_current_context`,
- `nested_scope_overrides_then_restores`).
-
-One implementation note: the extra future layer at the chokepoint pushed the
-`Send` auto-trait solver past the default depth on the deepest axum→tinyagents
-routes; the scoped future is re-boxed into a `ControllerFuture` and the crate
-sets `#![recursion_limit = "256"]` (both in `src/lib.rs` / `src/core/all.rs`).
-
-This is strictly a better realization of Stage B's intent; the explicit-param
-approach is not planned.
-
-## 2.b Registry collapse
-
-Replace the three hand-maintained parallel lists in `src/core/all.rs`
-(handlers `:105-344`, schemas `:375-509`, namespace descriptions `:530-690`)
-with one per-domain struct:
-
-```rust
-pub struct DomainRegistration {
- pub namespace: &'static str,
- pub description: &'static str,
- pub controllers: Vec<RegisteredController>, // schema + handler already paired
- pub cli: Option<CliHandler>, // absorbs CLI_ADAPTERS (all.rs:88)
-}
-fn all_domains() -> Vec<DomainRegistration> { vec![about_app::domain(), /* … one line per domain … */] }
-```
-
-**Implemented (partial — the drift-elimination half):**
-
-- `all_controller_schemas()` now **derives** the schema list from the
- registered controllers (`registry().iter().map(|c| c.schema.clone())`), so the
- parallel `build_declared_controller_schemas()` list is deleted and
- `validate_registry`'s declared-vs-registered cross-check is removed —
- the two lists can no longer drift. `validate_registry` keeps the
- duplicate-method / empty-namespace / duplicate-required-input checks on the
- registered set. Obsolete drift unit tests were removed.
-- **Explicitly rejected:** `inventory`/linkme link-section auto-registration.
-
-**Deferred (cosmetic, no correctness value):** folding the per-domain
-`all_X_controller_schemas()` fns and the `namespace_description` match into a
-single `DomainRegistration` struct. The per-domain schema fns still exist but
-are no longer aggregated centrally; collapsing them further is churn across 109
-domains for no behavior change, tracked as a follow-up.
-
-## 2.c Per-domain migration + store traits
-
-Domains migrate `_ctx` → real context usage opportunistically; **required**
-(because multi-context isolation in phase 3 needs them) for: `memory`
-(tinycortex seam handle), `people`, `attachments`, `config`. Everything else
-migrates when touched.
-
-Storage abstraction lands here, at the handle boundary:
-
-```rust
-impl CoreContext {
- pub fn people(&self) -> Arc<dyn PeopleStore>;
- pub fn attachments(&self) -> Arc<dyn AttachmentStore>;
- // … per-domain accessors added as domains migrate
-}
-
-pub enum StorageBackend { WorkspaceFs } // CoreBuilder::storage(..); only impl for now
-```
-
-- Traits are carved **per domain as it migrates** (drift-ledger column
- "store trait extracted?"), never as one up-front storage rewrite.
-- `WorkspaceFs` wraps the existing SQLite/JSON-on-disk stores byte-for-byte;
- the global facades (`*::global()`) delegate to the default context's
- handles so both paths hit the same instance.
-- Host-owned stores only (people, attachments, cost/x402 ledgers, config
- state, run ledgers). `tinyagents` (`StoreRegistry`, checkpointers) and
- `tinycortex` already own their internal store interfaces — the context
- holds _handles to_ those seams, it does not re-abstract them.
-- Adding a remote backend (e.g. Postgres) must become "new `StorageBackend`
- impl", but shipping one is out of scope.
-
-## Risks & mitigations
-
-| Risk | Mitigation |
-| ---------------------------------------- | -------------------------------------------------------------------------------------- |
-| Sweep-size diff unreviewable | three PR series: signature-only → registry collapse → per-domain |
-| Global facade and context handle diverge | facade delegates to default context (single instance); parity asserts in debug builds |
-| Store trait too narrow, churns later | extract traits from _observed_ handler usage per domain, not speculatively |
-| Coverage gate on mechanical diffs | signature/registry PRs carry existing tests; per-domain PRs add store-trait unit tests |
-
-## 2.d `DomainSet` — the runtime composition axis (#4796)
-
-`DomainSet` (in `src/core/runtime/builder.rs`, sibling of `ServiceSet`) is the
-**runtime** axis that selects which domain *families* exist, complementing
-`ServiceSet` (which selects background services). One flag per `DomainGroup`
-(`src/core/all.rs`); presets `full()` (default — byte-identical to pre-#4796),
-`harness()` (agent + memory + threads + config + security only), `none()`.
-
-Mechanism (Shape B — filter seam, **not** the full per-domain
-`DomainRegistration` struct collapse, which remains phase-2-deferred):
-
-- Every controller is tagged with its `DomainGroup` once, at the single
- registration site (`build_registered_controllers` /
- `build_internal_only_controllers`), via a `GroupedController { group,
- controller }` wrapper — the ~109 domain modules keep returning bare
- `RegisteredController` lists and never learn about groups.
-- The live surface filters by the **ambient** `CoreContext::domains()`:
- `all_registered_controllers` / `all_controller_schemas` (so `/schema` omits
- gated namespaces), `try_invoke_registered_rpc` (gated method ⇒ `None`, i.e.
- unknown-method), the agent tool surface (`tools::ops::all_tools_with_runtime`
- post-filter by `tool_group`), workspace-bound store init (`init_stores`), and
- domain event subscribers (`register_domain_subscribers`).
-- No active context (pre-boot unit tests) ⇒ no filtering (treated as full).
-- Per-gate Cargo `[features]` (children #4797–#4804) narrow the *compile-time*
- surface further; `DomainSet` is the runtime axis they compose with.
-
-## Verification
-
-- `pnpm test:rust` + `json_rpc_e2e` green after each sub-series.
-- Drift ledger lists every domain with columns: signature migrated / context
- usage / store trait / notes.
-- `all::try_invoke_registered_rpc` installs an ambient `CoreContext::scope`
- around registered handler futures, and tests verify `CoreContext::current()`
- propagation through registered RPC invocation.
-- `DomainSet`: `full_registration_is_byte_identical`,
- `harness_excludes_gated_namespaces`, `dispatch_returns_none_for_gated_method`,
- `group_mapping_smoke` (`src/core/all_tests.rs`) +
- `domain_set_presets_have_expected_flags` (`builder.rs`).
diff --git a/docs/plans/pluggable-core/phase-3-multi-context.md b/docs/plans/pluggable-core/phase-3-multi-context.md
deleted file mode 100644
index c52e7c4873..0000000000
--- a/docs/plans/pluggable-core/phase-3-multi-context.md
+++ /dev/null
@@ -1,75 +0,0 @@
-# Phase 3 — Bounded multi-context readiness (Stage C)
-
-**Status:** exit criterion **demonstrated for the first domain** (`people`);
-remaining domains + `RPC_TOKEN`/subscriber relocation are follow-ups.
-**Goal:** two `CoreContext`s in one test process serve memory/people/config
-reads without cross-talk. That sentence is the exit criterion — **not** "zero
-`OnceLock`s". Anything not needed for it stays process-scoped and gets
-documented instead of refactored.
-
-## Delivered
-
-- **Isolation primitive** (Phase 2): `CoreContext::scope` / `current` +
- `DEFAULT_CONTEXT`, scoped at the dispatch chokepoint. Unit-tested
- (`scope_sets_current_context`, `nested_scope_overrides_then_restores`).
-- **First per-context store**: `people::store::for_workspace(dir)` opens/caches a
- store per workspace, and `CoreContext::people()` resolves it for the context's
- workspace — additive alongside the legacy `people::store::get()` global, so the
- ~40 existing people handlers are untouched and migrate to
- `CoreContext::current()?.people()` incrementally.
-- **Exit test (people)**: `people_store_is_isolated_per_context_workspace` — two
- contexts over distinct workspaces resolve isolated stores; one context always
- resolves the same cached store. This is the exit criterion, realized for the
- first migrated domain.
-
-## Remaining (follow-ups)
-
-- Repeat the `for_workspace` + `CoreContext::<domain>()` pattern for `memory`,
- `config`, `attachments`, then migrate their handlers to read through
- `CoreContext::current()`.
-- Move `RPC_TOKEN` onto the context and make event-bus subscriber registration
- per-context (below) — only needed once a host actually runs >1 context in a
- process (the fleet uses process-per-user, so this is not on its path).
-
-## Scope
-
-### 3.1 Per-context state
-
-| Item | Today | After |
-| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| RPC bearer | `RPC_TOKEN: OnceLock<String>` (`src/core/auth.rs:75`) | field on `CoreContext` — it gates a per-runtime HTTP listener; `auth::get_rpc_token` facade reads the default context |
-| Workspace / active user | resolved once from `OPENHUMAN_WORKSPACE` → `active_user.toml` → `"local"` (`config/schema/load/dirs.rs:299`, `load_user_state.rs:21`) | resolution runs in `CoreBuilder::build` and the result is a `CoreContext` field; the marker-file chain remains the _default_ when the embedder passes no workspace |
-| Event-bus domain subscribers | `register_domain_subscribers` under `std::sync::Once` (`src/core/jsonrpc.rs:2232`) | registration keyed per context (subscription handles owned by `CoreContext`, dropped on shutdown); process-level dedupe kept only for genuinely process-global targets |
-| Stores migrated in phase 2.c | global facade → default context | second context constructs its own `StorageBackend::WorkspaceFs` instance over its own workspace dir |
-
-### 3.2 Permanently process-scoped (documented, not refactored)
-
-| Item | Why it stays global |
-| ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Keyring / master key (`keyring::init_master_key`, `src/lib.rs`) | OS keychain is per-process/user by nature |
-| Sentry (`src/main.rs`) | binary concern, not library concern — embedders bring their own |
-| `NativeRegistry` (`event_bus/native_request.rs:329`) | internal typed dispatch; handlers are stateless routers to context-owned state |
-| Env vars (`OPENHUMAN_CORE_RPC_URL` set_var, `jsonrpc.rs:2010`; `OPENHUMAN_WORKSPACE` reads) | child-process contract; this is exactly why multi-_tenant_ hosting is process-per-user (phase 4), and it is documented as a single-runtime-per-process constraint |
-
-This table ships in the README of this plan (or the drift ledger) as the
-authoritative "what is process-scoped and why" inventory for embedders.
-
-## Exit test
-
-`tests/` integration test: construct two `CoreContext`s over two temp
-workspaces in one process (`ServiceSet::none()`), write a person + a config
-value + a memory item through context A, assert context B sees none of them
-and vice versa; both contexts shut down cleanly (subscription handles
-dropped, no `Once` poisoning).
-
-Desktop path must be bit-identical: the single-context Tauri/CLI flow never
-constructs a second context; the test-only second context is the only
-consumer until in-process multi-workspace is deliberately productized.
-
-## Risks & mitigations
-
-| Risk | Mitigation |
-| ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
-| Double-firing subscribers when two contexts register | subscription handles owned per context; bus events carry context/workspace identity where a handler writes to stores |
-| Hidden global discovered late (some `*::global()` not in the phase-2 ledger) | the exit test is the detector; fix-forward per store, ledger updated |
-| `Once` removal regresses single-context boot | keep `Once` semantics for the default context; per-context path only activates for non-default contexts |
diff --git a/docs/plans/pluggable-core/phase-4-fleet-host.md b/docs/plans/pluggable-core/phase-4-fleet-host.md
deleted file mode 100644
index 6fed371f3b..0000000000
--- a/docs/plans/pluggable-core/phase-4-fleet-host.md
+++ /dev/null
@@ -1,124 +0,0 @@
-# Phase 4 — Fleet supervisor: team/cloud hosting
-
-**Status:** MVP **DONE** — `openhuman-fleet` binary (`src/bin/fleet.rs`,
-`[[bin]] name = "openhuman-fleet"`). Remaining: backend membership sync,
-ready-file port discovery, admin API for edge tokens (see "MVP vs production").
-
-**Goal:** a supervisor (`openhuman-fleet`) that hosts one core per team member
-and fronts them behind a single endpoint, so a team admin can
-provision/manage members' assistants while every existing client
-(`CloudHttpTransport`) keeps working unchanged.
-
-## Delivered (MVP)
-
-`src/bin/fleet.rs` — a self-contained binary (separate compile target, zero
-weight on the shipped desktop/lib build: it is gated behind the default-OFF
-`bin-tools` feature):
-
-- **Process-per-tenant MVP**: spawns `openhuman-core run --jsonrpc-only` per tenant
- with a per-user `OPENHUMAN_WORKSPACE`, a minted `OPENHUMAN_CORE_TOKEN`, and
- `OPENHUMAN_DISABLE_CHANNEL_LISTENERS=1` (this is the `ServiceSet::headless_api`
- shape from Phase 1). Before keeping a tenant registered, probes the assigned
- port through authenticated JSON-RPC with that tenant's core bearer; stale or
- fallback ports fail closed. Production multi-tenant security still requires
- distinct OS users or containers.
-- **Reverse proxy**: axum `POST /{user_id}/rpc` forwards the JSON-RPC body
- verbatim to that tenant's core, swapping the client's **edge token** for the
- tenant's **core bearer** — the wire contract is unchanged end to end, so
- `CloudHttpTransport` works against `http://<fleet>/<user_id>/rpc`.
-- **Edge auth / isolation**: distinct `EdgeToken` (client-facing) vs
- `CoreBearer` (fleet-only) types; the proxy rejects a token whose user does not
- match the path segment, so tenant A cannot reach tenant B's core. User ids are
- validated as single `[A-Za-z0-9_-]` segments (no path escape).
-- **Tests**: pure logic unit-tested (port assignment + overflow, user-scoped
- workspace derivation, user-id validation, provisioning distinct
- ports/bearers/edge-tokens, edge-token→user round-trip, bearer parsing).
-
-### MVP vs production (tracked follow-ups, logged not silently dropped)
-
-- Ports are assigned sequentially from `--base-core-port`; production should read
- each core's actually-bound port from a ready file / `EmbeddedReadySignal`
- (Phase 1). The MVP checks loopback availability before spawn and requires an
- authenticated JSON-RPC readiness probe on the assigned port before keeping the
- tenant registered.
-- Tenants come from `--users`; production reconciles membership against
- `tinyhumansai/backend` on a loop (same pattern as the cron scheduler).
-- Minted edge tokens are never printed to stdout. The MVP can write them to a
- restricted operator-selected file with required `--edge-token-output`; production
- should expose them through an authenticated admin API.
-- Container packaging (`HostKind::Docker`) and restart/backoff are not yet wired.
-
-## Decision recap (README §2.3)
-
-Process-per-tenant, not in-process multi-tenancy: it is the shape the
-architecture already has (Tauri = one core per user), it sidesteps the
-process-scoped items inventoried in phase 3 (env mutation for child tools,
-keyring, Sentry), and it keeps the production security boundary explicit:
-agents execute arbitrary tools, so real tenant separation must come from
-distinct OS users or containers, not from a same-user supervisor process.
-
-## Architecture
-
-```text
-client (CloudHttpTransport, per-user base URL + Bearer)
- │
- ▼
-openhuman-fleet supervisor
- ├─ edge auth: mint/validate per-tenant session tokens
- ├─ reverse proxy /:user_id/rpc → 127.0.0.1:<that user's core port>
- ├─ membership sync ⇄ tinyhumansai/backend (teams stay backend-truth)
- └─ lifecycle manager
- └─ per user: provision workspace volume →
- run core (child process or container, HostKind::Docker) with
- TokenSource::Fixed(per-tenant token), bind 127.0.0.1:0,
- ServiceSet::headless_api() + per-plan opt-ins (cron, heartbeat)
-```
-
-Key properties:
-
-- **Wire contract unchanged** inside and out — the proxy strips
- `/:user_id` and forwards `POST /rpc` verbatim; `CloudHttpTransport`
- (`app/src/services/transport/CloudHttpTransport.ts`) already speaks this
- with a profile Bearer token and per-profile `rpcUrl`.
-- **Port arbitration**: cores bind `:0`; supervisor reads the bound port from
- the existing `EmbeddedReadySignal` (child-process variant: ready line on
- stdout or a ready file — decide during implementation).
-- **Teams**: membership/roles/invites remain in `tinyhumansai/backend`
- (`src/openhuman/team/` proxy untouched). The supervisor consumes the same
- backend API to decide _which_ cores exist and who may reach them; it adds
- hosting, not authorization semantics.
-- **Secrets**: per-tenant token + per-tenant keyfile/env in the child's
- environment — no shared keyring across tenants (phase 3 inventory item).
-- **Storage**: per-user workspace volume (`StorageBackend::WorkspaceFs`).
- This is why storage abstraction (phase 2.c) is off this phase's critical
- path; a managed-DB backend would slot in later as a new `StorageBackend`.
-- **Health/restart**: existing health controllers over each core's `/rpc`;
- restart backoff via the existing `apply_startup_restart_delay_from_env`
- seam; container resource limits are the v1 noisy-neighbor answer.
-
-## Scope
-
-1. `openhuman-fleet` crate: tenant registry (backed by backend membership),
- lifecycle manager, token mint/validate, reverse proxy, health loop.
-2. Container image + deployment doc for `HostKind::Docker` cores
- (`ServiceSet::headless_api()`).
-3. Embedder guide in `gitbooks/developing/` covering all four consumption
- modes: Tauri embed, CLI one-shot, library (`AgentRuntime`), fleet.
-4. E2E: supervisor + 2 tenants + `CloudHttpTransport`-shaped client script;
- assert tenant A's token cannot reach tenant B's core.
-
-## Risks & mitigations
-
-| Risk | Mitigation |
-| ------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
-| Token confusion between edge session tokens and core bearer tokens | supervisor is the only holder of core bearers; clients only ever see edge tokens; naming kept distinct in code (`EdgeToken` vs `CoreBearer`) |
-| Resource blow-up (N cores × background services) | default `ServiceSet::headless_api()`; cron/heartbeat opt-in per plan tier |
-| Backend membership drift vs running fleet | reconcile loop (same pattern as cron scheduler); deprovision = stop core, retain volume per retention policy |
-| Supervisor as SPOF | stateless proxy + externalized tenant registry; ops concern, out of scope for v1 doc beyond noting it |
-
-## Out of scope (v1)
-
-- In-process multi-workspace hosting (deferred behind phase 3; optimization
- for read-mostly tenants, never a security boundary).
-- Managed-DB storage backend (needs phase 2.c traits; separate plan).
-- Autoscaling / placement across machines.
diff --git a/docs/plans/rlm-workflows/README.md b/docs/plans/rlm-workflows/README.md
deleted file mode 100644
index 8f422bcd38..0000000000
--- a/docs/plans/rlm-workflows/README.md
+++ /dev/null
@@ -1,66 +0,0 @@
-# RLM — Language-Based Workflows (Rhai/`.ragsh`) Integration Plan
-
-**Goal:** expose TinyAgents' Rhai-backed REPL language (the `.ragsh` / RLM /
-CodeAct surface, gated behind the `repl` cargo feature in
-`vendor/tinyagents/Cargo.toml`) as a **first-class `rlm` tool** in the
-OpenHuman Rust core, so the orchestrator agent can *write its own workflow
-scripts* — fan-out over subagents, batched tool/model calls, loops,
-conditionals — and execute them deterministically, similar to Claude Code
-Workflows and Recursive Language Models (RLMs).
-
-## Why
-
-Today the orchestrator composes work through fixed primitives:
-`spawn_subagent`, `spawn_parallel_agents`, `run_workflow` (WORKFLOW.md
-bundles), and typed tinyflows graphs. None of these let the model express
-*ad-hoc control flow* — "spawn N readers, dedupe their findings, verify each
-survivor with 3 refuters, loop until dry". The `.ragsh` session in TinyAgents
-is exactly that surface: a sandboxed, policy-bounded scripting engine whose
-only host access is capability functions (`model_query`, `tool_call`,
-`agent_query`, batched variants), with fail-closed limits on operations,
-wall-clock time, output bytes, call counts, and recursion depth.
-
-## Architecture summary
-
-```
-Orchestrator model turn
- └─ rlm tool call { script, session_id?, timeout_secs?, limits? }
- └─ src/openhuman/rlm/ (new domain)
- ├─ session manager (persistent ReplSession per rlm session_id)
- ├─ capability bridge (openhuman Tools/Subagents/Provider →
- │ tinyagents CapabilityRegistry)
- ├─ policy mapping (autonomy tier + SecurityPolicy → ReplPolicy)
- ├─ progress bridge (ReplCallRecord / EventSink → AgentProgress
- │ + DomainEvent bus)
- └─ tinyagents::ReplSession::eval_cell (spawn_blocking)
- └─ rhai engine — model_query / tool_call / agent_query /
- *_batched / emit / answer (fail-closed ReplPolicy)
-```
-
-Two repos change:
-
-1. **`vendor/tinyagents`** (submodule, separate PR against
- `tinyhumansai/tinyagents`): host-embedding gaps — external cancellation
- flag, live capability-call events on the `EventSink`, async-embedding
- documentation. Branch: `feat/repl-host-embedding`.
-2. **`openhuman`** (one gigantic PR against `tinyhumansai/openhuman`): the
- `repl` feature flag, the new `src/openhuman/rlm/` domain, the `rlm` tool,
- prompt/docs surfacing, and tests. Branch: `feat/rlm-language-workflows`,
- including the submodule pointer bump once the tinyagents PR lands.
-
-## Phases
-
-| Phase | File | Deliverable |
-| ----- | ---- | ----------- |
-| 1 | [phase-1-research.md](phase-1-research.md) | Research findings: what tinyagents `repl` provides, what openhuman provides, the gaps |
-| 2 | [phase-2-tinyagents.md](phase-2-tinyagents.md) | TinyAgents-side changes (cancellation, live events) — separate PR |
-| 3 | [phase-3-rlm-domain.md](phase-3-rlm-domain.md) | `src/openhuman/rlm/` domain: sessions, capability bridge, policy |
-| 4 | [phase-4-rlm-tool.md](phase-4-rlm-tool.md) | First-class `rlm` tool: schema, registration, prompt surfacing |
-| 5 | [phase-5-hardening.md](phase-5-hardening.md) | Error handling, timeouts, cancellation, limits, observability |
-| 6 | [phase-6-tests.md](phase-6-tests.md) | Tests (written last): unit, timeout/cancel/limit, RPC E2E |
-| 7 | [phase-7-delivery.md](phase-7-delivery.md) | PR strategy: tinyagents PR + one gigantic openhuman PR |
-
-Tests are deliberately the **final implementation phase** (per the feature
-brief): phases 3–5 land the behavior with verbose debug logging; phase 6
-back-fills unit and E2E coverage to the ≥80% changed-line gate before the PR
-is opened.
diff --git a/docs/plans/rlm-workflows/phase-1-research.md b/docs/plans/rlm-workflows/phase-1-research.md
deleted file mode 100644
index e196a12dd9..0000000000
--- a/docs/plans/rlm-workflows/phase-1-research.md
+++ /dev/null
@@ -1,127 +0,0 @@
-# Phase 1 — Research findings
-
-## 1. What TinyAgents' `repl` feature provides
-
-Feature gate: `repl = ["dep:rhai"]` with `rhai = { version = "1", features =
-["sync"] }` (`vendor/tinyagents/Cargo.toml`). The `sync` feature makes engine
-and values `Send + Sync` so a session can live inside an async task.
-
-There are **two** `ReplSession` types; we use the scripting one:
-
-- `tinyagents::repl::ReplSession` — line-oriented command *skeleton*
- (`load/compile/run/call` return `ReplOutcome::Planned`, never executed).
- Not our target.
-- `tinyagents::repl::session::ReplSession` (crate-root re-export
- `tinyagents::ReplSession` under the feature) — the **Rhai scripting
- session**. This is the RLM/CodeAct runtime.
-
-### Session lifecycle
-
-- `ReplSession::from_parts(capabilities, policy, run_context)`; builders
- `with_capabilities` / `with_policy` / `with_state` rebuild the engine.
-- `eval_cell(&mut self, script) -> Result<ReplResult>` — one cell per call;
- top-level `let` bindings persist across cells (persistent `rhai::Scope`).
-- `ReplResult { stdout, value, variables_changed, calls, final_answer,
- elapsed }` — typed, serializable (`ReplValue` = Unit/Bool/Int/Float/
- String/Array/Map).
-- Reserved names (`context`, `state`, `messages`, `history`, `run` + 16
- capability functions) are restored after every cell — scripts can shadow
- but never permanently replace capabilities.
-
-### Script-visible built-ins (`src/repl/session/builtins/`)
-
-| Built-in | Lowers to |
-| -------- | --------- |
-| `model_query(#{model, system?, prompt?, structured?})` | `registry.model(name).invoke(...)` |
-| `tool_call(#{tool, arguments?})` | `registry.tool(name).call(...)` |
-| `agent_query(#{agent, prompt})` | `registry.agent(name).run(SubAgentInput, events)` |
-| `model_query_batched / tool_call_batched / agent_query_batched([...])` | bounded concurrency via `stream::iter(..).buffered(max_concurrency)` |
-| `graph_run / graph_define / graph_validate / graph_compile / graph_diff / graph_register` | `.rag` compiler + resolver + review gate (graph_run returns a *reference*, does not execute) |
-| `emit(name, #{..})`, `answer(content)`, `show_vars()`, `print/debug` | recorded into `ReplResult` |
-
-Bridge mechanism: an `Arc<HostContext<State>>` (registry, state, policy,
-`EventSink`, shared `CellBuffers`) is cloned into every registered closure;
-results flow back through `Arc<Mutex<..>>` buffers.
-
-### Fail-closed limits (`ReplPolicy`, defaults)
-
-`max_operations` 1M · `max_iterations` 16 · `max_script_bytes` 64 KiB ·
-`max_output_bytes` 256 KiB · `max_model_calls` 64 · `max_agent_calls` 32 ·
-`max_tool_calls` 128 · `max_graph_calls` 32 · `max_depth` 8 · `timeout`
-30 s · `max_concurrency` 4 · `generated_graphs_require_review` true.
-
-Timeout is enforced at **two points**: the engine `on_progress` hook (pure
-script loops) and `bridge_block_on` (a timer-thread race that drops the
-in-flight capability future — cancel-safe reqwest). Precise
-`TinyAgentsError`s (Timeout, LimitExceeded, ModelNotFound, SubAgentDepth, …)
-are stashed via `CellBuffers::set_host_error` and surfaced verbatim.
-
-### Async story
-
-The engine is synchronous; capability calls run through a **blocking
-bridge** (`futures::executor::block_on`). `eval_cell` must therefore run on
-`tokio::task::spawn_blocking` (or a dedicated thread) — calling it on an
-async worker deadlocks a current-thread runtime.
-
-### Gaps a host must fill (drives Phase 2)
-
-1. **No external cancellation** — only per-cell wall-clock timeout; no
- abort handle to stop a running cell on demand.
-2. **No live progress** — `stdout`/`calls`/`emit` are only readable after
- the cell returns; nothing streams on the `EventSink` mid-cell.
-3. **No CodeAct driver loop** — the host owns the "model writes cell →
- eval → feed result back" loop (in our design, the orchestrator's normal
- tool-call loop *is* that loop; each `rlm` tool call is one cell).
-4. `graph_run` doesn't execute compiled graphs (returns a reference map) —
- out of scope for v1; we expose model/tool/agent capabilities only.
-5. Sync `eval_cell` + internal `block_on` — handled host-side with
- `spawn_blocking`, documented in tinyagents as part of Phase 2.
-
-## 2. What OpenHuman provides (integration points)
-
-- **Dependency**: `tinyagents = { version = "1.5.0", features = ["sqlite"] }`
- patched to `path = "vendor/tinyagents"` (git submodule,
- `tinyhumansai/tinyagents`). We add the `"repl"` feature.
-- **Tool trait** (`src/openhuman/tools/traits.rs:255`): `name` /
- `description` / `parameters_schema` / `async execute` (+
- `execute_with_context`, `permission_level_with_args`, `external_effect`,
- `timeout_policy`, `display_label/detail`). Registered by adding one
- `Box::new(...)` line in `all_tools_with_runtime`
- (`src/openhuman/tools/ops.rs`).
-- **Tool→tinyagents bridge already exists**: `ToolAdapter`
- (`src/openhuman/agent/tinyagents/tools.rs:78`) wraps `Arc<dyn openhuman Tool>`
- and implements `tinyagents::Tool<()>` — we reuse it to project openhuman
- tools into the REPL's `CapabilityRegistry`.
-- **Model bridge already exists**: `ProviderModel`
- (`src/openhuman/agent/tinyagents/model.rs`) implements the tinyagents model
- trait over openhuman's `Provider`; `assemble_turn_harness`
- (`src/openhuman/agent/tinyagents/mod.rs:1122`) already builds a
- `CapabilityRegistry<()>` per turn with models registered.
-- **Subagents**: `run_subagent(definition, prompt, options)`
- (`src/openhuman/agent/harness/subagent_runner/`) + parent allowlist
- (`allowed_subagent_ids`) + `MAX_SPAWN_DEPTH`. We wrap this in a
- `HarnessAgent` impl so `agent_query("researcher", ...)` spawns real
- openhuman subagents.
-- **Timeout/cancel**: `tool_timeout` domain clamps 1–3600 s;
- `workflows::run_log::register_run_cancel(run_id) -> CancellationToken`.
-- **Approval/security**: `external_effect_with_args == true` routes through
- the `ApprovalGate` middleware; per-tool security is enforced inside each
- tool via `Arc<SecurityPolicy>` — bridged tools keep their own checks, so
- the REPL inherits them for free.
-- **Progress**: per-turn `AgentProgress` mpsc sink (streams to UI + run
- logs) and the global `DomainEvent` bus (`ToolExecutionStarted/Completed`,
- `Workflow*` events).
-- **Prompt surfacing**: tool `description()` + `parameters_schema()` ride in
- the native tool-call API request; the orchestrator's narrative guide is
- `src/openhuman/agent/registry/agents/orchestrator/prompt.md` + `agent.toml`.
-- **No existing rhai/RLM surface** in `src/` — this is net-new, but it sits
- beside `workflows/`, `flows/`, `tinyflows/`, `agent_orchestration/`.
-
-## 3. Design decision: one cell per tool call
-
-The orchestrator's existing turn loop already is a CodeAct loop. So the
-`rlm` tool maps **one tool call → one `eval_cell`**, with an optional
-persistent `session_id` so a later call continues the same namespace
-(`let findings = ...` in cell 1, referenced in cell 2). This avoids building
-a bespoke driver loop, keeps every cell inside the normal approval/permission
-middleware, and gives the model natural iteration with feedback.
diff --git a/docs/plans/rlm-workflows/phase-2-tinyagents.md b/docs/plans/rlm-workflows/phase-2-tinyagents.md
deleted file mode 100644
index f714e854a9..0000000000
--- a/docs/plans/rlm-workflows/phase-2-tinyagents.md
+++ /dev/null
@@ -1,69 +0,0 @@
-# Phase 2 — TinyAgents-side changes (separate PR)
-
-Branch: `feat/repl-host-embedding` in `vendor/tinyagents` (repo
-`tinyhumansai/tinyagents`). Raised as its **own PR**; the openhuman PR bumps
-the submodule pointer to the merged commit.
-
-Scope is intentionally minimal — only the host-embedding gaps identified in
-Phase 1 that cannot be worked around from openhuman.
-
-## 2.1 External cancellation (`ReplCancelFlag`)
-
-**Problem:** a running cell can only be stopped by its wall-clock timeout.
-OpenHuman needs to abort an in-flight RLM cell when the user cancels a run
-(`workflows::run_log::cancel_run`) or the agent turn aborts.
-
-**Change:** add a shared cancellation flag to the session:
-
-- `repl/session/types.rs`: `pub struct ReplCancelFlag(Arc<AtomicBool>)` with
- `new() / cancel(&self) / is_cancelled(&self)`. Cheap `Clone`.
-- `ReplSession::with_cancel_flag(flag)` stores it; `CellBuffers` carries it
- alongside `deadline`.
-- Enforcement mirrors the deadline's two points, fail-closed:
- - the engine `on_progress` hook terminates the script with a
- `CANCELLED_TOKEN` sentinel → mapped to a new
- `TinyAgentsError::Cancelled` in `eval_cell`;
- - `bridge_block_on_raw` polls the flag in its timer race (tick the select
- with a short-interval timer when a flag is armed) so a blocked
- model/tool/agent call is dropped promptly on cancel.
-- New error variant `TinyAgentsError::Cancelled(String)` in `src/error.rs`.
-
-## 2.2 Live capability-call events on the `EventSink`
-
-**Problem:** `ReplResult.calls` is only available after the cell completes;
-long fan-outs look frozen in the UI.
-
-**Change:** in `builtins/`, emit a typed event on `HostContext.events`
-(the existing `EventSink` shared with the run context) at capability-call
-start and completion — `AgentEvent::Custom`-style records carrying
-`{session_id, kind: model|tool|agent|emit, name, elapsed?}`. The host
-(openhuman) subscribes an `EventListener` and forwards to its own progress
-sink. No new public types beyond what the event enum already supports; if
-`AgentEvent` lacks a suitable variant, add `AgentEvent::ReplCall
-{ record: ReplCallRecord, phase: Started|Completed }` behind the `repl`
-feature.
-
-## 2.3 Async-embedding documentation
-
-Document at the `eval_cell` API surface (rustdoc + module README) that the
-method blocks internally (`futures::executor::block_on`) and must be driven
-via `spawn_blocking`/dedicated thread from async hosts. This is currently
-only discoverable by reading `builtins/mod.rs`.
-
-## 2.4 Tests (in tinyagents, alongside the changes)
-
-TinyAgents' own convention requires tests with every behavior change, so
-this crate does **not** defer them:
-
-- cancel flag set before `eval_cell` → `Cancelled` without starting;
-- cancel mid-script-loop → terminated promptly (`on_progress` path);
-- cancel during a hanging capability future → dropped promptly
- (`bridge_block_on` path);
-- events observed on the `EventSink` for `model_query`/`tool_call` start +
- completion with a `ScriptedModel`/`FakeTool`.
-
-## Acceptance
-
-`cargo fmt --check && cargo clippy --all-targets -- -D warnings &&
-cargo test --features repl` green in `vendor/tinyagents`; PR opened against
-`tinyhumansai/tinyagents` with the summary + commands run.
diff --git a/docs/plans/rlm-workflows/phase-3-rlm-domain.md b/docs/plans/rlm-workflows/phase-3-rlm-domain.md
deleted file mode 100644
index 2127255c2f..0000000000
--- a/docs/plans/rlm-workflows/phase-3-rlm-domain.md
+++ /dev/null
@@ -1,96 +0,0 @@
-# Phase 3 — The `rlm` domain (`src/openhuman/rlm/`)
-
-New domain following the canonical module shape. Cargo change: root
-`Cargo.toml` gains `features = ["sqlite", "repl"]` on the tinyagents dep.
-
-```
-src/openhuman/rlm/
-├── mod.rs # exports only + controller schema pair (none in v1)
-├── types.rs # RlmSessionId, RlmRunSummary, RlmLimitsOverride, serde types
-├── policy.rs # autonomy tier + tool_timeout → tinyagents ReplPolicy
-├── bridge.rs # capability bridge: openhuman tools/model/subagents →
-│ # tinyagents CapabilityRegistry<()>
-├── sessions.rs # session manager: persistent ReplSession per session_id
-├── ops.rs # eval_cell orchestration: spawn_blocking, cancel, events
-├── tools.rs # RlmTool (Phase 4)
-└── README.md # module design doc
-```
-
-## 3.1 `policy.rs` — mapping openhuman config to `ReplPolicy`
-
-- Base on `ReplPolicy::default()` (already conservative).
-- `timeout` = min(caller `timeout_secs` clamped by
- `tool_timeout::explicit_call_timeout_secs`, global cap). Never unbounded.
-- `max_agent_calls` / `max_depth` respect `MAX_SPAWN_DEPTH` and the
- autonomy tier: `readonly` tier ⇒ RLM tool not registered at all (see
- Phase 4); `supervised` ⇒ defaults; `full` ⇒ caller may raise limits up to
- a hard ceiling (2× defaults) via the tool's `limits` arg.
-- `max_concurrency` capped at 8.
-- Log the resolved policy at `debug` with the `[rlm]` prefix.
-
-## 3.2 `bridge.rs` — the capability registry
-
-Builds a `tinyagents::registry::CapabilityRegistry<()>` for a session:
-
-- **Tools**: take the turn's `Vec<Arc<dyn openhuman Tool>>` (the same list
- the harness registered, minus exclusions), wrap each in the existing
- `crate::openhuman::agent::tinyagents::tools::ToolAdapter`, and
- `registry.replace_tool(name, adapter)`. **Exclusions** (recursion +
- duplication guards): `rlm` itself, `spawn_subagent`/`spawn_parallel_agents`
- (use `agent_query` instead), `run_workflow`/`await_workflow`. Because
- `ToolAdapter` carries each tool's own security/approval behavior, scripts
- get exactly the same gates as direct tool calls.
-- **Model**: register the turn's `ProviderModel` (and workload routes via
- `routes::build_route_models`) under the same names the harness uses, so
- `model_query(#{model: "chat-v1", ...})` hits the real provider with usage
- accounting intact.
-- **Agents**: for each `AgentDefinition` in the parent's
- `allowed_subagent_ids`, register a `SubagentCapability` — a small adapter
- implementing `tinyagents::graph::subagent_node::HarnessAgent` whose
- `run(input, events)` calls
- `agent::harness::subagent_runner::run_subagent(definition, prompt,
- options)` with the parent's workspace descriptor, model override, and
- progress sink threaded through. Depth accounting flows through the
- session's `RunConfig.depth` so `SubAgentDepth` fails closed.
-
-## 3.3 `sessions.rs` — session manager
-
-- `RlmSessionManager` (global `OnceLock`, like `ApprovalGate`): map of
- `session_id -> Mutex<ReplSessionEntry>` where the entry owns the
- `ReplSession<(), ()>`, its `ReplCancelFlag`, creation time, and cell count.
-- `get_or_create(session_id, registry, policy)`; sessions are keyed
- per-thread/turn-scope (`<thread_id>:<session_id>`) so parallel chats don't
- share namespaces.
-- Eviction: idle TTL (30 min) + LRU cap (16 sessions), enforced on access;
- explicit `close(session_id)`.
-- The `ReplSession` is `Send` (rhai `sync` feature) but `eval_cell` takes
- `&mut self` — one cell at a time per session, serialized by the entry
- mutex; a second concurrent call on the same session returns a typed
- "session busy" error rather than queueing forever.
-
-## 3.4 `ops.rs` — evaluating a cell
-
-`pub async fn eval_rlm_cell(req: RlmEvalRequest) -> anyhow::Result<RlmEvalResponse>`
-
-1. Resolve/verify session; register cancel token with
- `workflows::run_log::register_run_cancel`-style bookkeeping tied to the
- turn's cancellation context (`tinyagents/run_cancellation_context.rs`),
- linking user cancel → `ReplCancelFlag::cancel()`.
-2. Subscribe an `EventListener` on the session's `EventSink` that forwards
- REPL call events to the turn's `AgentProgress` sink
- (`ToolCallStarted/Completed`-shaped) and publishes coarse
- `DomainEvent`s (start/finish) on the global bus.
-3. `tokio::task::spawn_blocking(move || session.eval_cell(&script))` with an
- outer `tokio::time::timeout` at policy timeout + grace (5 s) as a
- belt-and-braces bound (the inner deadline should always fire first).
-4. Map `ReplResult` → `RlmEvalResponse { stdout, value, variables_changed,
- calls (summarized), final_answer, elapsed_ms, session_id, cells_used,
- limits_remaining }`, truncating per `max_result_size_chars`.
-5. Map every `TinyAgentsError` variant to a **model-consumable** error
- string (Phase 5 details) — errors return as tool results, never panics.
-
-## 3.5 Wiring
-
-- `src/openhuman/mod.rs` (domain list): add `pub mod rlm;`.
-- Debug logging throughout with `[rlm]` prefix, correlation fields
- `session_id`, `cell_index`, `thread_id`.
diff --git a/docs/plans/rlm-workflows/phase-4-rlm-tool.md b/docs/plans/rlm-workflows/phase-4-rlm-tool.md
deleted file mode 100644
index e9fa9d60c0..0000000000
--- a/docs/plans/rlm-workflows/phase-4-rlm-tool.md
+++ /dev/null
@@ -1,77 +0,0 @@
-# Phase 4 — The first-class `rlm` tool
-
-## 4.1 Tool definition (`src/openhuman/rlm/tools.rs`)
-
-`RlmTool` implementing `crate::openhuman::tools::Tool`:
-
-- `name()` → `"rlm"`.
-- `description()` — teaches the model the surface in one screen: what a
- cell is, the built-ins (`tool_call`, `agent_query`, `model_query`,
- `*_batched`, `emit`, `answer`), that `let` bindings persist within a
- `session_id`, the limits, and 2 worked examples (parallel fan-out over
- subagents; batched tool calls + reduce loop).
-- `parameters_schema()`:
-
-```json
-{
- "type": "object",
- "properties": {
- "script": { "type": "string", "description": "Rhai workflow cell to evaluate" },
- "session_id": { "type": "string", "description": "Continue a prior RLM session's namespace; omit for a fresh session" },
- "timeout_secs": { "type": "integer", "minimum": 1, "maximum": 3600 },
- "limits": {
- "type": "object",
- "properties": {
- "max_tool_calls": { "type": "integer" },
- "max_agent_calls": { "type": "integer" },
- "max_model_calls": { "type": "integer" },
- "max_concurrency": { "type": "integer" }
- }
- },
- "close_session": { "type": "boolean", "description": "Close the session after this cell" }
- },
- "required": ["script"]
-}
-```
-
-- `permission_level_with_args` → `Execute` (matches `spawn_subagent`).
-- `external_effect_with_args` → `false` for the tool itself: every effectful
- operation a script performs goes through the bridged inner tools, each of
- which carries its **own** `external_effect` and hits the `ApprovalGate`
- middleware inside `ToolAdapter`'s call path. (Verify in Phase 5 that the
- approval middleware is actually on the bridged path; if the gate lives
- only in the harness middleware stack and not in `ToolAdapter`, invoke
- `ApprovalGate::intercept_audited` inside the bridge — fail closed.)
-- `timeout_policy(args)` → `ToolTimeout::Secs(clamped timeout_secs)`,
- default `Secs(300)` — never `Inherit` (a fan-out legitimately outlives the
- default inherit budget), never `Unbounded`.
-- `scope()` → `ToolScope::AgentOnly` in v1 (orchestrator surface, not
- CLI/RPC).
-- `display_label` → "running RLM workflow"; `display_detail` → first line of
- the script, elided at 80 chars.
-
-## 4.2 Registration
-
-- Re-export from `src/openhuman/rlm/mod.rs`; glob re-export via
- `src/openhuman/tools/mod.rs` like other domains.
-- Add to `all_tools_with_runtime` (`src/openhuman/tools/ops.rs`), gated:
- **not registered** when the autonomy tier is `readonly`, or when
- `OPENHUMAN_RLM=0`. Env/config default: **on** for `supervised`/`full`.
-- The tool needs the turn's tool list + provider to build its bridge, so it
- is constructed with the same runtime handles `all_tools_with_runtime`
- already passes (security policy, config) plus a late-bound
- `RlmRuntimeContext` resolved per-call from the fork/turn context (the
- pattern `SpawnSubagentTool` uses via `current_parent()`).
-
-## 4.3 Prompt & docs surfacing
-
-- Native tool-call format carries `description()` + schema automatically —
- the primary model documentation.
-- Add a "Language workflows (rlm)" section to
- `src/openhuman/agent/registry/agents/orchestrator/prompt.md`: when to
- prefer `rlm` over `spawn_parallel_agents` (ad-hoc control flow, loops,
- dedup/verify pipelines), the one-cell-per-call model, and session reuse.
-- Update `src/openhuman/platform/about_app/` feature inventory (new user-facing
- capability).
-- `docs`/gitbooks: extend
- `gitbooks/developing/architecture/agent-harness.md` with the RLM section.
diff --git a/docs/plans/rlm-workflows/phase-5-hardening.md b/docs/plans/rlm-workflows/phase-5-hardening.md
deleted file mode 100644
index 2b334c2307..0000000000
--- a/docs/plans/rlm-workflows/phase-5-hardening.md
+++ /dev/null
@@ -1,66 +0,0 @@
-# Phase 5 — Error handling, timeouts, cancellation, observability
-
-The RLM tool executes model-authored code; every failure mode must be
-fail-closed, bounded, and reported back to the model as a *usable* tool
-result (so it can fix its script), never as a panic or a hung turn.
-
-## 5.1 Error taxonomy → model-consumable results
-
-| Failure | Source | Returned tool result |
-| ------- | ------ | -------------------- |
-| Script parse/runtime error | `TinyAgentsError::Validation` | `is_error=true`, rhai diagnostic verbatim + hint ("fix the script and retry in the same session") |
-| Wall-clock timeout | `TinyAgentsError::Timeout` | which phase timed out (script vs in-flight capability call), elapsed, configured limit |
-| Op/output/script-size/call-count limit | `LimitExceeded` | the specific limit + counter values + how to split work across cells |
-| Unknown capability | `ModelNotFound`/`ToolNotFound`/`Capability` | the bad name + the live list of registered tool/agent/model names |
-| Recursion depth | `SubAgentDepth` | depth + max |
-| User cancel | `Cancelled` (new, Phase 2) | "cancelled by user", partial `calls` summary |
-| Session busy / evicted / unknown `session_id` | rlm domain | typed message; unknown id ⇒ fresh session created and noted |
-| spawn_blocking join error / poisoned session | rlm domain | session is dropped (poisoned namespaces are never reused), error reported |
-
-Partial results: on timeout/cancel/limit, include whatever `CellBuffers`
-captured (stdout so far is not available from a failed `eval_cell` in v1 —
-note this; calls recorded before the failure are, via the live event
-stream).
-
-## 5.2 Layered time bounds (belt and braces)
-
-1. rhai `on_progress` deadline — pure script loops.
-2. `bridge_block_on` timer race — hung capability futures.
-3. Outer `tokio::time::timeout(policy.timeout + 5s)` around
- `spawn_blocking` — defends against bugs in 1–2; logs at `error` if it
- ever fires (it should not), and drops the session entry (the blocking
- thread may still be unwinding; never reuse it).
-4. Harness-level `ToolTimeout::Secs` — the final backstop; the tool's own
- timeout is always set below it.
-
-## 5.3 Cancellation flow
-
-user cancel / turn abort
-→ existing run-cancellation context (`tinyagents/run_cancellation_context.rs`)
-→ `ReplCancelFlag::cancel()`
-→ script terminated at next statement OR in-flight capability future dropped
-→ `Cancelled` tool result → session left intact (resumable).
-
-## 5.4 Resource-exhaustion guards beyond ReplPolicy
-
-- Session manager LRU cap + idle TTL (Phase 3) — no unbounded namespaces.
-- Result truncation via `max_result_size_chars` before returning to the
- model.
-- `calls` summarized (kind, name, elapsed, ok/err) — never raw payloads —
- in the tool result; full detail only at `debug` log level.
-- Nested `rlm` is impossible (excluded from the bridge) — no REPL-in-REPL.
-
-## 5.5 Observability (per debug-logging rules)
-
-- `[rlm]` tracing on: session create/evict/close, policy resolution, cell
- start/end (elapsed, counters), every capability call start/finish (name,
- elapsed, ok/err), every error mapping, cancellation, both timeout layers.
-- `AgentProgress` events for live UI: cell started, capability calls
- (forwarded from EventSink), cell completed.
-- `DomainEvent` bus: reuse the `tool` category events already published by
- `ToolAdapter` for inner calls; add coarse start/finish workflow events for
- the cell itself.
-- Langfuse: inner model/agent calls already traced through the existing
- provider/observability path; tag spans with `rlm.session_id`.
-- Never log script-embedded secrets: scripts are logged elided (first line,
- hash, byte size) at `info`; full script only at `trace`.
diff --git a/docs/plans/rlm-workflows/phase-6-tests.md b/docs/plans/rlm-workflows/phase-6-tests.md
deleted file mode 100644
index 0184f3206d..0000000000
--- a/docs/plans/rlm-workflows/phase-6-tests.md
+++ /dev/null
@@ -1,74 +0,0 @@
-# Phase 6 — Tests (written last)
-
-Per the feature brief, tests are back-filled **after** the behavior lands
-(phases 3–5). Target: ≥80% changed-line coverage (the `pr-ci.yml` diff
-gate) for the openhuman side. TinyAgents-side tests ship inside Phase 2
-(that crate's convention does not defer tests).
-
-## 6.1 Unit tests — `src/openhuman/rlm/`
-
-Use tinyagents testkit stubs (`ScriptedModel`, `FakeTool`, `StubAgent`) so
-no network and no real provider is needed.
-
-`policy.rs` (`#[cfg(test)] mod tests`):
-- timeout clamped to [1, 3600] and to the global cap; limits override
- ceiling (≤2× default) enforced; readonly tier → policy builder refuses.
-
-`bridge.rs`:
-- excluded tools (`rlm`, `spawn_*`, `run_workflow`) absent from registry;
-- an openhuman fake tool is callable via the registry and returns its
- `ToolResult` content;
-- subagent capability maps `agent_query` prompt → `run_subagent` input
- (with a stubbed runner seam) and threads depth.
-
-`sessions.rs`:
-- namespace persists across two `eval_cell`s in one session;
-- distinct `session_id`s isolated; thread-scoped keys isolated;
-- LRU eviction + idle TTL; `close_session` drops the entry;
-- concurrent second call on a busy session → typed "busy" error (no
- deadlock);
-- poisoned/errored session dropped, not reused.
-
-`ops.rs` / `tools.rs` (the error-proofing matrix, one test per row of the
-Phase 5 taxonomy):
-- happy path: script calling `tool_call` + `answer` → RlmEvalResponse with
- stdout/value/final_answer;
-- parse error → `is_error` tool result containing the rhai diagnostic;
-- `while true {}` → Timeout within policy bound (bounded test time: 1–2 s
- policy);
-- hanging fake tool future → Timeout via bridge race;
-- `max_tool_calls = 1` + two calls → LimitExceeded naming the limit;
-- unknown tool name → error listing registered names;
-- cancel flag fired mid-cell → Cancelled, session still usable after;
-- oversized output → LimitExceeded; result truncation applied;
-- schema validation: missing `script`, bad `timeout_secs` bounds.
-
-`RlmTool` metadata tests: name/permission/scope/timeout_policy/display
-label — the same shape other domains' tool tests use.
-
-## 6.2 Integration — `tests/` (mock backend)
-
-Extend `tests/json_rpc_e2e.rs` / `scripts/test-rust-with-mock.sh` **only if**
-the tool is reachable over RPC in v1; since `scope() = AgentOnly`, v1
-instead adds a Rust integration test that assembles the turn harness with
-the RLM tool registered and drives a scripted turn where the model calls
-`rlm` with a fan-out script (mock provider supplies the tool_call). Asserts:
-progress events observed on the `AgentProgress` sink, final tool result
-well-formed.
-
-## 6.3 Frontend
-
-No new UI surface in v1 (progress rides existing tool-call timeline cards),
-so no Vitest additions beyond any i18n keys if a display string is added —
-if one is, add the key to `en.ts` + all locale files and run
-`pnpm i18n:check`.
-
-## 6.4 Commands
-
-```bash
-GGML_NATIVE=OFF cargo check --manifest-path Cargo.toml
-pnpm debug rust rlm # targeted domain tests
-bash scripts/test-rust-with-mock.sh # full rust suite
-pnpm typecheck && pnpm lint # app unchanged, still gate
-cd vendor/tinyagents && cargo test --features repl
-```
diff --git a/docs/plans/rlm-workflows/phase-7-delivery.md b/docs/plans/rlm-workflows/phase-7-delivery.md
deleted file mode 100644
index 2e096e2a1d..0000000000
--- a/docs/plans/rlm-workflows/phase-7-delivery.md
+++ /dev/null
@@ -1,52 +0,0 @@
-# Phase 7 — Delivery: two PRs, one gigantic + one focused
-
-## 7.1 TinyAgents PR (first)
-
-- Repo: `tinyhumansai/tinyagents`, branch `feat/repl-host-embedding`
- (created off `357bcc8`, the commit the submodule currently pins).
-- Content: Phase 2 (cancel flag, live EventSink call events, embedding
- docs, tests). Small focused commits per tinyagents conventions.
-- Until it merges, openhuman development proceeds against the local
- submodule checkout (the `[patch]` already points at
- `vendor/tinyagents`), so nothing blocks.
-
-## 7.2 OpenHuman PR (the gigantic one)
-
-- Repo: `tinyhumansai/openhuman`, branch `feat/rlm-language-workflows` off
- `upstream/main`; push to `origin` (fork `senamakel/openhuman`), PR
- `--head senamakel:feat/rlm-language-workflows` against upstream.
-- One PR containing, as a series of small coherent commits:
- 1. `docs(plans)`: this plan folder.
- 2. `chore(deps)`: enable tinyagents `repl` feature.
- 3. `feat(rlm)`: types + policy mapping.
- 4. `feat(rlm)`: capability bridge.
- 5. `feat(rlm)`: session manager.
- 6. `feat(rlm)`: ops (eval, cancel, events).
- 7. `feat(rlm)`: the `rlm` tool + registration + prompt/about_app docs.
- 8. `fix/feat(rlm)`: hardening pass (error taxonomy, layered timeouts).
- 9. `test(rlm)`: the Phase 6 suite.
- 10. `chore(vendor)`: bump tinyagents submodule pointer to the merged
- Phase 2 commit (after the tinyagents PR lands; if it hasn't merged
- yet, the openhuman PR pins the branch head and notes the dependency
- in the PR body).
-- PR body: architecture summary (from README), the two-repo dependency,
- commands run, coverage numbers, and explicit callout that tests were
- authored in the final phase per the brief.
-
-## 7.3 Merge order & risk
-
-1. tinyagents PR merges → retag/pin.
-2. openhuman PR updates submodule pointer commit, CI full lane re-runs.
-3. Rollback story: the feature is dark unless the tool registers
- (`OPENHUMAN_RLM=0` kill switch + not registered on readonly tier);
- reverting the tool-registration commit disables the surface without
- touching the domain.
-
-## 7.4 Follow-ups (explicitly out of v1)
-
-- Graph execution from scripts (`graph_run` executing compiled graphs) —
- blocked on tinyagents implementing super-step execution behind the REPL.
-- RPC/CLI exposure of RLM sessions (controller schemas) + a dedicated UI
- timeline card for cells.
-- Durable session persistence across core restarts.
-- Streaming partial stdout from a running cell.
diff --git a/docs/plans/subconscious-factory/README.md b/docs/plans/subconscious-factory/README.md
deleted file mode 100644
index d2d04ae7d2..0000000000
--- a/docs/plans/subconscious-factory/README.md
+++ /dev/null
@@ -1,129 +0,0 @@
-# Subconscious factory — one reflection engine, many worlds
-
-Redesign `src/openhuman/subconscious/` around the split-brain spec
-(`state (1).md`, "Autonomous Closed-Loop LangGraph Harness"): the subconscious
-is the **Deep Reflection Layer** — an offline, cron-driven loop that consumes a
-compressed view of how a world changed and emits short, dense outputs that
-steer the rest of the system. Today that layer exists twice, fused together
-inside one engine. This plan pulls it apart into a **factory** that can
-instantiate a subconscious per *world*:
-
-- **`memory`** — OpenHuman's internal high-level world: the user's connected
- memory sources (Gmail/Slack/Notion/folders). Observes a `memory_diff`
- against a baseline checkpoint; reflects with the slim decision agent
- (to-dos, goals, `notify_user`, delegation).
-- **`tinyplace`** — the tiny.place orchestration world: harness-session
- interactions flowing through the `orchestration` domain. Observes the
- 20:1 compressed execution history + cumulative world-state diff; reflects
- with a tool-free steering synthesis that emits `STEERING_DIRECTIVE`s for the
- reasoning core.
-
-New kinds (e.g. a per-team world, a channels world) become one new profile
-file, not another engine.
-
-## Where we are today
-
-| Spec concept (state (1).md) | Existing implementation |
-| --- | --- |
-| Quick LLM / Front-End Agent | `orchestration/frontend_agent/` (`hint:chat`, two-pass) |
-| Reasoning LLM / orchestration core | `orchestration/reasoning_agent/` (`hint:reasoning`), wake graph in `orchestration/graph/` |
-| Bi-directional loop routing | `orchestration/graph/build.rs` + `ops::invoke_with_runtime` (debounce, idempotence cursor, dm_sent latch) |
-| 20:1 compression engine | `orchestration/graph/compress.rs` + `ProductionRuntime::compress` |
-| Cumulative world-state diff | `orchestration/graph/world_diff.rs` + `store::append_world_diff` |
-| Context lifecycle hooks (80–90%) | `context_guard`/`evict` nodes → memory-RAG eviction |
-| Subconscious LLM / steering | `orchestration/steering.rs` + `ops::run_orchestration_review` — **but invoked inline from `subconscious::engine::tick_inner`** |
-| Cron trigger | `subconscious/heartbeat/` driving `SubconsciousEngine::tick` |
-
-The problem is confined to `subconscious/engine.rs`: `tick_inner` is a
-hard-wired composite — stage 0 calls `orchestration::ops::run_orchestration_review`
-(the tiny.place world), then stages 1–3 run the memory world (memory_diff →
-context scout → decision agent). One tick lock, one circuit breaker, one
-status object, one baseline store — for two unrelated worlds. Neither can get
-its own cadence, provider signature, halt state, or status, and a third world
-cannot be added without growing the composite further.
-
-## Target shape
-
-```
-subconscious/
-├── mod.rs exports (unchanged public names + new factory surface)
-├── profile.rs SubconsciousProfile trait + Observation/Reflection types
-├── engine.rs generic SubconsciousInstance: tick graph (tinyagents CompiledGraph) + scheduler shell
-├── factory.rs SubconsciousKind + make_subconscious(kind, config)
-├── registry.rs (grown from global.rs) kind → instance map, lifecycle
-├── profiles/
-│ ├── memory.rs today's stages 1–3, extracted verbatim
-│ └── tinyplace.rs wraps orchestration::ops::run_orchestration_review
-├── store.rs instance-namespaced KV + legacy-key migration
-├── heartbeat/ unchanged scheduler; drives every registered instance
-├── agent/ unchanged (memory profile's decision agent)
-├── session.rs, user_thread.rs, source_chunk.rs, schemas.rs unchanged roles
-```
-
-The generic tick is a **`tinyagents` `CompiledGraph`** (the same runtime the
-orchestration wake path runs on — see phase 6), wrapped by scheduler concerns
-in `engine.rs`, identical for every kind:
-
-```
-lock → timeout guard → config load → provider gate + rate-cap halt (per-instance signature)
- → run graph: START ─► observe ─┬─(quiet)──────────────────────► commit ─► END
- └─► prepare_context ─► reflect ─► commit ─► END
- · nodes delegate to the profile (the profile IS the injected runtime)
- · SqliteCheckpointer → a killed tick resumes instead of losing its window
- → superseded-generation check
- → per-instance state/status update
-```
-
-Everything that is currently *good* about the engine — tick lock, generation
-counter, `TICK_TIMEOUT`, rate-cap circuit breaker (TAURI-RUST-HXF), tool-capability
-detection (TAURI-RUST-ADC), only-advance-on-success baselines, quiet-tick
-short-circuit — moves into the generic runner **once** and every world gets it
-for free.
-
-## The factory
-
-```rust
-pub enum SubconsciousKind { Memory, TinyPlace }
-
-pub fn make_subconscious(kind: SubconsciousKind, config: &Config) -> SubconsciousInstance {
- let profile: Arc<dyn SubconsciousProfile> = match kind {
- SubconsciousKind::Memory => Arc::new(profiles::memory::MemoryProfile::new(config)),
- SubconsciousKind::TinyPlace => Arc::new(profiles::tinyplace::TinyPlaceProfile::new(config)),
- };
- SubconsciousInstance::new(profile, config)
-}
-```
-
-`registry.rs` (today's `global.rs`) holds the instances, bootstraps the enabled
-set after login (`Memory` when `heartbeat.enabled`; `TinyPlace` when
-`orchestration.enabled`), and tears all of them down on user switch.
-
-## Invariants that must survive the refactor
-
-1. **Isolation** — the subconscious never contacts anyone. The tinyplace
- profile stays a tool-free provider chat; the memory profile's agent toolset
- keeps the no-channel/no-outbound test (`subconscious_agent_tool_surface_has_no_channel_or_effect_tools`).
-2. **Taint** — any tick that reacted to external content runs
- `SubconsciousTainted` (memory: diff-driven ticks; tinyplace: always).
-3. **State only advances on success**; a superseded tick discards its result.
-4. **Quiet ticks cost nothing** — no LLM call when `observe()` is empty.
-5. **`subconscious.status` never touches the tick mutex** — reads from SQLite.
-6. **Back-compat** — existing DB keys (`last_tick_at`, `baseline_checkpoint_id`)
- migrate to the `memory:`-namespaced keys; the RPC keeps its legacy top-level
- fields mirroring the memory instance.
-
-## Phases
-
-| Phase | File | Deliverable |
-| --- | --- | --- |
-| 1 | [phase-1-profile-and-engine.md](phase-1-profile-and-engine.md) | `SubconsciousProfile` trait, generic `SubconsciousInstance`, namespaced store |
-| 2 | [phase-2-memory-profile.md](phase-2-memory-profile.md) | Extract the memory flow into `profiles/memory.rs`, behavior-identical |
-| 3 | [phase-3-tinyplace-profile.md](phase-3-tinyplace-profile.md) | Wrap the orchestration review as `profiles/tinyplace.rs`; delete the inline call |
-| 4 | [phase-4-factory-registry-rpc.md](phase-4-factory-registry-rpc.md) | Factory + registry lifecycle, heartbeat fan-out, per-instance RPC |
-| 5 | [phase-5-tests-and-docs.md](phase-5-tests-and-docs.md) | Test matrix, migration tests, README/docs updates, rollout |
-| 6 | [phase-6-tinyagents-reuse.md](phase-6-tinyagents-reuse.md) | TinyAgents graph reuse map + upstream PRs to `tinyhumansai/tinyagents` (deadline, cancel token, checkpoint GC) |
-| 7 | [phase-7-ui.md](phase-7-ui.md) | UI: both kinds visible + triggerable — instance cards in the Subconscious tab, steering header on the orchestration tab's Subconscious window |
-
-Each phase is a separately compilable, committable slice; phases 2 and 3 are
-pure extractions (no behavior change), which keeps the diffs reviewable and
-the coverage gate satisfiable per-slice.
diff --git a/docs/plans/subconscious-factory/phase-1-profile-and-engine.md b/docs/plans/subconscious-factory/phase-1-profile-and-engine.md
deleted file mode 100644
index 53b6185226..0000000000
--- a/docs/plans/subconscious-factory/phase-1-profile-and-engine.md
+++ /dev/null
@@ -1,188 +0,0 @@
-# Phase 1 — `SubconsciousProfile` trait + generic instance runner
-
-Goal: introduce the abstraction without moving any behavior yet. At the end of
-this phase the existing `SubconsciousEngine` still works exactly as today; the
-new types compile alongside it and are exercised only by unit tests.
-
-## 1.1 `profile.rs` — the world contract
-
-```rust
-/// One "world" a subconscious can be instantiated over.
-#[async_trait::async_trait]
-pub trait SubconsciousProfile: Send + Sync {
- /// Stable instance id — store-key namespace, log prefix, RPC name.
- fn id(&self) -> &'static str; // "memory" | "tinyplace"
-
- /// Tick cadence for this world (heartbeat multiplies its base interval).
- fn cadence(&self, config: &Config) -> std::time::Duration;
-
- /// Stage 1: what changed in this world since my baseline?
- /// Errors and first-ever ticks surface as an empty observation
- /// (`has_changes == false`) so the runner's quiet-path handles them.
- async fn observe(&self, config: &Config) -> Observation;
-
- /// Stage 2 (optional): grounding context for the reflection turn.
- /// Default impl returns "" (the tinyplace profile skips this stage).
- async fn prepare_context(&self, _config: &Config, _obs: &Observation) -> String {
- String::new()
- }
-
- /// Stage 3: the reflection turn. Runs only when `obs.has_changes`.
- async fn reflect(
- &self,
- config: &Config,
- obs: &Observation,
- prepared_context: &str,
- ) -> Result<Reflection, String>;
-
- /// Advance this world's baseline/cursor. Called by the runner:
- /// - after a quiet tick (refresh the baseline), and
- /// - after a successful reflect (never after a failed or superseded one).
- async fn commit(&self, config: &Config, obs: &Observation);
-
- /// Turn-origin taint for this observation (memory: tainted iff the diff
- /// carried external content; tinyplace: always tainted).
- fn origin(&self, obs: &Observation) -> TrustedAutomationSource;
-}
-
-pub struct Observation {
- /// Rendered world diff handed to `reflect` (empty when quiet).
- pub rendered: String,
- pub has_changes: bool,
- /// Whether the change window contains third-party content (taint input).
- pub has_external_content: bool,
- /// Opaque token `commit` uses to advance exactly the observed window
- /// (memory: none needed — it re-checkpoints; tinyplace: newest reviewed
- /// compressed-row created_at for the review cursor).
- pub commit_token: Option<String>,
-}
-
-pub enum Reflection {
- /// The decision agent acted through tools (memory profile).
- Acted { response_chars: usize },
- /// A steering directive was emitted (tinyplace profile).
- Steered { directive_id: i64 },
- /// The model looked and correctly chose to do nothing.
- Idle,
-}
-```
-
-Design notes:
-
-- `observe` is **infallible by signature**: today `tick_inner` already treats a
- diff error as "quiet tick, refresh baseline"; encoding that in the type keeps
- the runner branch-free. The profile logs its own errors.
-- `reflect` returns `Err(String)` (matching today's `run_agent` error channel)
- so the runner can keep the existing error classifiers — the string is fed to
- `is_tool_capability_error` / `is_permanent_rate_cap_error` unchanged.
-- `commit_token` exists because the tinyplace world advances a *cursor over
- reviewed rows* (must not skip rows that arrived mid-tick), while the memory
- world re-checkpoints the whole world. Both fit one optional string.
-
-## 1.2 `engine.rs` — `SubconsciousInstance` (generic runner **as a tinyagents graph**)
-
-Rename the struct conceptually: `SubconsciousEngine` → `SubconsciousInstance`
-(keep a `pub type SubconsciousEngine = SubconsciousInstance;` alias until
-phase 4 updates the callers). The instance owns exactly what the engine owns
-today, minus every memory-specific line:
-
-```rust
-pub struct SubconsciousInstance {
- profile: Arc<dyn SubconsciousProfile>,
- graph: Arc<CompiledGraph<SubconsciousState>>, // built once at construction
- workspace_dir: PathBuf,
- mode: SubconsciousMode,
- interval_minutes: u32,
- enabled: bool,
- state: Mutex<EngineState>, // unchanged fields
- tick_generation: AtomicU64,
- tick_lock: Mutex<()>,
-}
-```
-
-The tick body is **not** hand-rolled control flow: it is one `tinyagents`
-[`CompiledGraph`] built with `GraphBuilder`, exactly the pattern
-`orchestration/graph/build.rs` established (nodes call an injected
-`dyn` runtime; the graph owns routing/termination; a stub runtime makes the
-mechanics unit-testable). Topology:
-
-```text
-START ─► observe ─┬─(quiet)────────────────────────────► commit ─► END
- └─(changed)─► prepare_context ─► reflect ─► commit ─► END
-```
-
-- `SubconsciousState` (serde, like `OrchestrationState`): the `Observation`,
- `prepared_context`, `Reflection` outcome, tick metadata (`tick_id`,
- generation). Channels are plain `LastValue`s — no message reducers needed.
-- The node handlers delegate 1:1 to the `SubconsciousProfile` methods — the
- profile trait **is** the injected runtime (mirroring
- `OrchestrationRuntime`); no second abstraction.
-- Conditional edge out of `observe` on `has_changes` (command-routing, same
- mechanism as the `frontend` router).
-- Checkpointing: `SqliteCheckpointer<SubconsciousState>` at
- `<workspace>/subconscious/graph_checkpoints.db`, thread id
- `subconscious:<instance>:<tick_id>`. A tick killed mid-reflect resumes (or
- is superseded cleanly) instead of losing the window — same durability story
- the wake graph already has. Baseline advancement stays in `commit`, so a
- resumed tick can never double-advance.
-- Observability for free: graph stream events / status snapshots
- (`tinyagents::graph::stream`/`status`) give per-node timing without bespoke
- logging (keep the `[subconscious]` log lines anyway per repo logging rules).
-
-What deliberately stays *outside* the graph, in `SubconsciousInstance`:
-the cadence loop trigger (heartbeat), the tick lock + 5s acquisition skip,
-the generation counter (supersede), `TICK_TIMEOUT`, provider gate + rate-cap
-halt, and status. Rationale: these are scheduler/circuit-breaker concerns
-identical to what `ops::invoke_with_runtime` keeps outside the wake graph —
-see phase 6 for the tinyagents-side gaps that would let some of them move
-into the runtime later.
-
-The pieces that stay verbatim in the runner:
-
-- 5s tick-lock acquisition timeout + skip log
-- `TICK_TIMEOUT` wall clock (30 min) — consider making it a profile constant
- later; not in this phase
-- config-load failure path
-- provider gate (`subconscious_provider_unavailable_reason`) and the rate-cap
- halt (`should_skip_for_rate_cap_halt` / `arm_rate_cap_halt`) — the halt
- signature gains the instance id prefix (`"memory|cloud"`) so one world's
- halt never silences another
-- tool-capability / rate-cap error classification on `reflect` failure
-- superseded-generation discard
-- `status()` — gains `instance: String` (the profile id)
-
-## 1.3 `store.rs` — instance-namespaced KV + migration
-
-Today: `subconscious_state` (REAL KV: `last_tick_at`) and
-`subconscious_state_text` (TEXT KV: `baseline_checkpoint_id`), one row each.
-
-Change the accessors to take the instance id and prefix the key
-(`"memory:last_tick_at"`, `"tinyplace:last_tick_at"`, …). One-time migration in
-the DDL block of `with_connection` (idempotent, like all our DDL):
-
-```sql
-UPDATE subconscious_state SET key = 'memory:' || key
- WHERE key IN ('last_tick_at') AND NOT EXISTS (SELECT 1 FROM subconscious_state WHERE key = 'memory:last_tick_at');
-UPDATE subconscious_state_text SET key = 'memory:' || key
- WHERE key IN ('baseline_checkpoint_id') AND NOT EXISTS (SELECT 1 FROM subconscious_state_text WHERE key = 'memory:baseline_checkpoint_id');
-```
-
-(Exact guard shape to be settled in implementation — requirement is: running
-old→new→old… never loses `last_tick_at`, and the migration is a no-op on a
-fresh DB. The tinyplace profile's *review cursor* stays where it lives today,
-in the orchestration store — the profile owns it via `commit`.)
-
-## 1.4 Tests (this phase)
-
-- A `FakeProfile` (scripted observations/reflections, call recorder) driving
- `SubconsciousInstance` directly:
- - quiet observation → no `reflect`, `commit` called, `last_tick_at` advanced
- - failing `reflect` → no `commit`, `consecutive_failures` bumped, baseline untouched
- - rate-cap error string → halt armed under `"<id>|<provider-sig>"`; second
- tick skips; signature change resumes
- - superseded generation → result discarded, no `commit`
-- Store: namespaced get/set round-trip; legacy-key migration (seed old keys,
- open, assert `memory:`-keys carry the values).
-
-Existing `engine_tests.rs` keeps passing untouched (the old engine still
-exists in this phase).
diff --git a/docs/plans/subconscious-factory/phase-2-memory-profile.md b/docs/plans/subconscious-factory/phase-2-memory-profile.md
deleted file mode 100644
index 6b931b39e3..0000000000
--- a/docs/plans/subconscious-factory/phase-2-memory-profile.md
+++ /dev/null
@@ -1,58 +0,0 @@
-# Phase 2 — Extract the memory profile (behavior-identical)
-
-Goal: move today's stages 1–3 out of `engine.rs` into
-`profiles/memory.rs`, switch the live engine to
-`SubconsciousInstance::new(MemoryProfile, config)`, and delete the old
-monolithic `tick_inner`. **No behavior change** — this phase is a pure
-extraction, verified by keeping `engine_tests.rs` green against the new
-composition.
-
-## 2.1 What moves where
-
-| Today (`engine.rs`) | Destination |
-| --- | --- |
-| baseline load + `diff_since_checkpoint` + `world_diff_change_count` | `MemoryProfile::observe` |
-| `render_world_diff` + `MAX_ITEMS_PER_SOURCE` | `profiles/memory.rs` (private) |
-| `prepare_context` (context_scout + `with_root_parent`, TAURI-RUST-HMW) | `MemoryProfile::prepare_context` |
-| `SUBCONSCIOUS_TOOL_CATALOG` | `profiles/memory.rs` |
-| `run_agent` (slim agent, `hint:subconscious`, Full autonomy, mode → iteration caps, user-message contract) | `MemoryProfile::reflect` |
-| `refresh_baseline` (`create_checkpoint` + persist id) | `MemoryProfile::commit` |
-| `tick_origin_source` | `MemoryProfile::origin` (keep the free fn for its unit test) |
-| **the inline `run_orchestration_review` call (stage 0)** | **stays temporarily** — moved in phase 3 |
-
-Note on the stage-0 call: during phase 2 it lives in a small shim at the top
-of the runner (`if profile.id() == "memory" { run_orchestration_review(...) }`)
-or equivalently stays as a pre-hook closure passed by the bootstrap. Ugly on
-purpose and clearly marked `// phase-3 removes this`; it keeps phase 2 purely
-mechanical.
-
-## 2.2 `MemoryProfile` specifics
-
-- `id()` → `"memory"`; `cadence` → `mode.default_interval_minutes().max(5)`
- minutes (today's value).
-- `observe`: returns `has_changes == false` for first-tick/no-baseline, quiet
- window, or diff error (each with today's log lines). Sets
- `has_external_content = true` whenever there are changes (every change
- originates from a source sync — today's comment carries over).
-- `reflect`: returns `Reflection::Acted { response_chars }`; the SubconsciousMode
- → `max_tool_iterations` mapping (15 / 30 / Off→short-circuit) is unchanged.
-- `commit`: re-checkpoint + persist under the namespaced key
- (`memory:baseline_checkpoint_id`). Best-effort, warn on failure (unchanged).
-- `origin`: `tick_origin_source(obs.has_external_content)`.
-
-## 2.3 Public-surface continuity
-
-`mod.rs` keeps exporting `SubconsciousEngine` (alias), `SubconsciousStatus`,
-`TickResult`, `notify_user`, session/source_chunk items — nothing outside the
-domain changes in this phase. `global.rs` swaps its construction call only.
-
-## 2.4 Tests
-
-- Port `engine_tests.rs` to construct `SubconsciousInstance` with
- `MemoryProfile` — assertions unchanged (rate-cap halt lifecycle, provider
- routing/signature, origin escalation, tool-capability detection).
-- New: `MemoryProfile::observe` unit tests over a seeded memory_diff store
- (quiet vs changed windows), reusing whatever fixture `memory_diff` tests use.
-- The agent-toolset isolation test in `orchestration/ops.rs`
- (`subconscious_agent_tool_surface_has_no_channel_or_effect_tools`) keeps
- compiling — `agent/agent.toml` does not move.
diff --git a/docs/plans/subconscious-factory/phase-3-tinyplace-profile.md b/docs/plans/subconscious-factory/phase-3-tinyplace-profile.md
deleted file mode 100644
index d92b0c75f3..0000000000
--- a/docs/plans/subconscious-factory/phase-3-tinyplace-profile.md
+++ /dev/null
@@ -1,85 +0,0 @@
-# Phase 3 — The tiny.place profile (orchestration steering)
-
-Goal: make the tiny.place/orchestration subconscious a first-class instance
-and delete the stage-0 shim from the runner. After this phase the two worlds
-tick independently: separate locks, cadences, circuit breakers, failure
-counters, and status rows.
-
-## 3.1 `profiles/tinyplace.rs`
-
-Wraps the machinery that already exists in `orchestration/`:
-
-- `id()` → `"tinyplace"`.
-- `cadence`: its own knob (see 3.3); default = the heartbeat interval, so the
- merged behavior matches today (review ran once per memory tick).
-- `observe`: the load half of `run_orchestration_review` —
- `review_cursor` → `list_unreviewed_compressed(REVIEW_BATCH)` +
- `list_recent_world_mutations(REVIEW_BATCH)` + `current_cycle_counter`.
- `has_changes = !compressed.is_empty()` (today's idle gate).
- `rendered = build_steering_prompt(&summaries, &mutations)`.
- `commit_token = newest reviewed created_at`.
- `has_external_content = true` always — harness DMs are third-party content.
-- `prepare_context`: default no-op (steering is deliberately tool-free; no
- scout).
-- `reflect`: the synth half — `synthesize_steering` (tool-free
- `create_chat_provider("subconscious")` chat, `SubconsciousTainted` origin,
- one retry on contract violation) + persist
- (`insert_steering_directive`, supersede prior, `record_subconscious_directive`
- into the local Subconscious window + event publish). Returns
- `Steered { directive_id }` or `Idle` (clean `NONE` / twice-failed —
- today both still advance the cursor; preserve that by returning `Idle`,
- not `Err`, for those cases).
-- `commit`: `set_review_cursor(commit_token)`. This is where the phase pays
- off: today the cursor advance is tangled into `run_orchestration_review`'s
- three exit paths; splitting observe/reflect/commit lets the runner enforce
- "advance only when the tick wasn't superseded" uniformly.
-- `origin`: always `SubconsciousTainted`.
-
-## 3.2 Refactor of `orchestration::ops`
-
-`run_orchestration_review` is currently the public entry called by the
-subconscious engine. Plan:
-
-- Split it into store-facing pieces the profile calls
- (`load_review_window(config) -> ReviewWindow`,
- `synthesize_and_persist(config, window, tick_id) -> Option<i64>`), keeping
- them in `orchestration::ops` — the orchestration domain still owns its
- store shapes and the steering contract; the subconscious profile is just
- the *scheduler + policy* around them.
-- Keep a thin `run_orchestration_review` wrapper for the two existing tests
- (or port those tests to drive the profile; implementor's choice — the
- invariants asserted must survive: emit-then-inject-next-cycle, idempotent
- re-tick, exactly-one-directive).
-- Delete the stage-0 shim in the subconscious runner (`// phase-3 removes
- this` marker from phase 2).
-
-## 3.3 Config
-
-- `orchestration.enabled` remains the master gate for the tinyplace instance
- (profile `observe` returns quiet when disabled — same as today's early
- `Ok(false)`).
-- Add `orchestration.review_interval_minutes: Option<u32>` (None = heartbeat
- interval) consumed by `cadence`. Schema change in
- `config/schema/orchestration.rs` + env override in `load.rs` +
- `.env.example` note.
-
-## 3.4 Isolation invariants (unchanged, now testable per-instance)
-
-- The tinyplace reflect path constructs **no Agent and no toolset** — it is a
- provider chat. Add a compile-level guard mirroring the existing agent-toml
- test: the profile module must not import `tinyplace::agent_tools` or any
- `send_message`-family symbol (source-scan test like
- `orchestration_logs_never_reference_message_bodies`).
-- The steering directive remains an out-of-band writer: it is read by
- `apply_cycle_steering` at the next wake, never edges into the graph.
-
-## 3.5 Tests
-
-- Profile-level: seeded orchestration store → observe has_changes; scripted
- provider (existing `test_provider_override`) → `Steered`; cursor advanced
- via runner commit; re-tick idle.
-- Runner-level: tinyplace + memory instances ticking concurrently against one
- workspace — no lock contention between them, independent `last_tick_at`
- keys, one instance's rate-cap halt does not gate the other.
-- Regression: the full-cycle orchestration graph test keeps passing (steering
- injection path untouched).
diff --git a/docs/plans/subconscious-factory/phase-4-factory-registry-rpc.md b/docs/plans/subconscious-factory/phase-4-factory-registry-rpc.md
deleted file mode 100644
index f6ff05ddd7..0000000000
--- a/docs/plans/subconscious-factory/phase-4-factory-registry-rpc.md
+++ /dev/null
@@ -1,90 +0,0 @@
-# Phase 4 — Factory, registry lifecycle, heartbeat fan-out, RPC
-
-Goal: the "make subconscious" surface — instantiate any set of worlds, drive
-them from the heartbeat, expose per-instance status/trigger over JSON-RPC.
-
-## 4.1 `factory.rs`
-
-```rust
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum SubconsciousKind { Memory, TinyPlace }
-
-impl SubconsciousKind {
- pub fn id(self) -> &'static str; // "memory" | "tinyplace"
- pub fn parse(s: &str) -> Option<Self>;
- /// Which kinds should run for this config (bootstrap set).
- pub fn enabled_kinds(config: &Config) -> Vec<Self> {
- // Memory ⇐ heartbeat.enabled && mode != Off (today's gate)
- // TinyPlace ⇐ orchestration.enabled (today's gate)
- }
-}
-
-pub fn make_subconscious(kind: SubconsciousKind, config: &Config) -> SubconsciousInstance;
-```
-
-`make_subconscious` is the *only* place profiles are constructed — tests and
-the trigger RPC go through it too, so a new kind is: profile file + one match
-arm + one `enabled_kinds` line.
-
-## 4.2 `registry.rs` (grown from `global.rs`)
-
-Replace the single `OnceLock<Arc<Mutex<Option<SubconsciousEngine>>>>` with a
-keyed registry:
-
-```rust
-static REGISTRY: OnceLock<Mutex<HashMap<SubconsciousKind, Arc<SubconsciousInstance>>>>;
-```
-
-- `get_or_init_instance(kind)` — lazy per-kind construction (same
- load-config-then-insert dance as today's `get_or_init_engine`).
-- `bootstrap_after_login()` — unchanged guard (`BOOTSTRAPPED` swap), then
- initializes every `enabled_kinds(config)` member, spawns the heartbeat, and
- (unchanged) the opt-in trigger orchestrator.
-- `stop_heartbeat_loop()` / `reset_engine_for_user_switch()` — abort the
- heartbeat, shut down the trigger orchestrator, then clear the whole map so
- a user switch rebuilds every instance against the new workspace.
-- Keep `get_or_init_engine()` as a deprecated alias for
- `get_or_init_instance(Memory)` until the RPC handlers are ported (below),
- then delete it.
-
-Instances stay `Arc` (not `Mutex<Option<..>>`): the instance's own
-`tick_lock`/`state` mutexes already serialize what needs serializing, and the
-status path must remain lock-free per invariant 5.
-
-## 4.3 Heartbeat fan-out
-
-`heartbeat/engine.rs` currently calls the single engine's `tick()` on its
-interval. Change: on each heartbeat interval, iterate the registry and tick
-every instance whose `cadence` has elapsed since its `last_tick_at`
-(per-instance keys from phase 1 make this a pure read). Instances tick
-**concurrently** (`tokio::spawn` per instance, joined with the existing
-cancel/abort semantics) — a slow memory tick must not delay a tinyplace
-review. The heartbeat's event-planner duties (meetings/reminders) are
-untouched.
-
-## 4.4 RPC surface (`schemas.rs`)
-
-Backward-compatible extension of the `subconscious` namespace:
-
-- `subconscious.status` → today's top-level fields stay, populated from the
- **memory** instance (existing UI keeps working), plus
- `instances: [SubconsciousStatus]` with one row per registered kind
- (each row gains `instance: "memory" | "tinyplace"`).
-- `subconscious.trigger` → optional `kind` param (`"memory"` default —
- today's behavior; `"tinyplace"`; `"all"`). Still fire-and-forget
- (spawned, returns immediately).
-- Status reads stay SQLite-only: per-instance `last_tick_at` comes from the
- namespaced KV; in-memory counters (failures, halt reason) come from the
- instance's `status()` which takes only the small `state` mutex, never
- `tick_lock` — same as today.
-
-Frontend consumption of these fields is phase 7 (instance cards in the
-Subconscious tab, steering header in the TinyPlace Orchestration tab). Not a
-blocker for the Rust work — the additions are backward-compatible.
-
-## 4.5 `about_app`
-
-Update `src/openhuman/platform/about_app/` copy: the subconscious is now described as
-per-world instances (memory awareness + tiny.place orchestration steering),
-per the repo rule that user-facing feature changes update about_app.
diff --git a/docs/plans/subconscious-factory/phase-5-tests-and-docs.md b/docs/plans/subconscious-factory/phase-5-tests-and-docs.md
deleted file mode 100644
index 25121f182a..0000000000
--- a/docs/plans/subconscious-factory/phase-5-tests-and-docs.md
+++ /dev/null
@@ -1,65 +0,0 @@
-# Phase 5 — Test matrix, docs, rollout
-
-## 5.1 Test matrix (cumulative — most land inside phases 1–4)
-
-| Layer | Test | Phase |
-| --- | --- | --- |
-| runner | FakeProfile: quiet / fail / rate-cap-halt / superseded lifecycles | 1 |
-| store | key namespacing + legacy→`memory:` migration round-trip | 1 |
-| memory profile | observe over seeded diff store; origin escalation; mode→iteration caps | 2 |
-| ported | all of today's `engine_tests.rs` against `SubconsciousInstance<MemoryProfile>` | 2 |
-| tinyplace profile | observe/reflect/commit against scripted provider; idle-NONE advances cursor | 3 |
-| cross-instance | two instances, one workspace: independent state keys, halts, no lock coupling | 3 |
-| factory | `enabled_kinds` gating per config; `make_subconscious` per kind | 4 |
-| registry | bootstrap set, user-switch reset clears map, deprecated alias | 4 |
-| heartbeat | fan-out ticks only elapsed cadences; concurrent tick spawn | 4 |
-| RPC | `status` legacy fields mirror memory; `instances` rows; `trigger kind=…` | 4 |
-| json_rpc_e2e | extend `tests/json_rpc_e2e.rs`: `subconscious.status` shape incl. `instances` | 4 |
-| isolation | tinyplace source-scan (no agent/toolset imports); agent.toml scan (exists) | 3 |
-
-Coverage gate: each phase is its own PR-sized slice with ≥80% diff coverage;
-the extraction phases (2, 3) inherit most coverage from ported tests.
-
-## 5.2 Docs
-
-- `src/openhuman/subconscious/README.md` — rewrite around the factory: the
- generic tick skeleton, the profile table (memory / tinyplace), per-instance
- persistence keys, RPC additions. Keep the gotchas list (post-login
- bootstrap, status-never-locks, state-advances-on-success, quiet-tick
- short-circuit, taint) — all still true, now per instance.
-- `orchestration/mod.rs` module docs — stage 6 wording: the review is now
- driven by the tinyplace subconscious instance, not inlined in the memory
- tick.
-- `gitbooks/developing/architecture/agent-harness.md` — if it names the
- subconscious loop, reflect the split. Run `pnpm docs:generate` +
- `pnpm docs:check` (Docs Drift lane) in the final slice.
-- `about_app` copy (phase 4.5).
-
-## 5.3 Rollout & risk
-
-- **No data-shape risk**: the only migration is KV key renaming inside
- `subconscious.db` (phase 1.3), designed to be old-version-tolerant. The
- orchestration store is untouched.
-- **Behavioral deltas to call out in the PR series** (all intentional):
- 1. The orchestration review no longer piggybacks on the memory tick — it
- runs on its own cadence, so it also runs when the memory world is quiet
- (today a memory-provider outage silently starves steering; after phase 3
- it doesn't).
- 2. A rate-cap halt on one world no longer pauses the other.
- 3. `subconscious.status` gains fields (additive only).
-- **Branch/PR sequencing**: one branch per phase off `upstream/main`
- (`feat/subconscious-profile-core`, `feat/subconscious-memory-profile`, …),
- stacked; each independently green on ci-lite. Phase 2+3 could merge as one
- PR if review prefers seeing the shim appear and disappear together.
-
-## 5.4 Explicit non-goals (this plan)
-
-- No change to the orchestration wake graph, compression ratio, context-guard
- thresholds, or steering contract — those already implement the spec.
-- No new subconscious kinds beyond the two (the factory makes them cheap
- later; e.g. a `team` world or a `channels` world).
-- No frontend redesign beyond phase 7's scoped additions (instance cards +
- steering header) — no new pages, routes, or Redux slices.
-- The opt-in event-driven trigger pipeline (`subconscious_triggers` +
- `LongLivedSession`) keeps its current shape; folding it into a profile is a
- possible follow-up once the factory exists.
diff --git a/docs/plans/subconscious-factory/phase-6-tinyagents-reuse.md b/docs/plans/subconscious-factory/phase-6-tinyagents-reuse.md
deleted file mode 100644
index 46eec0542b..0000000000
--- a/docs/plans/subconscious-factory/phase-6-tinyagents-reuse.md
+++ /dev/null
@@ -1,83 +0,0 @@
-# Phase 6 — TinyAgents graph reuse & upstream changes
-
-The subconscious runner (phase 1.2) is built on `tinyagents::graph` — the same
-durable-workflow runtime the orchestration wake path uses. This phase tracks
-(a) what we reuse as-is, and (b) the gaps that warrant changes **inside
-`vendor/tinyagents`**, which is a git submodule of the separate repo
-`tinyhumansai/tinyagents`: those changes go on their own branch there, raised
-as their **own PR**, and the openhuman PR bumps the submodule pointer to the
-merged commit (same workflow as `docs/plans/rlm-workflows/phase-2-tinyagents.md`).
-
-## 6.1 Reused as-is (no upstream change)
-
-| Need | tinyagents surface |
-| --- | --- |
-| tick topology + conditional quiet/changed routing | `GraphBuilder`, `Route`/command-routing, `START`/`END` |
-| typed per-tick state | serde state + `LastValue` channels |
-| crash-safe resume of an interrupted tick | `SqliteCheckpointer`, `CheckpointConfig`/`DurabilityMode` |
-| injected behavior (profile = runtime) | the `dyn`-runtime node pattern from `orchestration/graph/build.rs` |
-| stub-driven mechanics tests | `graph::testkit` |
-| per-node timing / run snapshots | `graph::stream`, `graph::status` |
-| bounded loops (none today, future kinds may loop) | `max_supersteps` backstop |
-
-## 6.2 Candidate upstream changes (each = one small PR to `tinyhumansai/tinyagents`)
-
-Confirm each gap against the vendored source before writing code; drop any
-that turn out to already exist. Ordered by how much openhuman scaffolding
-they delete:
-
-1. **Wall-clock graph deadline.** Today `TICK_TIMEOUT` wraps the whole run in
- `tokio::time::timeout` from the outside, which cannot leave a clean
- checkpoint. Add an optional per-run deadline to `GraphExecution` (abort
- between supersteps + best-effort in-flight cancellation, surfaced as a
- typed `GraphTimeout` error with the last checkpoint intact). Benefits the
- orchestration wake graph too.
-2. **External cancellation/supersede token.** The generation-counter
- supersede (`tick_generation`) currently only takes effect at the *end* of
- a tick (result discarded after the LLM spend). A shared cancel flag
- checked between supersteps — the graph twin of the REPL's `ReplCancelFlag`
- from the rlm-workflows plan — lets a newer tick abort an in-flight one
- before its reflect call completes. If the REPL flag work landed, reuse its
- primitive rather than adding a second one.
-3. **Checkpoint GC / retention.** Ticks are frequent (every N minutes,
- forever), so `graph_checkpoints.db` grows unboundedly. Add a retention
- policy to `SqliteCheckpointer` (keep last K threads / prune completed
- threads older than T). The wake graph has the same latent issue.
-4. **(Stretch) periodic-trigger helper.** A `graph::orchestration`-level
- "run this compiled graph every interval with jitter + overlap policy"
- would absorb our heartbeat fan-out (phase 4.3). Only worth it if the
- upstream maintainers want it — the openhuman heartbeat already works, so
- this is explicitly optional and last.
-
-Items 1–3 are independent; none blocks phases 1–5. Phase 1 ships with the
-outer `tokio::time::timeout` + end-of-tick supersede exactly as today, and
-swaps to the upstream primitives when the submodule bump lands — each swap is
-a small follow-up PR that deletes code.
-
-## 6.3 Sequencing with the vendor submodule
-
-1. Branch in `vendor/tinyagents` (e.g. `feat/graph-run-deadline`), implement
- with unit tests in the tinyagents style (`types.rs`/`mod.rs`/`test.rs`),
- PR against `tinyhumansai/tinyagents`.
-2. Meanwhile openhuman phases 1–5 proceed against the current pin.
-3. After the upstream merge: one openhuman PR per adopted primitive — bump
- the submodule pointer, replace the scaffolding (external timeout →
- deadline; end-of-tick supersede → cancel flag; add GC config), keep the
- behavior tests green.
-4. Never point the openhuman submodule at an unmerged tinyagents branch on
- `main`-bound PRs.
-
-## 6.4 Confirmation findings (checked against the current vendored pin)
-
-Each candidate from §6.2 was checked against `vendor/tinyagents/src/graph/`:
-
-| # | Candidate | Status against the current pin |
-| --- | --- | --- |
-| 1 | Wall-clock graph deadline | **Gap confirmed.** Only a *per-node* timeout exists (`ExecutorConfig::node_timeout` → `TinyAgentsError::Timeout` in `compiled/executor.rs`) and `total_timeout`/`item_timeout` on `parallel`. There is no whole-run deadline on `run_with_thread`. Still a valid upstream PR. Openhuman keeps the outer `tokio::time::timeout(TICK_TIMEOUT, …)` for now. |
-| 2 | External cancel/supersede token | **Gap confirmed (primitive exists, not wired).** `harness::cancel::CancellationToken` exists and is honoured by `parallel` (`with_cancellation`), but the main `CompiledGraph` superstep loop (`compiled/executor.rs`) does not check it between supersteps. Upstream work is "thread the existing token into the graph executor", not a new primitive. Openhuman keeps the end-of-tick + `commit`-node generation check for now. |
-| 3 | Checkpoint GC / retention | **Already exists — adopted now.** `Checkpointer` already exposes `prune(thread_id, keep_last)` and `delete_thread(thread_id)` (default trait methods + sqlite/file impls, `checkpoint/mod.rs`). No upstream PR needed. `SubconsciousInstance::run_graph` now calls `delete_thread` on the tick's unique thread after the run returns, so `graph_checkpoints.db` stays bounded (test: `completed_ticks_leave_no_checkpoint_threads`). |
-
-Net: candidate #3 is done in-tree using an existing primitive; candidates #1
-and #2 remain genuine, independent follow-up PRs against
-`tinyhumansai/tinyagents` and do **not** block this plan — phase 1 already ships
-the outer timeout + end-of-tick supersede they would later replace.
diff --git a/docs/plans/subconscious-factory/phase-7-ui.md b/docs/plans/subconscious-factory/phase-7-ui.md
deleted file mode 100644
index 5113001c00..0000000000
--- a/docs/plans/subconscious-factory/phase-7-ui.md
+++ /dev/null
@@ -1,95 +0,0 @@
-# Phase 7 — UI: see and interact with both subconscious kinds
-
-Goal: the two instances become visible, distinguishable, and individually
-triggerable in the app — in the **Subconscious tab** (both kinds' health and
-controls) and in the **TinyPlace Orchestration tab** (the tinyplace kind in
-its natural habitat, next to the steering it produces). Depends on the
-phase-4 RPC additions (`instances[]` on status, `kind` on trigger); pure
-`app/src` work otherwise. Existing building blocks are reused — notably the
-orchestration tab already renders the pinned Subconscious chat window
-(`chat.kind === 'subconscious'` in `TinyPlaceOrchestrationTab.tsx`), which is
-where directives stream in today via `useOrchestrationChats`.
-
-## 7.1 Types + clients (`app/src/utils/tauriCommands/subconscious.ts`)
-
-- Extend `SubconsciousStatus` with the additive phase-4 fields:
- `instances: SubconsciousInstanceStatus[]`, where each row is today's status
- shape plus `instance: 'memory' | 'tinyplace'`. Legacy top-level fields keep
- mirroring the memory instance, so nothing breaks while the UI migrates.
-- `subconsciousTrigger(kind?: 'memory' | 'tinyplace' | 'all')` — optional
- param passed through to `openhuman.subconscious_trigger`; no-arg call keeps
- today's behavior (memory).
-- All calls stay on `callCoreRpc` / `core_rpc_relay` per the frontend rules.
-
-## 7.2 Hook (`app/src/hooks/useSubconscious.ts`)
-
-- Surface `instances` alongside the existing fields; add
- `triggerTick(kind?)` and per-kind `triggering` state (two buttons must not
- share one spinner).
-- Keep polling/refresh cadence as-is; one status call still feeds everything.
-
-## 7.3 Subconscious tab (`IntelligenceSubconsciousTab.tsx`)
-
-Rework the status area from "one engine" to **two instance cards** under the
-existing mode/interval controls (which continue to govern the memory
-instance — mode semantics don't apply to tinyplace):
-
-- **Memory card** ("Your world" / connected sources): today's status row —
- total ticks, last tick, consecutive failures, provider-unavailable banner
- with the Settings deep-link — plus its own *Run now*.
-- **TinyPlace card** ("Orchestration steering"): enabled state (mirrors
- `orchestration.enabled`; show a disabled-with-hint state when off), last
- review tick, failures/halt reason, *Run review now*
- (`triggerTick('tinyplace')`), and a "View directives →" link that navigates
- to the TinyPlace Orchestration tab with the Subconscious window selected.
-- Shared `SubconsciousInstanceCard` component
- (`app/src/components/intelligence/SubconsciousInstanceCard.tsx`) so a third
- kind later is a data change, not new JSX.
-
-## 7.4 TinyPlace Orchestration tab (`TinyPlaceOrchestrationTab.tsx`)
-
-The pinned Subconscious chat window already shows emitted directives (built
-in an earlier slice — reuse, don't rebuild). Add the *instance* dimension on
-top of it:
-
-- A compact **steering status header** above that window's transcript:
- current directive (or "no active directive"), `expires_after_cycles`
- countdown against the live cycle counter, last review time, and a
- *Run review now* button — same `triggerTick('tinyplace')` path as 7.3.
- Data comes from the phase-4 status row plus a small read RPC if needed
- (`orchestration.status` already exists as the stage-7 read surface; extend
- it with `current_directive` rather than inventing a new method).
-- Badge the window in the chat list ("Subconscious · steering") so the two
- meanings of "subconscious" in the product read as one system: the tab shows
- the tinyplace instance *output*, the Subconscious tab shows both instances'
- *health*.
-- Cross-link back: the header links to the Subconscious tab for controls.
-
-## 7.5 i18n
-
-New keys (instance card titles/descriptions, run-review, steering header,
-badge) go into `en.ts` **and real translations in all locale files**
-(`ar bn de es fr hi id it ko pl pt ru zh-CN`). Gate: `pnpm i18n:check` +
-`pnpm i18n:english:check`.
-
-## 7.6 Tests
-
-- Vitest, co-located:
- - `subconscious.ts` client: trigger passes `kind`; status parses
- `instances` and tolerates its absence (older core during rollout).
- - `useSubconscious`: per-kind triggering state; instances plumbed through.
- - `IntelligenceSubconsciousTab`: renders two cards from a stubbed status;
- tinyplace card disabled state when orchestration is off; per-card Run now
- dispatches the right kind.
- - `TinyPlaceOrchestrationTab`: steering header renders directive/empty
- states; run-review calls trigger with `tinyplace`.
-- E2E (desktop spec, mock backend): Subconscious tab shows both cards;
- triggering the tinyplace review surfaces a directive message in the
- orchestration Subconscious window (mock `__admin/behavior` scripted).
-
-## 7.7 Slicing
-
-Two commits minimum: (a) types/client/hook + Subconscious tab cards,
-(b) orchestration tab steering header + cross-links. i18n rides with each.
-This phase can start as soon as phase 4's RPC shape is merged; it does not
-depend on phases 5–6.
diff --git a/docs/plans/tinychannels-integration.md b/docs/plans/tinychannels-integration.md
deleted file mode 100644
index 9150f2af86..0000000000
--- a/docs/plans/tinychannels-integration.md
+++ /dev/null
@@ -1,215 +0,0 @@
-# TinyChannels Integration Plan
-
-Plan for adopting the `tinychannels` crate
-(`~/work/tinyhumansai/tinychannels`) as the typed channel layer, deleting the
-duplicated copies in this repo, and fixing the channel bugs surfaced by the
-2026-07-04 cross-repo audit.
-
-Companion docs in the tinychannels repo:
-
-- `docs/spec/openclaw-hermes-channel-porting.md` — the upstream research spec.
-- `docs/spec/tinychannels-execution-plan.md` — the crate-side phased plan.
- Steps below reference its phases.
-
-## Current State
-
-- This repo now depends on `tinychannels` through the TinyChannels
- `feat/phase-0-hygiene` branch while the companion PR lands. The first
- duplicate-removal pass has landed:
-
- | openhuman-4 file | tinychannels file |
- | --- | --- |
- | `src/openhuman/channels/traits.rs` | re-exports `src/traits.rs` |
- | `src/openhuman/channels/controllers/definitions.rs` | re-exports `src/controllers/definitions.rs` |
- | `src/openhuman/channels/controllers/schemas.rs` schema declarations | converts from `src/controllers/schemas.rs` |
- | `src/openhuman/channels/controllers/ops/connect.rs` allowlist/key helpers | calls `src/controllers/credentials.rs` |
- | `src/openhuman/channels/controllers/ops/types.rs` | re-exports `src/controllers/types.rs` |
- | `src/openhuman/config/schema/channels.rs` | re-exports provider config from `src/config.rs`, while keeping OpenHuman-owned security/sandbox config local |
- | `src/openhuman/channels/context.rs` key/constants helpers | calls/re-exports `src/context.rs` where type-compatible |
- | `src/openhuman/channels/runtime/supervision.rs` in-flight sizing | re-exports `src/runtime.rs::compute_max_in_flight_messages` |
- | Telegram/Discord text splitting | calls `src/text.rs` chunker with UTF-16 measurement |
-
-- `OpenHumanChannelBackend` now lives in
- `src/openhuman/channels/controllers/backend.rs` and implements
- `tinychannels::ChannelBackend` by delegating to the existing
- `channels/controllers/ops/{connect,messaging,discord,telegram}.rs` flows.
-- The crate-side Phase 5 relay contract now includes typed gateway/connector
- relay frames, the request/response frame transport loop, a feature-gated
- WebSocket dialer with reconnect supervision, and a portable relay runtime
- config shape under `channels_config.relay`. OpenHuman now enables the
- crate's relay WebSocket feature and starts the relay runtime for complete
- relay config.
-- The metadata controllers (`channels.list` / `channels.describe`) now use
- `ChannelManager` for definition lookup. The `channels.status` and
- `channels.test` controllers now route through
- `ChannelManager<OpenHumanChannelBackend>`, preserving the existing no-log
- JSON response shapes while using the crate manager for definition lookup and
- credential validation where applicable. `channels.get_default` also routes
- through the manager while preserving the public `{ active_channel }` response,
- `channels.connect` and `channels.set_default` preserve their public log/value
- envelopes after manager dispatch, and the managed Telegram/Discord link
- controllers route through the manager while preserving their no-log typed
- responses. The no-log send/reaction/thread controllers now dispatch through
- the manager and unwrap the backend `raw` payload to preserve legacy top-level
- JSON shapes; `channels.send_message`, direct channel-bus backend sends, and
- legacy runtime/proactive/provider-helper `Channel::send` callers now cross
- the crate intent bridge as `ChannelOutboundIntent`s and get deterministic
- idempotency keys before legacy backend/provider calls.
- `channels.disconnect` also routes through the manager while preserving the old
- log string and extra fields such as
- `memory_chunks_deleted`. Discord guild/channel/permission discovery dispatches
- through the manager while restoring the old log strings and top-level provider
- JSON. Outbound sends now use the live relay transport for configured relay
- identities. The remaining OpenHuman work is still full session identity
- switchover, provider extraction, and the planned test split below; the first
- envelope slice is landed because the runtime now publishes a TinyChannels
- `ChannelInboundEnvelope` on `ChannelMessageReceived` events, memory
- conversation persistence records the TinyChannels session key as migration
- metadata, and startup now has a relay inbound handler that preserves the
- original authenticated relay envelope, including `scope_id`, from the live
- relay socket through dispatch.
-
-## Step 1 — Add the dependency, delete duplicates
-
-- **Landed:** Add the `tinychannels` git dependency to `Cargo.toml` (single
- crate, not a workspace; edition 2021 depending on an edition-2024 crate is
- fine).
-- **Landed for the first slice:** Delete the duplicated
- definitions/types/traits/config-schema/helper code and
- re-export from the old paths so the 100+ call sites keep compiling:
- - `src/openhuman/channels/mod.rs`: `pub use tinychannels::{Channel,
- ChannelMessage, SendMessage, ...};`
- - `src/openhuman/channels/controllers/...`: re-export `ChannelDefinition`,
- `ChannelAuthMode`, response types.
- - `src/openhuman/config/schema/channels.rs`: re-export `ChannelsConfig` and
- provider config structs. Note tinychannels inlined `EmailConfig` and
- `YuanbaoConfig`, which this repo currently sources from
- `channels::email_channel` / `providers::yuanbao` — repoint those two to
- the crate and delete the local definitions.
-- Still pending: delete migrated in-module tests once each suite is fully
- represented in tinychannels. The duplicate definitions, config-schema, and
- in-flight sizing helper suites have been deleted; keep everything provider-
- or app-specific (see Step 4).
-- Do not remove sandbox/security config from this repo based on the crate's
- copy: the crate is dropping its unwired `SecurityConfig`/`SandboxConfig`
- cluster as scope creep; this repo's originals (if used) stay where they are.
-
-## Step 2 — Implement `ChannelBackend`
-
-- **Landed:** New `OpenHumanChannelBackend` in
- `src/openhuman/channels/controllers/backend.rs`, delegating each trait
- method to the existing ops functions:
- - `send_message` → `messaging.rs::channel_send_message` (already composes
- `effective_backend_api_url` + `jwt::get_session_token` +
- `BackendOAuthClient`), with `send_message_value` preserving OpenHuman's
- arbitrary rich-message JSON for the public RPC controller.
- - `connect_channel` / `disconnect_channel` → `connect.rs` flows plus
- `credentials::ops::{store,remove}_provider_credentials` (keyed
- `"channel:<slug>"`), with disconnect returning the raw legacy payload for
- fields such as `memory_chunks_deleted`.
- - `channel_status` / `test_channel` → existing status/test ops plus
- `health::snapshot`.
- - Telegram login and Discord link/guild/permission methods → the existing
- `telegram.rs` / `discord.rs` ops.
-- **Landed:** The current `channels.*` controller entry points dispatch through
- `ChannelManager<OpenHumanChannelBackend>` where they cross this crate seam,
- while preserving the legacy public JSON/log envelopes.
-- The event bus, health bus, and dispatch engine stay app-side and *drive*
- tinychannels. Never add a tinychannels → openhuman dependency; the
- `runtime/` dispatch engine and the `web` provider are consumers of the
- crate, not porting candidates (they import ~45 openhuman modules).
-
-## Step 3 — Bug fixes coordinated with the crate
-
-Fix these here in lockstep with tinychannels Phase 1/2 (same semantics, one
-implementation — prefer calling the crate's new helpers over patching local
-copies):
-
-1. **Landed: UTF-16 chunking.** Telegram and Discord splitting now call the
- crate's Phase 2 chunker with UTF-16 code-unit measurement and markdown fence
- preservation.
-2. **Landed for existing helper semantics: Telegram history keys.**
- `channels/context.rs` now delegates to the crate helper, preserving
- OpenHuman's current Telegram topic behavior. Runtime received-message events
- now also carry the crate's normalized inbound envelope, with Telegram
- `thread_ts` projected as `topic_id`; conversation persistence records the
- TinyChannels session key when an event carries an envelope. Relay inbound now
- preserves the relay-supplied envelope and `scope_id` through dispatch. Full
- non-relay session identity switchover still needs provider-sourced
- `scope_id`.
-3. **Partially landed for relay inbound; non-relay providers still deferred:
- workspace/tenant discriminator.** Session keys
- (`channels/bus.rs:1005-1042`) omit guild/team/tenant; Slack channel ids are
- only workspace-unique. Relay inbound carries the relay envelope's `scope_id`
- through received-message events; provider-originated legacy messages still
- need native envelope construction with provider-sourced scope. Deferral
- reason: adding scope to the current legacy string keys would change
- conversation identity without the envelope migration that can preserve
- compatibility aliases.
-4. **Landed for portable send boundaries; provider wire enforcement remains
- platform-specific.**
- No idempotency key exists on legacy sends; a retry after a transport error
- double-posts. `channels.send_message` now routes through a crate
- `ChannelOutboundIntent` at the `ChannelBackend` seam while preserving the
- legacy public RPC response and backend JSON shape. The direct channel bus
- backend sends and runtime/proactive/provider-helper `Channel::send` paths use
- the same crate bridge, carrying deterministic idempotency keys through
- `SendMessage`. Provider-specific use of those keys on external wire APIs
- remains Phase 6/platform work.
-5. **Deferred pending product decision: `conversation_memory_key` intent
- check.** It keys on `msg.id`
- (per-message, not per-conversation) and this repo's tests assert that
- behavior (`tests/memory.rs`). Confirm whether per-turn keying is intended;
- the crate will rename or fix accordingly — this repo should follow.
-
-## Step 4 — Test split
-
-- **Partly landed:** the portable `controllers/schemas_tests.rs` schema-catalog
- assertions, pure allowlist/key helper tests, catalog/request-shape halves of
- `controllers/ops_tests.rs`, backend-agnostic default-channel validation, and
- config-backed channel status detection now live in tinychannels. The
- duplicate definitions suite, config-schema assertions, in-flight sizing
- helper assertions, and portable schema-catalog assertions were deleted here.
- This repo keeps handler parity, adapter conversion, params, legacy envelope
- helper tests, local security/sandbox config defaults, supervisor
- classification tests, and app-side persistence/REST wiring tests.
-- **Still migrate to tinychannels:** any remaining backend-agnostic assertions
- from `controllers/ops_tests.rs`, rewritten against a mock `ChannelBackend`,
- plus the already-mirrored suites listed in Step 1.
-- **Stay here:** all `providers/*_tests.rs` (telegram 148, web 93, imessage
- 58, discord 55+23, email 50, lark 42, whatsapp 41+29, irc 37, mattermost
- 33, signal 32, presentation 29, linq 23, qq 11), `bus_tests.rs`,
- `routes_tests.rs`, `runtime/dispatch_tests.rs`, `runtime/startup_tests.rs`,
- and the harness-driven `tests/` integration files (prompt, telegram/discord
- integration, runtime tool calls, health, identity).
-- The REST-wiring halves of `ops_tests.rs` become the test bed for
- `OpenHumanChannelBackend` (Step 2).
-
-## Step 5 — Provider extraction ladder (later, tracks crate Phase 6)
-
-Move provider wire code into tinychannels only when its dependencies reduce to
-crate traits:
-
-1. **Now portable (no cross-module imports):** email, irc, yuanbao, cli,
- imessage, mattermost, qq, dingtalk, presentation.
-2. **After a configured-HTTP-client trait** (replaces
- `config::build_runtime_proxy_client` / `apply_runtime_proxy_to_builder`):
- discord, slack, whatsapp, lark, signal.
-3. **After approval, voice/STT, pairing, and conversation-memory traits:**
- telegram (imports `approval`, `voice::create_stt_provider`,
- `memory_conversations`, `security::pairing`).
-4. **Never:** `web` provider and `runtime/` dispatch — they are the harness
- front-end and orchestrator that consume the crate.
-
-## Sequencing and risk notes
-
-- Land Step 1 and Step 2 together in one PR if possible: adding the dep while
- keeping duplicates invites split-brain imports (some call sites on the
- crate types, some on the local copies — Rust will treat them as different
- types).
-- Session-key changes (Step 3, items 2–3) change conversation identity. Ship
- them behind the crate's legacy-key canonicalization with a migration test
- that maps a sample of existing keys to new keys losslessly.
-- Positive invariants to preserve (verified in the audit): no secrets are
- logged in the channels tree, and no blocking calls exist in async provider
- paths. Any moved code must keep both properties.
diff --git a/docs/plans/tinyflows-integration/README.md b/docs/plans/tinyflows-integration/README.md
deleted file mode 100644
index f7ad22aa52..0000000000
--- a/docs/plans/tinyflows-integration/README.md
+++ /dev/null
@@ -1,304 +0,0 @@
-# tinyflows — Completion & Integration Plan (POA)
-
-> **Status**: proposed · **Date**: 2026-07-04
-> **Scope**: finish integrating the vendored `vendor/tinyflows/` workflow engine (our n8n/Zapier module) into the Rust core and the desktop UI, and close the feature gaps that separate it from a real n8n-class product.
-> **Reference product**: [n8n](https://github.com/n8n-io/n8n) — item-based data flow, `=`-expressions, node catalog, editable canvas, credentials, webhook/schedule triggers, executions view.
-
----
-
-## 1. Where we are today
-
-The integration is **not greenfield**. Three layers already exist; each is at a different maturity level.
-
-### 1.1 Engine (`vendor/tinyflows/`, v0.3.0 — mostly done)
-
-Host-agnostic library crate on the `tinyagents` state-graph runtime. Pipeline: `WorkflowGraph → migrate → validate → compile → engine::run`.
-
-| Area | State |
-| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Node kinds (12) | ✅ `trigger, agent, tool_call, http_request, code, condition, switch, merge, split_out, transform, output_parser, sub_workflow` |
-| Routing | ✅ linear, conditional (ports), parallel fan-out, merge fan-in barrier |
-| Data flow | ✅ n8n-style item arrays `{ json, binary?, paired_item? }`; `=`-expressions with **full jq** (`jaq-core`) already wired in `src/expr.rs` |
-| Error handling | ✅ per-node `on_error` (stop/continue/route), retry with fixed/exponential backoff, `node_timeout_secs` |
-| HITL | ✅ `requires_approval` → interrupt; in-process (`run_resumable`) and cross-process durable resume (`resume_with_checkpointer(thread_id)`) |
-| Observability | ✅ `RunObserver` trait (`on_run_start/on_step_finish/on_run_finish`), tracing spans, journaled variants (`GraphEventJournal`) for Langfuse |
-| Persistence | By design **none** — host injects `Checkpointer`, `StateStore`, and persists `Run`/`ExecutionStep` |
-| Capabilities | ✅ host-injected traits: `LlmProvider`, `ToolInvoker`, `HttpClient`, `CodeRunner`, `StateStore`; opaque `connection_ref` (host resolves secrets) |
-| Versioning | ✅ `schema_version` (graph) + per-node `type_version`, `migrate()` pre-parse |
-| Triggers | ⚠️ **declarative only** — `manual, schedule, webhook, app_event, form, execute_by_workflow, chat_message, evaluation, system`; the _host_ must fire them |
-
-Engine-side gaps (see Phase 7): `agent` node sub-ports (chat_model/memory/tool/output_parser) stubbed; `output_parser` is identity passthrough; README/Roadmap lag the code (claim jq and retry backoff are pending when both ship).
-
-### 1.2 Rust core seam (`src/openhuman/flows/` + `src/openhuman/flows/tinyflows/` — implemented, with holes)
-
-- **Domain** `flows::` (~3,700 lines + tests): `types.rs` (`Flow` wraps `WorkflowGraph` + `enabled`/`require_approval`/`last_status`; `FlowRun`, `FlowRunStep`, `FlowRunTrigger::{Rpc,Schedule,AppEvent,Resume}`), `store.rs` (SQLite incl. `flow_state` kv), `ops.rs` (validate/migrate + full run/resume under `TrustedAutomation → Workflow` origin, 600 s timeout), `schemas.rs`, `tools.rs` (`ProposeWorkflowTool` — validate-only, never persists), `bus.rs` (`FlowTriggerSubscriber`).
-- **RPC surface** (10 methods, wired in `src/core/all.rs`): `openhuman.flows_{create,get,list,update,delete,set_enabled,run,resume,list_runs,get_run}`.
-- **Capability seam** `src/openhuman/flows/tinyflows/`: `caps.rs` (LLM/Composio-tools/HTTP/code/state adapters), `observability.rs` (currently `NoopObserver`), `langfuse_export.rs` (post-run trace export).
-- **Schedule triggers work end-to-end**: `flows::ops::bind_schedule_trigger` registers a cron `JobType::Flow` → scheduler publishes `DomainEvent::FlowScheduleTick` → `FlowTriggerSubscriber` runs the flow.
-- **Composio `app_event` triggers also work end-to-end**: `flows/bus.rs::handle_app_event` matches `DomainEvent::ComposioTriggerReceived { toolkit, trigger }` against enabled `app_event` flows (case-insensitive toolkit/slug match, per-flow concurrency guard) and runs them under `FlowRunTrigger::AppEvent`. Since Composio triggers are delivered by the platform, this **is** our webhook story for third-party apps — no tunnel needed.
-
-**Known core gaps** (each becomes a workstream below):
-
-| # | Gap | Evidence |
-| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
-| G1 | **Raw `webhook` triggers unwired** (mitigated: Composio `app_event` triggers already cover third-party apps) — enabling a webhook-trigger flow only logs a warning; `bus.rs` observes `WebhookIncomingRequest` but explicitly does not dispatch; Composio trigger *subscriptions* are not auto-provisioned on enable | `flows/ops.rs:298` (`log_webhook_trigger_deferred`), `flows/bus.rs:232-242` |
-| G2 | **No live run observer** — `NoopObserver`; `FlowRunStep`s reconstructed post-hoc from final state, no per-step timing/attempts, nothing streamed while running | `flows/types.rs:76`, `flows/ops.rs:781-783` (`TODO(0.3)`) |
-| G3 | **Credential / connected-account resolution stubbed** — Composio nodes fall back to the ambient signed-in account; toolkit allow-listing hard-rejects real toolkits; HTTP credential resolution unimplemented (`connection_ref` is accepted but unresolvable) | `tinyflows/caps.rs:193,235-261,330,376,408` |
-| G4 | **No cancel/deny** — a dismissed approval leaves the run parked `pending_approval` forever; no `flows_cancel`/`flows_deny` RPC | UI comment in `FlowApprovalCard.tsx` |
-| G5 | **No JSON-RPC E2E coverage** — zero `openhuman.flows_*` calls in `tests/json_rpc_e2e.rs` (unit tests only) | grep of `tests/*.rs` |
-| G6 | Unfired trigger kinds: `chat_message`, `form`, `execute_by_workflow` (as a _trigger_), `evaluation`, `system` have no host dispatcher | `flows/bus.rs` |
-
-### 1.3 Frontend (`app/src/` — reachable, read-only)
-
-Shipped: `/flows` nav tab (FlowsPage list: enable toggle, Run, last status), `/flows/:id` **read-only** canvas (`@xyflow/react` v12, custom nodes, minimap), `FlowRunsDrawer` + `FlowRunInspectorDrawer` (2 s polling via `useFlowRunPoller`), chat `WorkflowProposalCard` (agent `propose_workflow` → user "Save & enable" is the **only** creation path), `FlowApprovalCard` HITL notifications. All components have co-located Vitest coverage; i18n namespaces `flows.*`/`flowRuns.*`/`notifications.flow.*` exist across locales.
-
-**Known UI gaps**:
-
-| # | Gap | Evidence |
-| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------- |
-| U1 | **No canvas editing** — `nodesDraggable/Connectable/elementsSelectable: false`; `xyflowToWorkflowGraph` in `graphAdapter.ts` is dead code awaiting the editor ("B5b.2+") | `components/flows/canvas/FlowCanvas.tsx` |
-| U2 | **No node config panel** — clicking a node does nothing; `config` shown only as truncated hint chips | — |
-| U3 | **No authoring entry** — "New workflow" navigates to `/chat` with a TODO; empty-state copy promises canvas creation that doesn't exist | `pages/FlowsPage.tsx` |
-| U4 | No trigger-config UI, no credentials picker, no template gallery, no import/export | — |
-| U5 | Approval "Dismiss" is client-only (blocked on G4) | `FlowApprovalCard.tsx` |
-| U6 | Run progress is poll-only; no socket push (blocked on G2) | `hooks/useFlowRunPoller.ts` |
-
-### 1.4 Disambiguation (do not conflate)
-
-The repo has **three** "workflow" systems. This plan touches only the first:
-
-1. `flows::` / `openhuman.flows_*` — **tinyflows typed graphs** (this plan).
-2. `workflows::` / `openhuman.workflows_*` — WORKFLOW.md/SKILL.md bundle discovery/install (separate product surface under `/skills`). **Slated for decommission** — it is essentially the skills feature wearing the "workflows" name; see Phase 8. Retiring it frees the "Workflows" branding for tinyflows (the `/flows` nav tab already reads "Workflows").
-3. `rhai::` — Rhai `.ragsh` language workflows (`docs/plans/rlm-workflows/`), positioned in `gitbooks/features/orchestration.md` as the _next_ layer on the same substrate. tinyflows remains the shipping visual/typed product; Rhai workflows do not replace it.
-
----
-
-## 2. Gap analysis vs n8n / Zapier
-
-What an n8n user would expect, mapped to our state:
-
-| n8n capability | tinyflows/OpenHuman today | Covered by |
-| ----------------------------------------------------- | ---------------------------------------------------------------------------- | ----------------- |
-| Editable node canvas (drag, connect, add/delete) | Read-only viewer | Phase 3 |
-| Node config side-panel with schema-driven forms | Missing | Phase 3 |
-| Webhook trigger with live URL | Declared but never fired | Phase 1 |
-| Cron/interval trigger | ✅ shipped | — |
-| App-event trigger (≈ Zapier polling/instant triggers) | Wired via Composio `ComposioTriggerReceived`, but account resolution stubbed | Phase 1 (G3) |
-| Credentials store + per-node credential picker | `connection_ref` plumbing exists; resolution unimplemented; no UI | Phase 2 |
-| Executions list + live run view | List + inspector exist; polling, post-hoc steps only | Phase 1–2 |
-| Cancel a running/paused execution | Missing | Phase 1 |
-| Expressions (`={{ }}` in n8n) | ✅ `=`-prefix + full jq | — |
-| Error workflow / retry per node | ✅ on_error/retry/backoff | — |
-| Sub-workflows | ✅ `sub_workflow` node (inline graph); _by-id_ reference missing | Phase 4 |
-| Templates gallery | Missing | Phase 4 |
-| Import/export workflow JSON, n8n import | Missing (feasible: model is deliberately n8n-shaped) | Phase 4 |
-| Partial execution / pin data / step-through debug | Missing | Phase 5 (stretch) |
-| Waiting/Wait node, human approval | ✅ HITL approval + durable resume | — |
-| AI Agent node with attached tools/memory | `agent` node = bare LLM call; sub-ports stubbed | Phase 6 |
-| Versioning of workflow definitions | ✅ schema_version + type_version + migrate | — |
-| Multi-user sharing/RBAC | Out of scope (desktop, single-user + team domain later) | — |
-
-Our structural advantages to preserve: the agent can _author_ workflows conversationally (`propose_workflow` → proposal card → single human "Save & enable" persistence gate), everything runs under the security policy/approval-gate substrate, and secrets never enter the engine (opaque `connection_ref`).
-
----
-
-## 3. Plan of action
-
-Ordering rationale: **backend correctness first** (triggers, cancellation, live observation, credentials) because every UI phase consumes those RPCs; the editable canvas is the largest UI lift and is independent of trigger work, so it proceeds in parallel from Phase 3.
-
-### Phase 0 — Substrate hygiene: tinyagents pin & tags
-
-Every workflow is, at run time, a **unique tinyagents state graph**: `compile()` wraps the `WorkflowGraph`, and the engine lowers it per run into a tinyagents graph (nodes → graph nodes, output ports → conditional edges, fan-in → waiting edges); run state (`MergeReducer` over a single JSON value), durable checkpointing, HITL interrupts, and the event journal are all tinyagents primitives, keyed per run by `thread_id`/`run_id`. So the health of the tinyagents pin is the health of the whole feature.
-
-Audit (2026-07-04):
-
-- ✅ **Single unified copy** — both Cargo worlds (`Cargo.toml:355`, `app/src-tauri/Cargo.toml:214`) patch `tinyagents` to `vendor/tinyagents`; exactly one `tinyagents 1.5.0` in both lockfiles. tinyflows' `tinyagents = "1.2"` requirement unifies onto the same copy (semver-compatible). No duplication, no type-identity risk.
-- ⚠️ **Not on a tag** — the submodule is pinned at `df391c4` = `v1.5.0-13-gdf391c4`: 13 untagged commits past v1.5.0 (REPL host-embedding / cancel work taken early for the Rhai workflow feature). The crate still self-reports `1.5.0`, so the version string understates the vendored code.
-- ⚠️ **Two minor versions behind** — upstream is at **v1.7.1** (60 commits past v1.5.0). The 13 early-adopted commits all landed upstream (via PR #19 etc.; `ReplSession::set_cancel_flag` verified present in v1.7.1), so retagging loses nothing.
-- ⚠️ Same pattern on tinyflows itself: submodule at `v0.3.0-1-g438f8fc` (one commit past tag).
-
-Work items:
-
-1. Bump `vendor/tinyagents` submodule to the **v1.7.1 tag**; bump root requirement `tinyagents = { version = "1.7", features = ["sqlite", "repl"] }` (verify both features still exist in 1.7); `cargo update -p tinyagents` in both lockfiles.
-2. Review the v1.5→v1.7 changelog for API breaks in the seams we touch: `Checkpointer`/`DurabilityMode`, `GraphEventJournal`/`GraphObservation`, interrupt/resume semantics (used by `flows::ops` + `src/openhuman/agent/tinyagents/` + Rhai workflows).
-3. Retag `vendor/tinyflows` on a proper release (v0.3.1) whose `Cargo.toml` requires `tinyagents = "1.7"` so the version story is coherent end-to-end.
-4. Gate with `cargo check` both worlds, `pnpm test:rust`, and the flows/Rhai unit suites; adopt a standing rule: **vendored tiny\* submodules pin release tags, never floating commits** (early-adopting an upstream PR requires a pre-release tag).
-
-### Phase 1 — Backend completion (triggers, lifecycle, observability)
-
-**1a. External event triggers — Composio-first (G1).**
-
-Product decision: **Composio triggers are the webhook story.** `app_event` dispatch already works end-to-end (see §1.2) and the platform handles inbound delivery, auth, and NAT traversal — so we do *not* build our own tunnel/webhook infrastructure for third-party app events. Remaining work is lifecycle and coverage, not plumbing:
-
-- **Trigger subscription lifecycle**: enabling an `app_event` flow should ensure the corresponding Composio trigger subscription exists upstream (create on `set_enabled(true)` via the `composio` domain, tear down on disable/delete when no other flow uses it) instead of assuming the user pre-configured it in Composio. Reconcile at boot like `bind_schedule_trigger` does.
-- **Payload hygiene**: trigger payloads are untrusted input — route through `prompt_injection` screening before any `agent` node consumes them (applies to all external-event runs).
-- **Trigger catalog surfacing**: expose the Composio trigger catalog (toolkit → available trigger slugs + payload schemas) over RPC so the UI (Phase 3 trigger config) and the builder agent (Phase 5 `search_tool_catalog`) offer real, connectable events instead of free-text slugs.
-- **Raw `webhook` trigger kind → demoted**: for arbitrary custom HTTP callers not covered by a Composio toolkit, keep the `webhook` kind but defer implementation (generic inbound via `webhooks::ops`/`create_tunnel` stays a backlog item). Until then, validation must **warn loudly** at save/enable time that a `webhook`-trigger flow will not fire, instead of today's silent log line (`flows/ops.rs:298`).
-
-**1b. Run lifecycle: cancel + deny (G4).**
-
-- New RPCs `openhuman.flows_cancel_run(run_id)` (terminal `cancelled` status; abort the tokio task / drop the checkpointed thread) and deny semantics on resume: `flows_resume(id, thread_id, approvals, rejections)` → rejected node routes to its `error` port or fails the run.
-- Sweep: TTL for parked `pending_approval` runs (align with the 10-min approval-gate TTL, configurable per flow).
-
-**1c. Live run observation (G2).**
-
-- Implement a real `RunObserver` in `src/openhuman/flows/tinyflows/observability.rs`: `on_step_finish` → persist `FlowRunStep` incrementally (timing, attempt count, status, output) via `flows::store`, and publish a new `DomainEvent::FlowRunProgress { run_id, node_id, status }`.
-- Bridge to the frontend socket (`socket` domain) so the inspector can subscribe instead of polling (UI lands in Phase 2/3; keep polling as fallback).
-- Wire the journaled run variants so Langfuse export happens per-step, not only post-run.
-
-**1d. Remaining trigger kinds (G6).**
-
-Full taxonomy, the generic event-dispatcher design, and the **cron → workflows migration** live in the companion doc **[triggers.md](triggers.md)**. Summary:
-
-- `form` + one-shot/interval schedule sugar first (cheap wins).
-- A **trigger catalog** (curated allowlist of `DomainEvent`s with stable payload schemas + jq filters) feeding one generic `system`-kind dispatcher in `FlowTriggerSubscriber` — instead of a bespoke handler per event. Guardrails: loop prevention via run provenance depth, per-flow rate limits, payload hygiene/risk classes.
-- `chat_message` from the channels pipeline (untrusted-input guardrails required first).
-- **Cron unification**: legacy `JobType::Shell`/`Agent` cron jobs become one-node scheduled flows (dual-write bridge, then backfill migration); cron remains only as the internal tick engine. "Everything automated is a workflow."
-- Until a kind's dispatcher ships, validation warns loudly at save/enable instead of silently never firing.
-
-**1e. E2E tests (G5).**
-
-- Extend `tests/json_rpc_e2e.rs` (+ `scripts/test-rust-with-mock.sh`): full lifecycle round-trip (create → run → steps → resume → cancel → delete), schedule-tick dispatch, webhook dispatch, approval park/deny. This is the merge gate for 1a–1d.
-
-**Deliverable**: every trigger kind either fires or loudly warns; runs can be cancelled/denied; run steps stream.
-
-### Phase 2 — Credentials & connections (G3)
-
-The `connection_ref` seam exists end-to-end but resolves nothing. This phase makes integration nodes real.
-
-- **Composio connected accounts**: resolve `connection_ref` → specific Composio connected account (today: ambient-account fallback). Fix toolkit allow-listing in `caps.rs:193` so real toolkits pass policy instead of being hard-rejected. Surface account choice in the node config (`connection_ref` = connected-account id).
-- **HTTP credentials**: back `connection_ref` for `http_request` nodes with the existing `credentials` domain (header/bearer/basic templates stored encrypted; injected server-side in `OpenHumanHttp::request` — never returned to the UI or the engine).
-- **RPCs**: `flows_list_connections()` (aggregate Composio connected accounts + stored HTTP credentials, ids + display names only) for the UI picker.
-- **Policy**: `code` and `http_request` node execution must respect the `[autonomy]` tier / `classify_command`-equivalent gating (network class); document the matrix in `flows/ops.rs`.
-
-**Deliverable**: an `http_request` or Composio `tool_call` node can be pointed at a chosen account/credential by reference, with secrets never leaving the core.
-
-### Phase 3 — Editable canvas (U1–U2) — the n8n builder
-
-Largest UI phase; runs in parallel with Phase 2 once Phase 1c's RPCs exist.
-
-- **3a. Edit mode in `FlowCanvas`**: flip the readonly defaults behind an `editable` prop; enable drag (persist `position`), connect (port-aware: derive valid source/target handles from node kind — reuse `graphAdapter` port logic), delete nodes/edges, and a node palette (12 kinds with the existing emoji/accent metadata). Wire the already-written `xyflowToWorkflowGraph` as the save path → `flows_update`.
-- **3b. Node config panel**: right-hand drawer on node select. v1 pragmatic approach: per-kind form components for the high-traffic kinds (`trigger` schedule/webhook config, `http_request` method/url/headers/body, `agent` prompt/model, `tool_call` slug/args, `condition`/`switch` expression, `transform` set-map, `code` editor with language toggle) + a raw-JSON escape hatch for the rest. `=`-expression fields get a monospace input with an "expression" affordance (full expression-editor with live preview is a stretch goal — needs a `flows_eval_expr` RPC against sample run data).
-- **3c. Validation UX**: new RPC `openhuman.flows_validate(graph)` (thin wrapper over `ops::validate_and_migrate_graph`, same path `propose_workflow` uses) → inline canvas errors (missing trigger, cycle, invalid config on node X) before save.
-- **3d. Draft/dirty state**: local draft in component state; explicit Save; unsaved-changes guard. No autosave in v1 (a saved+enabled flow is live — accidental saves fire schedules).
-- **3e. Live run overlay**: subscribe to `FlowRunProgress` socket events; animate node status on the canvas during a run (n8n's signature interaction) and in the inspector.
-
-**Deliverable**: create/edit a workflow entirely on the canvas; watch it execute live.
-
-### Phase 4 — Authoring entry points, templates, interop (U3–U4)
-
-- **4a. "New workflow"**: replace the `/chat` TODO with a chooser — _Start from scratch_ (blank canvas with a trigger node), _Describe it_ (interim: prefill chat composer → `propose_workflow`; superseded by the Phase 5 in-place prompt bar), _From template_.
-- **4b. Sub-workflow by id**: extend `sub_workflow`/`execute_by_workflow` to reference a saved `flow_id` (engine currently only inlines a child graph) — engine change upstreamed to `vendor/tinyflows` + host resolver in `caps`/ops.
-- **4c. Templates**: ship 5–10 curated `WorkflowGraph` JSONs (bundled resources, like agent prompts): e.g. "Daily digest to channel", "Webhook → agent triage → notify", "Scheduled scrape → transform → memory". Gallery UI on FlowsPage empty state.
-- **4d. Import/export**: export flow JSON; import with `migrate()` + validate. **n8n importer** (host-side, best-effort): map n8n workflow JSON → `WorkflowGraph` for the overlapping vocabulary (IF→condition, Switch, Merge, SplitOut, HTTP Request, Code, Schedule/Webhook triggers; `={{...}}` → `=` jq where trivially translatable); unmapped nodes land as annotated placeholder nodes rather than failing the import.
-- **4e. Proposal card upgrade**: "Open in canvas" action on `WorkflowProposalCard` (review/edit before Save & enable) — keeps the single persistence gate.
-
-### Phase 5 — Prompt-first authoring: the Workflow Builder agent
-
-The product stance ("the agent builds it, you approve it") gets a first-class surface: users prompt **from the Workflows UI itself** — not by wandering into `/chat` — and a dedicated, tool-scoped agent designs and iterates on the graph in place. This is the differentiator over n8n, so it deserves its own phase rather than being a bullet under 4a.
-
-**5a. A dedicated `workflow-builder` agent definition.**
-
-The harness already supports exactly this shape: `AgentDefinition` (`src/openhuman/agent/harness/definition.rs`) with `ToolScope::Named`, registered as a builtin in `harness/builtin_definitions.rs` and overridable by user TOML via `definition_loader.rs`.
-
-- New builtin definition `workflow-builder` (Worker tier): system prompt specialized for workflow design — knows the 12 node kinds, `=`/jq expression semantics, port/edge rules, trigger kinds and which ones are live, error-handling config (`on_error`/`retry`), and the "propose, never persist" invariant. Prompt ships in `src/openhuman/agent/prompts/` like the other bundled prompts.
-- `ToolScope::Named` — deliberately narrow toolset (see 5b): no shell, no file writes, no channel sends. `external_effect = false` end-to-end; the only side effects it can cause are validated *proposals*.
-- Reachable two ways: (1) directly from the Flows UI prompt surface (5c), spawned with the flow/draft as context; (2) by delegation from the main agent via the existing delegation tools (`agent/tools/delegate_to_personality.rs`, archetype/skill delegation in `agent_orchestration::tools`) so "set up a workflow that…" in normal chat routes to the specialist automatically.
-
-**5b. The builder's tool belt** (new tools live in `flows/tools.rs` per the tool-ownership rule, registered in `tools/ops.rs`):
-
-| Tool | Status | Purpose |
-| --- | --- | --- |
-| `propose_workflow` | ✅ exists | Validate a full graph + emit proposal payload (unchanged invariant: never persists) |
-| `revise_workflow` | new | Take the current draft graph + an instruction diff → emit an updated proposal; enables iterative refinement instead of regenerate-from-scratch |
-| `list_workflows` / `get_workflow` | new (read-only) | Inspect existing flows so the agent can reference, clone, or avoid duplicating them |
-| `get_workflow_run` | new (read-only) | Read a failed run's steps so the agent can debug/repair a workflow from an error report |
-| `list_flow_connections` | new | Enumerate Composio connected accounts + stored HTTP credentials (ids/names only — Phase 2's RPC surfaced as a tool) so generated nodes carry valid `connection_ref`s |
-| `search_tool_catalog` | new | Search the Composio/tools registry for real tool slugs, so `tool_call` nodes are grounded in tools that actually exist (today the agent can hallucinate slugs) |
-| `dry_run_workflow` | new | Execute the *draft* graph against mock/sandboxed capabilities (`tinyflows` `mock` feature or capped real caps with `requires_approval` forced on) and return step results — lets the agent self-verify before proposing |
-
-All read-only tools return `PermissionLevel::None`; `dry_run_workflow` is gated by autonomy tier since `code`/`http_request` nodes could execute.
-
-**5c. Prompt surface in the Flows UI.**
-
-- **FlowsPage prompt bar**: a "Describe a workflow…" composer at the top of `/flows` (and as the empty-state hero). Submitting spawns a `workflow-builder` turn in a dedicated thread; the resulting proposal renders inline (reuse `WorkflowProposalCard`) with **Open in canvas** and **Save & enable**.
-- **Canvas copilot panel**: on `/flows/:id` (and on drafts), a side panel chat bound to the same agent with the current graph injected as context. Each agent proposal updates a **draft overlay** on the canvas (diff-style: added nodes highlighted, removed ones ghosted) — accept/reject applies it to the local draft from Phase 3d. This is `revise_workflow` in a loop: "add a Slack notification on failure", "make the schedule weekdays only", "split this into a sub-workflow".
-- **Repair entry point**: from a failed run in `FlowRunInspectorDrawer`, "Fix with agent" opens the copilot with the run's failing step context preloaded (`get_workflow_run`).
-- Plumbing reuses the existing chat runtime (`ChatRuntimeProvider` already parses `propose_workflow` outputs into `pendingWorkflowProposalsByThread`); the new work is thread scoping per draft/flow, the canvas diff overlay, and routing turns to the `workflow-builder` definition instead of the main agent.
-
-**5d. Invariants** (carry over from the current design, enforced in review):
-
-- The agent **never persists or enables** a flow — `flows_create`/`flows_update`/`set_enabled` remain UI-only actions behind an explicit user click.
-- Proposals are always re-validated server-side at save time (`flows_validate` path), never trusted from the client.
-- `dry_run_workflow` output is labeled as sandbox output in the UI so users don't mistake it for a live run.
-
-**Deliverable**: a user types "every Monday, summarize my unread Slack messages and email me" into the Flows page, watches the graph appear on the canvas, iterates in plain language, then clicks Save & enable.
-
-### Phase 6 — Polish & debug tooling (stretch)
-
-- Partial execution ("run from this node" with pinned upstream data) — needs engine support for seeding node state; scope with tinyflows maintainers.
-- Run diff/inspector niceties: per-item data browser (n8n's table/JSON toggle), input↔output pairing via `paired_item`.
-- `flows_duplicate`, run retention/pruning policy, per-flow run-history limits.
-- Desktop E2E (WDIO) spec: create → run → inspect happy path.
-
-### Phase 7 — Engine (vendor/tinyflows) upstream work
-
-Tracked separately since it's a submodule with its own release cadence (host pins `0.3`, patched to path):
-
-1. `agent` node sub-ports (chat_model/memory/tool/output_parser wiring) — unlocks n8n-style "AI Agent with tools" composition.
-2. `output_parser`: schema validation + LLM auto-fix (currently identity).
-3. Sub-workflow by reference (4b) — config `workflow_id` alternative to inline `workflow`.
-4. Docs truth-up: README/Roadmap still claim jq and retry backoff are pending; both are implemented (`src/expr.rs` routes to jaq; `engine.rs` has fixed/exponential backoff + `node_timeout_secs`).
-5. Optional: cancellation token support in `engine::run` (cleaner than task-abort for 1b).
-
-### Phase 8 — Decommission the legacy `workflows::` bundle domain
-
-The `workflows::` domain (WORKFLOW.md/SKILL.md bundle discovery/install, RPC `openhuman.workflows_*`) predates tinyflows and is functionally the **skills** feature under a different name. Keeping two things called "workflows" confuses users, agents, and contributors alike. Plan: fold what's unique into `skills`, delete the rest, and hand the name to tinyflows.
-
-- **Audit consumers first**: `agent/tools/run_workflow.rs` (agent tool that runs WORKFLOW.md bundles — decide: retire, or repoint to `flows_run`/skills), the `/skills` UI surfaces (`WorkflowsTab`, `CreateWorkflowForm`, `WorkflowRunnerBody`, `WorkflowNew.tsx`, `WorkflowsRun.tsx`, `DevWorkflowPanel`, `workflowsApi.ts`), `about_app`, gitbooks, and the Rhai workflow plan's references to `run_workflow` as a composition surface.
-- **Migrate**: bundle discovery/install semantics that skills doesn't already cover move into the `skills` domain (it is metadata-only post-QuickJS-removal, so this is mostly file-format and registry work).
-- **Deprecate then delete**: mark `openhuman.workflows_*` deprecated for one release (RPC responses carry a deprecation notice), then remove `src/openhuman/workflows/`, its controllers from `src/core/all.rs`, the frontend clients/pages, and the `/workflows/new`//`workflows/run` routes (bare `/workflows` already redirects to `/settings/automations`).
-- **Not in scope**: `openhuman.workflow_run_*` (`agent_orchestration`'s declarative run ledger) is a different system and untouched here — though its name should also be revisited once "Workflows" ≡ tinyflows.
-- **Naming end-state**: one user-facing concept — **Workflows = tinyflows graphs** at `/flows`; skills are skills.
-
----
-
-## 4. Missing-features summary (checklist)
-
-Substrate: ☐ tinyagents submodule → v1.7.1 tag (+ root req bump, both lockfiles) · ☐ v1.5→v1.7 API-break review · ☐ tinyflows retag (v0.3.1, `tinyagents = "1.7"`) · ☐ tags-only submodule policy.
-
-Backend: ☐ Composio trigger-subscription lifecycle (auto-provision on enable) · ☐ trigger catalog RPC · ☐ loud validation warning for unfired trigger kinds · ☐ raw-webhook dispatch (deferred backlog) · ☐ `flows_cancel_run` · ☐ resume-with-rejection/deny · ☐ live `RunObserver` + incremental step persistence · ☐ `FlowRunProgress` socket events · ☐ `flows_validate` RPC · ☐ `flows_list_connections` · ☐ Composio connected-account resolution · ☐ HTTP credential resolution · ☐ toolkit allow-list fix · ☐ `chat_message` trigger dispatch · ☐ sub-workflow by id · ☐ parked-run TTL sweep · ☐ JSON-RPC E2E suite.
-
-Frontend: ☐ editable canvas (drag/connect/palette/delete) · ☐ node config panels · ☐ trigger config UI (cron builder, webhook URL display, app-event picker) · ☐ credentials picker · ☐ new-workflow chooser · ☐ template gallery · ☐ import/export + n8n import · ☐ live canvas run overlay (socket) · ☐ approval deny (real) · ☐ "Open in canvas" from proposal card · ☐ WDIO E2E spec.
-
-Agent authoring: ☐ `workflow-builder` builtin `AgentDefinition` + specialized prompt · ☐ `revise_workflow` tool · ☐ read-only `list_workflows`/`get_workflow`/`get_workflow_run` tools · ☐ `list_flow_connections` tool · ☐ `search_tool_catalog` tool · ☐ `dry_run_workflow` (sandboxed) · ☐ delegation routing from main agent · ☐ FlowsPage prompt bar · ☐ canvas copilot panel with draft diff overlay · ☐ "Fix with agent" from failed runs.
-
-Engine (upstream): ☐ agent sub-ports · ☐ output_parser validation · ☐ `workflow_id` sub-workflows · ☐ docs truth-up · ☐ cancellation.
-
-Decommission: ☐ `run_workflow` tool disposition · ☐ bundle semantics folded into `skills` · ☐ `workflows_*` RPC deprecation release · ☐ delete `src/openhuman/workflows/` + frontend pages/clients · ☐ docs/about_app rename sweep.
-
----
-
-## 5. Sequencing, estimates, risks
-
-```
-Phase 0 (tinyagents pin) ██ ~2–3 d do first; touches both lockfiles
-Phase 1 (backend) ██████ ~2–3 wk unblocks everything
-Phase 2 (credentials) ████ ~1–2 wk parallel w/ Phase 3
-Phase 3 (canvas) ████████ ~3–4 wk largest UI lift
-Phase 4 (authoring) ████ ~2 wk
-Phase 5 (builder agent) ██████ ~2–3 wk needs Phase 3 canvas + Phase 2 connections
-Phase 6 (polish) ██ opportunistic
-Phase 7 (engine) ── continuous, PR'd to vendor submodule ──
-Phase 8 (decommission) ── independent; audit early, delete after a deprecation release ──
-```
-
-**Risks / decisions to confirm:**
-
-1. **External-event delivery model** — decided: Composio triggers are the webhook story (platform handles delivery/auth/NAT). Raw custom webhooks (own tunnel via `webhooks::ops::create_tunnel`) stay deferred; revisit only if users need non-Composio HTTP callers.
-2. **Prompt-injection surface** — webhook/app_event payloads feeding `agent` nodes are untrusted; must go through the `prompt_injection` domain. Non-negotiable before G1 ships.
-3. **Editable canvas vs. agent-first authoring** — product stance so far is "the agent builds it, you approve it" (`gitbooks/features/workflows.md`). Phase 5 makes that stance first-class in the Flows UI itself (prompt bar + canvas copilot); the Phase 3 hand-editing canvas is the escape hatch, not the headline. Keep the prompt-first path primary in onboarding copy so the two don't compete.
-4. **GPL-3.0 licensing** of `vendor/tinyflows` — already vendored/linked; re-confirm distribution posture before expanding surface (flag for legal, not an engineering blocker).
-5. **Submodule cadence** — engine changes (Phase 7) must land in the tinyflows repo and re-vendor; keep host-side workarounds (e.g. by-id sub-workflow resolution in caps) so UI phases aren't blocked on vendor releases.
-
-**Per-repo conventions that apply to all phases**: new RPCs go through domain `schemas.rs` + controller registry (no `dispatch.rs` branches); ≥80 % diff coverage gate; verbose `[flows]`-prefixed debug logging on every new path; i18n keys added to `en.ts` **and all 13 locales**; update `src/openhuman/platform/about_app/` and `gitbooks/features/workflows.md` as features land.
diff --git a/docs/plans/tinyflows-integration/triggers.md b/docs/plans/tinyflows-integration/triggers.md
deleted file mode 100644
index 526736a377..0000000000
--- a/docs/plans/tinyflows-integration/triggers.md
+++ /dev/null
@@ -1,140 +0,0 @@
-# Trigger taxonomy & the cron → workflows unification
-
-> Companion to [README.md](README.md) (the tinyflows completion POA). This doc answers two questions: **what kinds of triggers can this platform offer**, and **how do we migrate cron so that "everything automated is a workflow"**.
-
-## 0. Thesis
-
-Almost every automated behavior in OpenHuman is already shaped like *event → conditions → actions*: cron jobs, Composio app events, channel-message reactions, subconscious escalations, meeting follow-ups, notification triage. Today each has bespoke plumbing. tinyflows gives us one uniform substrate (a tinyagents graph per run, durable, observable, approval-gated), and the event bus (`src/core/event_bus/events.rs`, ~130 `DomainEvent` variants) is already the spine every one of those signals travels on.
-
-**End state**: *Workflows are the single user-facing automation concept.* A trigger is just a subscription that seeds a flow run; the trigger catalog is a curated projection of the event bus plus time and manual entry points.
-
-## 1. What the engine already models
-
-`tinyflows::model::TriggerKind` (declarative — the host fires them): `manual`, `schedule`, `webhook`, `app_event`, `form`, `execute_by_workflow`, `chat_message`, `evaluation`, `system`.
-
-Host dispatch status today (`flows/bus.rs`):
-
-| Kind | Status |
-| --- | --- |
-| `manual` | ✅ `flows_run` RPC / UI Run button |
-| `schedule` | ✅ cron `JobType::Flow` → `FlowScheduleTick` |
-| `app_event` | ✅ `ComposioTriggerReceived` matching (toolkit + trigger_slug) |
-| `webhook` | ⏸ deferred (Composio is the webhook story — README Phase 1a) |
-| `chat_message`, `form`, `execute_by_workflow`, `evaluation`, `system` | ❌ no dispatcher |
-
-The gap is not engine capability — it's host dispatchers and a catalog. Crucially, `system` is a free config surface: we can build **one generic event-trigger dispatcher** instead of nine bespoke ones.
-
-## 2. Proposed trigger catalog
-
-Organized by source. "Backing event" = the existing `DomainEvent` variant(s) that would feed the dispatcher.
-
-### 2.1 Time (`schedule`)
-
-Already live via cron. Expose the full richness cron already has (`CronJob` in `cron/types.rs`):
-
-- **Cron expression** (today's path) and **interval** ("every 15 min") sugar.
-- **One-shot** ("run once at T") — cron's `delete_after_run` already models this; surface it in trigger config.
-- **Windowed schedules** (weekdays only, quiet hours) — respects `scheduler_gate`.
-
-### 2.2 Manual & parameterized (`manual`, `form`)
-
-- **Manual**: Run button / RPC / agent-initiated (`flows_run` with input).
-- **Form**: a manual run with a typed input schema. Trigger config declares fields; the UI renders a form; submission becomes the trigger payload. This is n8n's Form trigger and gives every workflow a shareable "mini-app" entry point. Cheap to ship: validation + a generated form in the canvas/run dialog.
-
-### 2.3 External apps (`app_event`, `webhook`)
-
-- **Composio triggers** (live): Gmail new message, Slack event, GitHub push, calendar event, … the platform delivers; we match toolkit/slug. Work remaining is subscription lifecycle + catalog surfacing (README Phase 1a).
-- **Raw webhook** (deferred): non-Composio HTTP callers via `webhooks::ops` tunnels. Backlog until demanded.
-
-### 2.4 Conversation (`chat_message`)
-
-Backing events: `ChannelInboundMessage` / `ChannelMessageReceived` / `ChannelReactionReceived`.
-
-- **Message received** with filters: provider/channel id, sender, regex or keyword, mention-of-me, DM vs group.
-- **Reaction added** (e.g. ✅ on a message → file it as a task).
-- Guardrail: these runs consume untrusted text — `prompt_injection` screening before any `agent` node, and a per-flow debounce/concurrency cap (the `app_event` dispatcher's guard generalizes).
-
-### 2.5 Agent & task lifecycle (`system`)
-
-Backing events: `AgentTurnCompleted`, `SubagentCompleted`/`SubagentFailed`, `ApprovalDecided`, `TaskSourceTaskIngested`, `TaskRunReclaimed`, `ThreadGoalUpdated`.
-
-Examples: "when any subagent fails, post a summary to my ops channel"; "when a task is ingested from a task source, enrich and label it"; "when an approval is denied, notify the requester thread".
-
-### 2.6 Memory & knowledge (`system`)
-
-Backing events: `MemoryStored`, `MemoryIngestionCompleted`, `MemoryDiffComputed`, `DocumentCanonicalized`, `TreeSummarizerHourCompleted`.
-
-Examples: "when a document is canonicalized, generate an abstract and store it"; "when the hourly summary lands, check for action items".
-
-### 2.7 Meetings & voice (`system`)
-
-Backing events: `MeetingSessionCreated`, `MeetingSummaryGenerated`, `BackendMeetTranscript`, `PttTranscriptCommitted`, `MeetingAutoJoinTriggered`.
-
-Examples: "when a meeting summary is generated, extract action items → create tasks → email attendees" — the flagship demo workflow.
-
-### 2.8 Notifications & devices (`system`)
-
-Backing events: `NotificationIngested`/`NotificationTriaged`, `DevicePaired`, `DevicePeerOnline`/`Offline`.
-
-Examples: triage automations ("when a notification from app X is ingested, decide urgent/ignore"), presence automations ("when my phone comes online, sync …").
-
-### 2.9 Platform & health (`system`)
-
-Backing events: `SystemStartup`, `HealthChanged`, `HealthRestarted`, `AutonomyConfigChanged`, `McpServerDisconnected`, `ProviderApiKeyRejected`, `EmbeddingModelUnhealthy`.
-
-Examples: self-healing/maintenance workflows ("on health degradation, run doctor and report"). These should default to `require_approval` off but notification-heavy.
-
-### 2.10 Subconscious escalations (`system`)
-
-Backing events: `SubconsciousTriggerProcessed`, `TriggerEvaluated`, `TriggerEscalated`.
-
-The subconscious domain is itself a mini automation engine (evaluate → escalate). Long-term convergence candidate: an escalation's *action* becomes "run flow X", making workflows the actuator layer for subconscious signals rather than a parallel system.
-
-### 2.11 Workflow-to-workflow (`execute_by_workflow`, `evaluation`)
-
-- `execute_by_workflow`: fired when another flow's `sub_workflow`/by-id call targets this flow (README Phase 4b) — enables composition and shared "library" flows.
-- `evaluation`: reserved for eval-harness runs of a flow (regression-test a workflow against recorded inputs); pairs with `dry_run_workflow` (README Phase 5b).
-
-## 3. Design: one generic event dispatcher, not N bespoke ones
-
-Adding a hand-written `handle_*` per event (like `handle_app_event`) doesn't scale to §2.5–2.10. Proposal:
-
-1. **Trigger catalog registry** (new, `flows/trigger_catalog.rs`): a curated allowlist of `DomainEvent` variants exposed as triggers — `{ key: "meeting.summary_generated", event: <variant match>, payload_schema, description, risk_class }`. Only cataloged events are subscribable; the raw bus is never exposed wholesale.
-2. **Generic dispatcher** in `FlowTriggerSubscriber`: one match arm per cataloged domain that projects the event into a stable JSON payload, then matches enabled flows whose trigger is `kind: system, config: { event: "<key>", filter: "=<jq expr>" }`. The existing jq engine (`tinyflows::expr`) evaluates the optional filter against the payload — no new expression language.
-3. **RPC** `flows_list_trigger_catalog()` → feeds the Phase 3 trigger-config UI and the Phase 5 builder agent (so prompts like "when a meeting ends…" ground to a real catalog key).
-4. **Guardrails** (non-negotiable, enforced in the dispatcher):
- - **Loop prevention**: flow runs emit events too; runs triggered by a flow-originated event carry a provenance chain with a max depth (reuse tinyagents `root_run_id` lineage); a flow can never trigger itself.
- - **Debounce/rate limits**: per-flow trigger token bucket + the existing per-flow concurrency guard.
- - **Payload hygiene**: catalog projection strips PII-ish fields by default; `prompt_injection` screening before agent nodes.
- - **Risk classes**: catalog entries tagged (e.g. conversation events = untrusted-input class → forces screening; health events = internal class); validation surfaces the class in the UI.
-
-## 4. Cron → workflows migration
-
-Today `cron` runs three job types (`cron/types.rs::JobType`): `Shell`, `Agent`, and `Flow` (already just a tick-publisher for flows). The inversion: **cron stops being a product surface and becomes the schedule service for workflows.**
-
-**M1 — Model mapping.** Every legacy job is a one-node flow:
-
-- `JobType::Shell { command }` → flow: `trigger(schedule)` → `code` node (or a dedicated `shell` tool_call, subject to the same `classify_command` gating cron uses today).
-- `JobType::Agent { prompt, agent_id, model, session_target }` → flow: `trigger(schedule)` → `agent` node (prompt/model in config; `agent_id` maps to the Phase 5+ agent-definition reference once engine sub-ports land — until then, definition prompt inlined).
-- `DeliveryConfig` / `session_target` (post result to main thread vs isolated) → flow-level `delivery` setting or an explicit terminal "notify/post" node. Prefer the explicit node: it's visible on the canvas, which is the whole point.
-- `delete_after_run` → one-shot schedule config (§2.1).
-
-**M2 — Dual-write bridge.** `cron_add`/`cron_update` agent tools and RPCs keep working but create flows under the hood (a `legacy_cron` tag preserves round-tripping for `cron_list`). New UI creation always goes through flows.
-
-**M3 — Backfill migration.** One-time migration (per-user, on upgrade): convert existing enabled shell/agent jobs into flows, preserving ids in metadata, next_run continuity, and run history linkage (`CronRun` rows stay readable; new runs are `FlowRun`s). Feature-flag + rollback window before deleting the legacy paths.
-
-**M4 — Surface consolidation.** Settings → Automations lists flows only; cron internals (`scheduler.rs`, jobs table) remain as the tick engine for `JobType::Flow`, which becomes the *only* job type. The `cron_*` tool family shrinks to a thin alias the agent can still call, documented as "creates a scheduled workflow".
-
-**What cron keeps**: the single tokio scheduler loop, persistence of next-fire times, catch-up semantics, `scheduler_gate`. That's infrastructure — workflows are the product on top of it.
-
-**Sequencing**: M1/M2 fit inside README Phase 1 (they're mostly `flows`-side); M3/M4 after the canvas + run inspector are solid (users must be able to *see* what their migrated jobs became), i.e. post-Phase 3.
-
-## 5. Rollout order for new trigger kinds
-
-1. `form` + one-shot/interval schedule sugar (cheap, immediately useful).
-2. Trigger catalog + generic `system` dispatcher, seeded with a small vetted set: `meeting.summary_generated`, `notification.triaged`, `subagent.failed`, `task.ingested`, `document.canonicalized`.
-3. `chat_message` (needs the untrusted-input guardrails first).
-4. Cron migration M1–M2, then M3–M4.
-5. `execute_by_workflow` (with Phase 4b sub-workflow-by-id), `evaluation` last.
-
-Each new dispatcher lands with: E2E test in `tests/json_rpc_e2e.rs`, catalog entry with payload schema, validation warning removal (the kind moves from "declared but never fires" to live), and a template (README Phase 4c) demonstrating it.
diff --git a/docs/plans/tinyflows-node-io-and-agent-kinds.md b/docs/plans/tinyflows-node-io-and-agent-kinds.md
deleted file mode 100644
index 49969b937b..0000000000
--- a/docs/plans/tinyflows-node-io-and-agent-kinds.md
+++ /dev/null
@@ -1,171 +0,0 @@
-# tinyflows — Node I/O Alignment & Selectable Agent Kinds (POA)
-
-> **Status**: proposed · **Date**: 2026-07-05
-> **Scope**: (A) fix the node input/output contract so producer/consumer shapes line up (agent ↔ tool*call ↔ merge), and (B) let a workflow pick \_which kind of agent* an `agent` node runs (coding agent, researcher, crypto agent, …) so each brings its own curated tool access.
-> **Companion**: extends `docs/plans/tinyflows-integration/README.md`; audit source `vendor/tinyflows/docs/AUDIT-n8n-gap.md` (§3 bugs, §4b I/O alignment).
-> **Reference product**: [n8n](https://github.com/n8n-io/n8n) — declared per-node output schemas, per-item execution, AI Agent node with pluggable tool/model sub-nodes.
-
----
-
-## 0. Why this plan
-
-Two problems surfaced in the audit that share a root cause — **nodes have no declared I/O contract**, so what one node emits and what the next reads are only accidentally aligned:
-
-1. **Shape drift.** Every capability node wraps its host capability's raw return verbatim into `Item.json` (`agent.rs:115`, `tool_call.rs:31`, `http_request.rs:24`). The `agent` node emits three different shapes depending on sub-ports, and its plain shape flips between "parsed model JSON" and `{text}` at runtime (`caps.rs:359,369`). Downstream `=item.<field>` expressions therefore guess.
-2. **No agent identity.** The `agent` node is a single bare `provider.chat` call with a free-form inline `tools` list (`caps.rs` `OpenHumanLlm::complete`, "no agent loop is driven here"). There is no way to say "run this step as the **coding** agent" or "as the **researcher**", even though OpenHuman already ships a 35-agent registry where each agent (`researcher`, `code_executor`, `crypto_agent`, …) declares its own toolset, model hint, sandbox, and iteration policy in an `agent.toml`.
-
-Part A fixes the contract; Part B builds selectable agent kinds on top of the existing registry. They are sequenced so A1 (the agent envelope) lands before B (agent kinds emit into that same envelope).
-
----
-
-## Part A — Node I/O alignment
-
-### A0. Design principle: a normalized item envelope
-
-Adopt a small, stable **output envelope** for capability nodes so every downstream expression has a guaranteed accessor, regardless of provider or config:
-
-```jsonc
-// agent / tool_call / http_request / code emit items shaped:
-{
- "json": <structured payload | null>, // parsed/structured result when there is one
- "text": <string | null>, // human-readable text when there is one
- "raw": <provider-native value>, // escape hatch: the untouched capability return
- "error": <null | { message, ... }> // present only on continue/route error items
-}
-```
-
-Rules: `=item.text` always resolves (or is explicitly `null`); `=item.json.<field>` is the structured path; `=item.raw` preserves today's behavior for anyone who needs the provider blob. This is additive — `raw` is exactly what nodes emit today — so migration is mechanical.
-
-> Keep the crate **host-agnostic**: the envelope is defined in `vendor/tinyflows` (`src/data.rs` / node executors). The host adapters (`caps.rs`) already produce `{text}` / parsed JSON, so they map onto `json`/`text` directly.
-
-### A1. Normalize the `agent` node output — _highest leverage, do first_
-
-- **Crate** (`vendor/tinyflows/src/nodes/integration/agent.rs:115`): wrap the completion in the envelope instead of `Item::new(value)`. If `output_parser` ran, the coerced value goes in `json`; the completion text (when present) in `text`; the untouched response in `raw`; a model-elected tool result stays under `json.tool_result` **and** mirrors to a stable `tool_result` accessor (see A2).
-- **Host** (`src/openhuman/flows/tinyflows/caps.rs` `OpenHumanLlm::complete`): return `{ json: <parsed-or-null>, text: <response.text>, raw: <full response> }` rather than either the bare parsed object _or_ the `{text}` fallback. Removes the runtime shape-flip (audit M1).
-- **Tests**: update `agent.rs` unit tests + `caps.rs` seam tests; add an e2e asserting `=item.text` resolves on both a JSON-emitting and a prose-emitting model (mock both).
-
-### A2. Unify inline-tool vs `tool_call`-node result shape (audit M2)
-
-Make a tool result reachable at the **same** path whether the tool ran inline in an `agent` node or as a standalone `tool_call` node. Standardize on the envelope: `tool_call` node emits `{ json: <tool output>, raw: <composio envelope> }`; the agent's inline tool result lands at `item.json.tool_result` and the node envelope's `raw` keeps the full completion. Document the one canonical accessor.
-
-### A3. Per-item execution for integration nodes (audit M3 — the silent-drop trap)
-
-Today `agent`/`tool_call`/`http_request` **always emit one item** and bind config against `input.first()` only, so `split_out (N) → tool_call` fires **once** and drops N−1 items.
-
-- Add a node config flag `execution: "once" | "per_item"` (default `per_item` for `tool_call`/`http_request`; default `once` for `agent`, since an agent turn is usually batch-level — but allow `per_item`).
-- In `per_item` mode: map the executor over `ctx.input`, re-resolving config per item (so `=item.x` means _this_ item), emit one output item per input, carry `paired_item` (`vendor/tinyflows/src/data.rs`).
-- Touches `agent.rs`, `tool_call.rs`, `http_request.rs`, and the per-item resolution path in `nodes/mod.rs`.
-- **Tests**: `split_out → tool_call` runs N times; `paired_item` lineage preserved; `once` mode unchanged.
-
-### A4. Port-aware `collect_input` (audit M4 — untaken-branch leak + BUG-3/BUG-4)
-
-`collect_input` (`vendor/tinyflows/src/engine.rs:171`) concatenates items from **every** predecessor slot regardless of `Edge.to_port` (stored, never read) or which port the predecessor emitted on. A node after a `condition` reads the not-taken branch's items.
-
-- Read `Edge.to_port` / the predecessor's recorded `port`; collect only items the predecessor actually emitted on the connecting port.
-- Enables **named merge inputs** (input A vs B) and removes the leak.
-- Fold in the merge-barrier gap (BUG-4) and mixed-port fan-out drop (BUG-3) from the audit — same routing/lowering surface (`engine.rs:422`, `789-826`).
-- **Tests**: condition-false slot not visible to a node wired on the true port; merge fed by a branching predecessor barriers correctly; the `main→a, main→b, error→h` shape runs both `a` and `b`.
-
-### A5. `merge` modes (audit M5)
-
-Add `merge.mode`: `append` (today's concat), `combine_by_key` (join items by a key field), `combine_by_position` (zip). Config-only change in `vendor/tinyflows/src/nodes/control_flow/merge.rs`; barrier semantics unchanged.
-
-### A6. Author-time alignment lint (feeds Part C tooling)
-
-A validation pass that, given a producer node's known/declared output envelope, flags downstream `=item.<field>` references the producer cannot emit — surfaced as structured, node-addressed diagnostics. Depends on tightening `validate.rs` (audit BUG-10). Wire into the agent-facing `validate` / `revise_workflow` tools so the builder agent gets the feedback.
-
-### A-bugs (bundle with the above — from audit §3)
-
-- **BUG-1 (security, hotfix now):** jq `env` builtin leaks host env — disable `jaq-std` default features / filter `env`/`input*` in `vendor/tinyflows/src/expr.rs:302`.
-- **BUG-2:** `switch`/`transform` don't get the `nodes` scope — use `expr_scope` (`switch.rs:26`, `transform.rs:27`).
-- **BUG-5/6:** sub-workflow HITL dropped; `on_run_finish` never fires on failure — verify against `FlowRunObserver`.
-- **BUG-9:** `code`/`output_parser`/`sub_workflow` skip `=`-resolution — make expression binding uniform.
-
----
-
-## Part B — Selectable agent kinds
-
-### B0. The idea
-
-Let an `agent` node declare **which agent** runs it, by referencing an OpenHuman registry agent:
-
-```jsonc
-{
- "kind": "agent",
- "config": {
- "agent_ref": "code_executor", // or "researcher", "crypto_agent", …
- "prompt": "=item.text",
- "connection_ref": "…", // still host-resolved, never model-supplied
- // optional per-node overrides:
- "model": "…",
- "max_iterations": 6,
- "tools_allow": ["grep", "edit"],
- },
-}
-```
-
-When `agent_ref` is set, the host runs that **registered agent** — with _its_ curated toolset, model hint, sandbox mode, and iteration policy — as a full multi-turn agent loop, instead of the current single `provider.chat` call. A coding step gets coding tools; a research step gets `web_search`/`web_fetch`; a crypto step gets market tools. This is exactly the registry's existing contract (`src/openhuman/agent/registry/agents/*/agent.toml`).
-
-### B1. Crate seam — new `AgentRunner` capability (host-agnostic)
-
-The crate must not know about OpenHuman's registry, and "run a named agent to completion (multi-turn, tool-using)" is a **different capability** than `LlmProvider.complete` (single shot). Add a trait to `vendor/tinyflows/src/caps/mod.rs`:
-
-```rust
-#[async_trait]
-pub trait AgentRunner: Send + Sync {
- /// Run a host-registered agent identified by `agent_ref` to completion.
- /// `request` carries prompt/input/overrides; `conn` is the opaque credential.
- async fn run_agent(&self, agent_ref: &str, request: Value, conn: Option<&str>) -> Result<Value>;
-}
-```
-
-- Add `agent: Option<Arc<dyn AgentRunner>>` to `Capabilities` (optional so hosts without a registry keep working).
-- **`agent.rs` dispatch**: if `config.agent_ref` is present _and_ `caps.agent` is wired → `run_agent(...)`; else fall back to today's `LlmProvider.complete` path. Both emit the A1 envelope, so downstream expressions are identical regardless.
-- Mock impl in `caps/mock.rs` (echo `agent_ref` + request) so crate tests exercise both paths.
-- `agent_ref` is **trusted config only**, never taken from model output (same rule as `tool_call.connection_ref`, `agent.rs:71-79`).
-
-### B2. Host adapter — implement `AgentRunner` over the registry + delegate runtime
-
-- `src/openhuman/flows/tinyflows/caps.rs`: new `OpenHumanAgentRunner` implementing `AgentRunner`.
-- `run_agent(agent_ref, request, conn)`:
- 1. `agent_registry::ops::get_agent(agent_ref)` → resolve the entry (tools, model hint, sandbox, `max_iterations`, `iteration_policy`).
- 2. Apply optional per-node overrides (`model`, `max_iterations`, and a **narrowing-only** `tools_allow` — a node may _subset_ the agent's tools, never add).
- 3. Drive the existing delegate runtime (`src/openhuman/agent/tools/delegate.rs`) with a `TurnOrigin` of the flow run (`src/openhuman/agent/turn_origin.rs` already has a flow origin variant).
- 4. Return `{ json, text, raw }` (A1 envelope): final structured output in `json`, final message text in `text`.
-- **Autonomy/security**: the agent kind's tools are still gated by `SecurityPolicy` / autonomy tier; a `sandboxed` agent (e.g. `code_executor`) runs sandboxed; the flow's own approval gate still parks outbound actions. No new privilege path.
-- **Depth/cost guard**: an agent node running a full agent loop inside a flow can fan out cost — bound it (reuse `MAX_SUB_WORKFLOW_DEPTH`-style counter or a per-run agent-invocation cap) and thread cancellation into the delegate run (today's sub-workflow path drops the token — BUG-5 — fix here too).
-
-### B3. Authoring surface — ground the choice for the builder agent
-
-- **Builder tool** `list_agent_profiles` in `src/openhuman/flows/builder_tools.rs`, backed by `agent_registry::ops::list_agents(false)`, returning `{ id, display_name, when_to_use, tools, sandbox_mode }`. Mirrors the existing `search_tool_catalog` pattern so the `workflow_builder` sub-agent picks a real `agent_ref` instead of hallucinating one.
-- **Validation** (`vendor/tinyflows/src/validate.rs` + host): an `agent` node with an `agent_ref` that doesn't resolve is a structured validation error (needs the host to pass the known-agent set into validation, or validate host-side in `flows::ops::validate`).
-- **workflow_builder prompt** (`src/openhuman/agent/registry/agents/workflow_builder/prompt.md`): document `agent_ref` and when to prefer a specialized agent over a bare completion.
-
-### B4. UI — agent-kind picker
-
-- The (upcoming) node config panel (`U2` in the integration plan) gets an **Agent kind** dropdown for `agent` nodes, populated from `agent_registry` `list_agents` RPC (already exists), showing `display_name` + `when_to_use`, with an optional tool-subset multiselect.
-- Read-only canvas: show the chosen agent kind as a node badge.
-
----
-
-## Part C — Sequencing & ownership
-
-| Phase | Work | Depends on | Surface |
-| ------ | -------------------------------------------------------------------------------- | --------------------- | ------------------------------------------------- |
-| **C0** | BUG-1 env-leak hotfix; BUG-2 switch/transform scope | — | `vendor/tinyflows/src/expr.rs`, `control_flow/*` |
-| **C1** | A0 envelope + **A1 agent output normalization** | C0 | `agent.rs`, `caps.rs` |
-| **C2** | A2 tool-shape unification; A3 per-item execution | C1 | `tool_call.rs`, `http_request.rs`, `nodes/mod.rs` |
-| **C3** | A4 port-aware `collect_input` (+ BUG-3/4); A5 merge modes | — (parallel to C1/C2) | `engine.rs`, `merge.rs` |
-| **C4** | **B1 `AgentRunner` capability** + mock | C1 (shared envelope) | `caps/mod.rs`, `caps/mock.rs`, `agent.rs` |
-| **C5** | **B2 host `OpenHumanAgentRunner`** over registry+delegate (+ BUG-5 cancellation) | C4 | `tinyflows/caps.rs`, `agent/tools/delegate.rs` |
-| **C6** | B3 `list_agent_profiles` + `agent_ref` validation; A6 alignment lint | C5, BUG-10 | `flows/builder_tools.rs`, `validate.rs` |
-| **C7** | B4 UI agent-kind picker | C5, U2 node panel | `app/src/components/flows/*` |
-
-Each phase ships with tests (crate unit + host seam + JSON-RPC E2E) per the repo's "tests before the next layer" rule, and records design decisions in `vendor/tinyflows/local/docs/11-decisions.md`.
-
-## Open questions
-
-1. **`agent_ref` in the crate**: prefer a dedicated `AgentRunner` capability (B1, recommended — keeps `LlmProvider.complete` a clean single-shot contract) vs. overloading `complete` to loop when it sees `agent_ref`. Recommendation: the capability.
-2. **Per-node model/tool overrides**: allow narrowing only (`tools_allow` subsets the agent's toolset) — never widen, to preserve the registry's security envelope. Confirm this constraint.
-3. **Cost/loop bounds** for agent-kind nodes inside a flow (and inside a sub-workflow): reuse the depth counter or introduce a per-run agent-invocation budget?
-4. **Custom agents**: `upsert_custom_agent` already exists — user-defined agent kinds are addressable by `agent_ref` for free. Confirm they should be selectable in flows.
diff --git a/docs/plans/tinymemory-bus-only/PLAN.md b/docs/plans/tinymemory-bus-only/PLAN.md
deleted file mode 100644
index 44bda50004..0000000000
--- a/docs/plans/tinymemory-bus-only/PLAN.md
+++ /dev/null
@@ -1,281 +0,0 @@
-# Removing `tinymemory-core` and `tinycortex` from OpenHuman
-
-Goal: the host links **`tinymemory-api` only**. All memory behaviour reaches the
-loaded TinyMemory TinyBus module through `MemoryProvider`; nothing in `src/`
-names an engine crate.
-
-Spans three repos: `openhuman` (host), `vendor/tinymemory`, `vendor/tinycortex`.
-Branch `tinymemory-bus-only` in each.
-
-## Measured starting point (2026-08-30)
-
-- `modules::registry` pins tinymemory **v1.13.3** — 144 bus members, 23
- capability families, all implemented by `ModuleMemoryProvider`. The in-tree
- docs claiming v1.0.1/v1.2.0 and a narrow seam are stale.
-- `DriverClass::Embedded` is refused (`binding.rs:252`), so every
- `MemoryProvider` call is already over the bus.
-- Production files naming `tinymemory_core::`: **23**. Naming `tinycortex::`: **~45**.
-- Deleting the six engine glob re-exports yields **40 compile errors in ~30 files**.
- That is the true host coupling.
-
-## The three clusters, and where each goes
-
-### A. Composio providers (~20 files, 8.8k LOC in `tinymemory-core`)
-
-Consumed mostly by `integrations/composio`, `flows` and `task_sources` — none of
-which is memory. Split by what the thing *is*:
-
-| Part | Destination | Why |
-| --- | --- | --- |
-| `tool_scope`, `catalogs*`, `descriptions`, `scope_lookup`, `capability_matrix`, `is_action_visible_with_pref` | **`tinymemory-bus::composio`** | static tables + pure functions, no I/O, no runtime. `ToolScope`/`UserScopePref`/`CuratedTool` types are already there; `tool_scope.rs` is a 32-line re-export of them. |
-| `user_scopes::load_or_default` | bus `KvGet`/`KvPut` via `MemoryGraph` | it is a KV read (`crate::store::MemoryClientRef`), not a table. |
-| `ComposioProvider` trait, `registry`, `ProviderContext`, provider impls (github/gmail/linear/notion/slack/clickup), `profile`, `profile_md`, `sync_state`, `periodic` | **stays sync-side** (tinycortex/module) | this is the syncing half. Host reaches it through `MemorySourceSync`. |
-
-Host `get_provider(..).curated_tools()` becomes `catalog_for_toolkit(..)` from
-the contract, which removes most `get_provider` call sites outright. The ones
-that remain are real sync behaviour (`fetch_tasks`, `list_databases`,
-`fetch_user_profile`) and need bus members.
-
-### B. Tree (~9 files) — becomes graph/recall/retrieval via the API
-
-Do **not** ask upstream for tree-shaped twins. Map onto the existing families:
-
-| Host call today | Goes to |
-| --- | --- |
-| `tree::retrieval::{fast_retrieve, FastRetrieveOptions, QueryResponse}` | `MemoryRetrieval::fast_retrieve` |
-| `tree::retrieval::source::query_source_scoped` | `MemoryTree::query_source` / `MemoryRetrieval::retrieve_source` |
-| `tree::retrieval::types::NodeKind` | `RetrievalNodeKind` |
-| `tree::score::extract::EntityKind` | `provider::retrieval::EntityKind` |
-| `tree::health::async_run_doctor` | `MemoryMaintenance::doctor` |
-| `tree::score::DEFAULT_DROP_THRESHOLD` consumer | `MemoryProfile::drop_facets_below` |
-
-**`summarise` does NOT come home — corrected 2026-08-30.** The first reading of
-this was "it builds an LLM chat provider, and the host owns inference, so it is
-host policy like `source_scope`". That is wrong, and the evidence is in
-`modules/memory_host.rs:45,406`: the **`ChatHost` seam already crosses the bus**
-(`ai.tinyhumans.tinymemory.ChatHost`), so the module can call the host's chat
-without the host owning the summariser. And `summarise` is not just a chat call
-— it is `prepare_summary_prompt` + `finish_provider_summary` +
-`fallback_summary` from `engine::backend::tree`, which know the summary tree's
-format and belong with the tree. Bringing them home would mean two copies of the
-tree's own prompt and parser, one of which the module keeps using.
-
-So this is an **upstream ask**, not a relocation: a summarise member taking
-`SummaryInput`s and a `SummaryContext`, so `agent/harness/archivist/recap.rs`
-can ask the module for a recap instead of linking the engine to build the
-prompt. `tree_runtime::engine::{run_summarization, rebuild_tree}` is the same
-shape (it drives `tinyagents::ChatModel` over the tree's own machinery).
-
-Genuinely missing from the contract, so upstream asks:
-
-- `MemoryEntities::entity_score(id)` — replaces `tree::score::store::get_score`
-- `DEFAULT_DROP_THRESHOLD` as a contract constant
-- `MemoryTree` extension for the node store: `read_node`, `read_children`,
- `tree_status`, `write_node`, `buffer_write`, namespace/node-id validation
- (`tree_runtime::store::*`)
-- **A staged diagnostic report.** `MemoryMaintenance::doctor` looked like the
- twin for `tree::health::async_run_doctor` and is not, so `memory/tools/doctor.rs`
- was deliberately **not** migrated. The contract's `MaintenanceReport` is
- `{operation, examined, changed, findings: Vec<String>}`; the engine's
- `DoctorReport` is `{healthy, stages: Vec<StageHealth>, first_blocking_cause:
- Option<PipelineFailure>, degraded: DegradedState, counters: DoctorCounters}`.
- The whole point of the `memory_doctor` tool is the per-stage health and the
- single first blocking cause, and `findings: Vec<String>` cannot carry either
- without the model parsing prose back into structure. Swapping would compile,
- return a plausible report, and quietly make the tool useless — the same shape
- of trap as `recall_namespace_scored` vs recency recall. The ask is a
- `DiagnosticReport` on `MemoryMaintenance` carrying stages and a blocking
- cause.
-
-### C. Sources (~4 files) — a crate the host can simply take
-
-This one needs **no bus work and no upstream change**, which the first pass
-missed. `tinymemory_core::sources` is a thin layer over a separate crate:
-
-- `sources::types` is already `pub use tinymemory_sources::{…}`.
-- `sources::registry` is "the host's config path + a write lock" around
- `tinymemory_sources::registry::SourceRegistry::new(config.config_path())` —
- CRUD over the host's own `sources.toml`. The host owns that file; it does not
- need the engine to read it.
-- `sources::readers` re-implements the reader dispatch over
- `tinymemory_core::Config`, where `tinymemory_sources::readers` takes a plain
- `workspace: &Path`.
-
-`tinymemory-sources` costs serde, schemars, serde_json, anyhow,
-`tinymemory-api`, async-trait, futures, regex, reqwest, walkdir, tracing,
-chrono, tokio, toml, uuid — every one of which the host already has. No
-`rusqlite`, no `tinycortex`, no engine.
-
-So: depend on `tinymemory-sources` directly and let `memory::sources` own the
-config-path and lock layer itself.
-
-**Read `tinymemory_sources::readers`' module docs before touching `reader_for`.**
-It returns `None` for the network kinds *deliberately* — "a network reader is
-constructed explicitly by a caller that has already decided the fetch is
-allowed; it is never handed out by the kind-dispatch that the workspace sync
-loop drives on a timer", which is what keeps the host in charge of egress,
-OAuth and cost. The engine's `reader_for` hands out all seven, so a literal
-port would quietly move that decision. `composio` and `twitter_query` have no
-reader in the crate at all (credentialed OAuth pipeline; unimplemented).
-
-### D. `tinycortex` direct calls — the hard one
-
-`tinycortex::memory::conversations::{list_threads, get_messages, ensure_thread,
-append_message, purge_threads, ConversationMessage, CreateConversationThread}`
-has **no contract family at all**. Callers: `memory/conversations/bus.rs`,
-`memory/conversations/blocking.rs`, `channels/host/adapters.rs`, `threads/`.
-Upstream ask: a `MemoryConversations` family.
-
-Also engine-shaped: `memory::archivist::store::{session_entries, record_turn}`
-(→ `MemoryEpisodic`, mostly covered), `memory::tree::{compile_flavoured_root,
-flavoured_root_abs_path, get_tree_by_scope}` (`memory/tools/flavour.rs`),
-`memory::persona::PersonaFacet` (→ `ProfileFacet`),
-`memory::ingest::canonicalize::{chat, document}`.
-
-## Ordering (each step must leave the tree green)
-
-1. **tinymemory-bus**: move the static composio catalog/scope surface into the
- contract. No release coupling — it is a compile-time crate.
-2. **Host**: repoint `integrations/composio`, `flows`, `task_sources` at the
- contract; delete `memory::sync::composio` re-export shims that are now dead.
-3. **Host**: bring `summarise` and the tree-runtime summarisation home.
-4. **Host**: repoint the tree/sources clusters onto retrieval/graph/recall.
-5. **Upstream tinymemory/tinycortex**: `MemoryConversations`, the `MemoryTree`
- node-store extension, `entity_score`. Release; re-pin `modules::registry`.
-6. **Host**: last engine callers; delete `host_impls` seam installation
- (`core/runtime/context.rs:616`), bring `thread_context` and
- `learning_candidate` home **in the same commit** as the engine's removal.
-7. Drop both crates from `Cargo.toml` (deps and dev-deps) and both `[patch]`
- blocks; delete `direct_engine_refs_tests` once it can only be empty.
-
-### Two traps that must not be split across commits
-
-- **`thread_context`** is a `tokio::task_local!`. `tinymemory_core::store::recall_policy.rs:58`
- reads it. Two `task_local!` invocations are two keys, and unset means
- *exclude nothing* — recall would silently start echoing the caller's own
- thread back. It comes home **with** the engine, not before.
-- **`learning_candidate::global()`** is a process-global ring buffer that the
- engine's `sync/composio/providers/profile.rs:129` pushes into. Moving it home
- while `sync::composio` still resolves into the engine gives two buffers and a
- silently empty one.
-
-
-## Landed so far on `tinymemory-bus-only`
-
-Baseline was green; each step below left `cargo check --lib` green.
-
-**`tinymemory-bus`** — the curated Composio catalogs moved into the contract:
-`catalogs/{business,google,messaging,microsoft,productivity,social_media}.rs`
-plus the five provider-colocated tables (`gmail`, `notion`, `github`, `linear`,
-`clickup`), `descriptions.rs`, and a new `catalogs/mod.rs` carrying
-`catalog_for_toolkit`, `is_action_visible_with_pref`, `curated_scope_for`,
-`toolkit_has_scope`, `CAPABILITY_TOOLKITS`, `NATIVE_PROVIDERS` and the
-sync-interval helpers. `FastRetrieveQuery` gained a `Default` matching the
-engine's.
-
-**`tinymemory-api`** — `host::composio::capability_matrix()`, which needs
-`ComposioCapability` and so cannot live in the bus crate.
-
-**`tinymemory-core`** — `catalogs.rs`, `descriptions.rs`, `scope_lookup.rs` and
-the five `<provider>/tools.rs` files are now re-exports of the contract, so the
-engine and the host read one table. A drift guard in
-`tree/retrieval/fast_tests.rs` pins the two `Default`s together.
-
-**Host** — `integrations/composio/providers` stopped being a glob over the
-engine and is split by what each half is: the catalog/scope/capability surface
-from the contract, the provider registry and run types still from the engine and
-listed by name. Every host call site moved off
-`memory::sync::composio::providers::…` onto that path, so the shim is the only
-file naming the engine's composio tree. All three `fast_retrieve` callers
-(`memory/agent/ops.rs`, `memory/schema/handlers.rs`,
-`agent/harness/subagent_runner/ops/runner.rs`) now go through
-`binding.provider().as_retrieval()` with an explicit `as_bus_scope()`, and the
-runner's test fixtures dropped their `tinycortex::` import.
-
-### A pre-existing bug the new tests caught
-
-`toolkit_description` keyed on `google_calendar` / `google_docs` /
-`google_drive` / `google_sheets` / `onedrive`, while `CAPABILITY_TOOLKITS` and
-`catalog_for_toolkit` key on the underscore-free slugs. Five toolkits — the four
-Google ones and OneDrive — had been rendering the generic
-"Interact with this connected service via its available actions" fallback in the
-capability matrix and in the orchestrator's connected-integration prompt. Fixed
-by aliasing; `toolkit_description_is_populated_for_every_capability_toolkit`
-pins it.
-
-
-## The sources migration (landed)
-
-`memory::sources` went from `pub use tinymemory_core::sources::*;` to **one**
-named engine line.
-
-- `Cargo.toml` takes `tinymemory-sources` directly (`features = ["network"]`,
- matching what `tinymemory-core` enables).
-- `memory/sources/registry.rs` — the config-path + write-lock layer, ported
- function for function over `tinymemory_sources::registry::SourceRegistry`.
- Same locking, same error stringification, same on-disk format. The `_in`
- variants keep taking an explicit config, because reading the process-global
- path from a workspace-bound caller is the cross-workspace leak the binding map
- exists to prevent.
-- `memory/sources/readers/` — the `SourceReader` trait (product-shaped, takes a
- `&Config`) plus seven readers. Five are adapters over
- `tinymemory_sources::readers`; `composio` and `twitter` came home from the
- engine unchanged, with their tests.
-- `memory/sources/types` re-exports the crate's vocabulary.
-
-Still the engine's, named rather than globbed: `sync`, `status`, `reconcile`.
-
-**`MemoryChunks::source_totals` is not a substitute for `status`.** It looks
-like one. `SourceTotal` carries `chunk_count` and `most_recent_ms` but **no
-`chunks_pending`** — and pending ("has no embedding, was not dropped, was not
-skipped for re-embed") is the whole point of a sync-status row. It also omits a
-source with zero chunks entirely, where `status_list` returns a row per
-*configured* source. Migrating onto it would compile and quietly report a
-healthy store. Upstream ask: a pending count on `SourceTotal`.
-
-### `reader_for` hands out network readers — do not reuse it from a loop
-
-`tinymemory_sources::readers::reader_for` returns `None` for the network kinds
-deliberately, so that the host stays in charge of egress, OAuth and cost. The
-host's `reader_for` hands out all seven, matching the engine's, because its
-callers are RPC handlers acting on an explicit user request naming one source
-id. That is written into the module docs. A polling loop must construct a
-network reader deliberately instead.
-
-## The kernel-floor ratchet is already red on `main`
-
-`scripts/check-kernel-floor.sh` fails with **289 packages / 271 names against a
-288 / 270 limit**, and it fails **identically on `main`** — verified by running
-it in both checkouts and diffing the resolved package lists, which are the same
-271 names with and without this branch's `tinymemory-sources` line. That
-dependency was already in the kernel graph transitively through
-`tinymemory-core`, so taking it directly costs nothing.
-
-Do **not** raise `scripts/kernel-floor.limits` as part of this work: the growth
-is not this branch's, and raising it here would launder someone else's
-regression into a memory-migration PR. It needs finding and justifying on its
-own.
-
-
-## Are `sync` / `status` / `reconcile` already on the contract? (answered)
-
-Mostly yes — an earlier note in this file said otherwise and compared against
-the wrong type. Corrected:
-
-| Engine module | On the contract? |
-| --- | --- |
-| **`sync`** | **Yes.** `MemorySourceSync::run_source_sync(source_id)` and `run_connection_sync(toolkit, connection_id)`. And the host barely uses this module: `sources::sync::sync_source` has **zero** call sites in `src/`; the only thing reached is `derive_scopes`, a pure helper over a `MemorySourceEntry` + `Config`. |
-| **`status`** | **Per-provider: yes, and already wired.** `MemorySourceSync::sync_statuses()` returns `SourceSyncStatus { provider, chunks_synced, chunks_pending, batch_total, batch_processed, last_chunk_at_ms, freshness }`, and `memory/sync/sync_status/rpc.rs` already calls it through `binding.provider().as_source_sync()`. **Per-source: no.** `sources::status::status_list` is keyed by `source_id` and returns a row per *configured* source, including ones holding zero chunks. |
-| **`reconcile`** | **Not a member, but not a bus gap.** `ensure_composio_sources` is `composio::scan_active_sync_targets` (a Composio API call) plus a registry batch upsert. The registry half is host-side already; the scan is Composio client work. This is a relocation, not an upstream ask. |
-
-**Correction to the earlier entry in this document.** It claimed status was
-inexpressible because `SourceTotal` carries no `chunks_pending`. That is true of
-`SourceTotal` and irrelevant: `MemoryChunks::source_totals` is a chunk-grouping
-read, not the sync-status twin. `SourceSyncStatus` is the twin and it *does*
-carry `chunks_pending`. The real gap is narrower than stated — the key
-(`provider` vs `source_id`) and the zero-chunk rows, not the pending count.
-
-The engine's own `status.rs` says the pending predicate is "the engine's own
-predicate from `list_sync_statuses`, kept identical so the per-source view and
-the per-provider one cannot disagree about the same chunk" — i.e. these are two
-deliberate views of one truth, and only one of them has a contract member.
diff --git a/docs/plans/transcript-derived-view.md b/docs/plans/transcript-derived-view.md
deleted file mode 100644
index 47da181ba2..0000000000
--- a/docs/plans/transcript-derived-view.md
+++ /dev/null
@@ -1,106 +0,0 @@
-# Transcript-Derived View — Raw Session Files as Source of Truth
-
-Status: **draft — approved direction, phased implementation**
-Branch: `feat/transcript-derived-view` (stacked on `fix/transcript-restore-fidelity`)
-Companion: [`conversations-timeline-refactor.md`](conversations-timeline-refactor.md) (Phases 1–2, 4–5 landed; this plan supersedes its Phase 5 hydration story for settled turns)
-
-## Goal
-
-Stop maintaining chat state that must be *synced* with what is live. Derive the settled
-transcript from the raw session files (`session_raw/*.jsonl`), and demote every other
-store to a cache over that file. Live token streaming is untouched: in-flight turns
-render from ephemeral socket-fed state exactly as today; the file is authoritative only
-for **settled** turns.
-
-This is the Codex rollout model (one JSONL replayed into both model context and UI,
-with an explicit persistence policy) adapted to our layout, plus hermes-agent's
-soft-compaction lesson (history is never destroyed, only superseded).
-
-## Why derivation is unsafe today (must fix first)
-
-1. **Destructive compaction.** `agent/harness/session/transcript.rs::write_transcript`
- full-rewrites the file so context reduction deletes earlier turns from disk.
-2. **Display data missing from the file**: interrupted partial answers, `request_id`
- turn boundaries, narration items. They exist only in `turn_state` snapshots.
-3. **Internal scaffolding in message content**: channel-context prefixes on user
- messages, tool-policy preamble in system content — must be sanitized (or tagged) at
- projection, never shown raw.
-
-## Architecture
-
-```
- live turn (unchanged)
-socket events ──► chatRuntimeSlice (ephemeral) ──► renderer
- │ chat_done
- ▼ invalidate
-settled turns:
-session_raw/{root}.jsonl ─┐
-session_raw/{root}__sub-*.jsonl ─┴─► core projection (threads.transcript_get)
- │ mtime-keyed cache
- ▼
- typed display items ──► renderer (same components)
-```
-
-- **Model context** keeps reading the same file via the existing loader, now replaying
- compaction records instead of trusting a rewritten file.
-- **`turn_state`** shrinks to live-turn crash recovery (interrupted `streamingText`
- until the interrupted line is appended to the file, then only the in-flight turn).
-- The 20-turn retention cap stops being user-visible loss: history comes from the file.
-
-## Phases
-
-### Phase A — append-only transcript (Rust, prerequisite)
-`transcript.rs` + harness call sites:
-- Replace full-rewrite with **append-only** line writes. Context reduction appends a
- `compaction` record `{ kind: "compaction", replacement_ids | replacement_history }`;
- the model-context loader (`read_transcript` path) replays records to reconstruct the
- post-compaction context; a new display reader returns *all* records.
-- Stamp `request_id` on every line of a turn (turn boundary markers); keep `iteration`,
- `ts`, `seq` alignment with the progress-bridge envelope.
-- On turn abort/interrupt, append the partial assistant line flagged
- `{ interrupted: true }` so the partial answer is in the file, not only in turn_state.
-- Migration: existing files are valid append-only files with zero compaction records —
- no migration needed. Old cores reading new files must skip unknown `kind` lines
- (verify the `_extra` flatten tolerates this; add a version field to `_meta`).
-- Tests: compaction round-trip (model context reduced, display history complete),
- interrupted-partial append, request_id stamping, legacy-file read.
-
-### Phase B — projection RPC (Rust)
-New `threads.transcript_get(thread_id, {cursor?, limit?})` in the threads domain
-(canonical module shape: ops/schemas):
-- Resolve root transcript via `find_root_transcript_for_thread`; discover
- `__sub-*.jsonl` children; project into typed display items:
- `user_message | assistant_message | reasoning | tool_call {args, result, status} |
- subagent {id, items} | turn_boundary {request_id} | interrupted_partial`.
-- Sanitize scaffolding (channel-context prefix, tool-policy preamble) at projection;
- tag rather than mutate where ambiguity exists.
-- Cache: per-thread projection keyed on (file paths, mtimes, lengths); invalidated
- implicitly by key change. No cache writes to disk — pure memory cache.
-- Pagination newest-first with cursor; default window sized for one screen.
-- Tests: JSON-RPC E2E (`tests/json_rpc_e2e.rs`) — write file, call RPC, assert items;
- subagent merge; sanitization; cache-key invalidation.
-
-### Phase C — frontend switch (TS)
-- Thread-open restore path: replace `turn_state_history` hydration for settled turns
- with `transcript_get`; map items onto the existing renderers
- (`PastTurnInsights`/`ToolTimelineBlock`/`ProcessingTranscriptView`, bubbles).
-- Live turn: untouched (socket → chatRuntimeSlice). On `chat_done`, drop the live
- turn's ephemeral state and refetch/append the settled projection.
-- Keep the turn_state hydration path as fallback behind a flag for one release.
-- Tests: restore renders identical item sequence to live for a scripted turn;
- interrupted partial visible; legacy thread (no request_id) fallback.
-
-### Phase D — cleanup
-- Demote/remove `turn_state` ring retention (keep live-turn snapshot only), drop the
- `.md` mirror or mark derived-only, delete the fallback flag.
-
-## Non-goals
-- No change to the socket streaming protocol or delta handling.
-- No SQLite consolidation (sessions.db stays an index; separate discussion).
-- Phase 3 of the timeline refactor (dedup consolidation) remains its own track.
-
-## Risks
-- **Old-core / new-file compat** — unknown `kind` lines must be skipped, not fatal.
-- **File growth** — append-only grows; mitigate later with Codex-style zstd of old
- sessions; out of scope here.
-- **Sanitization false positives** — prefer tagging + frontend hiding over deletion.
diff --git a/docs/plans/tui-chat-plan.md b/docs/plans/tui-chat-plan.md
deleted file mode 100644
index 84e1d8d5df..0000000000
--- a/docs/plans/tui-chat-plan.md
+++ /dev/null
@@ -1,100 +0,0 @@
-# Plan: `openhuman tui` — feature-gated terminal chat UI
-
-> Historical v1 plan. The shipped CLI now extends this foundation into a Logs-first four-tab UI
-> (Logs, Chat, Config, Settings). Bare `openhuman` auto-launches only with terminal stdin/stdout on
-> a non-container host; `--no-tui` suppresses that default and explicit `openhuman tui` still forces
-> the UI. Config uses curated safe getters/updaters, and Settings uses registered auth controllers.
-
-## Goal
-
-Running `openhuman-core tui` (alias `chat`) opens a ratatui-based terminal UI that is an
-interface into the general chat (the same `web_chat` surface the desktop app uses),
-gated behind a Cargo feature `tui`.
-
-## Architecture decisions (grounded in current code)
-
-1. **Cargo feature**: `tui = ["dep:ratatui", "dep:crossterm"]`, added to `default`
- (repo convention: gates default-ON). It must NOT ship in the desktop app —
- add `'tui': 'Terminal UI subcommand; the desktop app ships its own Tauri UI.'`
- to `INTENTIONALLY_NOT_FORWARDED` in `scripts/ci/check-feature-forwarding.mjs`.
-2. **Module**: crate-level `src/tui/`, gated at its declaration in `src/lib.rs`:
- - `mod.rs` always compiled; real submodules `#[cfg(feature = "tui")]`;
- `#[cfg(not(feature = "tui"))] mod stub;` exposing the same `run_from_cli`.
- - `stub.rs` `run_from_cli` bails with
- `"tui feature disabled at compile time … rebuild with --features tui"`
- (mirror `src/openhuman/mcp/server/stub.rs:42`).
- - No controllers, no agent tools, no `all.rs` changes (leaf client, like `flows`'
- philosophy: absence, not degraded registration — but here the only outside
- touch-point is the CLI arm, which uses the stub for a build-fact error).
-3. **CLI arm**: in `src/core/cli.rs` match (~line 63), add
- `"tui" | "chat" => run_tui_from_cli(&args[1..])`.
- Arm stays **un-cfg'd** (mcp precedent). Add `"tui" | "chat"` to the banner-suppression
- `matches!` at lines 48–50 (a TUI must own the terminal).
-4. **In-process core, no HTTP**: build a multi-thread tokio runtime with
- `AGENT_WORKER_STACK_BYTES` stack (copy `run_server_command` shape, cli.rs:219–311),
- then `CoreBuilder::new(HostKind::Cli).domains(DomainSet::full()).services(ServiceSet::none()).build()`.
- `channel.web_chat` needs `DomainGroup::Channels`, so `harness()` is not enough.
-5. **Chat flow**:
- - `client_id = "tui-<random hex>"`.
- - Threads via `runtime.invoke("threads.list"| "threads.create_new", …)`;
- CLI flags: `--thread <id>`, `--new` (default: create new thread).
- - Send turn: `runtime.invoke("channel.web_chat", {client_id, thread_id, message, …})`
- (schema: `src/openhuman/web_chat/schemas.rs:45`; ops entry `ops.rs:1199`/`start_chat` at 391).
- - Stream: drain `web_chat::subscribe_web_channel_events()` (broadcast bus,
- `src/openhuman/web_chat/event_bus.rs:14`), filter by our `client_id`.
- Render `text_delta`/`thinking_delta` (`delta`, `delta_kind` fields on
- `WebChannelEvent`, `src/core/socketio.rs:98`), show `tool_call`/`tool_result`
- as status lines, finish on `chat_done` (use `full_response` as authoritative
- final text) or `chat_error` (show `message`).
- - Cancel in-flight turn: `channel.web_cancel` on Esc.
-6. **UI v1 scope** (keep it tight):
- - Alternate screen + raw mode; transcript viewport with scrollback
- (PgUp/PgDn/mouse optional), single-line input box, status bar
- (thread id, model/turn state, key hints), spinner while streaming.
- - Keys: Enter=send, Esc=cancel turn, Ctrl+N=new thread, Ctrl+C/Ctrl+D=quit.
- - Distinguish user / assistant / thinking (dim) / tool activity / errors.
- Ocean-ish accent per design tokens is fine but keep it terminal-native.
-7. **Terminal hygiene (critical)**:
- - Panic hook + Drop guard that restores the terminal (leave raw mode,
- LeaveAlternateScreen) before the panic message prints.
- - **Logging must not hit stdout/stderr while the TUI owns the terminal** —
- inspect how `run_from_cli`/`run_server_command` init logging
- (`src/core/logging.rs`) and route core logs to file only (or suppress console)
- for the tui arm. Core boot logs corrupting the UI is a bug.
-8. **Separation for testability**: pure state module (`transcript.rs` or `state.rs`)
- holding a reducer `apply_event(&mut TranscriptState, &WebChannelEvent)` with no
- terminal deps — unit-testable. Rendering (`render.rs`) and event loop (`app.rs`)
- stay thin.
-
-## Tests / verification (definition of done)
-
-- Unit tests for the reducer: text_delta accumulation, thinking vs text separation,
- chat_done replaces with full_response, chat_error, ignores other client_ids,
- tool_call/result lines.
-- `src/core/cli_tests.rs`: `tui_subcommand_reports_disabled_build_when_gate_off`
- (+ `chat` alias) under `#[cfg(not(feature = "tui"))]`, mirroring the mcp tests
- (assert error contains "tui feature disabled" and NOT "unknown namespace").
-- Builds (Apple Silicon: prefix `GGML_NATIVE=OFF`):
- - `cargo check --manifest-path Cargo.toml`
- - `cargo check --no-default-features` (disabled build)
- - `cargo test --lib core::cli` and the tui module tests, both feature directions:
- `cargo test --lib --no-default-features core::`
-- `node scripts/ci/check-feature-forwarding.mjs` passes with the allowlist entry.
-- `cargo fmt` clean.
-
-## Docs
-
-- AGENTS.md: add `tui` row to the feature table + a short gate section
- (leaf-ish gate, sheds `ratatui`+`crossterm`, intentionally not forwarded to desktop).
-- `src/openhuman/platform/about_app/`: add user-facing feature entry for the terminal chat UI.
-
-## Non-goals (v1)
-
-- No thread-picker UI beyond `--thread/--new` flags, no markdown rendering,
- no image/artifact display, no approval-request interaction (surface as a status
- line telling the user to handle it elsewhere), no remote-core (HTTP) mode.
-
-## Workflow
-
-Small focused commits on `feat/tui-chat` in this worktree; don't push.
-Debug logging with `[tui]` prefix on all state transitions.
diff --git a/docs/resource-profiling-session-2026-07-21.md b/docs/resource-profiling-session-2026-07-21.md
deleted file mode 100644
index 63ecf587b3..0000000000
--- a/docs/resource-profiling-session-2026-07-21.md
+++ /dev/null
@@ -1,503 +0,0 @@
-# OpenHuman resource profiling session
-
-Date: 2026-07-21
-Platform: Apple Silicon macOS 26.5.1
-Worktree: `worktrees/tauri-resource-profiler`
-Primary question: What CPU and RAM does OpenHuman consume, which components account for it, and what would it take to use the Rust core as an efficient embedded library?
-
-## Executive summary
-
-The desktop application's large footprint is primarily outside the Rust core. The full Tauri/CEF process family measured about 1.2-1.4 GiB depending on CEF prewarming and spaCy. Disabling CEF prewarming saved about 86 MiB, and disabling spaCy after that saved another 146 MiB.
-
-The Rust core is much smaller:
-
-- A warmed one-agent roster used 38.7 MiB RSS with default features and 35.5 MiB in a slim build.
-- Growing from one to eight warmed agents cost only about 0.40 MiB per additional agent.
-- Ingesting 100 representative chat messages retained about 9.3 MiB and completed in about 2.25 seconds.
-- A cold chat turn that spawned two real subagents increased RSS by about 26-31 MiB, depending on feature selection and run conditions.
-- That subagent increase is overwhelmingly a first-use cost. After one complete warm-up turn, another equivalent turn added only 0.52 MiB with persistence disabled or 1.84 MiB with normal memory capture enabled.
-
-There is no single Rust module holding 45 MiB of live data. In the clean slim-build snapshot at approximately 42 MiB total RSS:
-
-- only 15.2 MiB was private physical footprint;
-- only 3.18 MiB was active heap allocation;
-- 18.7 MiB was resident executable code from the OpenHuman binary;
-- the malloc zones retained 9.4 MiB despite only about 3.2 MiB being live, indicating substantial allocator high-water retention/fragmentation.
-
-The most actionable module-level findings are:
-
-1. Parent and child agents each initialize full memory/SQLite infrastructure.
-2. TinyCortex's multilingual PII `RegexSet` and its regex caches dominate the identified live Rust heap growth during normal memory capture.
-3. The first turn touches about 15 MiB of previously nonresident OpenHuman executable code.
-4. Built-in agent TOML parsing, agent construction, unified-memory construction, and SQLite initialization dominate cold-path CPU.
-5. Compile-time feature selection reduces binary size dramatically but reduces live RSS only moderately.
-
-## Scope and methodology
-
-The session used three progressively narrower boundaries:
-
-1. The complete Tauri desktop process family, including CEF and helper processes.
-2. The standalone Rust core with no Tauri host.
-3. Direct Rust library paths for agent construction, memory ingestion, chat orchestration, and subagent delegation.
-
-All Rust measurements used release builds. Network inference was replaced by a deterministic provider behind the default-off `rss-bench` feature. The subagent scenario still used the real `LongLivedSession`, built-in agent registry, agent builder, `spawn_parallel_agents` tool, two researcher agents, memory infrastructure, prompt enforcement, and post-turn hooks.
-
-RSS was sampled every 5 ms during measured workloads. On macOS, the profiler obtains:
-
-- current RSS from `proc_pid_rusage`;
-- peak RSS from `getrusage`;
-- thread count from `proc_pidinfo`;
-- binary size from the running executable.
-
-macOS does not expose Linux `/proc`-style PSS and private clean/dirty page fields through the same interface, so those JSON fields remain zero. `vmmap`, `heap`, `malloc_history`, Instruments Allocations, and Samply were used for deeper attribution.
-
-Unless stated otherwise, summarized Rust results are medians from five fresh processes. CPU samples from `/usr/bin/time` are representative runs rather than five-run medians.
-
-## Desktop/Tauri measurements
-
-These measurements aggregate the desktop process family rather than only the Rust process.
-
-| Configuration | Mean RAM | Change |
-| ------------------------------ | ----------: | ---------------: |
-| Default CEF prewarm and spaCy | 1,439.8 MiB | baseline |
-| CEF prewarm disabled | 1,353.5 MiB | -86.3 MiB |
-| CEF prewarm and spaCy disabled | 1,207.6 MiB | -232.2 MiB total |
-
-The clearest desktop optimizations are therefore:
-
-- initialize spaCy lazily only when memory-tree operations require it;
-- avoid permanent CEF prewarming, or make the prewarm process short-lived;
-- keep accessibility snapshots and `osascript`-based probes event-driven and rate-limited rather than continuously polling.
-
-These desktop results motivated isolating the Rust core: most of the shipped application's memory is not explained by core agent objects.
-
-## Bare Rust agent roster
-
-The existing `rss-bench` binary constructs real OpenHuman agents without Tauri and measures stable RSS in fresh child processes.
-
-### Default feature build
-
-| Roster | Median RSS | Threads | Binary size |
-| -------- | --------------------: | ------: | ----------: |
-| 1 agent | 39,616 KiB / 38.7 MiB | 22 | 115.9 MiB |
-| 8 agents | 42,480 KiB / 41.5 MiB | 24 | 115.9 MiB |
-
-The seven additional agents added 2,864 KiB in total, or approximately 409 KiB per agent. The fixed runtime and linked-code cost is much larger than the marginal agent object cost.
-
-### Slim feature build
-
-The slim binaries were built with:
-
-```bash
-GGML_NATIVE=OFF cargo build --release \
- --no-default-features --features rss-bench \
- --bin rss-bench --bin library-profile
-```
-
-| Roster | Median RSS | Binary size |
-| -------- | --------------------: | ----------: |
-| 1 agent | 36,368 KiB / 35.5 MiB | 68.4 MiB |
-| 8 agents | 39,584 KiB / 38.7 MiB | 68.4 MiB |
-
-Feature selection reduced the profiling binary by about 40%, but reduced one-agent RSS by only 3.2 MiB. Compile-time gates are very valuable for download and embedding size, but they are not sufficient by themselves to minimize the active working set.
-
-## Rust-only memory ingestion
-
-The `memory-ingest` scenario creates an isolated workspace, disables local inference, Python, spaCy, and embeddings, then sends 100 representative chat messages through the real canonicalization, ingestion, admission, persistence, and memory-queue drain paths.
-
-### Default features
-
-| Metric | Median |
-| ---------------------- | -----------------------: |
-| Duration | 2,251 ms |
-| Baseline RSS | 16,624 KiB / 16.2 MiB |
-| Settled RSS | 26,144 KiB / 25.5 MiB |
-| Retained/peak increase | 9,536 KiB / 9.31 MiB |
-| Throughput | about 44 messages/second |
-
-### Slim features
-
-| Metric | Median |
-| ---------------------- | --------------------: |
-| Duration | 2,313 ms |
-| Baseline RSS | 15,536 KiB / 15.2 MiB |
-| Settled RSS | 24,320 KiB / 23.8 MiB |
-| Retained/peak increase | 8,784 KiB / 8.58 MiB |
-
-The feature change reduced settled RSS by about 1.8 MiB and had no meaningful throughput benefit.
-
-A representative default-feature `/usr/bin/time -l` run reported 0.18 seconds user CPU and 0.69 seconds system CPU. This should be treated as an upper bound: sampling RSS every 5 ms adds macOS process-inspection system calls, and the workload also performs real temporary-workspace I/O.
-
-## Rust-only subagent chat
-
-The `subagents` scenario uses a deterministic local provider but otherwise follows the real orchestration path:
-
-1. Build a long-lived subconscious session.
-2. Submit a promoted chat message.
-3. Call the real `spawn_parallel_agents` tool.
-4. Spawn two real `researcher` agents with separate ownership scopes.
-5. Verify that both child prompts were executed.
-6. Measure baseline, peak, and settled RSS.
-
-### Cold default-feature result
-
-| Metric | Median |
-| ---------------------- | --------------------: |
-| Duration | 163 ms |
-| Baseline RSS | 18,192 KiB / 17.8 MiB |
-| Settled RSS | 49,712 KiB / 48.5 MiB |
-| Retained/peak increase | 31,520 KiB / 30.8 MiB |
-
-A representative process used 0.04 seconds user CPU and 0.06 seconds system CPU. Model and network latency are deliberately excluded.
-
-### Cold slim-feature result
-
-| Metric | Median |
-| ---------------------- | --------------------: |
-| Duration | 158 ms |
-| Baseline RSS | 17,072 KiB / 16.7 MiB |
-| Settled RSS | 43,392 KiB / 42.4 MiB |
-| Retained/peak increase | 26,304 KiB / 25.7 MiB |
-
-The slim build saved about 6.2 MiB of settled RSS in this richer workload.
-
-## Deep memory attribution
-
-### Clean normal snapshot
-
-A non-instrumented slim-build run with normal memory capture settled at 43,104 KiB RSS, or 42.1 MiB.
-
-| VM/heap measurement | Result |
-| ------------------------------------- | ------------: |
-| Total RSS | 42.1 MiB |
-| Private physical footprint | 15.2 MiB |
-| Approximate clean/file-backed portion | 26.9 MiB |
-| Live heap allocations | 3.18 MiB |
-| Resident malloc regions | about 9.4 MiB |
-| Resident stacks | 0.97 MiB |
-| Resident OpenHuman executable text | 18.7 MiB |
-
-These categories overlap and must not be added together. For example, active heap and stacks are part of the private footprint, while executable text is part of clean/file-backed RSS.
-
-The key interpretation is that RSS is not equivalent to private heap. The process reports roughly 42 MiB RSS while holding only about 3.2 MiB of live heap allocations.
-
-### First-use executable paging
-
-Before the chat turn, only about 3.3 MiB of the profiling executable's `__TEXT` segment was resident. After the turn, 18.7 MiB was resident. The first turn therefore faulted in approximately 15.4 MiB of OpenHuman's own executable code.
-
-CoreFoundation, Foundation, ICU, Security, CoreAudio, and other macOS framework `__TEXT` residency was effectively identical in the controlled baseline and post-turn snapshots. The increase came from the OpenHuman executable, not from a single newly loaded macOS framework.
-
-Executable pages are clean, file-backed, reclaimable under pressure, and shareable between identical processes. They count toward RSS but are not the same as permanently retained private data.
-
-### Allocator retention
-
-The normal snapshot had about 3.2 MiB of active allocations inside approximately 9.4 MiB of resident malloc pages. Roughly 6 MiB was therefore allocator slack, fragmentation, size-class pages, or high-water retention after the burst of first-turn allocations.
-
-This does not prove a leak. A repeated-turn plateau test is more meaningful than expecting macOS RSS to immediately return to its pre-turn value.
-
-### Memory capture and PII cost
-
-A controlled profiler switch disabled both:
-
-- `memory.auto_save`;
-- `learning.episodic_capture_enabled` and its archivist hook.
-
-With those writes disabled, the median cold-turn increase fell from about 25.9 MiB to 22.0 MiB, saving approximately 3.8 MiB.
-
-Stack-logged allocations identified TinyCortex's multilingual PII sanitizer as the dominant live Rust allocation family during normal memory capture. Important allocations originated from:
-
-- `tinycortex::memory::store::safety::pii::SCREEN`;
-- the combined `RegexSet` NFA;
-- per-thread hybrid-DFA regex caches;
-- calls through `sanitize_text`, document upsert, FTS5 episodic insertion, autosave, and the archivist hook.
-
-The `SCREEN` implementation is described as a cheap prefilter, but its large multilingual, Unicode-aware combined automaton is not cheap in retained memory. A byte-oriented candidate scan followed by targeted regex evaluation is a promising replacement.
-
-### Prompt-injection detector
-
-With memory writes disabled, the next visible regex allocation family came from `prompt_injection::detector::DETECTION_RULE_SET`. It was materially smaller than the TinyCortex PII machinery, on the order of a few hundred KiB in this workload.
-
-This is not currently a first-priority RAM optimization, but its scratch/cache strategy should be considered if agent turns become highly parallel.
-
-### Timezone control
-
-`current_datetime_line` normally calls `iana_time_zone`, which uses CoreFoundation on macOS. Forcing the profiling build to use UTC saved only about 0.5-0.6 MiB in the isolated subagent scenario. This is measurable but not a primary explanation for the 42-49 MiB working set.
-
-## Cold-path CPU attribution
-
-A symbolized Samply profile was recorded across repeated no-network, no-memory-write, UTC-controlled runs. Inclusive percentages overlap because a sample contributes to every parent frame in its call stack.
-
-| Cold-path component | Approximate inclusive CPU |
-| -------------------------------------- | ------------------------: |
-| Built-in agent registry initialization | 17% |
-| `LongLivedSession::build_agent` | 16% |
-| `Agent::from_config_for_agent` | 15% |
-| Built-in agent TOML parsing/loading | 13% |
-| Unified-memory construction | 10% |
-| SQLite/unified-memory initialization | 7% |
-| Actual TinyAgents turn runner | 5% |
-
-The profile also showed `Config::load_or_init`, config serialization/migrations, filesystem synchronization, tool-policy cloning, prompt-injection initialization, and runtime task scheduling.
-
-The built-in registry is initialized before the profiler's RSS baseline, so its CPU appears in the whole-process profile but its already-resident pages are part of the baseline rather than the measured turn delta.
-
-## Warmed-process control
-
-The most important experiment prewarmed one complete two-subagent turn, dropped that warm-up session, then measured a new session performing the same workload in the same process.
-
-| Subsequent equivalent turn | Median duration | Median added RSS |
-| ----------------------------------- | --------------: | -------------------: |
-| Persistence disabled and UTC forced | 46 ms | 528 KiB / 0.52 MiB |
-| Normal memory capture | 60 ms | 1,888 KiB / 1.84 MiB |
-
-One normal-memory repetition was an 8.3 MiB outlier, consistent with asynchronous persistence or allocator behavior; the other four were between about 1.4 and 1.9 MiB.
-
-This result changes the interpretation of the cold 26-31 MiB increase. It is overwhelmingly initialization, code paging, global regex/cache construction, and allocator high-water behavior. It is not a linear 26 MiB cost per chat turn.
-
-## Library-design implications
-
-OpenHuman is feasible as a Rust library, but the current construction path behaves like an application bootstrap rather than a lightweight per-instance library API.
-
-### Share services between agents
-
-`Agent::build_session_agent_inner` constructs session memory and obtains a SQLite connection for the agent. Parent and child agents should instead receive shared instance services such as:
-
-```text
-OpenHumanLibrary
- Arc<ConfigSnapshot>
- Arc<AgentDefinitionRegistry>
- Arc<ToolCatalog>
- Arc<MemoryServices>
- Arc<ProviderRegistry>
- Arc<EventBus>
-```
-
-Subagents should borrow or clone these `Arc` handles rather than rebuilding configuration, memory stores, schema state, providers, and tool catalogs.
-
-### Offer explicit warm-up
-
-A library API should expose an optional warm-up method that initializes predictable first-use costs:
-
-- built-in agent definitions;
-- prompt and PII detectors;
-- memory schemas and connection pools;
-- tool catalogs and policy snapshots;
-- provider routing;
-- commonly used prompt fragments.
-
-This lets latency-sensitive hosts choose between low startup work and predictable first-message latency.
-
-### Separate runtime and compile-time slimness
-
-`DomainSet` is useful for runtime surface selection, but runtime-disabled code remains linked. Library consumers need documented compile-time feature recipes or a dedicated library/harness feature set so unrelated domains never enter the binary.
-
-### Avoid mandatory globals
-
-The profiling harness currently has to initialize a global event bus, a global built-in registry, environment-derived workspace selection, and a global provider override. Instance-owned state would make it safer to embed multiple OpenHuman instances in one process and would improve deterministic testing.
-
-## Recommended optimization order
-
-1. **Share unified-memory and SQLite services between parent and child agents.** This is the clearest architectural duplication in the cold path.
-2. **Replace the TinyCortex PII `RegexSet` screen with a lightweight candidate scan.** Preserve the strict regex/checksum validation after a candidate is found.
-3. **Add a warmed repeated-turn benchmark to CI or the local profiling suite.** Track both cold-start and steady-state behavior so one does not obscure the other.
-4. **Provide a supported library-minimal feature recipe.** Measure binary size, cold code paging, and steady RSS for that exact recipe.
-5. **Reuse temporary prompt, tool-schema, and sanitizer buffers.** Reduce burst allocation and malloc-zone fragmentation.
-6. **Benchmark an alternate allocator only in the profiling binary.** This can reveal how much of the 6 MiB malloc slack is allocator-specific, but the library should not impose a global allocator on consumers.
-7. **Add per-phase checkpoints.** Measure config load, agent build, memory construction, prompt render, delegation, child execution, merge, hooks, and teardown separately.
-
-## Functional observation
-
-In the deterministic `LongLivedSession` workload, both parallel child agents executed, but the session returned the last subagent result rather than performing the prepared parent synthesis response. Direct `Agent::turn` tests cover synthesis behavior elsewhere, so the long-lived-session boundary deserves a focused correctness audit. This is separate from the resource findings but was exposed by the same harness.
-
-## Reproducing the measurements
-
-Build the default-feature profiling binaries:
-
-```bash
-GGML_NATIVE=OFF cargo build --release --features rss-bench \
- --bin rss-bench --bin library-profile
-```
-
-Build the slim versions:
-
-```bash
-GGML_NATIVE=OFF cargo build --release \
- --no-default-features --features rss-bench \
- --bin rss-bench --bin library-profile
-```
-
-Run the bare roster benchmark:
-
-```bash
-target/release/rss-bench --repeat 5 \
- --out target/profile/rust-library/bare-agents.json
-```
-
-Run stateful library workloads:
-
-```bash
-target/release/library-profile memory-ingest
-target/release/library-profile subagents
-```
-
-Measure a warmed subagent turn:
-
-```bash
-OPENHUMAN_PROFILE_PREWARM_SUBAGENTS=1 \
- target/release/library-profile subagents
-```
-
-Isolate orchestration from persistence and local timezone initialization:
-
-```bash
-OPENHUMAN_PROFILE_DISABLE_MEMORY_WRITES=1 \
-OPENHUMAN_PROFILE_FORCE_UTC=1 \
- target/release/library-profile subagents
-```
-
-Hold a process at its baseline or settled state for `vmmap`, `heap`, or `malloc_history`:
-
-```bash
-OPENHUMAN_PROFILE_HOLD_BEFORE_SECS=120 \
- target/release/library-profile subagents
-
-OPENHUMAN_PROFILE_HOLD_SECS=120 \
- target/release/library-profile subagents
-```
-
-Example live inspection:
-
-```bash
-vmmap -summary <pid>
-heap -sH <pid>
-
-MallocStackLogging=1 OPENHUMAN_PROFILE_HOLD_SECS=120 \
- target/release/library-profile subagents
-malloc_history <pid> -allBySize
-```
-
-Record a symbolized CPU profile:
-
-```bash
-OPENHUMAN_PROFILE_DISABLE_MEMORY_WRITES=1 \
-OPENHUMAN_PROFILE_FORCE_UTC=1 \
-samply record --save-only --unstable-presymbolicate \
- --rate 1000 --iteration-count 5 \
- --output target/profile/rust-library/subagents-cpu.json.gz \
- -- target/release/library-profile subagents
-```
-
-## Artifacts and code added during the session
-
-- `src/bin/library_profile/main.rs`: hermetic memory-ingestion and subagent workloads, peak RSS sampler, isolation controls, warm-up control, and debugger hold points.
-- `src/openhuman/platform/proc_metrics/mod.rs`: macOS RSS, peak RSS, thread-count, and binary-size sampling.
-- `src/openhuman/inference/provider/factory.rs`: deterministic provider override enabled under the default-off profiling feature.
-- `src/openhuman/inference/provider/ops/provider_factory.rs`: routed-provider support for the same profiling override.
-- `src/openhuman/agent/prompts/render_helpers.rs`: profiling-only UTC control under `rss-bench`.
-- `target/profile/rust-library/`: ignored JSON, Instruments, and Samply artifacts from local runs.
-
-None of the profiling binaries or provider overrides enter normal shipped builds because they require the default-off `rss-bench` feature.
-
-## Validation completed
-
-- Default-feature release builds of `rss-bench` and `library-profile`.
-- Slim release builds using `--no-default-features --features rss-bench`.
-- Five-run fresh-process repetitions for the main scenarios.
-- macOS process-metric unit test.
-- Existing datetime prompt test with `rss-bench` enabled.
-- `cargo fmt --check`.
-- `git diff --check`.
-
-Repository warnings observed during builds were pre-existing unused-import/dead-code and future-incompatibility warnings; no new build failure was introduced by the profiling harness.
-
-## Bottom line
-
-OpenHuman's Rust core is not holding 45 MiB of agent objects. The steady process is mostly executable working set plus runtime/allocator pages, with a small live heap. The cold first turn is expensive because it initializes and touches a broad application-oriented path. Once warmed, subagent turns are inexpensive and appear to plateau rather than grow linearly.
-
-The best route to an efficient library is therefore not micro-optimizing every agent struct. It is narrowing and sharing the initialization graph: reuse memory and SQLite services, avoid rebuilding agent infrastructure for children, simplify the PII prefilter, expose an explicit warm-up lifecycle, and provide a compile-time library-minimal profile.
-
----
-
-## Addendum: library benchmarking session (2026-07-22)
-
-The follow-up session turned the manual investigation above into a permanent
-benchmark environment, executed two of the recommended optimizations, and
-answered the deployment-density question. Full detail lives in
-[`library-benchmarking.md`](library-benchmarking.md); this addendum records
-the deltas against this document.
-
-### What was built
-
-- **Ten hermetic scenarios** in `library-profile` (was two): `agent-turn`,
- `long-agent`, `workflow`, `subconscious`, `cold-phases`, `fleet`,
- `skill-run`, `subagent-storm` joined `memory-ingest`/`subagents`. All
- offline, mock-provider, JSON schema v2 with per-phase/per-turn checkpoints.
-- **Five driver scripts** under `scripts/profile/`: `library-bench.sh`
- (medians + summary), `library-fleet.sh` (agent-count sweep with a
- 2 GB/2 vCPU pass/fail gate), `library-instances.sh` (many-processes model),
- `library-cpu.sh` (samply), `library-heap.sh` (dhat).
-- **Professional profilers wired in**: dhat behind the default-off
- `rss-bench-dhat` feature; samply scripted; `proc_metrics` extended with
- CPU-time, fd counts, and a descendant process-tree sampler (`tree.rs`).
-
-### Headline results (Apple Silicon, default build unless noted)
-
-| Question | Answer |
-| --- | --- |
-| Cold turn cost, any shape (chat/subconscious/delegation/workflow) | ~29-30 MiB retained — shared bootstrap, not workload |
-| Warmed long-agent growth | 30-150 KiB/turn plateau; occasional 6-8 MiB async persistence bursts |
-| Live heap vs RSS (dhat, agent-turn) | 33.4 MB total allocated, 5.0 MB peak live, 3.1 MB at exit |
-| Fleet marginal per in-process agent | ~1.7-2.0 MiB (N=50/100/500 sweep) |
-| Idle CPU, parked fleet | ~3 ms per 10 s at every N |
-| **1000 agents in 2 GiB (one process)** | **PASS — projected ~1747 MiB @ 1000; real 500-agent run settled 1393 MiB** |
-| Same workload as N processes | ~48 MiB/instance flat → only ~42 instances per 2 GiB; one-process model is ~25x denser |
-| True cost of a JS skill run | node child ~72-75 MB RSS (tree ~121 MB vs ~51 MB self) |
-| Marginal per parallel subagent (storm K=8→32) | ~0.78 MiB |
-| Library-minimal build (`--no-default-features --features skills,flows`) | 81 MiB binary (60 stripped) vs 116; RSS -3.5 to -4.7 MiB |
-
-### Changes landed
-
-- **PII prefilter replaced upstream** (recommendation 2 above):
- tinycortex#119 swaps the resident 17-pattern `RegexSet` + per-thread DFA
- caches for a single-pass byte candidate scan gating lazily-compiled
- per-class regexes; superset-verified against the old set, no common-path
- heap regression, wins scale with thread/agent concurrency. Merged with
- #120 (unrelated rustdoc fix); submodule bumped.
-- **Library-minimal recipe** documented and measured
- ([`library-minimal-recipe.md`](library-minimal-recipe.md)); ranked
- follow-up sheds identified (an `inference` gate for whisper/GGML first).
-- **Harness comparison** ([`harness-comparison-2026-07-22.md`](harness-comparison-2026-07-22.md)):
- the scope-matched peer (Hermes, Python) self-reports ~10x our RSS; the
- ZeroClaw "7.8-12 MiB under load" figure has no locatable primary source and
- is now flagged unverified wherever cited. Our in-process ~2 MiB marginal
- scaling has no equivalent among the surveyed harnesses.
-
-### New watch-items surfaced by the fleet sweep
-
-1. **Thread growth ~0.35/agent** (71 @ N=50 → 211 @ N=500, →~420 projected at
- 1000). Attribute (SQLite? blocking pool?) and cap before 1000-agent runs.
-2. **CPU, not memory, is the load constraint on 2 workers**: p95 turn latency
- 25.5 s at N=500 under 200 ms mock latency. Scheduling/backpressure design
- matters more than RAM once the fleet is dense.
-3. **Interpreter children break the budget**: pooling/sharing the node and
- python runtimes is filed as tinyhumansai/openhuman#5106 — without it,
- ~25 concurrent JS skill runs exhaust the whole 2 GiB box.
-
-### Updated optimization order
-
-1. Shared services between parent/child agents (unchanged, still first; the
- fleet benchmark is its regression instrument).
-2. ~~PII prefilter~~ — done, merged upstream.
-3. Runtime pooling for node/python (#5106) — new, promoted to near-top by the
- skill-run measurement.
-4. Thread-growth attribution and cap (new).
-5. Warm-up API, allocator experiment, per-phase checkpoints in CI — the
- checkpoints now exist (`cold-phases`); CI wiring remains.
-6. `inference` compile gate (whisper/GGML) for the library-minimal profile.
-
-### Next: the live desktop app
-
-The same rigor now needs to reach the shipped Tauri/CEF app (the ~1.2-1.4 GiB
-family this document opened with). The prepared brief for that session —
-scenarios, reusable assets, gates — is
-[`tauri-live-profiling-brief.md`](tauri-live-profiling-brief.md).
diff --git a/docs/specs/2026-07-23-pr-5125-review-fixes-design.md b/docs/specs/2026-07-23-pr-5125-review-fixes-design.md
deleted file mode 100644
index 026243b3e8..0000000000
--- a/docs/specs/2026-07-23-pr-5125-review-fixes-design.md
+++ /dev/null
@@ -1,69 +0,0 @@
-# PR #5125 Review Fixes Design
-
-## Objective
-
-Address every actionable unresolved review thread on PR #5125 without broadening
-the already-large core-slimming change. Preserve the intended removal and
-relocation boundaries while restoring behavior that the migration accidentally
-dropped.
-
-## Approach
-
-Work in small review clusters and commit each validated cluster separately:
-
-1. Companion lifecycle and transport:
- - Centralize terminal cleanup so manual stop and TTL expiry cancel the active
- turn, stop microphone capture, remove the session, and emit an Idle state.
- - Let cancelled and empty-transcript turns return Listening to Idle without
- clobbering a newer capture.
- - Register the configured global hotkey when the user starts a companion
- session.
- - Resolve companion chat requests against the OpenHuman backend base, never a
- user-configured inference URL carrying different credentials.
-2. Persistence concurrency:
- - Clear goal continuation suppression through the tinyagents atomic mutation
- path, retaining the current goal identity and concurrent usage/status
- changes.
- - Serialize every thread-board read/modify/write mutation with the existing
- per-board async lock.
- - Verify that the already-updated boot migration path completes before
- runtime writers become available and does not block a Tokio worker.
-3. Product surfaces:
- - Restore the always-on listening switch in the Voice settings panel using
- the existing voice settings RPC.
- - Restore companion data-movement disclosure in the capability catalog.
- - Remove the stale launch-app catalog entry if it remains in current HEAD.
-4. Test and E2E alignment:
- - Replace or remove scenarios that target deleted autocomplete routes or the
- removed WhatsApp core RPC. Prefer the supported Tauri command path when the
- behavior still ships.
- - Add focused regression tests for every behavior-changing fix.
-
-Outdated review threads will be checked against current HEAD. If a later commit
-already fixed the reported behavior, no duplicate code change will be made; the
-thread will be resolved with the validating evidence.
-
-## Error Handling and Safety
-
-- Cleanup is idempotent: repeated stop, expiry, or cancellation calls must not
- panic or affect a newer session or turn.
-- Session credentials are sent only to the canonical backend origin.
-- Goal and board mutations must not reintroduce stale snapshot writes.
-- Removed product surfaces stay removed; fixes restore only behavior that still
- exists in the shipped desktop application.
-
-## Validation
-
-Each cluster receives its narrowest meaningful tests before its atomic commit.
-Final validation covers:
-
-- Rust formatting and targeted core tests.
-- Targeted Tauri companion tests and Tauri `cargo check`.
-- Targeted frontend tests, typecheck, lint, and formatting.
-- E2E inventory/script checks for retired scenarios.
-- Relevant default and disabled-feature core checks where touched code crosses
- compile-time gates.
-
-After all local checks pass, push the branch and poll PR checks plus unresolved
-review threads until required checks are successful and no actionable feedback
-remains.
diff --git a/docs/specs/2026-07-24-appimage-sharun-lib-path-design.md b/docs/specs/2026-07-24-appimage-sharun-lib-path-design.md
deleted file mode 100644
index 0b50a0f192..0000000000
--- a/docs/specs/2026-07-24-appimage-sharun-lib-path-design.md
+++ /dev/null
@@ -1,215 +0,0 @@
-# AppImage sharun library-path repair
-
-## Context
-
-Issue #5037 reports that Linux AppImages fail when launched outside their
-extracted AppDir. The launcher logs that `anylinux.so` cannot be preloaded and
-then fails to resolve `libxdo.so.3`, even though both libraries are bundled.
-Running the extracted application with an explicit AppDir-rooted
-`LD_LIBRARY_PATH` succeeds.
-
-Read-only analysis verified the final v0.61.2 and v0.63.1 amd64 AppImages:
-
-- `AppRun`, `sharun`, and `bin/OpenHuman` are hard links to the sharun ELF
- launcher.
-- The real application is `shared/bin/OpenHuman`.
-- `lib/` contains `anylinux.so`, `libxdo.so.3`, `libcef.so`, `libssl.so.3`, and
- `libcrypto.so.3`; `shared/lib` is a symlink to `../lib`.
-- `shared/lib/lib.path` contains the bare relative entry `shared/lib`.
-- sharun 2.2.4 and 2.2.5 expand the canonical `+` marker to an absolute path
- rooted at the AppDir's `lib/` directory. They do not anchor a bare
- `shared/lib` entry.
-
-The release postprocessor causes the malformed entry.
-`rewrite_sharun_lib_path` converts absolute CI paths beneath
-`squashfs-root/shared/lib` into `shared/lib`. The intended compensation,
-`patch_apprun_sharun_cwd`, only edits a shell `AppRun` and intentionally skips
-the shipped ELF `AppRun`.
-
-Consequently, `shared/lib` resolves from the caller's current directory. It
-works when the caller happens to be the AppDir and fails from locations such as
-`~/Downloads` or `/tmp`.
-
-## Evidence boundary
-
-Artifact hashes, SquashFS layouts, ELF metadata, release-script behavior, sharun
-path expansion, and caller-directory resolution were verified directly.
-
-This development host is macOS, and its Docker daemon is unavailable, so it
-cannot execute the Linux ELF launcher. An identical v0.63.1 process failure is a
-strong inference from the verified path semantics and must be confirmed by a
-Linux CI smoke test.
-
-## Goals
-
-- Write sharun-native, AppDir-anchored entries to `shared/lib/lib.path`.
-- Reject malformed bare-relative or CI-runner paths before an AppImage ships.
-- Cover the actual ELF `AppRun` layout used by released artifacts.
-- Validate the final repacked AppImage, rather than only the intermediate
- AppDir.
-- Exercise the final launcher from a working directory outside the AppDir on
- Linux.
-- Preserve the existing graphics-library stripping, interpreter repair,
- signing, updater archive, and multi-architecture behavior.
-
-## Non-goals
-
-- Making the unbundled AUR/core binary independent of system `libxdo`.
-- Changing the unconditional `enigo` dependency or voice input behavior.
-- Replacing bundled OpenSSL or claiming to resolve issue #3716's later-stage
- symbol-skew/segfault report.
-- Bypassing sharun with a custom `LD_LIBRARY_PATH` launcher.
-- Pinning mutable quick-sharun downloads; that is a separate supply-chain
- follow-up.
-- Converting the existing PR-quality AppImage job from advisory to blocking.
-
-## Considered approaches
-
-### 1. Emit sharun-native `+` paths and validate them
-
-Rewrite AppDir library roots to sharun's canonical `+` representation. A root
-library directory becomes `+`; any retained directory beneath it becomes a
-`+/subdir` entry. Preserve the format's entry separator without treating the
-marker itself as a separator.
-
-Validation rejects:
-
-- absolute CI runner paths;
-- bare relative entries such as `shared/lib`;
-- traversal components;
-- AppDir-relative targets that do not exist.
-
-This directly restores sharun's intended absolute path expansion and is the
-selected approach.
-
-### 2. Change the working directory in `AppRun.sh`
-
-Patching the shipped shell wrapper or setting a sharun working-directory
-variable could make `shared/lib` resolve by accident. It leaves malformed
-library-path semantics in place, depends on launcher shape, and does not explain
-the existing ELF `AppRun` skip clearly enough to be the primary fix.
-
-### 3. Bypass sharun
-
-A wrapper could execute `shared/bin/OpenHuman` with an explicit absolute
-`LD_LIBRARY_PATH`. This duplicates sharun's loader and portability behavior and
-risks losing its environment and compatibility hooks.
-
-## Design
-
-### Library-path normalization
-
-Refactor `rewrite_sharun_lib_path` in
-`scripts/release/strip-appimage-graphics-libs.sh` so CI-origin entries are
-normalized into sharun-native AppDir library entries.
-
-The normalizer must:
-
-1. Parse entries without destroying the `+` marker.
-2. Recognize CI paths rooted under an extracted `squashfs-root` or the existing
- build `data` layout.
-3. Map the AppDir's canonical library root to `+`, and valid descendants to
- `+/relative/subdir`.
-4. Deduplicate entries while preserving stable order.
-5. Exclude unrelated absolute host paths.
-6. Fail instead of falling back to a bare `shared/lib` entry when no valid
- AppDir library root can be derived.
-7. Be idempotent when the file already contains valid sharun-native entries.
-
-The implementation must follow sharun's actual `lib.path` delimiter grammar as
-confirmed from the bundled sharun version. Tests must pin the accepted textual
-forms rather than rely on an informal reconstruction.
-
-### Fail-closed validation
-
-Extend `validate_sharun_lib_path` to reject any non-empty entry that is:
-
-- a CI/build-machine absolute path;
-- a bare relative path not beginning with the sharun marker;
-- a traversal outside the bundled library root;
-- a marker-relative directory absent from the AppDir.
-
-The validation error must identify the offending entry and refuse to repack or
-publish the artifact.
-
-`patch_apprun_sharun_cwd` may remain as compatibility hardening for historical
-shell AppRun layouts, but the new tests must establish that an ELF AppRun does
-not need this patch once `lib.path` is valid. Comments that describe changing
-the working directory as the primary fix must be updated to reflect that role.
-
-### Regression tests
-
-Extend `scripts/release/test-strip-appimage-rpaths.sh` with isolated cases for:
-
-- a CI absolute `.../squashfs-root/shared/lib` entry rewriting to the canonical
- marker;
-- valid marker/subdirectory entries and stable ordering;
-- deduplication and idempotency;
-- rejection of bare `shared/lib`, CI paths, traversal, and missing targets;
-- the released launcher layout where ELF `AppRun`, `sharun`, and
- `bin/OpenHuman` are hard-linked or equivalent launcher entries;
-- expansion of the rewritten value according to sharun's algorithm, proving it
- resolves beneath the fixture AppDir regardless of the caller's directory.
-
-The test remains Linux-only because it needs ELF fixtures and `patchelf`; it
-continues to skip cleanly on unsupported development hosts.
-
-### Final-artifact validation and smoke
-
-After postprocessing and repacking, Linux CI must inspect the final `.AppImage`
-that will be uploaded:
-
-1. Extract it into a temporary directory.
-2. Re-run the sharun `lib.path`, required-library, ELF `NEEDED`, and RPATH
- validations against the extracted final layout.
-3. Change to an unrelated temporary working directory.
-4. Launch the extracted `AppRun` under a bounded timeout and the existing
- headless/Xvfb facilities.
-5. Fail on preload or loader diagnostics for `anylinux.so`, `libxdo.so.3`, or
- `libcef.so`.
-6. Treat reaching the normal application initialization boundary as success;
- the smoke does not require an interactive desktop session.
-
-The smoke belongs in the Linux desktop build path after
-`Strip host graphics libs from AppImage`, so it exercises the same final
-artifact that later signing/upload steps consume. It must cover amd64 first,
-where #5037 was reproduced, while keeping the validator architecture-neutral so
-arm64 can use it when an executable runner is available.
-
-## Failure behavior
-
-An invalid `lib.path`, missing bundled runtime library, failed final extraction,
-or foreign-CWD loader error fails the Linux artifact build before signing or
-upload. The release must not continue with a warning-only malformed launcher.
-
-The smoke must print the extracted path, caller working directory, normalized
-`lib.path`, and relevant loader diagnostics without leaking credentials.
-
-## Validation
-
-Local/macOS:
-
-- `bash -n scripts/release/strip-appimage-graphics-libs.sh`
-- the regression script skips cleanly when Linux ELF tooling is unavailable;
-- `git diff --check` and repository formatting checks.
-
-Linux:
-
-- run `scripts/release/test-strip-appimage-rpaths.sh` with `patchelf`;
-- run the final-artifact validator against a freshly built amd64 AppImage;
-- launch from a foreign working directory under timeout/Xvfb;
-- confirm no `anylinux.so`, `libxdo.so.3`, or `libcef.so` loader errors;
-- confirm the updater archive/signing flow still consumes the validated
- postprocessed artifact.
-
-## Acceptance criteria
-
-- Final `lib.path` uses only valid sharun-native AppDir entries.
-- Bare `shared/lib` and CI absolute entries fail validation.
-- Rewriting is deterministic and idempotent.
-- Released-style ELF AppRun fixtures are covered.
-- The final repacked amd64 AppImage launches from outside its AppDir without the
- #5037 preload/library-resolution errors.
-- Required bundled libraries, ELF dependencies, and RPATHs remain valid.
-- Existing graphics stripping, signing, updater archive, and non-Linux build
- behavior remain unchanged.
diff --git a/docs/specs/2026-07-24-knip-cleanup-design.md b/docs/specs/2026-07-24-knip-cleanup-design.md
deleted file mode 100644
index 7a1307bf15..0000000000
--- a/docs/specs/2026-07-24-knip-cleanup-design.md
+++ /dev/null
@@ -1,107 +0,0 @@
-# Knip Cleanup Design
-
-## Goal
-
-Remove unreachable frontend files, unused code, and unused package dependencies
-from the OpenHuman app without changing user-visible behavior or deleting
-framework, test, desktop, or tooling entry points that are loaded indirectly.
-
-## Scope
-
-This cleanup is limited to the `openhuman` repository and the
-`openhuman-app` workspace under `app/`. Rust code, vendored repositories,
-generated assets, other umbrella submodules, and unrelated refactors are out of
-scope.
-
-The initial `pnpm knip` baseline reports:
-
-- 34 unused files
-- 2 unused dependencies
-- 10 unlisted dependencies
-- 239 unused value exports
-- additional unused exported types and enum members
-- stale or redundant entries in `app/knip.json`
-
-These findings are candidates, not deletion instructions. Knip cannot always
-see Tauri, Vite, Vitest, WebdriverIO, package-script, or convention-based entry
-points.
-
-## Approach
-
-### 1. Make the analysis trustworthy
-
-Update `app/knip.json` and package declarations so Knip knows about every real
-application, test, desktop, and tooling entry point. Replace transitive
-dependency reliance with direct declarations where source files import a
-package. Remove stale ignores and patterns only when Knip can discover the
-corresponding usage without them.
-
-Configuration changes must be narrow. Broad ignore globs added solely to
-silence findings are not acceptable.
-
-### 2. Verify candidates independently
-
-For each reported file or symbol:
-
-1. Search the repository for static references, re-exports, scripts, generated
- manifests, test configuration, and string-based loading.
-2. Check whether a framework or desktop runtime discovers it by convention.
-3. Classify it as removable, internally used but over-exported, or deliberately
- public.
-
-Files are deleted only when they have no runtime, build, test, documentation, or
-tooling role. Used declarations with unnecessary exports become module-private
-instead of being deleted.
-
-### 3. Remove dead surface in small slices
-
-Apply the cleanup in independently verifiable groups:
-
-1. Knip configuration and dependency declaration corrections.
-2. Unreachable files and dependencies.
-3. Unused value exports and local declarations.
-4. Unused exported types and enum members where removal is source-compatible
- inside the repository.
-
-Each validated group is committed separately with `atomic-commit`, listing
-every touched file explicitly.
-
-### 4. Treat public contracts conservatively
-
-Exports used only by tests may remain exported when they are intentional test
-seams. Package-facing APIs, Tauri integration boundaries, generated-code
-inputs, and documented extension points remain unless repository evidence
-shows they are private and unused.
-
-Any intentional finding that cannot be modeled as an entry point will receive
-the narrowest possible Knip exception and a short reason.
-
-## Validation
-
-After each cleanup group:
-
-- run Knip and confirm the targeted findings disappear without new findings;
-- run TypeScript compilation;
-- run affected Vitest tests;
-- run lint and formatting checks for touched files.
-
-Before completion:
-
-- `pnpm knip`
-- `pnpm typecheck`
-- `pnpm test`
-- `pnpm lint`
-- `pnpm format:check`
-- `pnpm build`
-
-The cleanup is complete when Knip has no unexplained actionable findings, all
-quality gates pass, and the diff contains no behavior changes beyond removal of
-unreachable code and unnecessary export visibility.
-
-## Non-goals
-
-- Redesigning features or module boundaries
-- Changing UI behavior
-- Removing Rust code
-- Updating unrelated dependencies
-- Publishing branches or opening pull requests
diff --git a/docs/specs/2026-07-24-macos-clippy-ci-design.md b/docs/specs/2026-07-24-macos-clippy-ci-design.md
deleted file mode 100644
index 6a0b852efe..0000000000
--- a/docs/specs/2026-07-24-macos-clippy-ci-design.md
+++ /dev/null
@@ -1,129 +0,0 @@
-# macOS Clippy Coverage in CI Full
-
-## Context
-
-Issue #5019 identifies a platform gap in Rust lint coverage. CI Lite runs the
-root-core and Tauri clippy commands on Ubuntu, so code compiled only on macOS is
-not checked with warnings denied. The existing `build-macos-full` job builds the
-Tauri app on `macos-latest`, warming `app/src-tauri/target` (including the
-path-dependent core in that Cargo graph), and feeds its result into the blocking
-CI Full gate. Its Rust cache covers both Cargo workspaces, but the independent
-root `target/` can remain cold on a cache miss.
-
-The repository already owns the authoritative aggregate lint command:
-
-```text
-pnpm rust:clippy
-```
-
-That command runs clippy for the root `openhuman` crate and then the Tauri crate,
-with `-D warnings` configured by the existing package scripts.
-
-## Goals
-
-- Compile and lint macOS-gated Rust with warnings denied.
-- Cover both the root-core and Tauri Cargo worlds.
-- Reuse the existing macOS build job, two-workspace Rust cache, and warmed Tauri
- artifacts.
-- Preserve cancellation-aware behavior for the long-running command.
-- Make lint failures block CI Full through its existing gate topology.
-
-## Non-goals
-
-- Adding macOS runners to CI Lite.
-- Creating a separate macOS lint job that repeats setup and can cold-build both
- Cargo graphs on a cache miss.
-- Changing Rust lint flags or package scripts.
-- Fixing warnings that the new CI step may discover.
-- Changing the existing 60-minute job timeout without runtime evidence.
-
-## Considered approaches
-
-### 1. Lint inside `build-macos-full` after the app build
-
-Add one step after `Build E2E app`:
-
-```yaml
-- name: Clippy (macOS-gated Rust)
- run: bash scripts/ci-cancel-aware.sh pnpm rust:clippy
-```
-
-This reuses the existing runner setup and two-workspace Rust cache. The
-preceding build warms the Tauri target, while the independent root target may
-still require compilation on a cache miss. The step adds no new job dependency
-and naturally blocks the existing macOS build and CI Full gates.
-
-This is the selected approach.
-
-### 2. Add a separate macOS clippy job
-
-This makes lint timing and failures more visible, but it requires another runner,
-another dependency setup sequence, and likely another cold build of both Cargo
-worlds.
-
-### 3. Run macOS clippy in CI Lite
-
-This gives earlier feedback on every relevant pull request, but materially
-increases the cost and latency of the fast lane. CI Full is already the intended
-cross-platform gate.
-
-## Design
-
-Modify only `.github/workflows/e2e-reusable.yml`. In `build-macos-full`, insert
-the macOS clippy step immediately after `Build E2E app` and before packaging the
-artifact.
-
-The step must:
-
-- invoke the existing root `pnpm rust:clippy` script rather than duplicating its
- two Cargo commands in workflow YAML;
-- run through `scripts/ci-cancel-aware.sh`;
-- retain the existing Rust toolchain, dependency installation, cache, and
- environment setup from `build-macos-full`;
-- leave `timeout-minutes: 60` unchanged initially.
-
-Running after the build is deliberate: the build is the job's primary artifact
-producer, and it warms the Tauri target before clippy recompiles its
-lint-specific units. The independent root target benefits from the existing
-two-workspace cache but may still be cold on a cache miss. Running before
-artifact packaging also prevents a failed lint from publishing an artifact that
-downstream shards cannot consume.
-
-## Failure behavior
-
-A clippy warning or error exits the macOS build job unsuccessfully. Downstream
-macOS shards remain blocked by their existing `needs: build-macos-full`
-dependency, and the existing CI Full gate reports the failure. Cancellation is
-propagated by `scripts/ci-cancel-aware.sh`.
-
-If a cold-cache run shows that the extra lint step approaches the 60-minute
-ceiling, timeout adjustment is a separate evidence-driven follow-up in the same
-PR. The initial implementation does not speculate by increasing it.
-
-## Validation
-
-Local validation:
-
-1. Run Prettier's check against `.github/workflows/e2e-reusable.yml`.
-2. Run any repository workflow/YAML validation available in the checkout.
-3. Confirm the diff changes only the selected job and documentation/plan files.
-
-GitHub validation:
-
-1. Open the PR against `tinyhumansai/openhuman:main`.
-2. Run CI Full for the branch.
-3. Confirm `Build (macOS full)` executes both root-core and Tauri clippy through
- `pnpm rust:clippy`.
-4. Confirm the macOS build artifact and downstream shards still complete.
-5. Record the job runtime and adjust the timeout only if the observed cold-cache
- runtime requires it.
-
-## Acceptance criteria
-
-- CI Full executes `pnpm rust:clippy` on `macos-latest`.
-- The command is cancellation-aware.
-- Both Cargo worlds run with warnings denied through their existing scripts.
-- A lint failure blocks the existing CI Full gate.
-- Successful runs still package the macOS artifact and fan out to the full-suite
- shards.
-- CI Lite behavior and workflow scope remain unchanged.
diff --git a/docs/specs/2026-07-24-react-reuse-foundation-design.md b/docs/specs/2026-07-24-react-reuse-foundation-design.md
deleted file mode 100644
index 4016cc9be1..0000000000
--- a/docs/specs/2026-07-24-react-reuse-foundation-design.md
+++ /dev/null
@@ -1,201 +0,0 @@
-# React Reuse Foundation
-
-Date: 2026-07-24
-Status: Proposed
-
-## Purpose
-
-The React application has useful shared primitives, but features do not consistently
-promote repeated behavior into them. This work establishes a small set of reusable
-UI and state-management seams, then migrates proven duplicates without redesigning
-the affected screens.
-
-The governing rule is: when a second implementation repeats the same semantics,
-either reuse or extract a shared owner, or document why the two implementations
-must remain separate. Similar styling alone is not enough to justify an abstraction.
-
-## Goals
-
-- Remove exact and near-exact React implementations already repeated at least twice.
-- Prefer adopting existing primitives before adding new ones.
-- Give shared behavior a clear ownership level: global UI, settings, Agent World,
- flows, or a feature-local helper.
-- Preserve current user-visible behavior while improving accessibility and
- consistency.
-- Add regression coverage at the shared boundary before migrating consumers.
-- Land every independently validated slice as an atomic commit.
-
-## Non-goals
-
-- A wholesale redesign or restyling of the application.
-- A schema-driven form framework.
-- One universal status model spanning unrelated domains.
-- Combining drawers, blocking gates, sheets, and ordinary dialogs into one component.
-- Rewriting every large component solely to reduce its line count.
-- Changing RPC contracts, authorization semantics, or persistence formats.
-
-## Design principles
-
-### Promote to the narrowest stable owner
-
-Global presentation primitives belong under `app/src/components/ui`. Domain
-vocabulary and state mappings stay with the domain. For example, a global `Badge`
-owns shape and tone, while `JobStatusBadge` owns the mapping from job statuses to
-tones.
-
-Agent World-only presentation belongs under `app/src/agentworld/components`, and
-Agent World data hooks belong under `app/src/agentworld/hooks`. Flow-run query
-coordination belongs under `app/src/hooks` because it is consumed by pages and
-feature components.
-
-### Preserve domain semantics
-
-Extraction should consolidate mechanics, not erase meaning. Approval cards may
-share layout and request lifecycle, but tool, flow, and gate authorization actions
-remain distinct. Loading and error primitives expose variants rather than treating
-all warnings, validation messages, and fatal errors as the same state.
-
-### Prefer composition over configuration engines
-
-Shared components accept ordinary React content and small semantic props. Feature
-code continues to own validation, RPC calls, and domain-specific rendering.
-
-## Planned slices
-
-### 1. Adopt and strengthen existing UI primitives
-
-Extend existing primitives only where current consumers require a stable capability:
-
-- `ModalShell`: optional footer, close policy, and content/layout slots.
-- `ErrorBanner`: alert semantics, React content, size, and optional action.
-- `Input`: invalid and monospace presentation where raw inputs currently duplicate it.
-- `ChipTabs`: per-item accessibility relationships and compact presentation.
-- `Card`: polymorphic output only if required by semantic list or section consumers.
-
-Migrate exact matches before flexible variants. Drawers, full-screen gates, and
-consent overlays remain separate.
-
-Promote the Agent World confirmation dialog to
-`app/src/components/ui/ConfirmDialog.tsx`. It composes `ModalShell` and supports
-custom body content, destructive or neutral confirmation, busy labels, and
-close-disabled behavior.
-
-### 2. Extract Agent World reuse seams
-
-Add:
-
-- `StatusBlock`: semantic tone, title, optional body, loading state, and optional
- action. It replaces the eight current copies.
-- `useMyAgentId`: resolves the Solana wallet identity with explicit loading,
- disconnected, ready, and error states.
-- Small form primitives: `FormField` and `FormActions`. They own labels,
- descriptions, error association, and action layout, but not form state.
-- `ExpandableResourceRow`: disclosure mechanics and accessibility for job and
- bounty rows.
-
-Skeleton atoms and a live-stream indicator are follow-ups only if the initial
-migrations demonstrate that their geometry and semantics remain stable.
-
-### 3. Consolidate shared hooks and query coordination
-
-Add narrowly scoped hooks:
-
-- `useFlowRunsQuery`: initial load, latest-request protection, silent refresh,
- and flow-run live refresh.
-- A shared pending-approvals source with selector hooks so list and detail views do
- not poll the same endpoint independently.
-- `useLatestAsync`: latest-request and unmount protection without dictating how a
- caller stores or merges returned data.
-- `useDebouncedValue`: timer cleanup for search inputs.
-- `useClipboardFeedback`: copy status, failure state, timer replacement, and
- unmount cleanup. Sensitive clipboard flows opt in separately.
-- `useDismissLayer`: composition around the existing `useEscapeKey`, with explicit
- outside-pointer behavior.
-
-Socket subscription consolidation follows only after canonical-versus-legacy event
-alias behavior is decided and covered by tests.
-
-### 4. Consolidate repeated domain presentation and parsing
-
-- `ApprovalDecisionCard` shares approval presentation and action rendering while
- callers supply domain-specific action descriptors.
-- Flow-run status presentation shares tone and dot primitives without merging
- distinct status unions.
-- The workflow-proposal parser has one canonical implementation used by the API
- mapping layer.
-
-HTTP JSON-RPC transport consolidation is intentionally a later, non-React slice. It
-will be planned separately if the React-focused changes finish cleanly.
-
-## Component contracts
-
-Shared UI components use semantic props rather than accepting arbitrary Tailwind
-color classes. They forward accessibility attributes and allow targeted
-`className` overrides for layout, not replacement of their core visual contract.
-
-Dialog and drawer primitives must provide:
-
-- an accessible name;
-- Escape and backdrop behavior controlled by explicit policy;
-- focus placement and restoration;
-- a real close control when closing is allowed;
-- portal rendering where required;
-- no action after unmount.
-
-Async hooks expose discriminated state where the distinction affects rendering.
-They must prevent stale requests from overwriting newer state and must not log raw
-payloads or user-authored error content.
-
-## Migration strategy
-
-Each slice follows this order:
-
-1. Add or extend the shared boundary with focused tests.
-2. Migrate two representative consumers.
-3. Run related tests and TypeScript validation.
-4. Migrate remaining exact matches.
-5. Run related tests again and commit the slice.
-
-Consumers with materially different behavior remain untouched and are recorded as
-intentional exceptions. No migration should combine a behavior change with the
-reuse refactor.
-
-## Testing
-
-- Shared components receive rendering, interaction, keyboard, ARIA, busy-state,
- and focus-restoration tests as applicable.
-- Hooks receive success, error, unmount, stale-response, timer-cleanup, and
- concurrent-consumer tests as applicable.
-- Existing consumer tests remain green; targeted tests are added when a migrated
- behavior was previously uncovered.
-- Each slice runs its related Vitest files plus `pnpm typecheck`.
-- The completed branch runs `pnpm lint`, `pnpm test`, and `pnpm build`.
-- Rust domains, controller schemas, JSON-RPC methods, and transport behavior are
- unchanged, so no Rust/JSON-RPC implementation or new E2E scenario is needed.
- Existing consumer-flow E2E coverage remains applicable; focused interaction
- tests and the full frontend suite verify the migrated UI behavior.
-
-## Delivery order
-
-1. Global `ConfirmDialog` and simple `ModalShell` migrations.
-2. Existing loading/error primitive adoption.
-3. Agent World `StatusBlock`.
-4. Agent World `useMyAgentId`.
-5. Agent World form and expandable-row primitives.
-6. Flow-run query and pending-approval coordination.
-7. Clipboard, debounce, latest-async, and dismiss-layer hooks.
-8. Approval presentation, flow status presentation, and workflow parser.
-
-Every item is independently reviewable and committed with `atomic-commit`.
-
-## Success criteria
-
-- The eight Agent World status blocks share one implementation.
-- Repeated ordinary confirmations use the global dialog primitives.
-- Agent World wallet identity resolution has one hook and one state contract.
-- Flow-run surfaces share one race-safe query lifecycle.
-- Concurrent flow-run surfaces share pending-approval polling.
-- Existing exact loading, error, input, and chip duplicates use their established
- primitives.
-- No migrated feature loses behavior, accessibility, or test coverage.
-- Frontend lint, unit tests, type checking, and production build pass.
diff --git a/docs/specs/2026-07-24-remove-screen-awareness-design.md b/docs/specs/2026-07-24-remove-screen-awareness-design.md
deleted file mode 100644
index b41ff95bb7..0000000000
--- a/docs/specs/2026-07-24-remove-screen-awareness-design.md
+++ /dev/null
@@ -1,139 +0,0 @@
-# Remove Screen Awareness Design
-
-## Objective
-
-Remove every shipped screen-awareness and screen-capture capability from
-OpenHuman. The desktop app, embedded provider webviews, core RPC/CLI surface,
-agent tool surface, and companion must no longer capture, share, inspect, or
-reason from the user's screen.
-
-This is a hard removal. The deleted capabilities will not remain behind feature
-flags or compatibility stubs.
-
-## Product Boundary
-
-The removal includes:
-
-- the complete Rust `screen_intelligence` domain, including capture sessions,
- vision summaries, screen-derived memory, permission management, screen input
- actions, autocomplete integration, Globe listener controls, RPC controllers,
- CLI commands, and agent tools;
-- the `screen_awareness_agent` and every delegation, prompt, registry, MCP
- resource, and tool reference that makes it discoverable;
-- the standalone native screenshot tool and local CLI wrappers;
-- browser automation actions that return pixels, including `screenshot` and
- computer-use `screen_capture`, across every browser backend;
-- the Tauri screen-share source picker, thumbnail capture, command permissions,
- managed state, and injected `getDisplayMedia` shim;
-- CEF permission forwarding for desktop audio and desktop video capture, so an
- embedded provider cannot bypass the deleted picker and initiate capture
- directly;
-- companion foreground app/window context, screen-capture configuration,
- screen-aware prompting, pointing tags, pointing state, and pointing UI;
-- all screen-awareness settings, developer panels, connections/skills tabs,
- setup flows, routes, navigation entries, frontend state, RPC wrappers,
- translations, tool presentation metadata, and product tests; and
-- checked-in schemas, capability catalog entries, feature documentation,
- architecture documentation, and test inventories that advertise the removed
- behavior.
-
-The following remain:
-
-- DOM and accessibility-tree browser snapshots that return structured text
- rather than captured pixels;
-- user-supplied image attachments, including screenshots the user captured
- outside OpenHuman;
-- general image analysis and vision support for those supplied images;
-- camera and microphone capture that do not capture a display;
-- accessibility helpers still required by voice, dictation, hotkeys, or other
- non-screen features; and
-- developer-only test-runner failure screenshots and App Store asset-generation
- scripts, because they are not shipped product APIs.
-
-## Core and Configuration
-
-Delete `src/openhuman/screen_intelligence/` and remove its module registration,
-controller schemas, CLI dispatch, legacy aliases, startup/shutdown hooks,
-application snapshot data, built-in agents, agent tools, user-tool filters, MCP
-prompt resources, and capability catalog entries.
-
-Remove `ScreenIntelligenceConfig` and its update controller from the persisted
-configuration schema. Existing user configuration files may still contain a
-`screen_intelligence` table after upgrade; serde's normal unknown-field
-behavior will ignore it. No migration is required because no retained behavior
-consumes the data.
-
-Remove screen capture and Screen Recording permission helpers from the shared
-accessibility domain. Retain only independently used accessibility behavior.
-Removed RPC names must resolve as unknown methods rather than as deprecated
-stubs.
-
-## Browser and Desktop Shell
-
-Remove the top-level `screenshot` tool and its local CLI wrappers. Remove
-pixel-producing screenshot variants from browser action parsing, schemas,
-native WebDriver execution, Playwright execution, and computer-use sidecar
-dispatch. DOM `snapshot` remains the supported inspection action.
-
-Delete the Tauri `screen_capture` module and unregister its managed state and
-commands. Remove those commands from application permission allowlists. Delete
-the injected screen-share picker and `getDisplayMedia` replacement from the
-provider runtime.
-
-Update the vendored CEF permission policy to reject desktop audio and desktop
-video capture bits while continuing to allow device microphone and camera
-capture. Embedded Meet, Slack, Discord, Zoom, and similar provider webviews will
-therefore no longer offer working display sharing through OpenHuman.
-
-## Companion
-
-Keep companion voice and text conversations, but make them screen-independent.
-Remove foreground app/window collection, the `capture_screen` and
-`include_app_context` configuration fields, screen-context prompt construction,
-`[POINT:…]` instructions and parsing, pointing transitions, and corresponding
-settings/status UI. The companion receives only the user's current utterance
-and conversation history.
-
-## Frontend
-
-Delete the screen-intelligence feature hooks, panels, setup modal, debug
-surfaces, and their tests. Remove settings and connections/skills route
-registrations, redirects, tab parsing, navigation icons, developer-menu rows,
-CoreState fields, RPC method mappings, Tauri command wrappers, translations,
-and screen-capture tool labels.
-
-Old hashes such as `/settings/screen-intelligence` and
-`/settings/screen-awareness-debug` will fall through to the existing settings
-routing behavior. They will not redirect to another screen-awareness surface.
-
-## Compatibility and Security
-
-This change intentionally breaks callers of removed RPC, CLI, Tauri, browser,
-and tool interfaces. Retaining callable tombstones would leave a misleading
-surface and is outside the goal.
-
-The final CEF policy must deny desktop capture at the permission boundary, not
-merely hide the picker UI. Product-wide searches must confirm that no shipped
-runtime calls platform screenshot commands, registers display-capture commands,
-offers screenshot/browser capture tools, or exposes screen-awareness routes.
-
-## Delivery and Validation
-
-Implement the removal in small dependency-ordered steps, validating and
-committing each step separately:
-
-1. Remove the core domain, configuration, lifecycle, app-state, agent, catalog,
- schema, and core tests.
-2. Remove native screenshot and browser pixel-capture tools and their tests.
-3. Remove Tauri screen sharing, the provider shim, desktop-capture permission
- forwarding, and companion screen behavior.
-4. Remove frontend UI, routes, state, wrappers, translations, and tests.
-5. Remove or revise documentation, generated schemas, E2E inventories, and
- stale references.
-
-Validation must include Rust formatting, targeted core tests, root
-`cargo check`, Tauri tests and `cargo check`, targeted Vitest tests, frontend
-typecheck/lint/format checks, schema consistency checks, and repository searches
-for residual shipped capture surfaces. Test-only screenshot artifact helpers
-and user-image terminology may remain when each surviving match is demonstrably
-outside the shipped capture surface.
diff --git a/docs/specs/2026-07-28-agent-session-transcript-to-tinyagents-design.md b/docs/specs/2026-07-28-agent-session-transcript-to-tinyagents-design.md
deleted file mode 100644
index 931763bfb6..0000000000
--- a/docs/specs/2026-07-28-agent-session-transcript-to-tinyagents-design.md
+++ /dev/null
@@ -1,671 +0,0 @@
-# Agent session persistence → TinyAgents
-
-**Status:** spec + plan, awaiting a shape decision (§4). Written 2026-07-28
-against `main` (`ce6c3e9b5`).
-**Scope:** `src/openhuman/agent/harness/session/` — specifically the durable
-transcript layer. Everything else in `session/` is out of scope and stays.
-**Superseded in part (2026-07-28):** the maintainer has since decided to move
-`agent/` wholesale into TinyAgents — see
-[`plan-agents.md`](plan-agents.md).
-That decision reopens this document's §6 "permanent host" rows for `builder/`,
-`turn/`, `runtime.rs`, and `types.rs`, and selects **Option B** in §4 (the
-transcript format becomes crate-owned). The state map, crate gap table, and
-§3.5 analysis below remain accurate and are the input to that program's
-Phases 2–4.
-
-**Parent spec:** `2026-07-28-deshim-agent-inference-memory-seams-design.md`
-(this document is the expansion of its DS-8).
-**Related:** `docs/tinyagents-migration-plan-2026-07-22.md` (WP-1's
-`ChatMessage` decision is the governing precedent), `99-deletion-ledger.md`.
-
----
-
-## 1. The question this answers
-
-Should `agent/harness/session/` become a `tinyagents::sessions` module?
-
-**No — not as a unit.** But its durable transcript layer is a parallel
-implementation of an abstraction the crate already ships, and that part should
-converge. This document draws the line precisely, because drawing it wrong in
-either direction is expensive: too aggressive and a GPL crate ends up importing
-Composio; too timid and OpenHuman keeps two conversation-history models forever.
-
----
-
-## 2. Current state
-
-### 2.1 Size and split
-
-`session/` is **18,142 LOC** across 17 files (~11,073 production, ~7,069 tests).
-The transcript layer is:
-
-| File | Prod LOC | Tests |
-| --- | ---: | ---: |
-| `transcript.rs` | 1,997 | 1,384 (`transcript_tests.rs`) |
-| `turn_checkpoint.rs` | 105 | — |
-| `migration.rs` | 373 | 170 (`migration_tests.rs`) |
-| **Total** | **2,475** | **1,554** |
-
-### 2.2 Why only these three
-
-Measured host-domain fan-out (`grep -o "crate::openhuman::[a-z_]*" | sort -u`):
-
-| File | Prod LOC | Host domains | In scope? |
-| --- | ---: | ---: | --- |
-| `transcript.rs` | 1,997 | **2** (`agent::messages::ChatMessage`, `inference::provider::ToolCall`) | **yes** |
-| `turn_checkpoint.rs` | 105 | **2** (`ChatMessage`, `hooks::ToolCallRecord`) | **yes** |
-| `migration.rs` | 373 | **0** (`anyhow`, `std::fs`, `std::path`) | **yes** |
-| `builder/factory.rs` | 1,699 | 21 — composio, security, skills, subconscious, profiles, memory_store, memory_tools, agent_registry, agent_experience, agent_memory, embeddings, tokenjuice, learning, app_state, config, context, inference, tools, agent, tinyagents, … | no |
-| `turn/core.rs` | 2,207 | 10 — mcp_registry, thread_goals, agent_orchestration, agent_experience, agent_memory, composio, memory, util, agent, tinyagents | no |
-| `turn/session_io.rs` | 854 | 7 — learning, session_import, config, context, inference, agent, tinyagents | no |
-| `runtime.rs` | 817 | 14 — channels, composio, prompt_injection, agent_tool_policy, skills, memory, … | no |
-| `builder/setters.rs` | 666 | 10 | no |
-| `turn/tools.rs` | 650 | 6 — composio, profiles, skills | no |
-| `types.rs` | 477 | 11 | no |
-| `turn/context.rs` | 343 | 7 — app_state, learning, memory | no |
-| `turn/mod.rs`, `turn/graph.rs`, `builder/*`, `mod.rs`, `tool_progress.rs` | ~840 | 3–7 each | no (see §6) |
-
-**~8,600 of 11,073 production lines are host wiring.** `builder/factory.rs`
-reaches 21 OpenHuman domains; its job is literally "assemble OpenHuman's product
-surface into a harness". Moving it down inverts the dependency and violates the
-port plan's standing GPL/crates.io rule: only genuinely generic code goes into a
-publicly redistributed crate.
-
-### 2.3 What `transcript.rs` actually implements
-
-Storage layout:
-
-```text
-{workspace}/session_raw/{stem}.jsonl ← source of truth (flat dir)
-{workspace}/sessions/YYYY_MM_DD/{stem}.md ← human view, never read back
-```
-
-`stem` = `{unix_ts}_{agent_id}`, or `{parent_chain}__{unix_ts}_{agent_id}` for a
-sub-agent — timestamp-first so a plain directory listing sorts by creation time
-and `find_latest_transcript` is one directory scan.
-
-Semantics, in the order they matter:
-
-1. **Append-only event log.** `append_transcript_turn` never rewrites existing
- lines. It classifies the new logical message set against what was persisted:
- pure extension → append the tail; reduction/rewrite → append a single
- `{"kind":"compaction","replacement":[…]}` record carrying the full reduced
- set, leaving earlier turns on disk.
-2. **Two read paths from one log.** `read_transcript` replays for *model
- context* (compaction records replace the accumulator; `interrupted:true`
- partials are skipped). `read_transcript_display` returns **every** record in
- file order so the UI can render pre-compaction history, compaction markers,
- and interrupted partials.
-3. **Rewrite-free cumulative meta.** A fresh `{"_meta":{…}}` line is appended
- each turn; readers take the **last** `_meta` as authoritative, with line 1 as
- a valid fallback for older cores.
-4. **Forward/backward compatibility by construction.** `MessageLine` carries
- `#[serde(flatten)] _extra`; `MetaPayload` does not set
- `deny_unknown_fields`; `_meta.version` is `TRANSCRIPT_SCHEMA_VERSION`. Old
- cores skip unknown-kind lines instead of crashing. Legacy
- `session_raw/DDMMYYYY/` layout still resolves for resume.
-5. **Usage rollups.** `read_thread_usage_summary` →
- `ThreadUsageSummary` + `SubagentArchetypeUsage`.
-
-Public surface: 26 items — `SessionTranscript`, `TranscriptMeta`,
-`DisplaySessionTranscript`, `DisplayRecord`, `DisplayMessage`,
-`CompactionMarker`, `TurnUsage`, `MessageUsage`, `ThreadUsageSummary`,
-`SubagentArchetypeUsage`, plus `write_transcript`, `append_transcript_turn`,
-`append_interrupted_partial`, `read_transcript`, `read_transcript_display`,
-`read_transcript_legacy_md`, `read_thread_usage_summary`,
-`find_root_transcript_for_thread(_in_dir)`, `resolve_keyed_transcript_path(_in_dir)`,
-`resolve_new_transcript_path`, `find_latest_transcript(_in_subdir)`.
-
-### 2.4 Consumers
-
-**24 files across 5 domains** import `transcript::`: `agent`, `threads`,
-`session_import`, `learning`, `migrations`. Notable non-agent callers:
-
-- `threads/transcript_view/project.rs` — the derived-view projection
-- `threads/turn_state/mirror.rs` — `find_root_transcript_for_thread`, `append_interrupted_partial`
-- `threads/ops.rs` — `read_thread_usage_summary`
-- `session_import/{ops,convert,live}.rs` — external session import
-- `learning/transcript_ingest/mod.rs` — lesson extraction
-- `migrations/phase_out_profile_md.rs`
-
-This is the **transcript-derived-view architecture**: `session_raw` JSONL is the
-source of truth, `turn_state` is a derived cache. Any change here is a change to
-that contract, not just to one module.
-
----
-
-## 3. What the crate already ships
-
-`vendor/tinyagents` v2.1.0:
-
-| Crate capability | Module | Relevance |
-| --- | --- | --- |
-| `ChatHistory` trait — `messages(thread_id) -> Vec<Message>`, `append`, `replace`, `clear` | `harness::memory::types:48` | **The direct analogue.** Thread-scoped conversation history surviving across runs. |
-| `InMemoryChatHistory`, `StoreChatHistory<S: Store>`, `ShortTermMemory<H>` (trim policy), `MemoryScope` | `harness::memory` | Backends + short/long-term layering |
-| `Store` — kv (`get`/`put`/`delete`/`list`) **plus an append-only stream API**: `append(stream, value) -> u64`, `read_from(stream, offset)`, `len(stream)` | `harness::store` | The stream half is a closer structural match to the JSONL log than `ChatHistory` is |
-| `InMemoryStore`, `FileStore`, `StoreRegistry` | `harness::store` | Backends |
-| `Checkpointer`, `FileCheckpointer`, `SqliteCheckpointer`, `DurabilityMode` | `graph::checkpoint` | Superstep state snapshots — **different concern**, not a transcript |
-
-**So OpenHuman is not missing a home; it has a second implementation.** That is
-the whole argument for this work.
-
-### 3.1 Gap table — what crate `ChatHistory` cannot express today
-
-| OpenHuman semantic | Crate equivalent | Gap |
-| --- | --- | --- |
-| Append-only log, never rewrite | `Store::append`/`read_from` (stream API) | present on `Store`, **absent from `ChatHistory`** (`replace` is a bulk overwrite) |
-| Compaction record with `replacement` set | — | **missing** |
-| `interrupted:true` partials, skipped on model read | — | **missing** |
-| Dual read paths (model-context replay vs display-order) | — | **missing** — `messages()` is single-view |
-| Cumulative `_meta` totals appended per turn | — | **missing** |
-| Schema versioning + unknown-line tolerance | — | **missing** (a policy, easily added) |
-| `.md` companion render | — | **host** — product surface, never upstream |
-| Stem naming, latest/resume discovery, legacy dir fallback | — | **host** — OpenHuman workspace layout |
-| Thread/subagent usage rollups | `harness::usage`, `harness::cost` | partial; the archetype rollup is product |
-
-`ChatHistory` is a **strictly weaker interface** than what OpenHuman needs. A
-naive "just implement `ChatHistory`" that routes reads through `messages()`
-would silently drop compaction and interrupted-partial semantics — i.e. corrupt
-the model context on any compacted thread. This is the single most important
-constraint in this document.
-
----
-
-## 3.5 Re-examined: `builder/factory.rs` and `turn/core.rs`
-
-The §2.2 verdict ("21 imports, therefore host") describes the *wiring*, not the
-*shape*. A shape can be generic even when every value flowing through it is
-product-specific, so both files were re-read rather than dismissed on the import
-count. Result: **the structure is already in the crate; the residue is genuinely
-product — with two concrete exceptions worth acting on.**
-
-### 3.5.1 `Agent` is not a duplicate of `AgentHarness`
-
-`AgentHarness<State, Ctx>` (`harness/runtime/types.rs:259`) has **six** fields —
-`models`, `tools`, `middleware`, `policy`, `tool_timeouts`, `response_cache` —
-and a complete builder API: `new`, `register_model`, `set_default_model`,
-`register_tool`, `push_middleware`, `push_model_middleware`,
-`push_tool_middleware`, `with_policy`, `with_tool_timeout_settings`,
-`with_response_cache`. The seam already drives exactly this API
-(`tinyagents/mod.rs:1793–2302`).
-
-The host `Agent` (`session/types.rs:31`) has **40+ fields**, and the ones that
-define it are not execution config at all:
-
-- **Per-turn product accumulators:** `last_memory_context`,
- `last_turn_citations`, `last_turn_usage_totals`, `last_turn_hit_cap` — read
- by web-channel delivery to render citation chips, token/cost meters, and to
- distinguish "paused at the iteration cap" from "asked a question".
-- **Host service handles:** `memory`, `shared_experience_memory`,
- `memory_loader`, `tool_policy_session`, `workflows`.
-- **Product policy:** `learning_enabled`, `explicit_preferences_enabled`,
- `subagent_tool_ceiling_names`, `visible_tool_names`.
-- **Event identity:** `event_session_id`, `event_channel`.
-
-`Agent` is OpenHuman's **session-state + turn-result object**; `AgentHarness` is
-the crate's execution configuration. They are different things that both happen
-to hold tools and a model. That single overlap is already bridged by
-`SharedToolAdapter`, which the WP-4 decision fixed as a permanent boundary. And
-`Agent` already holds a crate type directly — `workspace_descriptor:
-tinyagents::harness::workspace::WorkspaceDescriptor` — which is what convergence
-looks like in practice: adopt crate types field by field, don't relocate the
-struct.
-
-**So there are not two builders competing.** There are two builders in series
-(host `Agent::from_config` → seam → crate `AgentHarness`), building two
-different objects. Moving `factory.rs` down would require the crate to import
-Composio, OpenHuman `SecurityPolicy`, `memory_store`, `skills`, `profiles`, and
-`subconscious` — the exact GPL/crates.io boundary violation the port plan
-forbids.
-
-### 3.5.2 `turn/core.rs` is preparation, and the engine already left
-
-WP-3 established that `turn/core.rs` "performs OpenHuman turn preparation and
-calls the TinyAgents session path" — it contains no turn engine. Reading it
-confirms that: `impl Agent` starts at line 432, and everything above it is
-product gating. What `turn()` actually does before delegating:
-
-- agent-experience retrieval and `prepend_experience_block`;
-- memory recall citation collection;
-- integration / MCP / skill announcement + retraction notes.
-
-None of that is framework-shaped. **But ~150 LOC of it is:**
-`tool_records_from_conversation`, `stamp_tool_failures`, `parse_tool_call_id`,
-`short_failure_detail`, `replace_last_assistant_reply` are pure message-list
-manipulation over roles and tool-call ids. Those are candidates for crate
-`harness::message` helpers — small, but genuinely generic.
-
-### 3.5.3 The one real duplicate: dispatcher-kind resolution
-
-`resolve_dispatcher_kind` (`factory.rs:1398`) picks Native / Xml / PFormat from
-`supports_native`, plus an `integrations_agent` override. The three
-`ToolDispatcher` impls then render and parse tool calls accordingly.
-
-**The crate already makes this decision.** `OpenAiModel` exposes
-`with_native_tool_calling(bool)` and internally computes
-`prompt_guided_tools = !self.profile.tool_calling && !request.tools.is_empty()`
-(`providers/openai/transport.rs:951`), replaying calls and results as text when
-prompt-guided — that is #55. So OpenHuman decides native-vs-prompt-guided at the
-session-build layer, and the crate decides it again at the model layer.
-
-This is the **same subsystem** as the parent spec's DS-5b (`harness/parse.rs`
-duplicating #55/#57 parsing). Dispatcher selection, tool-call rendering, and
-tool-call parsing are one concern split across two layers and two owners. They
-should be resolved together, and the answer is almost certainly: the crate owns
-the native-vs-prompt-guided decision and both directions of the wire format;
-OpenHuman keeps only the `integrations_agent` override as an explicit policy
-input, and the durable `to_provider_messages` serialization.
-
-### 3.5.4 The generalizable conclusion
-
-The productive question is not *"which file moves down"* but *"which extension
-point is missing upstream"*. `factory.rs` and `turn/core.rs` are large because
-the crate offers registries and middleware but no typed **turn-preparation**
-seam — so every product enrichment (experience, citations, and announcements)
-is hand-written into one `turn()` body instead of registered.
-
-If the crate grew a `ContextEnricher` / `TurnPreparation` pipeline —
-ordered, fallible, each returning prompt fragments plus metadata — OpenHuman's
-enrichment becomes registrations rather than a bespoke method, and the *shape*
-moves down while the *wiring* stays up. That is worth designing (S6), and it is
-what "enrich it as a library" should mean here. It is explicitly **not** a
-licence to relocate 3,900 lines of host wiring.
-
----
-
-## 4. The decision (§4 is the gate — pick one before writing code)
-
-### Option A — Host backend behind the crate trait *(recommended)*
-
-Keep `ChatMessage`, the `session_raw` format, and every host-only helper exactly
-as they are. Add `impl tinyagents::harness::memory::ChatHistory for
-SessionTranscriptHistory`, converting at the boundary via the existing
-`agent/message_convert.rs`. The harness talks to the crate trait; OpenHuman owns
-the format. Host-only semantics (display read, compaction markers, usage
-rollups, path resolution) stay on the concrete type, reached directly by the 24
-consumers that need them.
-
-- **On-disk change:** none. **Migration risk:** none.
-- **Removes:** ~15 LOC — the duplicated path-resolution block in
- `persist_session_transcript`. **Adds** ~90 for the read + locator seam
- (S2–S4 as a whole: +782 / −0). Option A buys a single documented,
- *substitutable* seam, not a line reduction. The original "~400 LOC of parallel
- abstraction" figure was measured and refuted — see
- [Where "~400 LOC" came from](#where-400-loc-came-from-and-why-it-is-struck)
- — and it contradicted this option's own **Weakness** bullet two lines below.
-- **Cost:** low. Reversible.
-- **Weakness:** the crate trait is only used on the narrow runtime path; most of
- `transcript.rs` stays. Honest framing: this fixes *"two abstractions"*, not
- *"two implementations"*.
-
-### Option B — Upstream a generic append-only history backend
-
-Add `JsonlChatHistory` to the crate beside `StoreChatHistory`, and extend
-`ChatHistory` (or add a `ReplayableChatHistory` supertrait) with the three
-missing generic semantics: compaction-replacement records, skippable partials,
-and a display-order read. `ChatMessage`'s durable fields survive as crate
-`Message` + a `raw` passthrough, mirroring how the tool-model decision preserves
-`ToolResult::raw`.
-
-- **Removes:** ~2,100 host LOC.
-- **Cost:** high — a trait extension in a published GPL crate, a durable format
- becoming public API, and an on-disk parity soak.
-- **Only justified if** a second host will use it. Compaction-aware append-only
- transcripts are genuinely generic agent-framework machinery, so this is
- defensible — but it is a crate-roadmap decision, not a cleanup.
-
-### Option C — Declare host-owned, close the question
-
-Record `transcript.rs` in the deletion ledger as HOST-OWNED (durable on-disk
-format + product read paths), same disposition as `tool_status` and
-`namespace_store`. Costs nothing, keeps two abstractions.
-
-**Recommendation: A now, B only if the crate roadmap wants a durable transcript
-primitive.** A is cheap, reversible, and removes the thing that actually
-confuses readers. B should not be smuggled in as refactoring.
-
----
-
-## 5. Plan (Option A)
-
-Every slice: failing-before/passing-after test, small validated commit on a
-feature branch, `atomic-commit` with explicit paths.
-
-### S0 — Ledger + decision record (no code)
-
-Add a ledger row for `harness/session/` recording the §2.2 split and the §4
-choice. Without this, a future audit re-opens "why didn't session move?" — which
-has already happened twice in this migration.
-
-**Exit:** row present; this doc linked from the parent spec's DS-8.
-
-### S1 — `migration.rs` disposition
-
-Zero host imports, but it migrates *OpenHuman's* directory layout
-(`session_raw/DDMMYYYY/` → flat). Generic code for a host-specific format.
-
-Expected outcome: **stays host**, recorded with that reason. Do the 10-minute
-check rather than assuming; if it turns out to be a general "flatten a
-date-bucketed log dir" utility with no OpenHuman naming, it can go down.
-
-**Exit:** one ledger row, either way.
-
-### S2 — Extract the trait-shaped surface
-
-Introduce `SessionTranscriptHistory { workspace_dir, stem }` in
-`session/transcript_history.rs`, wrapping the existing free functions. No
-behaviour change; purely a handle where a trait impl can live.
-
-**Exit:** `cargo check` + existing `transcript_tests.rs` green, untouched.
-
-### S3 — Implement crate `ChatHistory`
-
-```rust
-impl tinyagents::harness::memory::ChatHistory for SessionTranscriptHistory {
- async fn messages(&self, thread_id: &str) -> Result<Vec<Message>>; // read_transcript (model-context replay) → message_convert
- async fn append(&self, thread_id: &str, message: Message) -> Result<()>;
- async fn replace(&self, thread_id: &str, messages: Vec<Message>) -> Result<()>;
- async fn clear(&self, thread_id: &str) -> Result<()>;
-}
-```
-
-Hard requirements, each with its own test:
-
-- `messages()` MUST route through the **model-context** replay path, so
- compaction records replace the accumulator and `interrupted` partials are
- skipped. A test must construct a compacted transcript and assert
- `messages()` == `read_transcript()`, not the raw line set.
-- `replace()` MUST map onto the compaction-record path
- (`append_transcript_turn`'s reduction branch), **not** a file rewrite. The
- append-only invariant is the format's core property; a trait default that
- clears-then-appends would destroy history.
-- `clear()` semantics must be decided explicitly — truncate vs. start a new
- stem. Whichever, write it in the doc comment.
-
-**Exit:** compaction and interrupted-partial round-trip tests green; the
-byte-identity assertion against the pre-change reader passes.
-
-### S4 — Route the harness through the trait
-
-The turn path takes `Arc<dyn SessionHistory>` instead of calling transcript free
-functions. The 24 consumers that need display records, usage rollups, or path
-resolution keep using the concrete type — that is correct, not debt.
-
-**Exit:** `agent_harness_e2e` + `scripts/test-rust-with-mock.sh` green;
-`threads/transcript_view` projection output unchanged (golden test).
-
-#### Landed as `SessionHistory: ChatHistory`, not `ChatHistory` — and why
-
-S4's two halves as originally written contradict each other. `ChatHistory`
-(`vendor/tinyagents/src/harness/memory/types.rs`) has four methods, each
-carrying only a `thread_id: &str` plus `Message` / `Vec<Message>`. The turn
-path's write carries three things none of them can express:
-
-- **`request_id`**, stamped on every line. Drives `DisplayItem::TurnBoundary`
- and the `(request_id, ts)` root-turn segments that anchor every
- `DisplayItem::Subagent` in `threads/transcript_view/project.rs`.
-- **`turn_usage`**, attributed to the turn's last assistant row. Carries
- `model`, `iteration`, `ts`, `reasoning_content` and the native `tool_calls`.
- The projection reads **every** `DisplayItem::ToolCall` off
- `turn_usage.tool_calls`, so losing it deletes the tool rows outright (each
- following `role:"tool"` line then falls to the orphan branch), along with
- `Reasoning`, `AssistantMessage.{model,iteration}` and `interim`.
-- **`TranscriptMeta`'s cumulative fields** — `turn_count` plus the four
- token/cost rollups `read_thread_usage_summary` reports. The turn path computes
- these fresh each turn; the trait path can only re-read the file's existing
- `_meta`, which would freeze them at the previous turn's values.
-
-A literal `Arc<dyn ChatHistory>` write would therefore have failed S4's own exit
-criterion while looking complete. The criterion wins: what landed is
-`pub(crate) trait SessionHistory: ChatHistory`, declared in
-`agent/harness/session/transcript_history.rs`, whose single `append_turn` method
-forwards the same six arguments `append_transcript_turn` already takes. The
-indirection is real, `ChatHistory` stays in the bound so S2/S3 are not orphaned,
-and the on-disk bytes are unchanged by construction —
-`append_turn_is_byte_identical_to_the_free_function` writes one turn both ways
-and compares the files byte for byte.
-
-The **read** path does not cross `ChatHistory` either, and that half is settled
-for the same shape of reason: `ChatHistory::messages()` returns `Vec<Message>`,
-and converting back with `message_to_chat_message` flattens
-`Assistant.tool_calls` into plain text — exactly what
-`bound_cached_transcript_messages`' TAURI-RUST-7 trailing strip inspects, and
-what native providers reject with `400 assistant message with 'tool_calls' must
-be followed by tool messages`. (A round-trip probe confirmed the loss set:
-assistant `tool_calls`, plus `openhuman_turn_usage` `extra_metadata` and
-`AssistantMessage.id`, both inert here. The tool-failure marker is *not* in it —
-that is a write-side/display-side field `read_transcript` never re-emits.)
-
-An earlier revision of this section concluded from that the read must stay on
-the concrete free functions. That conclusion was wrong, and the reasoning behind
-it rested on a premise that is false of the type as it stands:
-`SessionTranscriptHistory` is bound to a resolved `PathBuf`, not to a stem — its
-two constructors merely *resolve* one — so a discovered path can be bound
-verbatim. What landed instead:
-
-- **`SessionTranscriptRead { path(); read_session() -> Option<SessionTranscript> }`**,
- a second supertrait of `SessionHistory`. `read_session` is the same
- `read_transcript` call the free-function readers made, returning the same
- struct, so losslessness is *structural*: nothing crosses `Message`, and
- compaction replay, `interrupted: true` partial skipping and the `_meta` header
- `maybe_shadow_read_session_store` needs all survive by construction. Split
- from `SessionHistory` rather than added to it because a discovered transcript
- can still be a legacy `.md` file, and handing read results out as
- `Arc<dyn SessionTranscriptRead>` makes appending JSONL into one impossible by
- construction rather than by convention.
-- **`SessionTranscriptHistory::opened_at(path, seed_meta)`**, which stores the
- discovered path verbatim. It deliberately bypasses
- `resolve_keyed_transcript_path_in_dir`, which `create_dir_all`s and forces a
- `.jsonl` extension — that would mangle the legacy `.md` case and create stray
- directories on a pure read.
-- **`SessionHistoryLocator`** (`latest_for_agent` / `root_for_thread` /
- `open_stem`), with `FileTranscriptLocator` as the default. Discovery *is* the
- thing `ChatHistory` cannot express — it is `thread_id`-keyed and returns
- messages, never a location — so it belongs on an OpenHuman-side object.
- Leaving it as free functions was what kept the read half on the filesystem no
- matter what handle was injected.
-
-**The injection point now exists**, which is what makes the `Arc<dyn …>`
-non-decorative. `AgentBuilder::with_session_history_locator` sets
-`Agent::session_history_locator`; `Agent::session_locator()` resolves `None`
-*lazily* into a `FileTranscriptLocator` over the **current** `workspace_dir` /
-`session_raw_subdir` (never frozen at build time — callers reassign
-`workspace_dir` after `build()`, and a captured locator would silently keep
-reading the old directory). One injected object now covers both resume reads
-*and* the session's own write handle, and
-`fake_locator_substitutes_the_whole_turn_path` drives all three through a fake
-and asserts nothing is written under the workspace.
-
-`persist_session_transcript`'s own path resolution went with it:
-`session_transcript_path` is now simply the bound handle's `path()`, so the two
-can no longer drift.
-
-**Widening `ChatHistory` upstream is REJECTED, not deferred.** S0's rationale
-notes this question has already been re-opened twice, so the finding is recorded
-here to stop a third round: the crate's `Usage` has no `cost_usd` /
-`context_window`; `TranscriptMeta` is a cumulative *file header*, not turn
-provenance; and the per-message tool-failure `extra_metadata` that
-`message_to_chat_message` drops is untouchable by any turn-level record. You
-would pay a tinyagents release and still need a `serde_json::Value` escape
-hatch — for a trait that has no consumer inside the vendored crate outside
-`harness/memory/`.
-
-One live defect was fixed on the way in: the handle resolved its path through
-`resolve_keyed_transcript_path`, which hardcodes `{workspace}/session_raw/`. A
-dedicated-memory profile's sessions live in `session_raw-<id>/`, so wiring the
-handle into the turn path as-written would have silently cross-written profile
-sessions into the shared profile's directory. `new_in_dir` takes the raw dir
-explicitly and is what the turn path uses.
-
-Deliberately **not** relocated: `persisted_transcript_messages` and
-`session_transcript_path` stay on `Agent`. The former is the in-memory diff
-cache the append-only writer needs; substituting the handle's disk re-read is
-lossy against `common_prefix_len` (`read_transcript` lifts `failure` /
-`failure_detail` out of `extra_metadata` and hoists turn-usage to top-level line
-fields), so the writer would emit a full compaction record every turn. The
-latter is what `maybe_dual_write_session_store` needs a concrete `&Path` for.
-
-Also deliberately kept: the `impl ChatHistory for SessionTranscriptHistory` from
-S3 still has **no production caller** after S4 — reads go through
-`read_session`, writes through `append_turn`. It is not deleted, because it is
-the crate-side seam Option A exists to establish and it supplies the
-`Send + Sync + 'static` bounds the shared handle needs. The trigger that would
-delete it is an explicit decision to drop `ChatHistory` from the
-`SessionHistory` bound, which frees `transcript_history.rs`'s
-`read`/`persisted`/`meta_for_write`/`write_logical_set`/`impl ChatHistory` plus
-most of its test module (~570 lines together). That is the only ~400-scale
-removal S4 can actually make — and it removes abstraction this work itself
-added, which is not what Option A was promising. Recorded so a future audit
-finds the decision rather than re-deriving it.
-
-#### Where "~400 LOC" came from, and why it is struck
-
-§4 Option A originally claimed it "Removes: ~400 LOC of parallel abstraction".
-The figure has no derivation anywhere in this document or its parent, and it is
-not achievable. Its arithmetic origin is recoverable: §2.1's in-scope table
-totals **2,475** LOC at this document's base commit (`transcript.rs` 1,997 +
-`turn_checkpoint.rs` 105 + `migration.rs` 373). Option B's "~2,100 host LOC" is
-exactly 1,997 + 105. The residual is **373 ≈ "~400" = `migration.rs`** — which
-§5 S1 and `docs/tinyagents-full-migration-plan/99-deletion-ledger.md:33` both
-resolve as HOST-OWNED, no deletion. Under Option A the §2.1 table loses **zero**
-lines.
-
-Every other candidate was checked and refuted:
-
-- **No host trait duplicates `ChatHistory`.** The only other match in `src/` is
- a `MemorySource::ChatHistory` *enum variant* in `memory/remember.rs`.
- `memory/store/memory_trait.rs` is the long-term semantic `Memory` trait — a
- different concern with a different shape.
-- **`ShortTermMemory`'s `trim` is an empty hook slot**
- (`vendor/tinyagents/src/harness/memory/types.rs`), so there is no crate-side
- policy for the host to be parallel to. The host side is 104 LOC of
- provider-400 defences (`trim_history`, `bound_cached_transcript_messages`)
- with no crate analogue — not duplicated, not deletable.
-- **`agent/context/`'s reducer was already deleted under #4249**, before this
- document was written (`context/manager.rs`: "Live history reduction/
- summarization moved to the tinyagents graph"). What remains is prompt
- assembly + stats.
-
-#### The one genuine parallel abstraction, and why S4/S5 cannot remove it
-
-The #4249 JSONL↔store mirror **is** a second session-persistence implementation,
-over crate `Store`/`AppendStore` rather than `ChatHistory`: `session_import/
-live.rs` (353), `Agent::maybe_shadow_read_session_store` /
-`maybe_dual_write_session_store` (119), the `StoreRegistry` registration in
-`agent/tinyagents/mod.rs`, two `AgentConfig` flags, and
-`config/migrations/enable_session_shadow_reads.rs` — ~565 prod LOC. It is the
-closest thing in the tree to "~400 LOC of parallel abstraction".
-
-It is out of scope here for two reasons. It is #4249's own 04.1/04.2 program,
-gated on that issue's Phase-2 parity soak (#5396, which flipped
-`session_shadow_reads` default-ON with a config migration); and its terminus —
-serving reads from the store — points the opposite way from this branch's
-non-negotiable zero-on-disk-change constraint. **It is also not S5's soak:** S5
-compares free-function reads against trait reads, an entirely different
-comparison. Track it as a #4249 phase-3 item ("retire the JSONL↔store dual path
-once the Phase-2 parity soak declares parity") with a deletion-ledger row naming
-the six sites above.
-
-### S5 — Shadow soak, then remove the parallel path
-
-One release with both paths live and a read-side comparison logged on mismatch
-(never panic — a mismatch on a user's real transcript must degrade, not crash).
-Then delete the redundant abstraction and update the ledger.
-
-**Exit:** ledger row terminal; `docs/` transcript-derived-view note restated in
-terms of the crate trait.
-
----
-
-### S6 — Follow-ups from the §3.5 re-examination
-
-Independent of S0–S5; each is separately shippable and none requires the
-transcript decision.
-
-1. **Unify dispatcher selection with the model layer** (§3.5.3). Merge with the
- parent spec's DS-5b — dispatcher choice, tool-call rendering, and tool-call
- parsing are one concern. Deliverable: the crate owns native-vs-prompt-guided;
- OpenHuman passes the `integrations_agent` override as policy and keeps
- `to_provider_messages` for the durable envelope. Est. host LOC removed when
- combined with DS-5b: **~2,400**.
-2. **Upstream the message-list helpers** (§3.5.2): `tool_records_from_conversation`,
- `stamp_tool_failures`, `parse_tool_call_id`, `short_failure_detail`,
- `replace_last_assistant_reply` → crate `harness::message`. ~150 LOC. Small,
- uncontroversial, do it alongside DS-5b's parity-test port.
-3. **Design a crate turn-preparation seam** (§3.5.4). A `ContextEnricher` /
- `TurnPreparation` pipeline — ordered, fallible, returning prompt fragments +
- metadata — so product enrichment registers instead of being hand-written into
- `turn()`. This is a **crate roadmap proposal, not a refactor**: write the
- design, get it accepted upstream, then migrate OpenHuman's enrichers
- (agent experience, recall citations, and announcements) onto it.
- Do not start by moving code.
-4. **Continue adopting crate types field-by-field on `Agent`**, following the
- `workspace_descriptor: tinyagents::harness::workspace::WorkspaceDescriptor`
- precedent. This is how `Agent` converges without ever relocating — record
- each adopted field in the ledger.
-
-**Exit:** items 1–2 landed; item 3 is an accepted-or-rejected upstream design
-doc, not an open question; item 4 has a standing ledger section.
-
-## 6. Explicitly out of scope
-
-Recorded so a later audit does not re-litigate:
-
-- `builder/` (1,699 + 666 + 96 + 55) — 21-domain host wiring, and it builds a
- *different object* than the crate's `AgentHarness` (§3.5.1). **Permanent
- host**, minus the dispatcher-selection carve-out in S6.1.
-- `turn/core.rs`, `turn/tools.rs`, `turn/context.rs`, `turn/session_io.rs`,
- `turn/mod.rs`, `turn/graph.rs` — product turn preparation; the engine already
- left in WP-3 (§3.5.2). **Permanent host**, minus the ~150 LOC of message-list
- helpers in S6.2 and whatever S6.3's preparation seam later absorbs.
-- `runtime.rs`, `types.rs` — `AgentSession` is a bag of host handles. **Permanent host.**
-- `tool_progress.rs` (256) — already the C4 Step-5 deletion target; belongs to
- the progress-tracing workstream (parent spec DS-5), not here.
-- `ChatMessage` itself — WP-1 settled this: it is the versioned on-disk record,
- and replacing it with crate `Message` changes existing users' data. Under
- Option A it does not move. Only Option B reopens it.
-
----
-
-## 7. Risks
-
-- **Silent model-context corruption is the top risk.** If `messages()` is wired
- to the display read path (or to a naive line replay), every compacted thread
- feeds the model duplicated pre-compaction history. It will not throw; it will
- degrade answers and inflate token cost. S3's compaction test is the gate.
-- **`replace()`'s trait default is dangerous here.** The crate's default clears
- then re-appends, which the crate's own docs flag as non-atomic. Against an
- append-only durable log it is worse than non-atomic — it is destructive.
- Override it; never inherit it.
-- **On-disk compatibility.** Existing installs have live `session_raw` files,
- including legacy `DDMMYYYY/` dirs. Resume must keep working across the change;
- the `read_transcript_legacy_md` path and the flat/dated fallback both need
- coverage in the soak.
-- **Blast radius beyond `agent/`.** 24 files across `threads`, `session_import`,
- `learning`, `migrations`. The `threads/turn_state` derived-view contract is
- the fragile one.
-- **≥ 80% diff-coverage merge gate.** S2/S4 touch many call sites; check
- `diff-cover` locally before pushing rather than discovering it in CI.
-- **Two Cargo worlds** — any vendored bump (only under Option B) regenerates
- root **and** `app/src-tauri` lockfiles.
-- **`GGML_NATIVE=OFF`** for local root-crate `cargo` runs on Apple Silicon.
-- **GPL/crates.io boundary** — under Option B, the `session_raw` format becomes
- public API of a redistributed crate. Nothing product-specific (agent ids,
- OpenHuman path conventions, `.md` rendering) may cross.
-
----
-
-## 8. Summary
-
-| | |
-| --- | --- |
-| Proposed | move `harness/session/` → `tinyagents::sessions` |
-| Verdict | **rejected as a unit** — ~8,600 of 11,073 prod LOC is host wiring; `builder/factory.rs` alone imports 21 OpenHuman domains |
-| In scope | `transcript.rs` (1,997), `turn_checkpoint.rs` (105), `migration.rs` (373) — ≤ 2 host imports each |
-| Key finding | the crate already ships `harness::memory::ChatHistory` + `harness::store` stream API; OpenHuman has a **second implementation**, not a missing home |
-| Key constraint | crate `ChatHistory` cannot express compaction records, interrupted partials, or dual read paths — a naive impl corrupts model context |
-| Recommendation | **Option A** — host backend behind the crate trait; zero on-disk change, reversible. Ledger is ≈ **−15 / +90 LOC** (S2–S4 overall +782 / −0), *not* the "~400 LOC removed" originally claimed — see §5 S4, [Where "~400 LOC" came from](#where-400-loc-came-from-and-why-it-is-struck) |
-| Escalation | **Option B** (upstream `JsonlChatHistory`, ~2,100 LOC) only as a deliberate crate-roadmap decision |
-| `builder/factory.rs` re-check (§3.5.1) | stays — builds `Agent` (40+ fields of product session state), not `AgentHarness` (6 fields of execution config); one real carve-out: dispatcher selection duplicates crate `with_native_tool_calling` |
-| `turn/core.rs` re-check (§3.5.2) | stays — the engine left in WP-3; residue is product enrichment. ~150 LOC of message-list helpers are upstreamable |
-| The generalizable ask | the missing artifact is a crate **turn-preparation seam** (S6.3), not a relocated file — move the shape down, keep the wiring up |
diff --git a/docs/specs/2026-08-02-core-kernel-domain-reorg.md b/docs/specs/2026-08-02-core-kernel-domain-reorg.md
deleted file mode 100644
index ac976b587e..0000000000
--- a/docs/specs/2026-08-02-core-kernel-domain-reorg.md
+++ /dev/null
@@ -1,345 +0,0 @@
-# Core kernelization, part 2 — the domain-family reorg
-
-**Status:** structural half complete · **Date:** 2026-08-02 · **Scope:** `src/openhuman/**`
-**Companions:** `docs/specs/kernel.md` — the subsystem/driver model this feeds into, still an
-uncommitted design draft, so it is referenced by name rather than linked ·
-[`../plans/pluggable-core/README.md`](../plans/pluggable-core/README.md) (the host-side
-`CoreBuilder`/`CoreContext` work) · `AGENTS.md` § *Compile-time domain gates*
-
----
-
-## 1. Where the program stands
-
-The kernelization program has two halves. **The dependency half is largely done**; the
-**structural half is complete** — 124 top-level domain directories are down to 31, and both
-root-level `*.rs` violations are gone.
-
-### Done (#4795 epic, then #5314)
-
-`#5314` took the `--no-default-features --features flows` profile from **418 → 280** unique crate
-names by gating dependency cohorts, and — more importantly — **built the ruler**:
-
-| Tool | What it does | CI-wired? |
-| --- | --- | --- |
-| `scripts/kernel-floor.sh` | Counts packages / unique names / native-toolchain builds for a profile | via the checker |
-| `scripts/kernel-floor.limits` | The ratchet. Only goes down; raising a number needs written justification | yes |
-| `scripts/check-kernel-floor.sh` | Fails CI when a profile exceeds its limit | `ci-lite.yml:460` |
-| `scripts/assert-shed.sh` | Proves a crate is absent from the **normal** edge graph | manual |
-| `scripts/ci/check-feature-forwarding.mjs` | Fails when a default-ON gate is not forwarded to the desktop shell | yes |
-
-> **`assert-shed.sh`, not `cargo tree -i`.** The older checklists (including the first draft of
-> this plan) said to prove a shed with `cargo tree -i <crate>`. That is wrong twice over: it
-> *exits non-zero* when the crate is absent, so a naive `if` inverts the result; and `-i` resolves
-> against the whole package set, so a crate that survives only as a dev-dependency is reported as
-> present. Use `scripts/assert-shed.sh <profile> <crate>...`.
-
-Current floor, measured 2026-08-02: **312 packages / 285 names / 6 native**
-(`aws-lc-sys`, `libgit2-sys`, `libsqlite3-sys`, `libz-sys`, `lzma-sys`, `ring`).
-Stated target: **222 names / 2 native** (`libsqlite3-sys`, `ring`).
-
-The 312/285 line is above the 280 low-water mark because merging `origin/main` inherited +5 names
-from unrelated upstream work (#5232 SDK vendoring, #5202/#5233 backend-client refactors). All
-seventeen previously-shed crates were re-asserted absent. Do not raise it again without re-running
-that assertion — a merge silently re-adding a shed crate looks identical to upstream growth if you
-only compare totals.
-
-### In progress — the structural half
-
-At the start of this work `src/openhuman/` was **124 flat directories** plus two root-level
-`*.rs` files (`util.rs`, `dev_paths.rs`) violating the AGENTS.md "no new root-level `*.rs`" rule,
-with only **12** carrying a module-level `#[cfg]`. A single capability was spread across sibling
-top-level dirs — `memory*` is 13, `agent*` is 6, `mcp_*` is 4, `runtime_*` was 3 — so every gate
-meant `#[cfg]`-ing scattered `pub mod` lines and hand-syncing five parallel registries
-(`DomainGroup`, `DomainSet`, `StoreInitPlan`, `DomainSubscriberPlan`, `tool_group()`).
-
-**Steps 1–9 landed: 124 → 31 directories, 2 → 0 root-level `*.rs`.** Families so far: `meet/`,
-`util/`, `sandbox/cwd_jail`, `cron/scheduler_gate`, `runtime/`, `media/`, `desktop/`, `hosted/`,
-`subconscious/{triggers,monitors}`, and `mcp/`, and the existing-gate families `voice/audio_toolkit`,
-`web3/{wallet,x402}`, `medulla/chat`, `flows/{tinyflows,rhai}`,
-`channels/{whatsapp_data,webview_accounts}`, and step 6's seven medium families —
-`threads/{goals,todos}`, `tools/{registry,status,timeout,agent_policy}`, the new `platform/`
-(ten host-platform domains), `config/{migrations,migration_helpers,workspace}`,
-`integrations/{composio,recall_calendar,file_storage,task_sources}`,
-`skills/{catalog,runtime,webhooks}`, `inference/{embeddings,tokenjuice}`, and step 7's kernel
-`security/{approval,credentials,keyring,keyring_consent,encryption,prompt_injection,devices}`.
-The `heartbeat/` re-export shim is deleted, step 8 folded fourteen domains into `agent/`, and
-step 9 folded thirteen domains into `memory/` — the last and largest family.
-
-**That is what this document is about.** The remaining dependency sheds are blocked on it or are
-cross-repo; the structural work is what makes the next twenty gates cheap instead of expensive.
-
----
-
-## 2. The organizing rule
-
-> **A family directory exists if and only if its members would be compiled out together.**
-
-Family boundary == future gate boundary. Directories whose names merely rhyme do not merge
-(`orchestration` vs `agent_orchestration`; `web_chat` is **not** part of `channels`).
-
-Kernel vs subsystem is decided by the `kernel.md` §4 criterion: *would a build whose only driver is
-a third-party external backend still need this file?* Yes → kernel. No → subsystem.
-
-### Why the move is safe
-
-RPC namespaces are **string literals in `ControllerSchema`**, not derived from module paths. So
-the `/rpc` surface, `/schema` output, agent-tool names, `DomainEvent::domain()`, and the frontend
-catalog are **byte-identical after a move**. All `include_str!`/`include_bytes!` sites and all
-`#[path = "…"]` attributes are intra-directory and travel with their directory. There are zero
-`module_path!()` call sites in `src/`.
-
-Corollary, and the pilot proved it: after moving `agent_meetings` → `meet/backend_bot`, the
-namespace string is still `"agent_meetings"`. **Do not "fix" namespace strings to match new
-paths** — directory layout and wire surface are independent axes.
-
-### Rules for a move PR
-
-- One PR per family. `git mv` + a mechanical path rewrite. No logic change, no behaviour change.
- If a hunk isn't a path, it doesn't belong in the PR.
-- **No `pub use` transition shims.** The compiler catches 100% of intra-crate breakage.
- `src/openhuman/heartbeat/` was the standing counter-example: a 10-line shim added "so external
- paths keep compiling without a crate-wide rename", which then sat there indefinitely with live
- call sites. It had three real callers; step 3 retargeted them and deleted it. Worse than
- useless, a shim is an always-compiled `pub mod` re-exporting into a gated tree, which defeats
- the gate it fronts.
-- Do not touch `DomainGroup`/`DomainSet`. That realignment is Phase 5 and needs its own tests.
-- **A `#[cfg]` may move, but the compiled set may not change.** Nesting a facade+stub domain under
- a leaf-gated parent forces the parent to become a facade (see the pilot). That is a mechanical
- consequence, not a behaviour change, and the both-ways tests prove it.
-
----
-
-## 3. Pilot — `meet/` (landed)
-
-```
-src/openhuman/meet_agent/ -> src/openhuman/meet/agent/
-src/openhuman/agent_meetings/ -> src/openhuman/meet/backend_bot/
-```
-
-Chosen as the pilot because it is the smallest family that already has a gate *and* exercises all
-three module patterns at once: `meet` was leaf-gated, `meet/agent` is leaf-gated internally, and
-`meet/backend_bot` is facade+stub with three always-compiled callers.
-
-It surfaced the one non-obvious rule above: `pub mod meet;` had to become **ungated**, with the
-`#[cfg(feature = "meet")]` pushed down onto each submodule in `meet/mod.rs`, because
-`backend_bot`'s stub must resolve in a `meet`-less build. Same set of items compiles either way.
-
-Verification that a family-move PR must reproduce:
-
-```bash
-GGML_NATIVE=OFF cargo check --all-targets
-GGML_NATIVE=OFF cargo check --lib --no-default-features
-GGML_NATIVE=OFF cargo check --manifest-path app/src-tauri/Cargo.toml
-GGML_NATIVE=OFF cargo test --lib core:: # gates on
-GGML_NATIVE=OFF cargo test --lib --no-default-features core:: # gates off
-cargo fmt --check
-bash scripts/check-kernel-floor.sh --verbose # must not move
-node scripts/ci/check-feature-forwarding.mjs
-node scripts/generate-test-inventory.mjs --check # keyed on namespaces, so it should pass unchanged
-```
-
-Expect `cargo fmt` fallout: longer paths re-wrap imports. That is the whole diff outside the
-renames.
-
-### Gotchas the first two moves hit
-
-- **Braced imports.** `use crate::openhuman::{scheduler_gate, todos};` is invisible to a
- `s/openhuman::scheduler_gate/…/` rewrite. There are only a handful crate-wide; the compiler
- finds them immediately, but budget for a hand-fix per family.
-- **The rewrite loop must not word-split in zsh.** `sed -i … $files` passes the whole newline-
- separated list as *one* argument under zsh (which does not word-split unquoted parameters), so
- the rewrite silently does nothing and the greps still show old paths. Use
- `grep -rlZ … | xargs -0 sed -i …`.
-- **One observable string DID change, deliberately.** The tracing target in
- `tools/agent_policy/engine.rs` went from `"openhuman::agent_tool_policy"` to
- `"openhuman::tools::agent_policy"` (6 sites). Tracing targets mirror module paths by
- convention — the other three `target: "openhuman::…"` literals in the crate all do — so
- leaving the old value would have pointed a log filter at a module that no longer exists.
- Nothing operator-facing referenced it (no docs, scripts, or CI). Recorded here because a
- pure-move commit must never change an observable string *silently*; `RUST_LOG=openhuman::
- agent_tool_policy=debug` now matches nothing, and tracing's EnvFilter fails open.
-- **Pre-existing failures to not chase.** `cron::scheduler::tests::{run_agent_job_returns_error_without_provider_key,
- cron_agent_job_short_loopback_send_error_stays_retryable}` overflow the stack on `main`, before
- any reorg. Verify with `git stash -u` + rerun before assuming a move caused a failure.
-
----
-
-## 4. Target tree — 124 dirs + 2 root files → ~30 dirs + 0 root files
-
-### Subsystems (gateable families)
-
-| Family | Absorbs |
-| --- | --- |
-| `memory/` | ✅ **landed** — `memory_store→store`, `memory_sync→sync`, `memory_tree→tree`, `memory_search→search`, `memory_sources→sources`, `memory_queue→queue`, `memory_diff→diff`, `memory_goals→goals`, `memory_conversations→conversations`, `memory_tools→tool_memory`, `tinycortex`, `agent_memory→agent`, `people`; parent stays put (kernel, ungated) — `memory/sync.rs` renamed to `memory/sync_events.rs` first to free the name, and `memory_tools` lands as `tool_memory` to dodge the pre-existing `memory/tools/` |
-| `agent/` | ✅ **landed** — `agent_experience→experience`, `agent_orchestration→orchestration`, `agent_registry→registry`, `agentbox`, `harness_init`, `session_db`, `session_import`, `context`, `profiles`, `learning`, `plan_review`, `file_state`, `artifacts`, `tinyagents`; parent stays ungated (kernel) and keeps its own name — no `agent/core` rename |
-| `inference/` | ✅ **landed** — `embeddings`, `tokenjuice`; parent stays ungated (kernel). NB the `inference` Cargo feature gates only the cpal capture stack + microphone probe, *not* this directory |
-| `skills/` | ✅ **landed** — `skill_registry→catalog` (not `registry` — `skills/registry.rs` and the stub's inner `pub mod registry` both already own that name), `skill_runtime→runtime`, `webhooks`; parent stays ungated (three facades, two with `stub.rs`), and `webhooks` is a permanently-ungated child |
-| `flows/` | ✅ **landed** — `tinyflows`, `rhai_workflows→rhai`; parent is leaf-gated on `flows` (no stub — every external site is a registration site) |
-| `mcp/` *(new)* | ✅ **landed** — `mcp_server→server`, `mcp_registry→registry`, `mcp_audit→audit`, `mcp_client::{registry,stdio,spawn_env,setup_agent}→config_servers` *(leaf-gated)*, `mcp_client::{client,client_helpers}→http_client` *(ungated carve-out)*, `mcp_client::sanitize→util/sanitize`; parent stays ungated (three facades with `stub.rs` + the always-compiled `http_client`) |
-| `channels/` | ✅ **landed** — `whatsapp_data`, `webview_accounts`; parent stays ungated (the `traits`/`cli` carve-outs), gate pushed onto each child |
-| `meet/` | ✅ **landed** — `meet_agent→agent`, `agent_meetings→backend_bot` |
-| `voice/` | ✅ **landed** — `audio_toolkit`; parent stays ungated (facade + `stub.rs`), gate pushed onto the child |
-| `web3/` | ✅ **landed** — `wallet`, `x402`; parent stays ungated (all three are facades with their own `stub.rs`) |
-| `media/` *(new)* | ✅ **landed** — `media_generation→generation`, `image`; parent is leaf-gated on `media` since both children were wholly gated |
-| `medulla/` | ✅ **landed** — `medulla_chat→chat`; parent stays ungated (facade + `contract`/`events` type carve-out), gate pushed onto the child |
-| `runtime/` *(new)* | ✅ **landed** — `runtime_node→node`, `runtime_python→python`, `runtime_python_server→python_server`, `runtime_pool→pool`, `javascript` |
-| `integrations/` | ✅ **landed** — `composio`, `recall_calendar`, `file_storage`, `task_sources` (a move into an already-populated parent) |
-| `hosted/` *(new)* | ✅ **landed** — `billing`, `referral`, `announcements`, `team`, `orchestration` |
-| `desktop/` *(new)* | ✅ **landed** — `accessibility`, `overlay`, `dashboard`, `provider_surfaces`, `notifications`, `app_state` |
-| `subconscious/` | ✅ **landed** — `subconscious_triggers→triggers`, `monitor→monitors`, `heartbeat/` shim deleted |
-| standalone | `search/`, `tinyplace/`, `web_chat/`, `http_host/`, `test_support/` |
-| `json_schema/` | **kernel, deliberately unowned.** Vendor-neutral JSON Schema / JSON value walking, shared by the Composio catalog (`integrations/composio`, always compiled) and the tinyflows capability adapters (`flows/tinyflows`, gated). It belongs to neither: housing it in either would force a dependency edge from the other, and one of those directions is the always-on → gated back-edge the kernelization work exists to remove. Ungated, no gate planned. |
-
-### Kernel (never gated)
-
-| Family | Absorbs |
-| --- | --- |
-| `config/` | ✅ **landed** — `migrations`, `migration→migration_helpers`, `workspace`; the two migration dirs stay distinct per rule 7 |
-| `security/` | ✅ **landed** — `approval`, `credentials`, `keyring`, `keyring_consent`, `encryption`, `prompt_injection`, `devices`; parent and every child stay ungated (kernel). No collision with the pre-existing `security/pairing.rs` |
-| `tools/` | ✅ **landed** — `tool_registry→registry`, `tool_status→status`, `tool_timeout→timeout`, `agent_tool_policy→agent_policy` |
-| `platform/` *(new)* | ✅ **landed** — `service`, `startup`, `update`, `doctor`, `health`, `proc_metrics`, `connectivity`, `about_app`, `cost`, `socket` |
-| `threads/` | ✅ **landed** — `thread_goals→goals`, `todos` |
-| `cron/` | ✅ **landed** — `scheduler_gate` |
-| `sandbox/` | ✅ **landed** — `cwd_jail` |
-| `util/` *(new)* | ✅ **landed** — `util.rs` split into `util/{mod,text,retry,types}.rs`, `tls→util/tls`, `dev_paths.rs` deleted, `mcp_client::sanitize→util/sanitize` (landed with the `mcp/` move) |
-
-### Name collisions — dodge, don't pay
-
-`memory/` already contains `sync.rs` and `tools/`. Renaming `memory → memory/core` costs ~545
-import rewrites; instead rename `memory/sync.rs → memory/sync_events.rs` (6 external refs) and
-land `memory_tools` as `memory/tool_memory/` (3 refs). Likewise `agent/tool_policy.rs` already
-exists, so `agent_tool_policy` goes to `tools/agent_policy/`; `agent/cost.rs` exists, so `cost`
-goes to `platform/`.
-
-### Must not move / must not change
-
-1. **`web_chat/` stays top-level** — deliberately decoupled from `channels` in #5002/#5003;
- always-compiled despite its `DomainGroup::Channels` tag; the channels both-ways test asserts
- `channel` survives with the feature OFF.
-2. `channels::{traits, cli}` stay ungated carve-outs — reached by the always-on
- `agent::harness::session::runtime::run_interactive`.
-3. `skills::{types, ops_types}` stay ungated and stay put — ~236 files consume `ToolResult` /
- `ToolContent` through `tools/traits.rs`. This is the largest import fan-out in the crate.
-4. `tools/` ownership rule untouched — domain tools stay in each domain's `tools.rs`, re-exported
- through the globs in `tools/mod.rs`. Only the glob's *path* changes.
-5. `mcp::registry::types`, `mcp::audit::types`, `mcp::server::tools::types` stay ungated.
-6. `tinyplace/` does **not** go under `web3/` — its signer works via ed25519 independently.
-7. Do not merge `migration/` into `migrations/` during a move (pure moves only).
-8. **`scripts/ci/orch-ip-gate.sh` hard-codes domain paths and fails *open* on a wrong path.**
- Retargeted to `src/openhuman/hosted/orchestration/…` in step 3; its
- `src/openhuman/subconscious/profiles/tinyplace.rs` reference is still valid because
- `subconscious/` stayed put. Re-check this script on any move that touches either path, and
- confirm the directory it names actually exists — a pass proves nothing on its own.
-9. `scripts/agent-batch/` specs use `owned_paths: ["src/openhuman/<dom>/"]` — sweep live specs.
-
-### Order
-
-1. ✅ `meet/` — pilot.
-2. ✅ `util/` + `sandbox/` + `cron/` — cleared both root `*.rs` violations and deleted dead
- `dev_paths.rs`. (`sanitize` moves out of `mcp_client` with step 5, not here — a pure move PR
- should not also carve a module out of an unrelated domain.)
-3. ✅ `runtime/`, `media/`, `desktop/`, `hosted/`, `subconscious/` — new parents. `hosted/` also
- retargeted `scripts/ci/orch-ip-gate.sh` (see rule 8).
-4. ✅ `voice/`, `web3/`, `medulla/`, `flows/`, `channels/` — existing gates; each validates that its
- `stub.rs` survives relocation.
-5. ✅ `mcp/` — the only family with a genuine *split*. `mcp_client` divided three ways:
- `config_servers` (leaf-gated), `http_client` (ungated carve-out), `sanitize` → `util/`.
-6. ✅ `threads/`, `tools/`, `platform/`, `config/`, `integrations/`, `skills/`, `inference/` — seven independent families, one commit each.
-7. ✅ `security/` — the kernel security family; `kernel.md` §3.4's `Guard<D>` draw set made physical.
-8. ✅ `agent/` — fourteen domains folded in; `agent/` itself stayed put as the parent (an
- `agent → agent/core` rename would have cost ~999 extra import rewrites and buys no gate).
- Kernel: no `#[cfg]` anywhere in the family.
-9. ✅ `memory/` — **last**, deliberately: it is `kernel.md` §5's pilot subsystem, so its
- layout gets drawn with the driver contract in hand rather than guessed.
-
-Rationale for biggest-last: the tooling (rewrite script, check matrix, PR template) gets proven on
-fifteen cheap families before being pointed at the two that are ~57% of the total churn.
-
----
-
-## 5. Remaining dependency sheds
-
-Target is 6 → 2 native builds. Four of the six are addressable, and two of those are unblocked by
-the reorg:
-
-| Native crate | Owner | Gate | Status |
-| --- | --- | --- | --- |
-| `libgit2-sys` (via `git2`) | `memory_store/content/wiki_git` **and** `tinycortex/git-diff` | `memory-git` | **cross-repo** — see below |
-| `lzma-sys` (via `xz2`) | *(none — removed)* | — | ✅ **done**, and better than planned: extraction moved into the `tinyruntime` module, so `xz2` left the manifest for **every** configuration rather than only for builds that opted out of `runtime-node` |
-| `libz-sys` | shared (`flate2`/`zip`/`git2`) | — | partly falls out of the above |
-| `aws-lc-sys` | TLS stack | — | needs a rustls-provider decision, own slice |
-| `libsqlite3-sys`, `ring` | kernel | — | **target keeps these** |
-
-Also ready, no native build: `objc2-contacts` (macOS, sole owner `people/address_book.rs`) behind
-a `contacts` gate.
-
-### `memory-git` is a cross-repo change
-
-`vendor/tinycortex` is its own submodule (`tinyhumansai/tinycortex`) and the root pins it with
-`features = ["git-diff", …]`, so gating the host's `wiki_git` alone sheds nothing — `git2` still
-arrives through the crate. The host's `memory_diff` domain also re-exports
-`tinycortex::memory::diff::*`, which lives behind that same feature, and has two real
-non-registration callers (`subconscious/profiles/memory.rs`, `memory_sources/sync.rs`).
-
-The clean shape, and the vendor crate is already 90% of the way there —
-`vendor/tinycortex/src/memory/diff/types.rs` exists and `git2` is confined to `ledger.rs` +
-`ledger_helpers.rs`:
-
-1. **tinycortex PR** — carve `memory::diff::{types, source, snapshot, checkpoint, diff}` out from
- behind `git-diff`, leaving only `ledger`/`ledger_helpers`/`DiffEngine` gated. Same "inert types
- stay ungated, only behaviour gates" rule the `skills` and `mcp` gates follow.
-2. **openhuman PR** — `memory-git = ["dep:git2", "tinycortex/git-diff"]`; pin tinycortex with
- `default-features = false, features = ["persona", "sync"]`; leaf-gate host `wiki_git`; make
- `memory_diff` facade+stub with `types` ungated so the two callers need no `#[cfg]`.
-3. Bump the gitlink; lower `kernel-floor.limits` in the same PR.
-
-Off-state semantics: wiki content is still written to disk, just not versioned; diff/checkpoint
-RPCs are unregistered and the `MemoryDiffTool` is absent.
-
----
-
-## 6. Superseded by #5314 — do not re-do
-
-- A `check-gate-sheds.mjs` that parses `# SHEDS:` comments → **`assert-shed.sh` +
- the `kernel-floor.limits` ratchet already cover this**, and the ratchet is the stronger guard: a
- gate that stops shedding raises the floor and fails CI.
-- A binary-size budget lane → **`check-kernel-floor.sh` is wired at `ci-lite.yml:460`** and counts
- crates/native builds, which is a better proxy for an embeddable library than stripped bytes.
-- Making `enigo`/`arboard`/`rdev` optional, the Polymarket/ethers cohort, `starship-battery` →
- all landed in #5314.
-
-## 7. Out of scope — do not re-litigate
-
-- **Gating `agent` wholesale** — `agent::harness` has ~448 external references; `tools/`,
- `web_chat`, and `medulla_session` all depend on it. The harness *is* the kernel's execution engine.
-- **Gating `tools` wholesale** — `tools::traits` has ~248 external references. Kernel, permanently.
- Only the `tools/impl/*` families gate.
-- **Gating `memory` wholesale** — it becomes a subsystem *slot* (`kernel.md` §5), not
- a feature.
-- **Dropping `keyring`, `rusqlite`, `tinyagents`, `tinychannels`, `tinycortex`, `tinyplace`** —
- load-bearing across always-on domains. `tinychannels` in particular was addressed by gating
- *providers inside the vendored crate* (`email`, `lark`), not by gating the crate out; repeat
- that shape rather than proposing the crate-level gate again.
-
----
-
-## 8. Definition of done
-
-1. `src/openhuman/` is ~30 directories, zero root-level `*.rs` besides `mod.rs`.
-2. Every family directory maps 1:1 to a gate or is declared kernel in this document.
-3. `kernel-floor.limits` reaches 222 names / 2 native.
-4. Each gate has both-ways tests in `src/core/all_tests.rs` and `tools/ops_tests.rs`.
-5. ✅ **Done.** `DomainGroup` gained seven variants, not four: `Inference`, `Integrations`,
- `Automation` (cron + subconscious), `Runtimes` (runtime + sandbox), `Desktop`, `Hosted`,
- `Relay` (tinyplace). The extra three over the original estimate are `Inference`, `Desktop`
- and `Hosted` — carving those out is what lets `embedded()` stop setting `platform: true`
- just to reach credentials and config. `Platform` now holds only `platform/`, `tools/`,
- `http_host/`, `test_support/`. `DomainSet::kernel()` and `examples/embed_kernel.rs` exist;
- the example runs and demonstrates memory-on / agent-unknown-method.
-
- The realignment also fixed two defects the flat tree had hidden: `harness()` was dropping
- ten namespaces (including `harness_init`) into `Platform` despite claiming their families,
- and `StoreInitPlan.people` keyed on `Platform` while its controllers moved to `Memory` —
- which would have registered the people RPC surface with no store behind it.
-6. Hand off to `kernel.md`'s subsystem registry (`src/core/subsystem/`, `Driver`,
- `Guard`, `subsystems_status`).
diff --git a/docs/specs/2026-08-11-loadable-native-modules.md b/docs/specs/2026-08-11-loadable-native-modules.md
deleted file mode 100644
index 3c39ff4d63..0000000000
--- a/docs/specs/2026-08-11-loadable-native-modules.md
+++ /dev/null
@@ -1,130 +0,0 @@
-# Loadable native modules
-
-Status: Implemented (`documents` is the first consumer)
-
-## Problem
-
-A codec is not kernel work, and each one drags a tree of parsers into a binary
-that mostly does something else. The document surface was the clearest case: the
-`documents` gate carried `docx-rs`, `ppt-rs` and `pdf-extract` plus their font,
-PostScript and XML tails — 39 crates, including four native C builds — to support
-three agent tools.
-
-Gating them helped the builds that turned them off and did nothing for the build
-that ships, which turns them on. What was needed was a boundary that survives
-compilation: the capability present, the dependencies absent.
-
-## Goals
-
-- Run a capability as a compiled artifact loaded at runtime, outside this binary.
-- Verify what gets loaded, from a decision made at build time rather than by
- whatever a release page serves.
-- Keep the tool surface, the tool schemas and the agent-facing errors unchanged.
-- Leave the kernel profile untouched: a host embedding workflows must not acquire
- a dynamic-library loader.
-
-## Non-goals
-
-- Running untrusted third-party code. A module is first-party code that ships
- separately; anything untrusted belongs in a process.
-- A module marketplace, or any path by which a server or a config file can name
- an artifact to load.
-- Unloading. tinybus never unloads a library, and nothing here pretends otherwise.
-
-## Behaviour
-
-`openhuman::modules` owns a private in-process broker, a tinybus `ModuleHost`, and
-a compiled-in registry. A registry entry names a module's id, the interfaces it
-claims, its release tag, and one SHA-256 per published artifact.
-
-On first use of a capability a module provides, `ops::ensure_loaded` resolves it —
-already serving, then a configured local artifact, then the install directory,
-then the tinybus module search path, then a verified download — and caches the
-outcome for the process. Loaded, the module is an ordinary bus peer, and the core
-calls it over a proxy.
-
-Inbound payloads ride tinybus streams alongside the call. Outbound payloads are
-held by the module and pulled in chunks, because a served object cannot open a
-stream back to its caller.
-
-Config (`[modules]`) controls whether modules load, whether this host may fetch
-them, where they install, and whether a local build stands in for a release. It
-cannot add a module.
-
-## Invariants and constraints
-
-- **A loaded module is trusted in-process code.** It shares the address space, the
- privileges and the crash domain. Deadlines, bounded queues and caught panics
- contain ordinary misbehaviour, not a segfault. The ABI, manifest and digest
- gates decide what is *admitted*, never what is *safe*.
-- **The set of loadable modules is compiled in.** A registry that config or RPC
- could extend would be remote code execution with a download step.
-- **Digests are the host's half of a two-sided check.** tinybus fetches the
- release's own checksum manifest, compares it with the pinned digest, hashes the
- download, and extracts only after. A release re-cut under the same tag stops
- matching rather than silently replacing what runs in-process.
-- **Failure is terminal for the process.** tinybus never unloads, so a refused or
- faulted module cannot reach a different outcome without a restart. Failures are
- cached and say so.
-- **Admission is permissive, not strict.** Strict mode also refuses a module whose
- rustc version differs from the host's, and released artifacts are built on
- whatever toolchain CI had while this crate pins its own — the real published
- artifact is refused that way. Everything protecting the address space is still
- enforced; only the toolchain string is relaxed.
-- **A target triple is not enough.** A library built against glibc 2.39 fails to
- `dlopen` on a 2.35 host. Artifact selection is an ordered list of candidates,
- glibc-aware, and empty on a host no published artifact targets.
-- **Modules cannot publish `DomainEvent`s.** `OnceBus::init_in_process` owns its
- broker privately, so modules run on a second one.
-- **The loader stays out of the kernel profile.** `tinybus/modules` is forwarded
- from this crate's `modules` feature, never enabled on the dependency, because
- `tinybus` is always-on surface.
-
-## Acceptance criteria
-
-- The `documents` gate carries no codec: `docx-rs`, `ppt-rs`, `pdf-extract`,
- `lopdf`, `syntect`, `pulldown-cmark` and `xml-rs` are absent from both the
- `documents` and the product profiles, proven with `scripts/assert-shed.sh`.
-- The kernel profile is unchanged against upstream: `scripts/kernel-floor.sh
- flows` reports the same packages, names and native builds.
-- `modules.*` is unknown-method with the feature off, and both halves are pinned
- by tests.
-- The three document tools produce openable artifacts through a loaded module,
- including a deck whose images cross as a stream.
-
-## Testing notes
-
-**The module bus belongs to whichever runtime creates it.** The core has one
-runtime and never notices. Two `#[tokio::test]` functions each build their own,
-and the second to call a loaded module finds a broker whose tasks died with the
-first — the call hangs until a deadline above it fires, rather than failing.
-
-Any test that drives a real module must therefore be the only one in its process.
-The module-backed tool tests are `#[ignore]`d for that reason, not merely because
-they need an artifact. Run them one at a time:
-
-Linux, where the artifact is a `.so`. On macOS the built library is
-`libtinydocs_module.dylib` and on Windows `tinydocs_module.dll`; substitute the
-filename, and use the platform's own temporary directory rather than `/tmp`.
-
-```sh
-cargo build --release --package tinydocs-module \
- --manifest-path vendor/tinydocs/Cargo.toml
-mkdir -p /tmp/oh-modules && chmod 700 /tmp/oh-modules
-cp vendor/tinydocs/target/release/libtinydocs_module.so /tmp/oh-modules/
-
-OPENHUMAN_MODULE_PATH=/tmp/oh-modules \
- cargo test -p openhuman --lib --features documents -- --ignored \
- implementations::document::tests::execute_happy_path
-```
-
-## Open questions
-
-**A reply-stream seam in tinybus would delete the module's output store.** The
-only reason a produced document is held at all is that `Interface::call` receives
-no caller identity and no connection, so a served object cannot stream a reply.
-
-**Per-interface method lists in `module_export!`** would let one module serve a
-transfer interface and a format interface separately. Today the macro attaches its
-method list to the first entry in `provides` and leaves the rest empty, so a
-second fully-declared interface is not expressible.
diff --git a/docs/specs/2026-08-13-memory-module-port.md b/docs/specs/2026-08-13-memory-module-port.md
deleted file mode 100644
index 0510b9efb0..0000000000
--- a/docs/specs/2026-08-13-memory-module-port.md
+++ /dev/null
@@ -1,1226 +0,0 @@
-# Porting the memory subsystem into the TinyMemory module
-
-**Goal.** Reach memory only through the loaded `tinymemory` TinyBus module, and
-drop `tinymemory`, `tinymemory-api`, `tinymemory-core`, `tinymemory-tinycortex`
-and the direct `tinycortex` memory surface from this crate's dependency graph.
-
-**Status.** Audit complete; port staged below.
-
----
-
-## 1. What is already done
-
-The module architecture is finished and correct. This port is not building it —
-it is finishing a cutover that stopped half way.
-
-- `tinymemory-module` ships as a released `cdylib`, pinned with per-platform
- digests in `src/openhuman/modules/registry.rs` (`TINYMEMORY`, v1.0.1).
-- `src/openhuman/modules/memory.rs` implements `MemoryProvider` by forwarding
- ~53 methods — the full thirteen-family contract — one for one over the bus,
- lazily, with `memory::api::wire` mapping errors on **both** ends.
-- The hard problem is solved. An out-of-crate engine still needs to embed,
- summarise and extract, so three reverse bus services carry those calls back:
- `ChatHost`, `EmbeddingHost` and `RuntimeHost`, served by
- `src/openhuman/modules/memory_host.rs`. Credentials never cross —
- `BusEmbeddingHost::resolve_api_key` returns `None` by construction.
-- `src/openhuman/memory/binding.rs` already refuses embedded drivers outright
- and aliases the legacy `tinycortex` driver id onto the module.
-- `src/openhuman/memory/api/` is a host-local copy of the contract, and the
- binding and the module client already compile against it rather than against
- `tinymemory-api`.
-
-> ## ⚠ Scope correction (2026-08-15): §2's numbers understate the surface by ~3×
->
-> The counts below were derived by grepping for explicit `tinymemory_core::`
-> imports. That misses most of the direct-engine access, because
-> `memory/mod.rs` **re-exports the engine's modules under host-local paths**:
->
-> ```rust
-> pub use tinymemory_core::{ chat, global, queue, search, source_scope, store,
-> tinycortex, tree_policy, tree_source, util, … };
-> ```
->
-> So a call site written `crate::openhuman::memory::store::chunks::store::list_chunks(…)`
-> is engine access that looks exactly like host-local code, and never appears in
-> a `tinymemory_core` grep.
->
-> Measured properly: **100 files** reach the engine this way — 82 production,
-> and **52 of those outside `memory/`**. The heaviest users are
-> `store::chunks` (50), `store::create_memory` (31), `store::profile` (26),
-> `tree::tree_runtime` (22) and `tree::health` (20), concentrated in the agent
-> harness (`archivist`, `learning`, `session`) and `memory/read_rpc/`.
->
-> `memory/read_rpc/` is the sharpest example: four files serving a live RPC
-> surface straight off the memory database, one of them (`admin.rs`) opening a
-> raw `rusqlite::Connection` on the DB path. None of them names
-> `tinymemory_core`.
->
-> **What this changes.** Stages 2–3 are roughly three times the work the plan
-> assumed, and much of it is not "swap a call for a provider method" — whole
-> subsystems (`create_memory`, `profile`, `tree_runtime`, `health`) have no
-> contract representation and would each need a design decision like the ones
-> in §1d. The staging and sequencing still hold; the size estimate does not.
->
-> **Measured empirically:** deleting just `store` from that re-export list —
-> one of ~24 names — breaks **89 call sites across 51 files** in production
-> code alone (`cargo check`, no tests). That is one re-export.
->
-> **The facade was deleted first — see §2g.** Converting call sites from an
-> incomplete list could never converge while the facade kept generating new
-> ones; removing it turns the compiler into the inventory.
-
-## 2. What actually blocks dropping the crates
-
-**Roughly half the host's memory surface never went through `MemoryProvider`.**
-It reaches the engine directly, in-process.
-
-| Crate | References | Concentrated in |
-| --- | --- | --- |
-| `tinymemory_core` | 115 (30 real `use` sites) | `memory/{tools,query,tree,sync,host_impls}` |
-| `tinymemory_api::host` | 46 | `config/schema/*`, `inference/`, `cron/`, `integrations/` |
-| `tinycortex::memory` | 98 across 40 files | 56 of them **outside** `memory/` |
-
-### 2.1 The consequence is a split brain, not a style problem
-
-`memory_vector_search` calls `list_chunks(&config, &query)`
-(`memory/tools/search/vector_search.rs:160`). That resolves the workspace path
-and opens the same SQLite database the loaded module has already opened. With
-the module driver bound — which is now the only supported binding — the process
-runs **two independent engine instances over one database file**. The module is
-not authoritative today.
-
-### 2.2 The wire contract has real gaps
-
-These direct call sites are not all "provider calls written the lazy way". Four
-things they need have no representation in the thirteen families:
-
-| Missing | Needed by |
-| --- | --- |
-| **People** — `PeopleStore`, `PersonId`, `Handle`, `Interaction`. No capability family exists. | `memory/tools/people.rs`, `memory/people/` |
-| **Chunk-level store access** — `list_chunks`, `get_chunk`, `get_chunk_embeddings_for_signature_batch`, `ListChunksQuery`, `SourceKind` | `tools/search/{vector,hybrid,chunk_context}`, `tools/raw_store/*`, `query/*` |
-| **Retrieval primitives** — `fast_retrieve`/`FastRetrieveOptions`, `cover_window`, `search_entities`/`EntityKind`, `RetrievalHit`/`QueryResponse` | `query/{fast_walk,cover_window,search_entities,backend}` |
-| **Unified store types** — `MemoryKind`, `MemoryItemKind`, `UnifiedMemory` | `tools/search/hybrid_search.rs`, `tools/raw_store/kinds.rs` |
-
-Each needs a decision: widen the contract, or keep it host-side over data the
-provider already returns. Widening is not free — every method added to the wire
-is engine semantics both ends must agree on forever.
-
-### 2.3 Some of `tinymemory-core` belongs back in the host
-
-`tinymemory_core::{sync, composio_host, chat, learning_candidate, nlp_host}`
-and `memory/host_impls.rs` are orchestration, credentials and scheduling. By
-TinyMemory's own README split those are host concerns. They move **back** into
-OpenHuman rather than into the module, and `host_impls.rs` is deleted in favour
-of the bus services in `modules/memory_host.rs`.
-
----
-
-## 3. The landmine: two live copies of the embedding signature
-
-`src/openhuman/memory/api/host/` is a near-duplicate of `tinymemory_api::host` —
-11 of 17 files byte-identical, 6 diverged. One divergence is dangerous.
-
-`format_embedding_signature` exists in **three** places with **two** behaviours:
-
-| Copy | Form |
-| --- | --- |
-| `tinymemory_api::host::embeddings` (crate) | `provider={name};model={model};dims={dims}` |
-| `tinycortex::memory::store::vectors` | byte-identical to the above, pinned by a parity test in `tinymemory/core/src/tinycortex/parity.rs` |
-| `memory/api/host/embeddings.rs` (host-local) | **length-prefixed**: `provider={len}:{name};model={len}:{model};dims={dims}` |
-
-The host-local copy is a *correctness fix* — it stops two distinct
-(provider, model) pairs colliding onto one signature, and carries a regression
-test for exactly that. It is also, right now, **dormant**:
-`src/openhuman/inference/embeddings/provider_trait.rs:20` re-exports the **crate**
-version, so every vector written today uses the naive form and matches the
-engine.
-
-**This port will make the host-local copy live.** Re-pointing
-`inference/embeddings` at `memory::api::host` — which stage 1 does — silently
-switches the signature format. Every stored embedding is keyed by that string,
-so the effect is not a compile error or a test failure: recall quietly matches
-nothing and the system re-embeds the entire corpus.
-
-**Therefore:** the signature change must be landed as its own deliberate change,
-upstream in TinyMemory first, so the crate, TinyCortex and the host move
-together with a migration for stored vectors — *not* as a side effect of a
-re-point. Until then the host-local copy must be reverted to the naive form so
-the two copies agree.
-
-Two lesser divergences, both harmless and both resolved in favour of host-local:
-`subsystems.rs` defaults the driver to `"tinymemory"` (crate still says
-`"tinycortex"`), and `mod.rs` gates test support on `#[cfg(test)]` rather than a
-feature.
-
----
-
-## 4. Staged plan
-
-Each stage compiles and ships on its own.
-
-**Stage 0 — neutralise the landmine.**
-Revert `memory/api/host/embeddings.rs` to the naive signature form, keeping the
-collision test as `#[ignore]` with a pointer to this section. Open a TinyMemory
-issue for the real fix. *No behaviour change; makes every later stage safe.*
-
-> **Ordering constraint — `tinymemory-api` goes last, not first.**
-> `tinymemory_core::Config` is `dyn tinymemory_api::host::MemoryHostConfig`
-> (`tinymemory/core/src/lib.rs:32`), and `memory/host_impls.rs` implements eight
-> of these traits *for host types*. So for as long as `tinymemory-core` is a
-> dependency, the host's config must implement the **crate's** trait, and
-> re-pointing those references at the host-local copy would not compile. The
-> contract crate can only be dropped after the engine crate. Stages 1 and 5 were
-> the wrong way round in the first draft of this plan.
-
-**Stage 1 — close the wire gaps.**
-
-*Decision: all four surfaces are pushed down into TinyCortex and exposed through
-the TinyMemory contract. None is rebuilt host-side.* The host calls them over
-the bus like every other provider method, and the engine stays the single owner
-of storage and scoring.
-
-The audit shows this is far less new code than it looks, and **three of the four
-surfaces need no migration at all** — a first reading of the file lists suggested
-`tinymemory-core` carried a parallel implementation of retrieval and chunks. It
-does not:
-
-| Surface | Where it is today | Work |
-| --- | --- | --- |
-| Retrieval primitives | Algorithms already in `tinycortex::memory::retrieval`. `tinymemory-core/tree/retrieval/{cover,fast,search,drill_down,fetch,source}.rs` are 26–64 line **shims** that add source-scope filtering, limit truncation and logging — a policy layer, not a fork. | Expose only |
-| Chunk-level access | `tinymemory-core/store/chunks/store.rs` is a pure delegating wrapper — `engine_config(config)` then straight through to `tinycortex::memory::chunks`. | Expose only |
-| Unified store types | Same shim relationship over `tinycortex::memory::store`. | Expose only |
-| **People** | `tinymemory-core/people` — 2,138 LOC, its own SQLite database, its own migrations, a workspace-keyed process-global store, and **zero** TinyCortex references. | Genuine migration down into TinyCortex, then a new People capability family |
-
-### 1a. People migration — landed
-
-`tinymemory-core/people` (2,138 LOC, 34 tests) now lives at
-`tinycortex::memory::people`, behind a default-off `people` feature that implies
-`tokio` (the store shares its connection as an `Arc<tokio::sync::Mutex<_>>`).
-`tinymemory-core/people/mod.rs` is a re-export shim, matching `store/chunks`.
-Six `tracing::` calls became `log::` — all plain format strings, no structured
-fields — so `people` pulls in no dependency TinyCortex did not already have.
-
-**A live bug fell out of it.** The `contacts` gate was never forwarded. The
-reader has always lived below this crate, but `contacts` enabled four `objc2`
-crates *in the host* — which no file in `src/` names — and never reached
-`tinymemory-core`, where the `#[cfg]` is. So the macOS arm of `address_book.rs`
-was always compiled out: `SystemContactsSource` returned the empty stub,
-`people.refresh_address_book` reported success having seeded nothing, and macOS
-paid to compile four unused crates for it.
-
-This is the `voice` (#4901) / `tokenjuice-treesitter` (#4918) failure shape
-exactly — an unforwarded gate does not break the build, it silently does
-nothing. Fixed by forwarding (`contacts = ["tinymemory-core/contacts"]` →
-`tinycortex/contacts`), deleting the host's four unused `objc2` declarations,
-and adding `contacts_feature_reaches_the_engine_reader`, which asserts the
-property that was missing: that enabling the feature *here* changes what the
-reader does *there*. A `cfg!(feature = ...)` self-assertion would have passed
-throughout the bug.
-
-**Verification.** TinyCortex: 34 people tests pass; default and `contacts`
-builds clean. Host: builds clean both ways; feature-forwarding gate passes;
-`openhuman::memory::` is 711 passed / 26 failed / 1 ignored against `main`'s
-710 / 26 / 0 — the 26 are pre-existing and identical on a clean `main`
-checkout (they need the module artifact, which is not fetched locally), so this
-adds one passing test and one deliberately ignored one, and no new failures.
-
-### 1b. The People capability family — landed in the contract
-
-`Capability::People` is family fourteen, appended (never inserted — declaration
-order is bit order in the `Capabilities` bitset, so moving a variant would
-silently re-interpret an already-transmitted set). `CONTRACT_VERSION` goes
-`(2, 0)` → `(2, 1)`.
-
-**A new family, not methods on an existing one — the version rule forces this.**
-Adding these calls to `MemoryEntities` would have been a **major** bump, because
-a new method on a family a driver may already advertise is breaking: negotiation
-cannot protect a caller from a method an older driver never implemented. A new
-family is a minor bump, and an older driver simply does not advertise it.
-
-`MemoryPeople` carries seven methods, derived from the seven agent tools and
-four RPC controllers that exist today rather than guessed at: `list_people`,
-`get_person`, `resolve_handle`, `add_handle_alias`, `score_person`,
-`record_interaction`, `seed_from_address_book`. Its types are the contract's
-own — TinyCortex's `Person`/`Handle`/`Interaction` never cross — and identity
-travels as an opaque `PersonRef` string, since the contract does not promise
-every engine identifies people by UUID.
-
-Wired through: both contract copies, `NullMemoryProvider`, the `MemoryGuard`
-decorator (`GuardedPeople`), and the recording test fixture. In the guard,
-`resolve_handle` takes the **write** tier check when `create_if_missing` is set
-and the read check otherwise — classifying the whole method as a read would have
-handed a `readonly` operator a working insert through the back door.
-
-**A drift guard now holds the two contract copies together.** There are two
-copies of this contract — the host-local one the module *client* compiles
-against, and `tinymemory-api` which the module *service* compiles against — and
-they meet only over a bus, where a mismatch is not a type error but a method
-never called or a capability filtered away on one side. That duplication already
-produced one live defect (§3). Two tests now pin the families and the version
-across both copies; both were verified to actually fail by temporarily diverging
-a wire string, then to go green again. They are deleted with the
-`tinymemory-api` dependency in stage 5, when one copy remains.
-
-**Verification.** `openhuman::memory::api` 190 passed / 0 failed;
-`openhuman::memory::guard` 56 / 0; `core::all` 91 / 0; `openhuman::memory::`
-back to exactly the 26 pre-existing failures with no new ones; `cargo fmt`
-clean. (The full `--lib` run aborts on a pre-existing stack overflow in
-`agent::harness::session::runtime`, identical on a clean `main` checkout.)
-
-### 1c. Engine implementation, module service, host client — landed
-
-**Not in `tinymemory-tinycortex`.** That adapter holds only an
-`Arc<dyn Memory>` and documents its own scope as the mandatory three, because
-the optional families need a host's configuration. The implementation belongs
-to `tinymemory-module`'s `ModuleMemoryProvider`, which already holds
-`workspace_dir` and implements the other ten.
-
-**Conversions destructure; they do not round-trip through serde.** The module's
-`Self::cross` helper is a serde value round-trip, and it would have compiled
-and then failed at runtime on the first call: the engine's `Interaction` names
-its timestamp `ts` where the contract names it `at`. Explicit destructuring
-makes a renamed or added field a compile error instead — the rule
-`tinymemory-tinycortex::convert` already follows.
-
-Two smaller decisions worth keeping:
-
-- A malformed `PersonRef` is `Invalid`, not `NotFound`. `NotFound` would tell a
- caller their id was well-formed but absent, sending them to look for a deleted
- person rather than at the id they built.
-- Ranking sorts with `total_cmp`, not `partial_cmp`. A NaN from a degenerate
- score makes `partial_cmp` return `None`, and `sort_by` on a non-total ordering
- may panic or produce garbage order.
-
-Service side: seven methods on `ai.tinyhumans.tinymemory.Memory`, with
-`ListPeople` size-checked like the other list-returning methods — `limit` bounds
-the count but not the bytes. Host side: seven forwards through `module_call!`
-and an `as_people()` accessor.
-
-**The nested TinyCortex submodule was fast-forwarded** (`be7b395` → `566804c`,
-verified as an ancestor first) so the module crate can actually build and test
-against the engine change. That pointer bump is part of the release anyway.
-
-### Release-ordering hazard — read before shipping stage 2
-
-`ModuleMemoryProvider::capabilities()` answers `Capabilities::all()`
-**statically**. That set grew with the contract; the *artifact* only grows when a
-release is cut and `modules/registry.rs` is re-pinned. Between those moments the
-host over-claims, and `verify()` logs the disagreement without narrowing the
-advertised set.
-
-`people` is in that window now: served by the module source in this tree, not by
-the pinned `1.0.1` artifact. It is **inert today** because nothing in the host
-reaches `as_people()` yet. It stops being inert the moment the people RPC
-handlers are routed through the driver, so **that change and the module release
-must land together**. Documented at the `capabilities()` call site too.
-
-### 1d. The `Chunks` and `Retrieval` families — landed
-
-Families fifteen and sixteen, contract now `(2, 1)` with three additions (one
-minor bump covers all three — capability negotiation is what makes each safe).
-
-- **`MemoryChunks`** — `list_chunks`, `get_chunk`, `chunk_embeddings`. A
- deliberately lower-level surface than the rest of the contract: it exists so a
- host doing its *own* ranking (cosine + MMR, hybrid keyword/vector) can get the
- rows without reaching around the driver into the engine's tables — which is
- the split-brain this port exists to end.
-- **`MemoryRetrieval`** — `fast_retrieve`, `cover_window`, `search_entities`.
-
-Three decisions worth keeping:
-
-**Source scope had to become an explicit wire argument.** `tinymemory-core`'s
-in-process entry points read it from a **task-local**. That task-local belongs to
-the host's task and does not exist on the module's side of a bus call, so it
-would have read as `None` there — and `None` means *unrestricted*. A
-per-profile source gate would have failed open, silently, on every scoped
-retrieval. So `cover_window_scoped` and `fast_retrieve_scoped` were added
-alongside the ambient-scope originals (mirroring TinyCortex's own
-`cover_window_scoped`), and every scoped method on the wire takes `scope` as an
-argument and never infers it.
-
-**Entity kinds travel as strings, not as an enum.** The engine's `EntityKind` is
-`#[non_exhaustive]` and has grown twice. A closed enum on the wire means the
-first time the engine emits a kind this build has not heard of, the **response
-fails to deserialize** — a new entity category would break retrieval outright
-rather than showing up as an unfamiliar label. Responses therefore carry an open
-snake_case vocabulary. Requests are the opposite case and *are* validated: an
-unknown kind in a filter is `Invalid`, because silently matching nothing is
-indistinguishable from a genuine empty result.
-
-**`chunk_embeddings` sorts its result.** The engine returns a `HashMap`, whose
-iteration order varies per process; an otherwise-identical call would return a
-differently-ordered list. It is also the largest thing this interface returns —
-a 1536-dimension vector is roughly 10 KiB of JSON — so it is size-checked and
-refused by name rather than truncated, since a short batch is indistinguishable
-from "those chunks have no vector".
-
-**Verification.** Module crate 34/0 · host `memory::api` 190/0 ·
-`memory::guard` 56/0 · `core::all` 91/0 · `openhuman::memory::` failing set
-byte-identical to the pre-existing 26 · `cargo fmt` clean across all four
-crates.
-
-### Still open in stage 1
-
-- Routing the host's people / chunk / retrieval RPC + agent tools through the
- driver (stage 2) — that is what makes these three families load-bearing and
- what ends the split brain.
-- A module release, the digest update in `modules/registry.rs`, and the
- TinyMemory-side submodule pointer commit.
-
-**Why People moves rather than staying put.** `tinymemory-core` survives this
-port — it is the module's own implementation crate, it just stops being an
-*OpenHuman* dependency — so leaving People there would compile. But the contract
-defines a capability and each engine implements it; a second engine binding in
-TinyCortex's place must bring its own People store. Storage belongs to the
-engine, which is exactly the split that makes the contract engine-neutral.
-
-Then: widen `MemoryProvider` and the capability set, extend the module service
-and the host client in `modules/memory.rs`, cut a TinyMemory module release and
-update the digests in `modules/registry.rs`.
-
-This is the largest stage and the only cross-repo-blocking one — it needs a
-published module release, taken verbatim from the release's `checksum.toml`,
-never recomputed from a local build.
-
-**Stage 2 — cut the direct engine calls over.** *(in progress)*
-Rewrite the 30 `tinymemory_core` call sites in `memory/{tools,query,tree}` onto
-the provider. Ends the split brain.
-
-### 2a. A guard bug caught before any call site moved
-
-The `GuardedChunks` / `GuardedRetrieval` decorators written in stage 1 forwarded
-the caller's `scope` argument **unchanged**. That is the exact widening leak
-`GuardPolicy::narrow_scope` exists to close, and its own docs record the earlier
-version of it: with a pass-through, a source-restricted turn can name a
-collection its restriction excluded and have that become the sole query
-predicate, so the restriction vanishes.
-
-Fixed to intersect via `narrow_scope`, matching `GuardedTree::query_source`.
-Four regression tests added (`families_tests.rs`), and each was verified to
-**fail** against the pass-through version before being kept — a scope test that
-cannot fail is worse than none.
-
-### 2b. Call sites converted
-
-| Tool | Was | Now |
-| --- | --- | --- |
-| `memory_vector_search` | `list_chunks(&config, …)` + `get_chunk_embeddings_for_signature_batch` | `as_chunks()` |
-| `memory_chunk_context` | `get_chunk` + `list_chunks` | `as_chunks()` |
-| `memory_store_raw_chunks` | `list_chunks` | `as_chunks()` |
-| `memory_tree` walk | `fast_retrieve` | `as_retrieval()` |
-| `memory_tree_cover_window` | `cover_window` | `as_retrieval()` |
-
-`memory_vector_search` is the case §2.1 names: it resolved the workspace path
-and opened the same SQLite database the loaded module already had open. It no
-longer touches the engine.
-
-Two of these dropped their `load_config_with_timeout()` entirely — the config
-load existed only to reach the database.
-
-**A test moved to `#[ignore]`, deliberately.**
-`raw_chunks::execute_success_path_returns_json_array` was a pure-SQLite test: it
-opened the workspace store in-process and read an empty table. That *is* the
-split brain. With no module artifact the binding now falls back to the null
-driver and the tool refuses — the correct answer, not a regression — so the test
-joins the module-backed set (`OPENHUMAN_MODULE_PATH`, own process), the same
-pattern the `tinydocs` tool tests use.
-
-**Verification.** `openhuman::memory::` 716 passed, failing set byte-identical
-to the pre-existing 26; `memory::guard` 60/0 (four new).
-
-### 2c. Second batch converted
-
-`memory_tree_search_entities`, `memory_store_raw_search` (both onto
-`as_retrieval()`), and `memory_tools_list` (a stale doc link only).
-`memory_chunk_context`'s remaining `chunk_source_allowed` call was re-pointed at
-the host's own `memory::source_scope` path, which is how `guard/policy.rs`
-already reaches it — the predicate is host *policy* over a host task-local, so
-relocating it properly is stage 4.
-
-**Entity-kind validation moved into the driver**, as flagged. The host used to
-`EntityKind::parse` before touching disk; the vocabulary is open on the wire
-(§1d) and the driver is its authority, so a host-side copy would either reject a
-kind the engine understands or drift out of date. The cost is named rather than
-hidden: a bad `kinds` value used to fail with no workspace and now needs a bound
-driver, so `execute_rejects_invalid_kind_after_validation` became a
-module-backed test rather than being quietly relaxed.
-
-**Eight tools are now off the engine entirely** — `vector_search`,
-`chunk_context`, `raw_chunks`, `raw_search`, `tool_memory/list`, `fast_walk`,
-`cover_window`, `search_entities` name no engine crate at all.
-
-**Six tests moved to `#[ignore]`, all for the same reason and none of them
-cosmetic.** Each asserted a success path by reading the workspace store
-in-process — which *is* the split brain. Two also ran the tool and then called
-the engine directly on the same workspace to assert both agreed; that second
-reader is precisely what this port removes, so the parity half is gone rather
-than reworked. This is a real loss of local coverage until the module release
-lands, not a cleanup.
-
-### 2d. The retrieval trio, `interaction_count`, and a merge from `origin/main`
-
-**Three methods added to `MemoryRetrieval`**, unblocking `backend.rs` and its
-three tool wrappers: `retrieve_source`, `retrieve_children`, `retrieve_leaves`.
-
-**The names are deliberate, and one was forced.** `MemoryTree` already has
-`drill_down` and `query_source` with *different* semantics — the tree family
-returns a node and its direct children, or the raw chunks filed under a source;
-these return ranked hits across the summary tree, several levels deep. Beyond
-the ambiguity, both families are served on **one bus object**, so `drill_down`
-collided outright and would not compile. Renaming the trio consistently
-(`retrieve_*`) resolves both.
-
-`query_source_scoped` joins `fast_retrieve_scoped` and `cover_window_scoped` in
-`tinymemory-core` for the same reason as §2c: a task-local scope does not cross
-a transport, and reading it as absent means unrestricted.
-
-**`RankedPerson::interaction_count`** added, restoring the field the people RPC
-payload carries. It is worth carrying for its own sake: a score alone cannot be
-read honestly, since 0.9 from three exchanges and 0.9 from three hundred are the
-same number and very different facts.
-
-**Merged `origin/main`** (90 commits). One thing to know: the merge commit
-correctly recorded `tinyagents → 30d6b3b` and `tinyflows → c242184`, and then
-the **auto-commit hook committed the stale worktree submodule pointers straight
-back**, reverting both gitlinks and breaking the build with an unresolved
-`tinyagents::harness::artifacts`. Restored from the merge commit and the
-submodules checked out to match. Worth watching for on any future merge in this
-repo — the hook cannot tell a stale submodule worktree from an intended change.
-
-**Now converted:** `backend.rs` (a doc comment is all that mentions the engine),
-plus `query_source`, `drill_down` and `fetch_leaves`. Five more success-path
-tests became module-backed, for the same reason as the earlier six — each read
-the workspace store in-process, and three carried a direct-engine parity half
-that has no second reader to agree with any more.
-
-**Verification.** `memory::` 708 passed / 26 failed — failing set identical to
-the post-merge baseline, no new failures · `memory::api` 190/0 ·
-`memory::guard` 60/0 · `core::all` 91/0 · module crate 34/0 · `cargo fmt` clean
-· both contract copies byte-identical apart from the intentional doctest path.
-
-### 2e. People converted
-
-`people/rpc.rs`, `people/schemas.rs`, `tools/people.rs` and a **third caller the
-first survey missed** — `flows/tinyflows/memory_adapter.rs`, which called
-`rpc::handle_list` directly — all now reach the driver's people family. None of
-the four names an engine crate.
-
-**`interaction_count` moved from `RankedPerson` to `PersonScore`.** `handle_score`
-needs it too, and duplicating the field would have let the two copies disagree.
-It belongs on the score anyway: the score and the sample size it was computed
-from should travel together, so every caller that gets one gets the other.
-
-Two deliberate behaviour changes, both surfaced rather than absorbed:
-
-- **`person_id` is no longer validated as a UUID host-side.** `PersonRef` is
- opaque by contract — the driver issues the id and owns its format — so a
- host-side UUID check would reject a driver that identifies people some other
- way. `parse_person_id_rejects_non_uuid` was inverted into
- `parse_person_id_accepts_any_non_empty_token`, with a companion asserting that
- a *missing* id is still the host's to reject: that is a malformed call, not an
- unrecognised identity.
-- **`permission_denied` in `people.refresh_address_book` is now always `false`.**
- The contract reports a host without an address book, or without permission,
- as `seeded: 0` rather than a distinct error — both mean the same thing to a
- caller, and the alternative leaks a platform detail into an engine-neutral
- contract. The field is kept so the published shape does not change, but
- surfacing "grant Contacts access" now needs a host-side permission probe.
-
-**The RPC tests were rewritten, not gated.** They used to build a real
-in-memory `PeopleStore`; they now drive a small fake `MemoryPeople`. That is
-better coverage, not worse: ranking and scoring moved into the engine and are
-tested there, so what is left host-side is the published JSON shape and the fact
-that the driver's order is passed through rather than re-sorted — and there is
-now an explicit test that the host does **not** re-sort, since a host-side sort
-would silently override the ranking authority.
-
-### 2f. People's split brain closed at the store, not just the call sites
-
-Converting the callers left the *store* still being opened host-side. Four sites
-seeded a process-global that nothing read any more, so the host held a second
-connection to `<workspace>/people/people.db` — the file the module owns — purely
-to populate a global no handler consulted. All four are gone:
-
-| Site | Was |
-| --- | --- |
-| `core/runtime/context.rs` | boot seed under `StoreInitPlan.people` |
-| `security/credentials/ops.rs` | rebind after login, and after logout |
-| `desktop/app_state/ops.rs` | rebind on active-user switch |
-
-`CoreContext::people()` and the `StoreInitPlan.people` field went with them. The
-active-user rebinds needed no replacement: people resolves through the memory
-binding now, and `rebind_default_workspace` already moves that.
-
-**No host site opens the people database any more.** The engine still compiles
-it in — that is where it belongs.
-
-**Three context tests were removed rather than repointed**, and it is worth
-being precise about what that costs. `people_store_is_isolated_per_context_workspace`
-and `rebind_workspace_updates_context_store_resolution` proved per-context
-workspace isolation *using people as the example*; that property is proved
-unchanged by `memory_binding_is_isolated_per_context_workspace` and
-`rebind_workspace_updates_context_memory_binding`, which is what people resolves
-through now — so this is redundancy removed, not coverage lost.
-`people_rpc_uses_scoped_context_store` is different: it asserted a scoped
-`people_resolve` wrote workspace A and not B by opening **both stores directly**.
-There is no second reader to check against any more, and the isolation it tested
-belongs to the binding. `degraded_context_rejects_workspace_bound_stores` now
-asserts `workspace_dir()` directly — the gate every workspace-bound store passes
-through, and what `people()` was standing in for.
-
-**Verification.** `memory::` 713 passed / 26 failed, no new failures ·
-`core::runtime` 27/0 · `core::all` 91/0 · `memory::people` 13/0 ·
-`security::credentials` 183/0 · `desktop::app_state` 32/0 · `cargo fmt` clean.
-
-### 2g. The re-export facade is gone
-
-`memory/mod.rs` no longer re-exports **any** engine module. All ~24 names
-(`store`, `queue`, `global`, `chat`, `search`, `tinycortex`, `source_scope`,
-`util`, …) were removed and every call site now says `tinymemory_core::`
-explicitly — ~190 references across 86 files in `src/`, plus 14 integration
-tests and 4 binaries.
-
-This is not a conversion: **no behaviour changed**, because each rewritten path
-resolved to exactly the symbol it now names. What changed is visibility. Before,
-`crate::openhuman::memory::store::chunks::store::list_chunks(…)` was engine
-access indistinguishable from host-local code; a `tinymemory_core` grep returned
-30 files and the truth was 100. Now `grep tinymemory_core src/` **is** the
-inventory: **127 production files**, plus 94 naming `tinycortex`.
-
-Flat *type* re-exports (`memory::MemoryCategory`, `memory::Memory`) were kept
-and re-pointed. They still have to move to `memory::api`'s equivalents, but a
-type name hides nothing the way a module tree does.
-
-**A latent test bug surfaced and was fixed.** `agent::learning::startup`'s tests
-build a real `MemoryClient`, which needs the host seams wired — and that module
-never called `install_for_tests`. It passed only when another test in the same
-binary happened to run first; alone, or filtered to that module, it failed with
-"no EmbeddingHost installed". Verified pre-existing (`git log -S` shows the call
-was never there, and no commit in this work touched `host_impls.rs`, the only
-caller of `set_embedding_host`). The whole-suite runs never caught it because
-the pre-existing stack overflow in `agent::harness::session::runtime` aborts
-that binary first. One `Once`-guarded call fixes it: 144 → 145 passing.
-
-### 2h. The measured remaining surface, after the facade came down
-
-`grep tinymemory_core src/` is now the inventory. By engine module:
-
-| Module | Refs | What it is, and what it needs |
-| --- | --- | --- |
-| `store::chunks` | 52 | Partly `MemoryChunks` already; `memory/read_rpc/` uses `with_connection` and raw SQL and needs its own design |
-| `store::create_memory` | 31 | **30 of these are tests.** Only *one* production site constructs a `MemoryClient` — the "31 per-site decisions" reading was wrong. Test constructions are not a split brain and go when the dep does |
-| `store::profile` | 26 | The learning/profile subsystem (`ProfileFacet`, `FacetState`, `UserState` + SQL). No contract representation; needs a family design like §1d |
-| `global` | 40 | The process-global memory client — the same shape as the people global just deleted |
-| `queue` | 37 | The ingest job queue |
-| `tinycortex` | 26 | Direct engine reach-through |
-| `store::safety` | 14 | **Blocked, see below** |
-| `store::{UnifiedMemory,trees,segments,fts,content}` | ~45 | Engine internals with no contract analogue |
-
-**`store::safety` cannot simply come home.** TinyMemory's README puts redaction
-on the host, and the 2,065-LOC PII/secret detector currently sits in the engine
-— but the engine *uses* it on its own write paths in 14 places (`store::kv`,
-`goals::store`, `persona`). Moving it host-side would fork it, and a forked
-redactor is the same class of hazard as §3's forked embedding signature, with
-worse consequences. It is a third-crate extraction (the `tinydocs` /
-`tinywallet` shape), not a move.
-
-**Production vs test, measured.** The raw counts mix both. Split properly:
-**342 production references across 131 files**, and 125 test references. The
-split matters per cluster — `create_memory` is 1 production / 31 test, while
-`store::safety` is 14 / 0 and `store::profile` is 24 / 2. Test-side engine use
-is not a correctness problem; it disappears with the dependency.
-
-**Honest sizing for the rest.** Stages 2–5 need, at minimum: a contract family
-for the profile/learning subsystem; a decision for each `create_memory` call
-site; a design for `memory/read_rpc/`'s raw-SQL surface; the `global` and
-`queue` seams; a `tinysafety` extraction; then the module release, the
-`tinymemory-api` retirement (§ordering constraint) and the dep drop. That is a
-programme measured in weeks, not a tail-end sweep — and the number is now
-trustworthy, which it was not before §2g.
-
-### 2i. `hybrid_search` — the worst split brain, removed
-
-`memory_hybrid_search` called `UnifiedMemory::new(&config.workspace_dir, …)`:
-it constructed **an entire second engine** over the workspace the loaded module
-already owns. Not a stray query — a whole store instance, with its own
-embedder and its own SQLite handles.
-
-It needed scored hits with their signal breakdown so it could re-rank under a
-weight profile, which `MemoryRecall` does not expose — it returns ranked
-entries and keeps its scoring private. Added
-`MemoryRetrieval::recall_namespace_scored`, returning
-`NamespaceMemoryHit` (whose `score_breakdown` the contract *already* defined),
-so re-ranking is host policy over engine signals rather than a second retrieval
-implementation. Also added `MemoryChunks::chunk_detail`, a one-call inspection
-view — four accessors would have been four bus round trips per rendered row.
-
-**Adding methods to `MemoryRetrieval` keeps the version at (2, 1)**, which looks
-like it violates the major-bump rule. It does not: the rule protects *deployed*
-drivers, and `(2, 1)` has never shipped — `Retrieval` itself is new in it. Once
-the module release goes out, this stops being true.
-
-`MemoryClient::unified_handle` was added beside the existing `memory_handle`
-for the module's scored-recall path, documented as the narrower-surface
-exception it is.
-
-### 2j. Two pre-existing test defects, diagnosed and fixed
-
-Both surfaced because converting call sites changed which tests run together.
-
-- **`sync_pipeline_e2e_tests` was flaky**, alternating pass/fail across
- identical runs (708/707). It counted events published across two tinybus task
- hops after a single `yield_now()`. The file already had a `wait_for` helper
- written for exactly this, with a doc comment explaining the two-hop problem —
- three call sites just did not use it. One of them additionally needed to wait
- for the **terminal** `completed` stage rather than any stage event.
-- **The same module never installed the host seams**, so it passed only when
- another test in the binary had. Same defect as `agent::learning::startup`
- (§2g), same one-line fix.
-
-Verified stable: 708 passed across three consecutive full runs, where it
-previously alternated.
-
-### 2k. The `Profile` capability family
-
-Family seventeen. `store::profile` + the `global::client_if_ready()` calls that
-existed only to reach `profile_store()` were one cluster, not two — the learning
-and archivist subsystems read and write the engine's facet table directly.
-
-`MemoryProfile` carries eleven methods over `ProfileFacet` / `FacetType` /
-`FacetState` / `UserState`. Three decisions worth keeping:
-
-- **The host owns the learning; the driver owns the rows.** `ProfileFacet`
- carries a `stability` and a `state` the driver never computes — it records
- what the host's stability detector decided. Extraction, scoring, promotion and
- eviction all stay host-side; this family is only the persistence seam beneath
- them.
-- **`user_state` outranks the score, and that is a contract obligation.**
- `Pinned` stays active however low stability falls; `Forgotten` stays dropped
- however much new evidence arrives — a user who says "forget that" must not
- have it re-learned. `drop_facets_below` is documented as required to honour
- both, so a future driver cannot quietly sweep against an override.
-- **`workflow_identity_matches` returns `bool`, not `Result<bool>`**, matching
- the engine method it replaces. Every caller is an "is this row the user?"
- predicate whose only sane reading of a failure is *no*; threading a `Result`
- through them invites an `unwrap_or(true)` somewhere. The guard, the wire and
- the client each answer `false` on refusal, absence and transport failure
- respectively — the one place the contract deliberately swallows an error, and
- it says so.
-
-`ProfileStore`'s methods are synchronous and hold a `parking_lot::Mutex` across
-SQLite, so every module-side call goes through `spawn_blocking` rather than
-being awaited on the runtime thread.
-
-Wired through both contract copies, the null driver, the guard, the fixture, the
-module implementation, the bus service and the host client. **Call sites are not
-converted yet** — that is the next step, and it is what makes the family
-load-bearing.
-
-### 2l. The learning subsystem converted onto `MemoryProfile`
-
-`FacetCache` reads and writes through the driver now, and the subsystem went
-async with it: `load_learned_from_cache`, `StabilityDetector::rebuild`,
-`ProfileMdRenderer::render`, and every call site in `schemas`, `tools`,
-`scheduler` and `startup`.
-
-**Async-ifying removed work.** `render()` was wrapped in `spawn_blocking`
-specifically to keep in-process SQLite off the executor. With the store behind
-the module there is no blocking I/O left to move, so the hop is gone.
-
-**No coverage was lost.** The ~50 learning tests built real in-memory SQLite
-stores. Rather than park them on `OPENHUMAN_MODULE_PATH`, they drive an
-in-memory `MemoryProfile` (`agent/learning/test_profile.rs`) — those tests are
-about stability scoring and prompt rendering, not persistence. 145 pass.
-
-Two defects the tests caught in this work:
-
-- **The fake's `drop_facets_below` was wrong**, and the existing assertions
- failed on it. The engine sweeps only rows already in `FacetState::Dropped`,
- and protects only `Pinned`. The contract doc had **overstated the guarantee**
- by claiming `Forgotten` was protected too; corrected, with the reason the
- asymmetry is deliberate — a Forgotten facet is already Dropped and is meant to
- be collected.
-- **`test_profile` was first written `#[cfg(test)]`**, which integration tests
- cannot see — the exact trap `ProfileStore::for_tests` documents. Now
- `#[doc(hidden)] pub`.
-
-**The bypass allowlist shrank.** Five entries justified by *"the contract has no
-profile family"* are gone. One was added — a boot-time `binding::for_workspace`
-that resolves a **guard** (not a raw client) for a known workspace, as
-`active_memory_guard`'s own fallback does — with that reason recorded in both
-the test and `docs/specs/memory-guard-allowlist.md`.
-
-### 2m. The `Arc<dyn Memory>` seam — attempted, reverted, and why
-
-`AgentExperienceStore` looked like the next bounded conversion: it uses only
-`get` / `list` / `store`, all in `MemoryCore`. It was converted, and then
-reverted.
-
-`agent/harness/session/turn/core.rs` builds experience stores from the
-session's own `Arc<dyn Memory>` **and** from a second, *shared* experience
-memory. The guard is per-workspace; the session may legitimately hold two
-memory handles. Converting only the `ops.rs` door would have left
-`AgentExperienceStore` with two constructors, one guarded and one not — which
-the bypass allowlist would rightly flag, and which is worse than the current
-state.
-
-So `Arc<dyn Memory>` is not a call-site cluster at all: it is a **seam**
-threaded through the session builder, the flows adapter and the experience
-store, and it has to be replaced as one design rather than file by file. That
-is the largest single item left, and it is the reason the remaining `global`
-sites cannot simply be deleted the way the people global was.
-
-### 2n. A way through the `Arc<dyn Memory>` seam
-
-The seam looked un-splittable in §2m because every consumer is *handed* a
-memory handle by `build_tools(memory: Arc<dyn Memory>, …)`, which is fed from
-the session builder. Converting one consumer meant converting the constructor,
-which meant converting the builder.
-
-There is a way through, and this port already established it: **a converted tool
-resolves the guard itself**. `vector_search`, `chunk_context`, `raw_chunks`,
-`fast_walk` and the rest hold no handle — they call `active_memory_guard()` per
-invocation. Applying that to a seam consumer removes its dependency on the
-constructor parameter entirely, and the parameter dies of disuse once the last
-consumer stops reading it.
-
-`memory_recall`, `memory_store` and `memory_forget` are converted on that
-pattern: each is now a unit struct (or holds only its `SecurityPolicy`), and
-`build_tools` no longer passes them a handle. Holder count 33 → 30.
-
-Two details the conversion surfaced:
-
-- **`recall`'s options changed shape.** The engine trait takes a borrowed
- `RecallOpts`; the contract takes `&OwnedRecallOpts` plus an explicit `scope`.
- `None` is passed for scope, which is not "unrestricted" — the guard
- intersects it with the ambient allowlist, so it can only narrow.
-- **`store` gained a taint argument.** The engine's `store` has none; the
- contract requires one because a driver that could default provenance could
- launder external content as internal. The tool passes `MemoryTaint::default()`
- as a *request*, and the guard stamps the effective value.
-
-Their engine-backed tests join the module-backed set (the read-back goes through
-a real `UnifiedMemory`, so those assertions need the artifact). `name_and_schema`
-stopped needing a store at all.
-
-### 2o. The seam's root is four call sites, not thirty
-
-Triaging the remaining `Arc<dyn Memory>` holders against the contract:
-
-| What they need | Files | Status |
-| --- | --- | --- |
-| `store` / `get` / `forget` / `list` / `recall` | most | **covered** — `MemoryCore` + `MemoryRecall` |
-| `namespace_summaries()` | 7 | **covered** — the contract's `namespaces()` has the identical signature and return type; it is a rename |
-| `count()` | 3 | **test-only.** No production call site uses the trait's `count` |
-| `recall_relevant_by_vector()` | 0 | unused anywhere |
-| `memory_handle()` | 4 | **the root** |
-| `tool_memory_store(…)` / `preferences::…` | 3 | engine helpers taking `&Arc<dyn Memory>` |
-
-So the seam is not thirty independent conversions. Nearly every holder just
-*receives* a handle; only four production sites **mint** one —
-`agent/experience/ops.rs` (×2), `agent/harness/session/builder/factory.rs`,
-`flows/bus.rs` and `flows/tinyflows/memory_adapter.rs`, each calling
-`MemoryClient::memory_handle()`.
-
-Convert those four to hand out the guard and the downstream holders change type
-mechanically, because what they call is already in the contract. That is the
-finish line for the seam, and it is a much smaller target than the holder count
-suggests.
-
-Two consumers need engine helpers that take `&Arc<dyn Memory>` —
-`tool_memory_store` and `preferences::recall_related_preferences`. Those are
-host-layer helpers living engine-side; they come home with stage 4 rather than
-being wrapped.
-
-### 2p. ⚠ The seam root is blocked on an architectural decision, not on typing
-
-Converting the four `memory_handle()` roots turns out not to be mechanical, and
-the reason is worth stating precisely because it is **not in the original plan
-and it gates the rest of the port**.
-
-`agent/harness/session/builder/factory.rs` does not take a handle to the
-workspace's memory. It **constructs its own engine instance**:
-
-```rust
-let session_memory = memory_store::factories::create_session_memory_with_local_ai(
- …, &config.workspace_dir, &memory_subdir, // "memory" | "memory-<profile-id>"
-)?;
-let archivist_connection = session_memory.sqlite_connection;
-let memory: Arc<dyn Memory> = Arc::from(session_memory.memory);
-```
-
-Two things fall out, and the module architecture accommodates neither:
-
-1. **Per-profile memory subtrees.** A profile with `dedicated_memory` gets its
- own store at `<workspace>/memory-<id>`, which is the whole point of that
- feature — isolation. The contract and the binding address a **workspace**
- (`binding::for_workspace(workspace_dir, cfg)`); there is no notion of "open
- the store rooted at subdirectory X". One loaded module serving one store per
- workspace cannot express this.
-2. **A raw `sqlite_connection` handed to the archivist.** `ArchivistHook::new`
- takes the live SQLite connection out of the session's memory. A connection
- cannot cross a bus, so there is no forwarding fix — the archivist's storage
- has to be re-homed, not re-routed.
-
-There is also a third store in play: a dedicated-memory session *additionally*
-holds `shared_experience_memory`, a handle to the **global** store, so
-pre-profile unstamped experiences stay recallable. So one session can legitimately
-hold two stores plus a raw connection.
-
-**This is a design decision, not a conversion.** The options are roughly:
-extend the contract so a driver can serve named stores within a workspace
-(a real widening, and the module would need to load or multiplex per subtree);
-or bind one module per memory subtree; or re-scope `dedicated_memory` so
-isolation is expressed inside one store rather than by a separate database. Each
-changes user-visible behaviour or the module's lifecycle, and none should be
-picked without an explicit call.
-
-Everything downstream of these four sites is mechanical once that is settled —
-§2o shows the receivers need only what the contract already has. But the roots
-themselves cannot be converted until per-profile memory has an answer.
-
-### 2q. An in-memory provider, so conversions stop costing coverage
-
-Every seam conversion had been paying the same toll: the consumer's tests handed
-it a real `UnifiedMemory` over a temp dir and asserted a genuine round trip, and
-converting to the guard turned them into `#[ignore]`d module-backed tests. That
-is ~36 tests parked so far.
-
-`memory/guard/in_memory.rs` ends that. It is a `HashMap` behind a mutex
-implementing the **mandatory three**, so it can be wrapped in a *real*
-`MemoryGuard` — `guarded_in_memory()` returns both. A converted consumer's tests
-keep their round-trip assertions, and gain the policy layer on the path where
-production has it.
-
-`RecordingProvider` could not serve: it records calls and answers empty, which
-proves a call was made but never that the data came back.
-
-Two deliberate limits, stated in the module so nobody mistakes it for the
-engine: `recall` is a substring match, not ranked retrieval (a test about
-*ordering* must use the real engine), and `list`/`namespaces` sort explicitly
-because a `HashMap`'s iteration order would make otherwise-identical assertions
-flaky. It is `#[doc(hidden)] pub`, not `#[cfg(test)]`, for the integration-test
-reason this port has already tripped over twice.
-
-**First use: `flows/bus.rs`.** The run-digest subscriber now resolves the guard,
-and its `store_with_taint` call became `store` — the contract carries taint on
-the one door, so the engine trait's second door is unnecessary. All 33 bus tests
-keep their assertions and pass.
-
-The bypass allowlist lost its two `flows/bus.rs` entries with it.
-
-**A third order-dependent test defect surfaced** — `flows::ops` tests build an
-agent, which constructs a memory client, which needs the host seams; they had
-never installed them and passed only on ordering. Same one-line fix as
-`agent::learning::startup` and `sync_pipeline_e2e_tests`. That is three
-independent instances of the same latent defect this port has now found and
-fixed.
-
-### 2r. Both flows roots converted
-
-`flows/tinyflows/memory_adapter.rs` and the `flows/memory_tools.rs` helpers it
-delegates to (`cross_flow_recall`, `FlowMemoryRecallTool`,
-`FlowMemoryRememberTool`) now go through the guarded driver. Two of the four
-`memory_handle()` roots are gone; the remaining two are the ones downstream of
-the per-profile decision in §2p.
-
-Three shape changes, each removing a door rather than adding one:
-
-- **`namespace_summaries()` → `namespaces()`.** Identical signature and return
- type; the contract simply names it differently. This is what makes the seven
- files that call it mechanical.
-- **`store_with_taint(…)` → `store(…)`.** The contract carries taint on the one
- store method, so the engine trait's second door has no counterpart and needs
- none.
-- **`is_potentially_untrusted` stopped taking a `MemoryEntry`.** Two entry types
- are in play during the port, and the predicate needs neither — it reads a
- namespace and a key. It takes those now, so callers on either side use it
- without conversion, and the signature states what it depends on.
-
-The bypass allowlist lost both `memory_adapter.rs` entries. Across this port it
-has now shed nine: five profile/facet, two `flows/bus.rs`, two
-`memory_adapter.rs` — against one added (a boot-time guard resolution, with a
-reason). Its own rule is that it may shrink and must never grow.
-
-### 2s. The tool registry stopped taking a memory handle
-
-`all_tools` / `all_tools_with_runtime` took an `Arc<dyn Memory>` and threaded it
-into exactly **two** tools: `SavePreferenceTool` and `ToolStatsTool`. Each used
-one mandatory-family method (`forget`, `list`). Converting those two to resolve
-the guarded driver per call made the parameter dead, and dropping it collapsed
-**both remaining engine-construction sites** in one step:
-
-| Site | Was |
-| --- | --- |
-| `channels/runtime/startup.rs` | `create_memory_with_local_ai(...)`, plus a second fallback construction with `embedding_provider = "none"` when the embedder failed (#3712) |
-| `runtime/node/ops.rs` | `tinymemory_core::store::create_memory_with_local_ai(...)` |
-
-The #3712 fallback goes away with the construction it protected: there is no
-embedder to fail to build here any more, because the host no longer builds a
-store at all. The degradation it bought — channels still start when the
-embedding provider is misconfigured — now belongs to the driver, which is a
-better place for it: it applied to one of the four construction sites, and the
-other three had no such protection.
-
-`ChannelRuntimeContext.memory` became `Arc<MemoryGuard>` in the same change,
-and `build_memory_context` with it.
-
-### 2t. `preferences` came home, and cost the contract nothing
-
-`tinymemory_core::preferences` was host policy living in the engine: which two
-namespaces the lanes use, how many standing preferences a prompt may carry, and
-the similarity floors for Lane-B recall and the contradiction check. A second
-engine would have had to reimplement all of it identically or the product would
-change underneath it. It is now `src/openhuman/memory/preferences.rs`.
-
-**The move needed no new contract surface**, which is worth recording because
-the reflex was to add a `recall_relevant_by_vector` method. The engine's
-version was itself a *default* method over `query_namespace_hits` — the query
-the contract already exposes as `MemoryRetrieval::recall_namespace_scored` — so
-the filter (keep hits whose `score_breakdown.vector_similarity` clears the
-floor) is reproduced host-side verbatim. Check for a default implementation
-before widening the contract; twice now the surface was already there.
-
-A driver without `Capability::Retrieval` yields **no** preferences rather than
-an error, preserving the engine default that let keyword-only backends opt out.
-Both callers degrade correctly: an absent Lane-B block and an absent
-contradiction check, rather than a failed chat turn or a failed preference
-write.
-
-The two `KwEmbedder`-based contradiction tests were deleted, not ported. They
-existed to make vector similarity move at all through a real `UnifiedMemory`;
-the new tests script the score breakdown directly, which pins the similarity
-gate the embedder was only an indirect way of reaching.
-
-### 2u. Two reusable test providers now exist
-
-Conversions kept costing test coverage, so `memory/guard/in_memory.rs` now
-carries two, both `#[doc(hidden)] pub` rather than `#[cfg(test)]` so integration
-tests under `tests/` can see them:
-
-- **`InMemoryProvider`** — real storage; for round trips. `recall` substring-matches.
-- **`FixedRecallProvider`** — `recall` answers a scripted list whatever the
- query; everything else inert. For the channel/context tests that assert on
- what the *caller* does with a result set (scoring filter, truncation, budget),
- where recall itself must be a constant.
-
-`guard_over(provider)` wraps either — or a test's own provider — in a real
-`MemoryGuard`, so these run through the same policy decorator production uses.
-
-**Where a fake is not enough.** A test whose assertion turns on *ranked* recall
-cannot use either, and gets parked on `OPENHUMAN_MODULE_PATH` with the existing
-reason string. Three joined that set here: the two `tool_stats` tests, the
-`save_preference` storage tests, and the channels autosave test (which asserts
-an autosaved turn is later recalled by a differently-worded question — ranking,
-not substring).
-
-### 2v. A pre-existing debug-stack overflow in the whole-lib run
-
-`agent::harness::session::runtime::tests::run_single_publishes_completed_and_error_events`
-aborts the **entire** `cargo test --lib` run with a stack overflow. It is deep
-frames, not recursion: it passes under `RUST_MIN_STACK=16777216`.
-
-**It is not this port's.** Verified by building the branch's merge-base with
-`main` (`c5d5eaab6`) in a scratch worktree and running the single test there —
-same overflow, same abort. Reverting this port's two edits to the turn body did
-not change it either.
-
-It matters here for one practical reason: because the abort kills the process,
-**a whole-lib run reports nothing at all** — no counts, no failure list. Every
-verification in this port is therefore module-scoped, and a claim of "no new
-failures" rests on comparing per-module failing sets against the recorded
-baseline, not on a green whole-suite run. Anyone re-checking this work should
-know that the suite cannot currently be run end to end, and that this is true
-of `main` as well.
-
-Worth knowing separately when adding an `await` to the turn body, since it is
-already close to the edge: `situational_preferences` and `standing_preferences`
-are free functions rather than inline blocks so their state machines stay off
-the caller's frame.
-
-A second pre-existing failure surfaced by the same sweep, verified the same way
-against `c5d5eaab6`:
-`agent::harness::session::turn::tests::turn_triggers_configured_memory_agent_before_parent_prompt`
-asserts the parent turn answers `"parent final"` and gets the *memory agent's*
-scripted reply instead. Only one model call reaches the test's `SequenceProvider`,
-because `run_subagent` builds the memory agent its own model from config rather
-than inheriting the parent's — so the subagent never consumes response #0 and
-the parent does. Identical on the merge-base; not this port's, and not fixed
-here.
-
-### 2w. Twelve more `install_for_tests` order-dependence defects
-
-The module-by-module sweep found twelve tests that build an agent or a memory
-client without calling `host_impls::install_for_tests()` — nine in
-`integrations::composio::ops_tests`, three in `cron::scheduler_tests`. Each
-fails with *"no EmbeddingHost installed"* when its module is run on its own and
-passes in a bigger run, because the installer is `Once`-guarded and some earlier
-test happened to call it.
-
-That brings this port's total to **fifteen** (after `agent::learning::startup`,
-`sync_pipeline_e2e_tests` and `flows::ops`). The pattern is consistent enough to
-state as a rule: **a test that builds an agent, a memory client or a cron job
-must install the seam itself.** Relying on a sibling makes the test's own
-scoped run a false negative, which is exactly how these survived — nobody runs
-`cargo test --lib openhuman::cron` in CI, and the whole-lib run aborts (§2v)
-before the counts print.
-
-### 2x. The raw SQLite connection is gone — `Episodic`, the 18th family
-
-The archivist post-turn hook held the last live `rusqlite::Connection` in the
-host, handed to it straight out of the session factory. A connection cannot
-cross a bus, so this was the hard half of the blocker: while it existed, the
-engine could not leave regardless of what happened to the store selector.
-
-It turned out to be much less entangled than "a raw connection" suggests. The
-hook issued **no ad-hoc SQL** and knew nothing of the schema; it called ten
-typed free functions, and **two of those took no connection at all**. So the
-split was already there, waiting to be named:
-
-| Went to the contract (`Capability::Episodic`) | Stayed host-side (`archivist::boundary`) |
-| --- | --- |
-| `insert_turn`, `session_turns` | `detect_boundary` + its `BoundaryConfig` / `BoundaryDecision` / `BoundaryReason` |
-| `open_segment`, `create_segment`, `append_turn` | `incremental_mean_embedding` |
-| `close_segment`, `set_segment_summary`, `upsert_segment_embedding` | `fallback_summary` |
-
-Persisting a segment is storage. Deciding *that a segment should end* — how long
-a pause means the subject moved on, how many turns is too many, which phrases
-announce a change of topic — is a product judgement about what a conversation
-is, and the host that renders these segments is the only thing that can tune it
-against what users see. The thresholds are carried over verbatim: this is a
-move, not a retune, so a regression stays attributable.
-
-**`insert_turn` returns the id, and that is a bug fix, not just a round trip
-saved.** The old code inserted a row and then asked `SELECT last_insert_rowid()`
-on the same connection. That is *connection-local* state: any interleaved insert
-from another task yields the wrong id and files the turn under the wrong
-segment. Returning the id from the insert removes the race and the second hop
-together.
-
-`ConversationSegment` carries `embedding` for the same reason the family exists
-at all — boundary detection is host policy but reads the driver's centroid, so
-it comes back on the read rather than costing a second call.
-
-Version: **(2, 1) → (2, 2)**, a minor bump, per the rule that a new family is
-made safe by capability negotiation alone.
-
-Both contract copies, the guard decorator (`GuardedEpisodic`), the
-`RecordingProvider` fake and the four count pins moved together. The count pins
-are worth keeping literal: each one forced a deliberate look rather than sliding
-past, which is exactly what caught `every_capability_family_is_accounted_for_in_the_rpc_surface`
-needing an entry.
-
-### 2y. The module driver ignores the workspace it is bound for
-
-Found while sizing the store-selector half, and it is worth stating plainly
-because it changes what that work is:
-
-`binding::for_workspace` caches on `(workspace_dir, cfg)` and `build()` logs
-`workspace=…`, but `module_provider(_workspace_dir)` **discards the argument**.
-`ModuleMemoryProvider` resolves against the `Config` published once at boot by
-`set_modules_policy`, and reaches a single object path on the bus. So today the
-module serves exactly **one store per process** — not one per workspace, and
-certainly not one per profile subtree. Two workspaces get two `MemoryBinding`s
-that talk to the same store.
-
-That means the `dedicated_memory` question is not "how do we keep the existing
-per-subtree behaviour through the bus" — there is no per-subtree behaviour on
-the module path to keep.
-
-### 2z. `OpenStore` — the module opens stores, so the contract does not change
-
-Two candidates presented themselves first, and both were wrong:
-
-- **A store selector on the wire** — the object is a singleton by construction,
- so selecting a store means a parameter on *every method of all 18 families*: a
- major contract bump, to express something that is not a property of a memory
- operation at all.
-- **Profile subtrees become namespaces** — no contract change, but it relocates
- user data on disk and needs a migration.
-
-The third dissolves the problem. **Which store you are talking to is settled
-when you are handed a driver**, exactly like which workspace you are bound to —
-it was never a per-call fact. tinybus already supports `serve_at` on many paths,
-so the module's root object gained one method:
-
-```text
-OpenStore(memory_subdir) -> object_path
-```
-
-Each opened store is an ordinary `MemoryService` exporting the identical
-interface. `MemoryProvider` still describes one store; a proxy still talks to
-one store. **No contract change, no migration, and paths on disk are exactly
-where they already were.**
-
-What landed:
-
-| Side | Change |
-| --- | --- |
-| `tinymemory-core` | `create_memory_client_in_subdir` — the existing client factory hardcoded `"memory"` |
-| `tinymemory-module` | `StoreOpener`, `OpenStore`, per-subtree object paths, `MemoryService::root` vs `::new` |
-| host | `ModuleMemoryProvider::in_subdir` + lazy `OpenStore` resolution; `binding::for_subtree`; the cache key gained the subtree |
-
-Four decisions worth keeping:
-
-- **Only the root object opens stores.** An opened store has no `StoreOpener`,
- so the recursion is finite by construction rather than by a depth check.
-- **Idempotent per subtree, and recorded only after `serve_at` succeeds.** Two
- live handles to one SQLite file is not hypothetical — the engine migrates on
- open, and concurrent migrations on one file corrupt it invisibly. Caching the
- path before the serve succeeded would strand callers on a path nothing
- answers.
-- **The object path is derived and character-checked, never free-form.** A
- subdir arrives from a profile id; an id that fails validation must produce a
- refusal, not a malformed bus path. The rejection message does not echo it —
- it is user data.
-- **`in_subdir("memory")` is `None`.** Callers pass whatever
- `memory_subdir_for_suffix` produced without special-casing the shared tree,
- and the shared tree costs nothing extra because the root object is served
- eagerly at setup.
-
-This also fixes the workspace-ignoring bug above for the axis that matters: the
-workspace still comes from the boot policy (the module is loaded once per
-process and captures it at setup), but the **subtree** is now per binding.
-
-### Still open in stage 2
-
-| File | Why it is not converted |
-| --- | --- |
-| `query/backend.rs` + its three tool wrappers (`drill_down`, `fetch_leaves`, `query_source`) | **Needs contract surface that does not exist.** `backend::query_source(config, source_id, source_kind, time_window_days, query, limit) -> QueryResponse` has a different shape from `MemoryTree::query_source`, and `fetch_leaves` has no equivalent at all. Three more `MemoryRetrieval` methods, or a widened `MemoryTree` — the latter would be a **major** contract bump. |
-| `tools/people.rs` + `people/rpc.rs` | The `People` family exists, but the RPC layer is the real call site and its `people_list` payload carries `interaction_count`, which `RankedPerson` does not. Either the contract gains that field or the RPC wire shape changes; `schemas_tests` pins the current one. |
-| `tools/diff.rs` | Uses `tinymemory_core::sources::{get_source, list_sources}` — the source *registry*, which is host-layer config, not engine storage. Belongs in stage 4, not behind the driver. |
-| `tools/raw_store/kinds.rs` | `MemoryKind` is the engine's **storage-shape** catalog (raw / chunk / entity / tree / vector / kv / contact) and is unrelated to the contract's `MemoryItemKind`. The tool is a static enumeration with no database access, so there is nothing to route — the question is whether the contract should expose engine storage shapes at all, or whether the tool should go. Needs a decision. |
-| `tools/search/hybrid_search.rs` | Uses `UnifiedMemory` + `MemoryItemKind` + `tinycortex::WeightProfile` — a whole retrieval facade rather than a single call. Largest remaining conversion. |
-| `query/ingest_document.rs`, `query/query_source.rs` | Type-only imports (`SourceKind`, `SourceRef`) plus test-only direct engine calls; trivial once `backend.rs` is resolved. |
-
-**Stage 3 — the 98 `tinycortex::memory` references.**
-56 sit outside `memory/` (`agent/`, `threads/`, `subconscious/`, `channels/`,
-`security/`), mostly `tinycortex::memory::conversations`. Route through the
-provider or through a host-owned conversation store.
-
-**Stage 4 — bring host-layer code home, and drop `tinymemory-core`.**
-Move `sync`, `composio_host`, `chat`, `learning_candidate`, `nlp_host` out of
-`tinymemory-core` into `memory/`. Delete `host_impls.rs` in favour of the bus
-services in `modules/memory_host.rs`.
-
-**Stage 5 — retire `tinymemory-api`.**
-Only reachable once stage 4 lands, per the ordering constraint above. Re-point
-the 46 `tinymemory_api::host` references at the host-local `memory::api::host`
-and reconcile the 6 diverged files. Touches `config/schema/*`, `inference/`,
-`cron/scheduler_gate`, `integrations/composio`. These config types are persisted
-serde — field names, defaults and `#[serde(...)]` attributes must not move.
-Drop the crate cross-check test in `memory/api/host/embeddings.rs`; the golden
-test beside it is what carries the format guarantee afterwards.
-
-**Stage 6 — drop the deps and ratchet.**
-Remove all five entries from `Cargo.toml`, forward the gate to
-`app/src-tauri/Cargo.toml`, and re-baseline `scripts/kernel-floor.limits` —
-`libsqlite3-sys` should leave the kernel profile with the engine.
-
-## 5. Verification
-
-- Both-ways gate tests in `src/core/all_tests.rs` for any new feature gating.
-- A regression test per stage, failing before and passing after.
-- `scripts/check-kernel-floor.sh` re-baselined only at stage 6, and the shed
- written back — an unratcheted improvement grows back unnoticed.
-- Prove each claimed shed with `scripts/assert-shed.sh`, never `cargo tree -i`.
diff --git a/docs/specs/2026-09-10-library-agent-host.md b/docs/specs/2026-09-10-library-agent-host.md
deleted file mode 100644
index 51b852f587..0000000000
--- a/docs/specs/2026-09-10-library-agent-host.md
+++ /dev/null
@@ -1,343 +0,0 @@
-# OpenHuman library host: one core, many agents
-
-**Status:** in progress — library identity and JSONL lock sharding implemented;
-the typed per-agent resource API and RSS gate remain proposed.
-
-## Objective
-
-OpenHuman must be usable as an in-process execution library by products such as
-OpenCompany. One host starts one core and then creates many independently
-configured agent handles over it. The first capacity target is 100 live agent
-handles and 100 concurrent turns in one process, without an OpenHuman account or
-login flow and without duplicating core-wide services per agent.
-
-The host supplies all product policy and resources programmatically:
-
-- provider id, OpenAI-compatible URL, credential, model and model capabilities;
-- agent definition and system prompt;
-- skills and MCP servers, including per-agent allowlists;
-- workspace/action root, tool policy, access policy and persistence policy;
-- optional memory, transcript and event sinks.
-
-Library mode must never discover an operator's OpenHuman login, configuration,
-skills, MCP servers or workspace as an implicit fallback.
-
-## Current state
-
-The existing embedding surface already provides two important pieces:
-
-- `CoreBuilder` can start an in-process `CoreRuntime` without HTTP or background
- services.
-- `embed::Core::agent()` can run concurrent routed turns against that runtime.
-
-It does not yet provide the required ownership model:
-
-1. `HarnessBuilder` owns and builds a core. `HARNESS_LIVE` consequently permits
- one harness per process. Removing the atomic is unsafe because several core
- resources are still process-scoped.
-2. Resolved: `HostKind::Library` bypasses the desktop registration check for a
- routed caller-supplied provider. The default harness no longer writes a fake
- `Session::local` auth state.
-3. `TurnRequest` can select a route and model but not an agent definition.
- `inference::local::ops::agent_chat` always builds the orchestrator.
-4. Agent definitions come from the process-global `AgentDefinitionRegistry`;
- skills are copied into a workspace; MCP servers are installed into the
- core-wide static registry. Those are discovery/configuration mechanisms, not
- per-agent dependency injection.
-5. Every turn constructs a full `Agent`, including its tool objects, prompt
- machinery, provider selection and session adapters.
-6. Resolved for independent transcripts: OpenHuman's JSONL conversation store
- now uses a per-root lifecycle lock, per-root metadata lock and per-thread
- message locks. Shared `threads.jsonl` metadata fsyncs remain serialized
- within one root.
-
-The desired model is therefore **not** 100 `Harness` or `CoreRuntime` values.
-It is one library host with 100 cheap agent handles.
-
-## Public API
-
-Names below describe ownership and are not required to preserve the current
-`Harness` naming.
-
-```rust
-let host = LibraryHost::builder()
- .workspace(host_workspace)
- .persistence(Persistence::Sqlite)
- .limits(HostLimits {
- max_concurrent_turns: 100,
- max_blocking_tasks: 16,
- ..Default::default()
- })
- .build()
- .await?;
-
-let analyst = host.agent(
- AgentSpec::new("company-analyst")
- .prompt(analyst_prompt)
- .provider(
- ProviderSpec::openai_compatible(
- "opencompany-primary",
- provider_url,
- provider_credential,
- )
- .model("gpt-5"),
- )
- .skills(analyst_skills)
- .mcp_servers(company_mcp_servers)
- .tool_policy(analyst_tool_policy)
- .memory(MemoryPolicy::SharedNamespace("company".into())),
-)?;
-
-let session = analyst.session(SessionSpec::new("customer-42:analysis-7"))?;
-let result = session.turn("Review this company").send().await?;
-```
-
-### Ownership
-
-- `LibraryHost` owns the single `CoreRuntime`, shared provider transports,
- module runtimes, registries, stores, resource limits and shutdown.
-- `AgentHandle` is an `Arc`-backed immutable compiled `AgentSpec`. Cloning it is
- cheap and does not open stores, spawn tasks or build a new HTTP client.
-- `AgentSession` binds an agent to a conversation and mutable turn state. It
- serializes turns for its own session only. Different sessions run in
- parallel.
-- `Turn` owns per-call overrides and cancellation. Dropping a handle never
- shuts down the host.
-
-`LibraryHost`, `AgentHandle` and `AgentSession` must be `Send + Sync`.
-
-### Provider input
-
-`ProviderSpec` requires a stable provider id, endpoint, credential and model.
-The provider id is not inferred from the URL and is used for pooling,
-rate-limit state, metrics and redacted diagnostics. Credentials are stored in a
-redacting secret type and are never written to `Config`, auth profiles or the
-workspace.
-
-A provider instance/cache is keyed by the fields that affect transport and
-model behavior. Agents sharing a provider reuse its HTTP connection pool,
-retry/rate-limit state and model profile.
-
-### Definitions, skills and MCP
-
-The host accepts values, not only filesystem locations:
-
-- `AgentSpec` owns an `AgentDefinition` value. It never needs insertion into the
- process-global definition registry for a root turn.
-- `SkillSource` supports an already parsed skill bundle and an explicitly named
- directory. Directory loading occurs once during agent compilation. Skills are
- immutable after the handle is returned.
-- `McpServerSpec` is supplied as data. The host owns one connection per distinct
- server identity and agents hold allowlisted views over its tool catalog.
-
-Sub-agent definitions form an immutable registry owned by the compiled agent
-graph. The existing global registry remains a compatibility path for the
-desktop, but library turns do not read it.
-
-## Authentication and host policy
-
-Add an explicit library host policy to `CoreContext`; do not identify library
-mode by the absence of a token or by a magic local session.
-
-```rust
-pub enum HostKind {
- TauriShell,
- Cli,
- Docker,
- Library,
-}
-```
-
-For `HostKind::Library`:
-
-- routed providers do not call `verify_session_active`;
-- no auth session is created, read, refreshed or cleared;
-- managed OpenHuman inference and login-gated hosted APIs are unavailable
- unless the embedder explicitly installs a backend-auth port;
-- provider credentials grant access only to their declared provider;
-- tool authorization still comes from the supplied access/tool policy. Library
- mode is not an automatic `full` autonomy grant.
-
-The bypass must consult the ambient `CoreContext` installed by dispatch. The
-desktop, CLI and Docker paths retain their current registration gate exactly.
-
-## Runtime composition
-
-Introduce a minimal `DomainSet::library()` and `ServiceSet::library()` rather
-than using `DomainSet::embedded()`, which currently includes Medulla, flows,
-channels, integrations and automation for a different embedding use case.
-
-The default library set includes only the kernel needed for agent turns:
-
-- agent, config, security and inference;
-- threads and memory only when the selected persistence/memory policy needs
- them;
-- skills, MCP and runtimes only when at least one agent declares them;
-- no desktop, hosted, Medulla, channels, cron, heartbeat, update, Socket.IO or
- HTTP server.
-
-Core-wide services are initialized once. Agent construction must not start a
-background service.
-
-## Concurrency rules
-
-The API distinguishes **live handles** from **in-flight turns**. One hundred
-live handles should add only their compiled prompts, tool views and small
-session metadata. In-flight turns additionally consume model context, tool
-state and response buffers.
-
-- A per-session async mutex prevents two turns from racing the same transcript
- and conversation state.
-- No mutex spans provider I/O or tool execution across different sessions.
-- A host semaphore provides configurable global backpressure. Reaching the
- limit waits or returns a typed overload error; it never creates unbounded
- queues.
-- Per-provider semaphores support upstream rate limits without blocking other
- providers.
-- Cancellation propagates through provider calls, tool execution and queued
- persistence work.
-
-The default limit should be conservative and configurable. Supporting 100
-concurrent turns means the implementation remains correct at 100; it does not
-mean every machine should default to 100 simultaneous provider streams.
-
-## Persistence
-
-The JSONL conversation store no longer has a process-wide mutex: lifecycle is
-coordinated per root, shared metadata per root, and transcript IO per thread.
-Every message append still fsyncs shared `threads.jsonl` metadata, so SQLite WAL
-remains the preferred durable path for sustained high write throughput.
-
-The library path should use a store contract with two initial implementations:
-
-- `InMemory`, for ephemeral agents and tests;
-- SQLite in WAL mode, for durable sessions.
-
-SQLite uses a small bounded connection pool, transactional message + thread
-metadata writes, indexed thread reads and busy timeouts. WAL allows concurrent
-readers while one short write transaction commits. Pool size is a host limit,
-not proportional to the number of agents.
-
-The desktop JSONL implementation may remain during migration, but the store
-must be selected through the existing session-history/store seams rather than
-by `HostKind` checks scattered through the turn path. A compatibility importer
-can move old JSONL transcripts into SQLite; dual-writing is not part of the hot
-path.
-
-The immediate lock fix is implemented and stress-tested with 100 distinct
-threads. It also shards message-file IO by thread, beyond merely keying the old
-mutex by root. It does not remove the same-workspace metadata serialization
-point.
-
-## Memory budget
-
-The implementation is accepted on measured retained memory, not only type
-shape. Add a benchmark executable that records RSS at these checkpoints:
-
-1. process start;
-2. library host built;
-3. 100 distinct `AgentHandle`s built;
-4. 100 sessions idle;
-5. 100 turns blocked on a mock streaming provider;
-6. all turns complete and transient state is dropped.
-
-The benchmark uses a local mock provider and fixed prompts/tool catalogs so it
-is deterministic. CI records the measurements; a dedicated performance lane
-can enforce thresholds once stable baselines exist.
-
-Initial targets on Linux x86_64 release builds:
-
-- 100 idle agent handles and sessions add no more than 64 MiB over the built
- host;
-- provider clients and MCP connections scale by unique provider/server, not by
- agent;
-- completed turns return to within 10% of the pre-turn retained-memory level
- after caches have warmed;
-- no Tokio runtime uses a 16 MiB stack per agent. Stack allocation is per
- worker thread, and worker count is explicitly configured by the host.
-
-### 2026-09-10 baseline
-
-The repaired `library-profile fleet` scenario constructed 100 shipped
-orchestrator `Agent` values in one process, then ran one overlapping mock turn
-per agent on four Tokio workers. On this Linux host, the optimized build
-measured 19,904 KiB RSS before construction, 290,828 KiB after construction
-(2,709.24 KiB marginal RSS per agent), and 477,336 KiB after the load phase.
-The 100-turn latency was p50 11 ms, p95 16 ms, p99 19 ms, max 22 ms.
-
-That baseline proves the current full `Agent` is too heavy to serve as the
-public live handle: 100 idle instances add about 265 MiB, well above the 64 MiB
-target. The proposed `AgentHandle` therefore needs to retain only a compiled
-immutable spec and shared resources; constructing and parking 100 current
-`Agent` values is not the intended final architecture.
-
-## Delivery sequence
-
-### Milestone 1: correct library identity and selectable agents
-
-- Add `HostKind::Library` and remove the local-session requirement for routed
- library turns only.
-- Add `agent_id` to the typed turn request and route it to
- `Agent::from_config_for_agent`.
-- Add a cheap `Core::agent_named(id)`/`AgentHandle` facade over the existing
- runtime.
-- Prove 100 concurrent mock-provider turns on distinct session ids complete on
- one core with no auth state.
-
-This milestone can initially use the core-wide definition/skill/MCP registries;
-it establishes correct lifecycle and concurrency without pretending injection
-is finished.
-
-### Milestone 2: injected immutable agent graphs
-
-- Accept `AgentDefinition`, skills, MCP specs and policies as values.
-- Compile and cache shared provider/tool/MCP resources at `host.agent(...)`.
-- Stop rebuilding immutable tools and provider clients for every turn.
-- Keep the desktop registry/config loaders as adapters into the same compiled
- representation.
-
-### Milestone 3: scalable stores and measurement
-
-- Add in-memory and SQLite-WAL session/conversation stores through the existing
- history/store seams.
-- Keep measuring the sharded JSONL path and replace the remaining per-root
- metadata serialization with SQLite WAL where sustained throughput needs it.
-- Add the RSS/concurrency benchmark and flamegraph allocation checkpoints.
-
-### Milestone 4: API stabilization
-
-- Run OpenCompany on the library API without environment mutation or fake auth.
-- Document shutdown, cancellation, overload and secret-handling guarantees.
-- Deprecate `HarnessBuilder::session(Session::local(..))` for library-routed
- providers after downstream migration.
-
-## Acceptance tests
-
-The feature is complete when all of the following are automated:
-
-1. A library host runs a routed turn with no auth-profile files and no backend
- calls.
-2. Desktop/CLI custom-provider calls still fail without their required app
- session.
-3. Two injected agents with different prompts, providers, skills and MCP
- allowlists cannot observe or call each other's resources.
-4. One hundred sessions run concurrently against a deterministic mock provider;
- every response and progress stream is correlated to the correct agent and
- session.
-5. Concurrent turns in the same session serialize; turns in different sessions
- overlap.
-6. Provider HTTP clients and MCP connections are constructed once per unique
- identity.
-7. No process-wide conversation mutex is acquired by the scalable store path.
-8. The RSS benchmark reports the checkpoints and satisfies the adopted budget.
-
-## Non-goals
-
-- Multiple independent `CoreRuntime`s or workspaces in one process. That is a
- different multi-context problem and is unnecessary for many agents sharing
- one OpenCompany host.
-- Treating agents as security boundaries inside one process. Untrusted tenants
- still require OS/container isolation.
-- Running local heavyweight inference models once per agent. Local engines, if
- enabled, are core-owned shared resources.
-- Making all 100 turns unbounded. Backpressure is part of the contract.
diff --git a/docs/specs/kernel.md b/docs/specs/kernel.md
deleted file mode 100644
index 2f6b74e877..0000000000
--- a/docs/specs/kernel.md
+++ /dev/null
@@ -1,274 +0,0 @@
-# OpenHuman as a Kernel — Subsystem & Driver Model
-
-**Status:** proposed · **Date:** 2026-07-28 · **Scope:** `src/` (core crate), all `src/openhuman/*` domains
-**Companion spec:** [`plan-memory.md`](plan-memory.md) — memory is the first subsystem cut to this model.
-
----
-
-## 1. Thesis
-
-Linux is a good kernel because it does not implement filesystems, network cards, or
-schedulersuites — it defines **narrow contracts** (VFS, netdev, block layer), owns **policy and
-mechanism** (permissions, namespaces, scheduling, lifecycle), and lets independently-developed
-**drivers** implement the actual behaviour behind those contracts. A driver can be built in, a
-module, or absent; userspace never learns which.
-
-`openhuman-core` should be that kernel for a personal AI runtime. Today it is closer to a
-monolith with one very good in-tree implementation per capability: memory *is* TinyCortex, agents
-*are* TinyAgents, channels *are* TinyChannels. Each already has a seam (`src/openhuman/tinycortex/`,
-`src/openhuman/tinyagents/`), which proves the shape works — but the seams are **bespoke per
-domain**, the contracts are **not versioned**, and there is **no way for a third implementation to
-be bound at runtime**.
-
-This spec defines the general model. It deliberately generalises patterns the repo already has
-rather than inventing new ones.
-
-**Non-goal:** a plugin marketplace, dynamic `.so` loading, or an ABI. Drivers are Rust crates
-compiled in, or out-of-process services reached over a documented wire contract. Nothing here
-requires unsafe dynamic linking.
-
----
-
-## 2. What already exists (the raw material)
-
-| Kernel concern | Existing mechanism | Gap for the kernel model |
-| --- | --- | --- |
-| Syscall surface | Controller registry (`src/core/all.rs`), JSON-RPC `/rpc`, `/schema` | Method set is fixed at compile time; cannot vary by bound driver |
-| Runtime composition | `DomainSet` / `DomainGroup` on `CoreBuilder` | Selects *whether* a domain runs, not *which implementation* |
-| Build composition | Per-domain Cargo `[features]` (`voice`, `web3`, `mcp`, `channels`, …) | Gate = on/off, not a choice between implementations |
-| Service lifecycle | `ServiceSet`, `src/core/runtime/services.rs` | No per-subsystem health/degraded state |
-| IPC | `event_bus/` broadcast + native request/response | Fine as-is; becomes the kernel's internal bus |
-| Policy | `SecurityPolicy`, approval gate, `MemoryTaint`, `source_scope`, redaction | Enforced *inside* domains, so a swapped implementation could bypass it |
-| Trust metadata | `CapabilityProviderConfig` (`config/schema/capability_providers.rs`) | Already the right shape; unused by domains |
-| Seams | `src/openhuman/tinycortex/`, `src/openhuman/tinyagents/` | Adapter to *one* crate, not to a trait a second crate could also satisfy |
-
-The kernel model is mostly **naming and enforcing** the above, plus one genuinely new piece: the
-**subsystem registry with a bound driver per slot**.
-
----
-
-## 3. Model
-
-### 3.1 Definitions
-
-- **Kernel** — `src/core/` plus the always-on platform domains. Owns: RPC transport and the
- controller registry, the event bus, config load/validation, `SecurityPolicy` and the approval
- gate, scheduling/cron, the workspace and path roots, observability, and the subsystem registry.
- The kernel contains **no capability implementation**.
-- **Subsystem** — a named capability slot: `memory`, `inference`, `channels`, `skills`, `flows`,
- `sandbox`, `voice`. Each subsystem owns a **contract** (a set of Rust traits + value types), a
- **config section**, a **stable RPC namespace**, and an **agent-tool family**.
-- **Driver** — an implementation of a subsystem contract. Three classes:
- - **`embedded`** — an in-tree/vendored Rust crate (`tinycortex`, `tinyagents`, `tinychannels`).
- The default; no network, no extra process.
- - **`external`** — an out-of-process backend reached through a transport adapter over a
- documented wire contract (HTTP/JSON, or MCP). This is how a third party ships a driver
- without touching this repo.
- - **`null`** — a stub advertising zero capabilities. What a compiled-out or unconfigured
- subsystem binds to. Replaces today's hand-written `stub.rs` files with one generic answer.
-- **Binding** — exactly **one** driver is bound per subsystem per process, chosen by config at
- boot. Same rule OpenClaw uses for `plugins.slots.memory`: installing a second memory backend
- disables the first with a warning, because two live memory backends means two truths. Fan-out
- across several backends is expressed as a **composite driver** (§3.5), not as a second binding.
-
-### 3.2 The contract shape (normative)
-
-Every subsystem contract is defined in an **API module with no engine dependencies** and follows
-the same five-part shape:
-
-```rust
-// 1. Identity + lifecycle — every driver implements this.
-#[async_trait]
-pub trait Driver: Send + Sync + 'static {
- fn id(&self) -> &str; // "tinycortex", "supermemory", "null"
- fn class(&self) -> DriverClass; // Embedded | External | Null
- fn capabilities(&self) -> Capabilities; // 2.
- async fn health(&self) -> DriverHealth; // Ready | Degraded { reason } | Down { reason }
- async fn shutdown(&self) -> Result<()>;
-}
-
-// 2. Capability descriptor — a bitset/struct of optional trait families, not a version number.
-// 3. Capability traits — one per family; a driver implements only what it advertises.
-// 4. Value types — serde-only, dependency-free, shared by every driver.
-// 5. Errors — a typed enum with a mandatory `Unsupported { capability }` variant.
-```
-
-**Rules:**
-
-1. **Capabilities are negotiated, not assumed.** The kernel asks `capabilities()` once at bind
- time and caches it. Calling an unadvertised capability is a kernel bug, not a driver error.
-2. **Value types are inert.** Serde/std only — no SQLite, no tokio-specific types, no engine
- types. This is the same carve-out rule the `skills` and `mcp` Cargo gates already follow
- (`AGENTS.md`: *"put a domain's inert types in a dep-free submodule and leave it ungated"*), now
- applied across crate boundaries so an external driver can depend on the API without pulling
- the embedded engine.
-3. **Drivers never see kernel concerns.** No RPC schemas, no `SecurityPolicy`, no keychain, no
- event bus, no `Config`. Everything a driver needs is passed in its constructor or per call.
-4. **Contracts are versioned.** Each API module carries `pub const CONTRACT_VERSION: (u16, u16)`.
- Minor bump = capability added; major bump = existing signature changed. External drivers
- report the version they speak in their handshake; a major mismatch fails the bind.
-
-### 3.3 Degradation is a first-class outcome
-
-When a bound driver does not advertise a capability, the kernel does **not** register a handler
-that returns "not implemented". It behaves exactly like today's compile-time gates:
-
-- the corresponding **RPC methods are unregistered** — unknown-method over `/rpc`, absent from
- `/schema`;
-- the corresponding **agent tools are absent** from the tool list, not present-and-failing;
-- the **UI** reads the capability set from `<subsystem>_status` and hides the surface.
-
-Absence beats a stub that errors. A registered-but-failing method teaches the model that the
-capability exists and makes it retry (the exact reasoning already recorded for the `flows` gate).
-The one exception is the **CLI**, which keeps its subcommand arm and reports a *build/config fact*
-("memory driver `supermemory` does not support tree summarisation") — same reasoning as the
-retained `mcp` and `tui` CLI arms.
-
-Implemented for memory at the CLI boundary. `core::cli_capability` resolves the bound driver
-directly — no CLI subcommand except `run`/`serve` builds a `CoreContext`, so the ambient
-`capability_allowed` gate would always default open — and `core::all::capability_for_parts` /
-`sole_capability_for_namespace` supply the **unfiltered** lookup that tells "no such command"
-apart from "gated", which every filtered lookup has already collapsed into one absence. Both CLI
-paths are covered: the generic `openhuman <namespace> <function>` dispatcher and the hand-written
-`openhuman memory <sub>` adapter. `core::dispatch` is deliberately untouched — it is the shared
-`/rpc` path, where the absence rule above still holds. A genuinely unknown command still reports
-unknown namespace / function / subcommand; collapsing the two would make real typos harder to
-diagnose.
-
-### 3.4 Policy is kernel-side and non-bypassable
-
-Every subsystem call from product code goes through a kernel-owned **guard decorator**, never to
-the driver directly:
-
-```text
-agent tool / RPC handler
- │
- ▼
- Guard<D> ── SecurityPolicy · taint stamping · scope allowlist · redaction ·
- │ egress budget · approval gate · audit event · tracing span
- ▼
- bound driver D
-```
-
-`Guard` implements the same contract traits as `D`, so it is transparent to callers and
-impossible to skip by construction. This closes the single largest risk of a driver model: today
-`MemoryTaint`, `source_scope`, and redaction are enforced *inside* the memory domain, so a
-replacement implementation would silently drop them. After this change a driver **cannot** see
-un-redacted content it was not granted, and cannot stamp its own provenance.
-
-**External drivers additionally require:** a `CapabilityProviderConfig` entry with an explicit
-`trust_state` (fail-closed `untrusted`), a recorded egress decision, and per-call budget
-accounting. Sending user memory to a hosted backend is an egress event and is treated as one.
-
-### 3.5 Composition instead of kernel special-cases
-
-Multi-backend behaviour is expressed as drivers that wrap drivers:
-
-- **`composite`** — fan out reads across N drivers, merge/rank, write to a designated primary.
-- **`mirror`** — write to both, read from primary; the migration path between backends.
-- **`cache`** — embedded driver in front of an external one.
-
-Each is just another `Driver`, so the kernel keeps exactly one bind and zero special cases.
-
-### 3.6 Config shape (uniform across subsystems)
-
-```toml
-[subsystems.memory]
-driver = "tinycortex" # the bound slot; "null" disables
-
-[subsystems.memory.drivers.tinycortex]
-# embedded driver options
-
-[subsystems.memory.drivers.supermemory]
-class = "external"
-transport = "http"
-endpoint = "https://…"
-credential_ref = "keychain:supermemory" # never an inline secret
-```
-
-Secrets are **references**, resolved kernel-side through the existing keychain, and passed to the
-driver as a redacted `SecretString` — the pattern already pinned for Composio credentials.
-
-### 3.7 Runtime axes (unchanged, now three)
-
-| Axis | Question | Mechanism |
-| --- | --- | --- |
-| Compile-time | Is this code in the binary? | Cargo `[features]` |
-| Runtime composition | Does this domain run this process? | `DomainSet` / `ServiceSet` |
-| **Binding (new)** | **Which implementation answers?** | **subsystem registry + config** |
-
-They compose: a subsystem compiled out binds `null`; a subsystem gated off by `DomainSet` is not
-bound at all; a subsystem present and enabled binds the configured driver, falling back to the
-embedded default if that driver fails to construct (logged loudly, surfaced in status, never
-silent).
-
-> **Feature-forwarding gate applies.** Any new default-ON gate (e.g. `memory-embedded`) must be
-> added to `app/src-tauri/Cargo.toml`'s explicit feature list — the shell sets
-> `default-features = false`. `scripts/ci/check-feature-forwarding.mjs` enforces this; the `voice`
-> incident is why.
-
----
-
-## 4. Kernel/driver split criterion
-
-One question decides where any file lives:
-
-> **Would a build whose only driver is a third-party external backend still need this file?**
-
-- **Yes → kernel.** RPC schemas and ops, agent-tool definitions, `SecurityPolicy` and policy
- guards, provenance/taint, scope and redaction, credentials and keychain, schedulers and cron,
- the event bus, config mapping, the driver registry and transport adapters, export/import.
-- **No → driver crate.** Storage engines, indexes, chunking, embeddings pipelines, retrieval and
- ranking, summary trees, job engines, source readers and parsers, provider-specific
- normalisation, on-disk formats and migrations.
-
-This is a sharper rule than "is it product policy or engine logic", which is how the
-2026-07-28 cutover evaluation landed on keeping several engine-shaped modules in the host. Under
-the kernel criterion those modules are **implementation of the default driver** and belong to it —
-see the memory spec §6 for the concrete re-disposition.
-
----
-
-## 5. Subsystem roadmap
-
-| Subsystem | Default driver | Contract status | Order |
-| --- | --- | --- | --- |
-| **memory** | `tinycortex` (embedded) | To be defined — companion spec | **1st (pilot)** |
-| inference | `tinyagents` routing | Partly exists (`routing`, provider traits) | 2nd |
-| channels | `tinychannels` | Trait exists (`channels::traits`, already an ungated carve-out) | 3rd |
-| sandbox | local OS jail | Already trait-shaped (Docker / Landlock / Noop) | 4th — smallest, good validation |
-| skills · flows | in-tree | Gated already; contract later | later |
-
-Memory goes first: it has the most mature seam, a golden-workspace parity harness, and a real
-external demand (pluggable backends such as Supermemory/mem0).
-
----
-
-## 6. Definition of done (kernel layer)
-
-1. `src/core/subsystem/` exists: `Driver`, `DriverClass`, `DriverHealth`, `Capabilities`,
- `SubsystemRegistry`, `Guard`, and the `[subsystems.*]` config mapping.
-2. Binding happens once at `CoreBuilder` time; a failed bind falls back to the embedded default,
- emits a `DomainEvent`, and is visible in `<subsystem>_status`.
-3. Controller registration in `src/core/all.rs` is filtered by the bound driver's capability set,
- the same way it is filtered by `DomainSet` today.
-4. Agent-tool assembly is filtered by the same set.
-5. `Guard` is the only path from product code to a driver; a test asserts no direct driver call
- site exists outside the registry module.
-6. `openhuman subsystems` CLI + `subsystems_status` RPC list slot, bound driver, class, health,
- contract version, and capabilities.
-7. Docs: `gitbooks/developing/architecture/kernel.md` describes the model; `AGENTS.md` gains a
- "adding a subsystem driver" checklist.
-
-## 7. Risks
-
-- **Capability sprawl.** Every optional trait is a branch in RPC registration and tool assembly.
- Mitigation: capability families are coarse (≤10 per subsystem) and adding one requires a
- contract minor bump plus a both-ways test.
-- **Guard bypass.** Mitigation: drivers are private to the registry module; a lint test greps for
- out-of-module construction.
-- **Parity regressions.** Mitigation: the golden-workspace harness that already backs the
- TinyCortex cutover is promoted to the general conformance suite (§ memory spec 7).
-- **Over-abstraction.** Mitigation: memory ships end-to-end and a second real driver exists before
- a second subsystem is cut over. One proven seam beats five speculative ones.
-
diff --git a/docs/specs/memory-guard-allowlist.md b/docs/specs/memory-guard-allowlist.md
deleted file mode 100644
index e56ec4bdda..0000000000
--- a/docs/specs/memory-guard-allowlist.md
+++ /dev/null
@@ -1,176 +0,0 @@
-# Memory-guard allowlist
-
-Every place in the tree that still reaches memory **without** going through
-`MemoryGuard`, and why. Produced by M4b; consumed by M4c.
-
-Pinned by the ratchet in `src/openhuman/memory/bypass_allowlist_tests.rs`
-(M4c), which fails **both ways** — when a new unguarded call site appears
-(`no_new_memory_driver_bypasses`), and when an allowlisted one is cleaned up
-without being struck from the list (`bypass_allowlist_has_no_stale_entries`).
-Two further tests stop the lint rotting into a rubber stamp: the scanner must
-find a known bypass, and every needle must still match something.
-
-M4b shipped a provisional, file-keyed version of this guard inside
-`memory/ops/guard_tests.rs`. M4c deleted it — two allowlists over one tree must
-both be struck on every cleanup, and the one nobody remembers is exactly the
-dead-string rot the ratchet exists to prevent.
-
-## Scope
-
-The lint scans the host and vendored `tinymemory-core` sources for nine
-patterns, keyed on `(file, pattern)` so the
-failure message names the needle that tripped:
-
-| Pattern | What it hands out |
-| --- | --- |
-| `global::client_if_ready(` | `MemoryClientRef` |
-| `.profile_conn(` | raw `Arc<Mutex<rusqlite::Connection>>` (one in-family site) |
-| `.profile_store(` | a typed `ProfileStore` — confined, but still unguarded |
-| `.get_document(` | `pub(crate)` read-one escape hatch |
-| `NullMemoryProvider::new(` | a driver, built outside `binding::for_workspace` |
-| `MemoryClient::from_workspace_dir(` | a second engine on the same store |
-| `binding::for_workspace(` / `.memory_binding(` | a raw `MemoryBinding` |
-| `.unguarded_provider(` | the raw `Arc<dyn MemoryProvider>` off a `MemoryBinding` |
-
-**By-path test files (`*_tests.rs`, `tests.rs`, `test_support/`) are out of
-scope.** Driver tests construct drivers — that is what a driver test *is* —
-so allowlisting them would add ~25 entries that can never shrink and would
-churn on every new test. Inline `#[cfg(test)] mod tests` blocks are *not*
-stripped, because brace-tracking Rust with a line scanner is fragile and
-getting it wrong silently hides production sites; the four files affected are
-allowlisted with a reason saying so. Comment lines are skipped, so doc-comment
-references are not mistaken for calls.
-
-`global::init(workspace)` is deliberately **not** scanned. It binds the
-workspace; it does not read or write memory, and every call site is a
-login / active-user-switch / boot / CLI-entry lifecycle event
-(`security/credentials/ops.rs`, `desktop/app_state/ops.rs`,
-`core/runtime/context.rs`, `core/memory_cli.rs`, `core/subconscious_cli.rs`,
-`memory/ops/documents.rs`'s `memory_init`, `memory/tinycortex/sync.rs`).
-
-## What M4b re-pointed
-
-Four RPC handlers, all in `src/openhuman/memory/ops/`, each of whose contract
-twin is a literal one-line delegation to the same host method on the same
-store:
-
-| Handler | Contract method | Driver body |
-| --- | --- | --- |
-| `documents::doc_put` | `MemoryDocuments::put_document` | `client.put_doc(input)` |
-| `kv_graph::kv_set` | `MemoryGraph::kv_put` | `client.kv_set(ns, key, &value)` |
-| `tool_memory::tool_rule_list` | `MemoryToolMemory::tool_rules` | `tool_memory_store(memory).list_rules(tool)` |
-| `tool_memory::tool_rule_delete` | `MemoryToolMemory::delete_tool_rule` | `tool_memory_store(memory).delete_rule(tool, id)` |
-
-Two **agent tools** followed the same route:
-
-| Tool | Contract method | Note |
-| --- | --- | --- |
-| `memory_tools_list` | `MemoryToolMemory::tool_rules` | 1:1 — same rules, same order, same serialization. |
-| `memory_tools_put` | `MemoryToolMemory::put_tool_rule` + `tool_rules` | The contract method returns unit while the tool answers with the *stored* rule, so the write is followed by a read-back on the id `ToolMemoryRule::new` generated before the write. Exact, not lossy: there is no server-assigned identity, and `tool_memory_namespace` normalises the caller's raw `tool_name` the same way the write did. A concurrent delete in that window errors rather than fabricating a rule. |
-
-`memory_tools_put` therefore now refuses under the `readonly` autonomy tier
-with `"memory guard: "`-prefixed text, and store-level validation errors arrive
-as `MemoryError::Invalid` rather than as a raw string. Both are intended.
-
-**Three deltas ride along, and they are the point of the milestone, not
-accidents:**
-
-1. **Tier enforcement.** A write now goes through `ToolOperation::Act`, so a
- `readonly` autonomy tier refuses it and the hourly action budget is charged
- one unit. Reads take `ToolOperation::Read`, which `SecurityPolicy` answers
- `Ok` for unconditionally today.
-2. **Error strings gain a method prefix.** The driver wraps host failures
- through `host_error(context, error)`, so `"<orig>"` becomes
- `"put_document: <orig>"`. Additive context, never a swallowed cause.
-3. **Taint may be raised.** `doc_put` still passes `MemoryTaint::Internal`; the
- guard's `stamp_taint` promotes it to `ExternalSync` when the turn runs under
- a source scope. It can never launder the other direction.
-
-Redaction is a byte-identical pass-through for an embedded driver, and the
-ambient source scope is applied only on `MemoryTree::query_source`, so neither
-changes anything here.
-
-## The allowlist
-
-### A. Legitimate residents — the driver, the seam, the bind site
-
-| Path | Reason |
-| --- | --- |
-| `memory/tinycortex/sync.rs` | The engine seam. |
-| `vendor/tinymemory/crates/tinymemory-core/src/backfill.rs` (`.get_document(`) | The connector-tree backfill (tinymemory#136 / openhuman#6012) reads each stored connector document back through the engine's read-one escape hatch before re-filing it into the memory tree. Engine-internal and beneath the module contract; the host reaches it only through `MemoryMaintenance::backfill_connector_trees`, which the kernel guard tiers as a read for a dry run and a write for a real pass. |
-| `memory/global.rs` | The process-global slot itself. |
-| `memory/ops/helpers.rs` | Defines `active_memory_client`. |
-| `memory/ops/guard.rs`, `guard_tests.rs` | The guarded resolver; matches only in prose and in its own fallback. |
-| `memory/ops/provider.rs` (`.unguarded_provider(`) | Health probe on the bound driver; a liveness probe is not product code. |
-| `core/cli_capability.rs` (`binding::for_workspace(`) | The CLI's capability gate (`kernel.md` §3.3's one exception to "degradation is absence"). Reads the driver id and advertised capability set only — the same two values `memory.provider_status` already returns over RPC — and never reaches memory content. No CLI subcommand except `run`/`serve` builds a `CoreContext`, so `CoreContext::memory()` resolves to nothing and there is no guard to route through. `core/memory_cli.rs` calls `bound_memory_driver_for` rather than binding itself. |
-| `core/subsystems_cli.rs` | The `openhuman subsystems` slot table. Delegates to `memory_subsystem_status` (which itself resolves the binding in `memory/ops/provider.rs`, already allowlisted above), so `subsystems_cli.rs` never touches `binding::for_workspace(` directly — the CLI's command arms go through `bound_memory_driver_for`. |
-
-### B. Unguardable raw SQLite — `profile_conn()`, out of scope for M4
-
-No decorator can wrap an `Arc<Mutex<rusqlite::Connection>>`. These reach the
-profile / facet tables beneath all seven policy steps. **This is why "the guard
-is the only path" is not yet a true invariant.**
-
-> **Update (memory module port).** The `agent/learning/*` facet bypasses are
-> gone. They were justified by "the contract has no profile family"; it now has
-> [`MemoryProfile`], and the learning subsystem reads and writes facets through
-> the bound driver, guard included. `agent/learning/schemas.rs` and
-> `agent/learning/tools.rs` no longer appear below at all, and
-> `agent/learning/startup.rs` keeps two entries: a `#[cfg(test)]`-only
-> construction the scanner cannot brace-track, and a boot-time
-> `binding::for_workspace(` that resolves a **guard** (not a raw client) for a
-> known workspace, exactly as `active_memory_guard`'s own no-ambient-context
-> fallback does.
-
-| Path | Sites |
-| --- | --- |
-| `vendor/tinymemory/crates/tinymemory-core/src/store/identity.rs` | 2 — the engine's cross-toolkit identity matcher resolves its global client and then reads the typed profile store. This is below the module contract, not a host-side path. |
-
-TinyMemory v1.13.4 removed the old in-process Composio sync pipeline, so its
-former profile-store entries are intentionally absent. The identity matcher is
-the remaining vendor-internal reader counted by this guard.
-
-### C. Needs a concrete engine type the contract does not expose
-
-| Path | Reason |
-| --- | --- |
-| `agent/experience/ops.rs` | `AgentExperienceStore::new` takes `Arc<dyn Memory>`; the non-`"memory"` subdir branch also builds `UnifiedMemory::new_with_memory_dir` directly — a per-profile store the binding has no concept of. |
-| `agent/harness/session/builder/factory.rs` | `.memory_handle()` → `Arc<dyn Memory>`. |
-| `flows/tinyflows/memory_adapter.rs` | Returns `Arc<dyn Memory>` to satisfy a tinyflows engine trait. The contract has no `Arc<dyn Memory>` door. |
-| `flows/bus.rs` | `resolve_memory() -> Option<Arc<dyn Memory>>`, and carries a `#[cfg(test)] memory_override` seam a guard would bypass. |
-
-### D. No contract method exists, or the wire shape would change
-
-| Path | Reason |
-| --- | --- |
-| `memory/ops/sync.rs` | `client.ingestion_state().snapshot()` — queue telemetry, absent from the contract. |
-| `flows/ops.rs` | The production namespace clear uses `MemoryDocuments`; only the directly injected `MemoryClientRef` test seam remains raw. |
-| `integrations/composio/schemas.rs` | Passes `&MemoryClientRef` into `user_scopes::save`. |
-| `memory/sync/composio/providers/user_scopes.rs`, `types.rs` | Same `&MemoryClientRef` parameter shape. |
-| `agent/learning/linkedin_enrichment.rs` | `MemoryClient::store_skill_sync` — derives the `skill-<id>` namespace and stamps every write `MemoryTaint::ExternalSync`, so the subconscious gate can see the provenance through the persistence layer. No provider family exposes either, and reimplementing them at the call site is the duplication the method exists to prevent. **It does not get the opaque-`document_id` key protection:** this caller passes `None`, and `store_skill_sync` names it as the exception — the key stays the title (`LinkedIn profile: {url}`) and does go through `upsert_document`'s secret/PII key guard. Harmless in practice for a LinkedIn URL, recorded because this column is what a future reviewer relies on to tell deliberate from forgotten, and a reason that overclaims is worse than none. **Newly listed, not newly bypassed:** this site previously reached the same client through `MemoryClient::new_local()`, for which the scanner had no needle — and which pinned `~/.openhuman` regardless of `OPENHUMAN_WORKSPACE`, so on a scoped host the profile was written to a store nothing else reads. |
-
-### E. Tests
-
-`flows/ops_tests.rs`, `flows/tinyflows/memory_node_e2e_tests.rs`,
-`integrations/composio/ops_tests.rs`, `core/runtime/context.rs` (its `#[cfg(test)]`
-module).
-
-TinyMemory v1.13.4 removed the in-process Composio sync test support along with
-the pipeline itself. The remaining vendored global-client use is the
-engine-internal identity matcher described above.
-
-## Honest scorecard
-
-The document listing/mutation handlers, the full KV/graph handler family, the
-tool-memory handlers, and flow namespace cleanup now use the shared memory API.
-Raw profile/facet access and consumers whose foreign traits require
-`Arc<dyn Memory>` remain unguarded and are enumerated above. The defensible
-claim is therefore:
-
-> Every memory RPC handler covered by a shared capability family routes through
-> the guard, and every remaining bypass is enumerated here with a reason and
-> pinned by a drift guard.
-
-"Impossible to skip by construction" is **not** true until `memory_handle()`
-is gone and the profile/facet tables have a capability family to be guarded
-against.
diff --git a/docs/specs/plan-agents.md b/docs/specs/plan-agents.md
deleted file mode 100644
index 5eeec6f770..0000000000
--- a/docs/specs/plan-agents.md
+++ /dev/null
@@ -1,660 +0,0 @@
-# Moving `agent/` into TinyAgents
-
-**Status:** spec + plan. Direction decided by the maintainer on 2026-07-28
-after two rounds of pushback; this document plans the move rather than
-re-arguing it. The open questions below are *how*, not *whether*.
-**Scope:** relocate `src/openhuman/agent/` (152 files, 70,530 LOC) into
-`vendor/tinyagents` as a generic agent runtime, with OpenHuman's coupling
-expressed as trait injection.
-**Supersedes:** the "permanent host" dispositions for `builder/`, `turn/`,
-`runtime.rs`, and `types.rs` in
-`2026-07-28-agent-session-transcript-to-tinyagents-design.md` §6, and the
-`agent/ remainder — STAYS` row in `tinyagents-migration-plan-2026-07-22.md` §7.
-Those rows are reopened by this decision and must be updated in the ledger.
-
----
-
-## 1. Why this is feasible (the enabling fact)
-
-The earlier objection was dependency direction: `agent/` reaches 45 OpenHuman
-domains, so relocating it appeared to force a GPL-redistributed crate to import
-Composio, `SecurityPolicy`, and `memory_store`.
-
-That objection assumes the code moves *as written*. It does not have to,
-because **the crate is already generic over a host-supplied state type**:
-
-```rust
-pub struct AgentHarness<State: Send + Sync, Ctx: Send + Sync = ()> { … }
-pub trait Tool<State: Send + Sync>: Send + Sync { … }
-pub trait ChatModel<State: Send + Sync>: Send + Sync { … }
-pub trait Middleware<State: Send + Sync, Ctx: Send + Sync = ()>: Send + Sync { … }
-```
-
-`State` is the injection vehicle. A relocated agent runtime does not import
-`crate::openhuman::memory` — it is generic over a `State` that *provides*
-memory, and OpenHuman supplies the impl. The crate already ships **18 extension
-traits** on exactly this pattern (`ChatModel`, `Tool`, `ChatHistory`, `Store`,
-`AppendStore`, `Summarizer`, `EmbeddingModel`, `VectorStore`, `ResponseCache`,
-`WorkspaceIsolation`, `HarnessEventJournal`, `HarnessStatusStore`,
-`EventListener`, `Middleware`, `ModelMiddleware`, `ToolMiddleware`,
-`ModelBaseCall`, `ToolBaseCall`). This move adds ~10 more of the same kind. It
-is not a new architecture; it is more of the one already in use.
-
-The GPL/crates.io concern also narrows correctly: the constraint is that no
-*OpenHuman product logic* is published, not that no agent runtime is. Traits and
-a generic loop are publishable; `provider_role_for`'s `subconscious` routing and
-the `integrations_agent` dispatcher override are not — they become host impls.
-
----
-
-## 2. Ground truth: the coupling to invert
-
-### 2.1 Outbound — what `agent/` imports (45 domains)
-
-By reference count:
-
-| Refs | Domain | Becomes |
-| ---: | --- | --- |
-| 195 | `config` (`Config` 53, `AgentConfig` 45, `MemoryConfig` 28, `ContextConfig` 24, …) | **crate config structs**, populated host-side. The single largest blocker — see §4.1 |
-| 91 | `tinyagents` (the seam) | dissolves — becomes internal |
-| 84 | `tools` | existing `Tool<State>` + `SharedToolAdapter` |
-| 72 | `inference` | existing `ChatModel<State>` + a `ModelResolver` trait |
-| 57 + 41 + 16 + 11 + 5 + 3 | `memory`, `memory_store`, `memory_tree`, `agent_memory`, `memory_tools`, `memory_conversations` | **`MemoryProvider`** trait |
-| 52 | `context` | **`ContextComposer`** trait |
-| 34 + 22 | `profiles`, `agent_registry` | **`DefinitionRegistry`** trait |
-| 28 | `composio` | host `Tool` impls — no new trait |
-| 25 + 10 + 6 + 4 + 2 | `security`, `approval`, `agent_tool_policy`, `sandbox`, `prompt_injection` | **`SecurityGate`** trait |
-| 22 + 1 | `skills`, `skill_runtime` | host `Tool` impls |
-| 21 | `todos` | already crate `graph::todos` (parent spec DS-1) |
-| 19 + 7 + 4 | `tokenjuice`, `cost`, `scheduler_gate` | **`BudgetGate`** trait |
-| 11 | `learning` | **`LearningSink`** trait |
-| 8 | `subconscious` | host impl behind `LearningSink` |
-| 6 + 4 | `web_chat`, `channels` | **`ProgressSink`** trait |
-| 5 | `tool_status` | **`ToolOutcomeClassifier`** trait |
-| 5 | `thread_goals` | host impl behind `ContextComposer` |
-| 5 | `embeddings` | existing `EmbeddingModel` |
-| 5 | `agent_orchestration` | existing `graph::orchestration` |
-| 3 | `agent_experience` | **`ExperienceStore`** trait |
-| remainder (`util`, `app_state`, `session_db`, `file_state`, `task_sources`, `mcp_registry`, `threads`, `session_import`, `migrations`, `tinycortex`, `tool_timeout`) | ≤ 4 refs each | host impls or inlined generics |
-
-**~10 new traits** cover 45 domains, because most domains reach `agent/` through
-one of a few conceptual seams.
-
-### 2.2 Inbound — what imports `agent/` (48 domains)
-
-This is the half the earlier analysis under-weighted, and it is the larger risk.
-By symbol:
-
-| Refs | Symbol | Note |
-| ---: | --- | --- |
-| 275 | `agent::harness::*` | the bulk; moves down |
-| 58 | `agent::turn_origin` | product enum — **stays host** |
-| 43 | `agent::messages` (`ChatMessage`) | durable DTO — **stays host** (WP-1) |
-| 24 | `agent::triage` | product — **stays host** |
-| 22 | `agent::progress` (`AgentProgress`) | UI contract — **stays host**, produced via `ProgressSink` |
-| 14 | `agent::prompts` | `SOUL.md`/`IDENTITY.md` — **stays host** |
-| 14 | `agent::host_runtime` | **stays host** by definition |
-| 14 | `agent::bus` | event-bus glue — **stays host** |
-| 12 | `agent::task_board` | already crate `graph::todos` |
-| 12 | `agent::message_convert` | boundary adapter — **stays host** |
-| 11 | `agent::hooks` | trait defs move; impls stay |
-| 8 | `agent::error`, 8 `agent::cost`, 7 `agent::tool_policy`, 7 `agent::progress_tracing`, 7 `agent::pformat`, 6 `agent::task_dispatcher`, 4 `agent::stop_hooks` | mixed; see §3 |
-
-**Consequence:** `agent/` does not empty out. Roughly **20–25k LOC stays** as
-the host adapter layer (`ChatMessage`, `AgentProgress`, `turn_origin`, prompts,
-triage, bus, host_runtime, message_convert, the trait impls). The deliverable is
-"the runtime moves down and OpenHuman keeps an adapter", not "the directory
-disappears".
-
-### 2.3 Honest cost
-
-45 inbound domains to invert, 48 outbound consumers to repoint, ~29k LOC of
-tests to migrate or re-home, a cross-repo change in two Cargo worlds, and an
-on-disk/behavioural surface (transcript format, progress events, cost
-accounting) that users depend on. **This is a multi-quarter program, not a
-refactor.** §5 sequences it so every phase is independently valuable and the
-program can be halted at any phase boundary without leaving the tree broken.
-
----
-
-## 3. Disposition
-
-### Moves into `tinyagents` (generic over `State`)
-
-| Host area | Prod LOC | Lands as |
-| --- | ---: | --- |
-| `harness/session/{runtime,types,builder}` — session lifecycle & assembly | ~3,700 | `harness::session` — `Session<State>` + builder over capability traits |
-| `harness/session/turn/*` — turn orchestration shell | ~4,476 | `harness::session::turn` — generic loop + `TurnPreparation` pipeline |
-| `harness/subagent_runner/` | ~5,541 | merges into existing `harness::subagent` + `graph::orchestration` |
-| `harness/session/transcript.rs` + `turn_checkpoint.rs` | ~2,100 | the crate **`Store`/`AppendStore` session journal** (`{workspace}/tinyagents_store/`), via the in-flight #4249 migration — **not** a `JsonlChatHistory`; corrected 2026-08-03, see §5 Phase 2 |
-| `harness/{parse,definition,definition_loader,tool_filter,required_output,graph,agent_graph,fork_context}.rs` | ~3,300 | `harness::{tool_calling, definition, graph}` — merges with #55/#57 |
-| `harness/artifact_offload/`, `tool_result_artifacts/` | ~1,400 | `harness::artifacts` — **`artifact_offload` landed** (tinyagents#101); `tool_result_artifacts/` still to do |
-| `harness/run_queue/`, `harness/memory_context*.rs` | ~1,000 | `harness::runtime`, behind `MemoryProvider` |
-| `task_dispatcher/`, `dispatcher.rs` (parse half), `pformat.rs`, `stop_hooks.rs`, `hooks.rs` (trait defs) | ~3,000 | `harness::{tool_calling, hooks}` |
-| `progress_tracing/` | ~3,186 | deleted, not moved — crate observability already covers it (parent spec DS-5) |
-| `multimodal.rs` (resolution half) | ~1,300 | `harness::multimodal` behind the `multimodal` cargo feature — **landed**, see §5 Phase 5 |
-
-### Stays in OpenHuman as the adapter layer
-
-`messages.rs` (`ChatMessage`), `message_convert.rs`, `progress.rs`
-(`AgentProgress`), `turn_origin.rs`, `prompts/`, `triage/`, `bus.rs`,
-`host_runtime.rs`, `error.rs`, `cost.rs`, `tool_policy.rs`,
-`agent/tools/`, `archivist/`, `schemas.rs`, plus **every impl of the ~10 new
-traits**. Estimated ~20–25k LOC including tests.
-
-> **`multimodal.rs` moved off this list.** It read `multimodal.rs` until
-> 2026-08-21, when the maintainer reversed that row and the module was split.
-> The row was not wrong about the part that matters — the `ChatMessage`
-> adapters, the config mapping, the proxy client, the PDF extractor and the
-> on-disk attachment stash are all still here — it was wrong that *nothing*
-> generic was underneath them. Marker parsing, `data:` URI decoding, MIME
-> detection, the limit clamps and the rendered payload are the same for any
-> host, and they are now `harness::multimodal`. The host file is ~1,300 lines
-> lighter and reads as what §5 calls the irreducible remainder.
-
----
-
-## 4. The two decisions that gate everything
-
-### 4.1 Config (195 refs — the real blocker)
-
-`agent/` reads `Config`, `AgentConfig` (742-line schema), `MemoryConfig`,
-`ContextConfig` directly. A generic runtime cannot import OpenHuman's config
-schema. Options:
-
-- **A — Crate-owned config structs.** The crate defines `SessionConfig`,
- `TurnConfig`, `ToolConfig`; OpenHuman maps its schema into them at build time.
- Explicit, versionable, and mirrors how `MemoryConfig` is derived for TinyCortex
- (`tinycortex/config.rs::memory_config_from`). **Recommended.**
-- **B — `ConfigProvider` trait** with ~40 getters. Avoids a mapping layer but
- turns every config read into a virtual call and makes the trait a dumping
- ground.
-- **C — Generic `State` carries config.** Least code, worst discoverability;
- every crate-side read needs a bound.
-
-Pick A. It is the pattern the org already uses successfully one crate over.
-
-### 4.2 `ChatMessage` and the transcript format
-
-Moving the session runtime down forces the durable conversation record to
-become crate-owned, and `ChatMessage`'s durable fields must survive as crate
-`Message` + a `raw` passthrough (the `ToolResult::raw` precedent). This is the
-change with real user-visible risk — existing installs have live transcripts and
-resume must keep working. Phase 2 exists solely to de-risk it.
-
-> **Corrected 2026-08-03.** This section previously said the decision was
-> "**Option B** of the transcript spec: the `session_raw` JSONL format becomes
-> crate-owned public API". It is not. The in-flight migration (issue #4249,
-> `src/openhuman/session_import/`) converges on the crate's **`Store` /
-> `AppendStore` journal**, not on promoting the legacy JSONL layout to crate
-> API. The legacy `session_raw/*.jsonl` format stays a host implementation
-> detail and is retired once readers move; it never becomes public crate
-> surface. See the Phase 2 note in §5.
-
----
-
-## 5. Phased plan
-
-Each phase is independently valuable and leaves the tree green. Stop-anywhere is
-a hard requirement, not a nicety.
-
-**Phase 0 — Ledger + trait catalogue (no code).** — *in progress (2026-08-02)*
-Reopen the superseded rows (§ header). Write the ~10 trait signatures as an
-upstream RFC in `vendor/tinyagents/docs/`. Nothing moves until the trait
-catalogue is accepted upstream — otherwise the first mover defines the seams by
-accident.
-*Exit:* accepted RFC; ledger rows reopened.
-
-Draft landed: [`docs/spec/host-capability-traits-rfc.md`](https://github.com/tinyhumansai/tinyagents/blob/main/docs/spec/host-capability-traits-rfc.md)
-in the `tinyagents` repo (vendored here at `vendor/tinyagents/`; linked by URL
-because the link checker does not check out submodules)
-— all ten signatures, grounded in measured reference counts. **Not yet
-accepted**; it carries four open questions that block Phase 1, the hard one
-being a name collision: `tinyflows` 0.5.1 shipped its own, unrelated
-`MemoryProvider` trait, and both crates are in OpenHuman's dependency graph.
-
-**Phase 1 — Land the traits upstream, empty.**
-Add the traits + no-op/in-memory default impls to the crate. No host change.
-*Exit:* crate `cargo test --all-features` green; version bump; both lockfiles.
-
-**Phase 2 — Transcript to the crate session store.** — *soak started
-(2026-08-03)*
-Do this early and alone: it is the only phase with on-disk risk. One release of
-shadow-read parity, mismatch logged never panicked, legacy `DDMMYYYY/` and
-`read_transcript_legacy_md` paths covered.
-*Exit:* resume works across upgrade on a real workspace; parity soak clean.
-
-> **This phase was mis-specified, and most of it was already built.** Two
-> corrections, found on starting it:
->
-> **1. The target is not `JsonlChatHistory`.** The heading previously read
-> "Transcript to crate `JsonlChatHistory` (transcript spec Option B)". No such
-> convergence is in progress. The real target — already chosen and half-shipped
-> under issue #4249 — is the crate's `Store` / `AppendStore` journal at
-> `{workspace}/tinyagents_store/{kv,journal}`. Building a `JsonlChatHistory`
-> would have introduced a **third** store alongside the legacy JSONL and the
-> one being migrated to.
->
-> **2. It was ~2/3 done before this phase opened.** `src/openhuman/session_import/`
-> (2,452 LOC) already implements:
->
-> | Slice | State |
-> | --- | --- |
-> | Phase 1 — importer (legacy JSONL → store) | done |
-> | 04.1 — live dual-write, `session_dual_write` | done, **defaults ON** |
-> | shadow-read comparison + `ShadowReadOutcome` | done, was default OFF |
-> | 04.2 — flip readers to the store | **not started** |
->
-> Legacy `session_raw/*.jsonl` remains the authoritative reader *and* writer;
-> the store is mirror-only. That is the correct sequencing and it was already
-> right — this phase's job is to finish it, not restart it.
-
-**Done this pass.**
-
-- **Closed the two legacy-shape coverage gaps this phase's own exit criteria
- name**, neither of which had a test (`session_import/live_tests.rs`):
- - date-grouped `session_raw/DDMMYYYY/` resolves the same store stream as a
- flat transcript. The session key is the file *stem*, so the enclosing
- directory must not change it; if it ever did, every pre-migration session
- would read as `Unavailable` and the soak would look clean while covering
- nothing.
- - a legacy `.md` session reads as `Unavailable`, never `Divergence`. These
- predate the store, so no stream exists — reporting divergence would flood
- the soak with false positives from every old transcript on disk, and the
- point of the soak is that a warning means something.
-- **`session_shadow_reads` now defaults ON**, starting the parity soak. Safe to
- default on because it is observation-only: legacy stays authoritative, the
- probe runs on a background task once per *resume* (not per turn), a store-read
- failure degrades to `Unavailable`, and `OPENHUMAN_SESSION_SHADOW_READS=0` is a
- kill switch. Worst case of a bad soak is log noise, not a broken resume.
-
-**Remaining for Phase 2** — and the reason it is not yet done:
-
-1. **Soak.** Collect `[session_shadow_read]` divergence rates from real
- workspaces across one release. There is no data yet, so nothing below is
- justified.
-2. **04.2 — flip readers**, gated on the same flag, only once the soak is clean.
-3. Retire the legacy writer once reads have run on the store for a release.
-
-**Do not skip to 2.** The whole design of this phase is that the reader flip is
-bought with evidence, and the evidence does not exist until a release has
-shipped with the probe on.
-
-**Phase 3 — Config mapping (§4.1 Option A).** — *in progress (2026-08-02)*
-Introduce crate config structs + a host `session_config_from(&Config)` mapper.
-Repoint `agent/` internals to the crate structs *in place*, before moving.
-*Exit:* zero `crate::openhuman::config::` references inside the code slated to
-move.
-
-Landed so far — foundation only, nothing repointed yet:
-
-- `tinyagents::harness::config` — `SessionConfig`, `TurnConfig`, `ToolConfig`,
- `MemoryLimits`, `RequiredOutput`, `ToolDispatcher`. Inert (serde + std only),
- defaults pinned to OpenHuman's current values.
-- `src/openhuman/tinyagents/config.rs` — `session_config_from` plus
- `apply_team_models` / `apply_delegate`, following the
- `tinycortex::config::memory_config_from` precedent. Split three ways because
- OpenHuman's model pins are **not global**: `Config::teams` is keyed by team
- and `Config::agents` by delegate, so one flat mapper would have to invent the
- model for a session.
-- 23 tests across both sides. The load-bearing one is
- `default_config_maps_to_the_crate_defaults`, which fails if the two default
- sets ever drift.
-
-`ToolDispatcher` is an enum where the host has a `String`. The four accepted
-spellings are `auto` / `native` / `xml` / `pformat` — **not** the
-`auto`/`native`/`parsed` triple a reasonable person would guess. An unknown
-value maps to `Auto` with a warning rather than failing: the host's own schema
-lets a typo through validation, so refusing to build the session would turn a
-cosmetic config error into an agent that cannot run.
-
-### Repointing: what the "37 files" actually decomposes into
-
-The 37-file figure counts every `agent/` production file with a qualified
-`config::` path. **Only ~19 are in the moving set** — the rest (`host_runtime`,
-`bus`, `triage/`, `schemas`, `multimodal`, `prompts/`, `agent/tools/`,
-`archivist/`, `progress_tracing/`) stay host-side per §3 and *should* keep
-reading `Config`; they are the mapper's callers. Repointing them would be
-actively wrong. Within the moving set: **41 qualified refs**, which split into
-three very different problems.
-
-**1. Ambient config loads — 11 sites. Not a repoint; a signature refactor.**
-*(Done 2026-08-02 — 11 sites → 2 genuine + 1 boundary snapshot.)*
-
-`Config::load_or_init().await` appeared 11 times inside code slated to move.
-A generic runtime has no config file and no `load_or_init`, so these could not
-be pointed at a struct — the config had to be **threaded in from the caller**.
-
-`load_or_init` is **not cached**: it re-resolves the config dirs and re-reads
-`config.toml` on every call. `run_typed_mode` called it six times, so one
-sub-agent spawn hit the disk six times and could observe six *different*
-configs mid-spawn. `run_subagent` now takes a single snapshot
-(`LoadedConfig = Result<Arc<Config>, String>`) and hands it down.
-
-`Result<_, String>` rather than `Option` because the `integrations_agent` path
-reports the load error to its caller while the other five degrade silently —
-keeping both shapes lets each site preserve its original failure behaviour. The
-snapshot is taken **after** `tier_gate_decision`: `load_or_init` can initialize
-config on first run, and a spawn the tier gate rejects should not have that
-side effect.
-
-The sub-agent graph got the same treatment: `build_subagent_context_mw` now
-takes `Option<&Config>` (and is no longer `async`), plumbed through
-`run_subagent_via_graph` and a new `AgentTurnRequest::config` field so the
-custom-graph path keeps its `[context]` knobs rather than silently falling back
-to defaults. The four graph tests pass `None`, which makes them hermetic — they
-previously read whatever `config.toml` was on the developer's machine.
-
-**Scope correction: `task_dispatcher/` is not in the moving set.** §3 lists it
-beside `dispatcher.rs`, both mapping to `harness::{tool_calling, hooks}`. That
-conflates two unrelated modules. `dispatcher.rs` parses tool calls out of model
-output and is genuinely generic. `task_dispatcher/` is a task-**card board**
-dispatcher reaching `task_sources`, `threads`, `web_chat`, `todos`, `profiles`
-and `scheduler_gate` — product logic that stays host-side. Its three
-`load_or_init` calls are boundary code and are correct as they are. **§3's row
-should be split.**
-
-Two loads remain in moving files, both host-boundary code that gets extracted
-rather than moved:
-
-- `session/turn/tools.rs:123` — Composio integration fetch. Config is *already*
- threaded via the session's `runtime_config` (set in
- `factory.rs`); this is only the fallback when a session is built through
- the raw setter path. Composio is host product logic and becomes a `Tool` impl
- in Phase 4, so the fallback was left rather than risk silently disabling
- integration fetching for setter-built sessions.
-- `harness/definition.rs:781` — `load_for_default_workspace()`, a convenience
- constructor with exactly one caller: `src/core/agent_cli.rs:415`. It is a CLI
- boundary helper that stays host-side when `definition.rs` moves.
-
-**2. Blocked on Phase 2 — the session cannot drop `AgentConfig` yet.**
-
-The session reads only **9 distinct `AgentConfig` fields**, 7 of which the crate
-structs already cover. The two that do not — `session_dual_write` and
-`session_shadow_reads` (`session/turn/session_io.rs`) — are *transcript*
-live-store migration flags. They have no crate home until Phase 2 decides where
-the transcript lives, so `Agent.config: AgentConfig` has to stay for now.
-
-Adding a crate `SessionConfig` *alongside* it was considered and rejected:
-`session/runtime.rs:181` mutates `self.config.max_tool_iterations` after build
-(the iteration-cap override), so two configs would silently diverge on exactly
-the field most read. One source of truth or none.
-
-**3. Blocked on Phase 4 — `builder/factory.rs`.**
-
-`factory.rs` reaches 21 domains and is going to be *split* into host trait impls,
-not moved verbatim. Repointing its `Config` usage now is rework.
-
-### Done in this pass
-
-`RequiredOutputContract` → crate `RequiredOutput`, the one clean type swap
-available: `harness/required_output.rs` (pure logic, no host domains) and
-`session/turn/session_io.rs`, converting at the read site in
-`session/turn/core.rs` via `tinyagents::config::required_output_from`. The
-crate type gained `all_keys()` with semantics identical to the host's, including
-the subtle one — a blank `block_key` makes the contract inert *even when
-`required_keys` lists siblings*. The 12 existing `required_output` tests pass
-unchanged against the crate type, which is the proof the swap is behaviour-
-preserving.
-
-The mapper was also split into per-section functions (`turn_config_from`,
-`tool_config_from`, `memory_limits_from`, `apply_agent_config`) because the
-session builder takes a **per-agent `AgentConfig` override** — mapping only from
-the global `Config` would have discarded it and run every agent on the global
-limits.
-
-### Revised remaining work
-
-1. ~~Thread config through the ambient-load sites.~~ **Done 2026-08-02.**
-2. After Phase 2: replace `Agent.config` with crate config; migrate the two real
- external `agent_config()` consumers (`agent_orchestration/parent_context/`,
- `subconscious/session.rs`).
-3. After Phase 4: `factory.rs`, and the Composio fetch in `session/turn/tools.rs`.
-4. Split §3's `task_dispatcher/` + `dispatcher.rs` row — only the latter moves.
-
-> **Test note.** `openhuman::agent::` needs `RUST_MIN_STACK=16777216` or
-> `session::tests::turn_dispatches_spawn_subagent_through_full_path` overflows
-> the stack (already flagged in §6). With it set, the suite is 1080 pass / 1 fail
-> — `builder_tests::profile_allowed_tools_restrict_shared_session_builder` fails
-> **on a clean tree too** when run with the full suite and passes in isolation, so
-> it is a pre-existing order-dependence, not Phase 3 fallout.
-
-**Phase 4 — Implement the traits host-side, still in place.** — *adapters
-landed (2026-08-03); call sites not yet repointed*
-`AgentMemory`, `ContextComposer`, `SecurityGate`, `BudgetGate`,
-`DefinitionRegistry`, `ExperienceStore`, `LearningSink`, `ProgressSink`,
-`ToolOutcomeClassifier`, `ModelResolver`. `agent/` calls them instead of
-reaching into domains directly. **This phase delivers most of the architectural
-value with none of the relocation risk** — after it, `agent/`'s outbound
-coupling is ~10 traits instead of 45 domains, and the program can legitimately
-stop here.
-*Exit:* `grep -c "crate::openhuman::" src/openhuman/agent/harness/session/` down
-from its baseline to the adapter layer only.
-
-> **Exit-criterion baseline corrected.** The figure above read "~2,000 refs".
-> Measured: **295** in `session/` production code (548 including tests). The
-> larger number counted a wider tree. 295 is the number to drive down.
-
-**Landed: all ten adapters** in `src/openhuman/tinyagents/host/`
-(~6,000 LOC, 140 tests). Each wires one crate trait to the real OpenHuman
-domains, with policy enforced adapter-side. `agent/` **does not call them yet**,
-so the exit criterion is still at 295 — writing the adapters and repointing the
-callers are two separate pieces of work and only the first is done.
-
-Two defects were found and fixed at integration, both of the kind that compiles
-cleanly and fails silently:
-
-- **`security_gate`: a channel `RequireApproval` verdict was resolving to
- `Allow`.** The mapping returned "no verdict" on the theory the call would fall
- through to the approval park — but the park is reached only from the `shell`
- and external-effect branches, so any ordinary tool was authorized with nobody
- asked. `agent_tool_policy::engine` files `RequireApproval` under
- `blocked_tool_names` alongside `Deny`, so this inverted the host's own
- semantics. Latent only because `build_session` does not currently emit
- `RequireApproval` — i.e. a trap armed for whoever turns it on. Now routed to
- the park, and **denied** when no approval gate exists (the one place this
- adapter set denies where the legacy middleware allows, argued in the module
- header). Pinned by `require_approval_never_silently_allows_a_plain_tool`.
-- **`experience_store`: cross-agent record collision.** The domain's
- `stable_experience_id_for_profile` hashes task + tool sequence + outcome +
- profile and deliberately **excludes `agent_id`**; the native capture hook is
- protected only incidentally, by always supplying a real tool sequence. This
- adapter has none to supply, so two agents recording the same task with the
- same outcome collided on one id and `put` upserted — the second writer
- silently destroying the first's record. The agent id is now folded into the
- hashed tool-sequence slot.
-
-**Remaining for Phase 4 — repointing. Investigated 2026-08-04 and found
-blocked, not merely hard.** Four findings, each measured:
-
-**1. The exit criterion counts the wrong code.** Of the 118 non-adapter-layer
-refs in `session/`, roughly two-thirds are not consumption at all:
-
-| Where | Refs | What it is |
-| --- | ---: | --- |
-| `builder/` (factory 29, setters 12, mod 3, helpers 2) | 46 | assembly — becomes the trait *impls*, per §3 |
-| `types.rs` | 16 | field type annotations — the injection points themselves |
-| `runtime.rs` | 13 | session state management (e.g. `rebuild_tool_policy_session`) |
-| `turn/` | 40 | the only genuine runtime consumption |
-| misc | 3 | |
-
-Driving `session/` "down to the adapter layer only" therefore cannot happen by
-repointing: most of those refs **are** the adapter layer. The honest metric is
-`turn/`'s ~40.
-
-**2. The session distributes handles more than it consumes them.** All 11 uses
-of `self.memory` hand the `Arc<dyn Memory>` to a collaborator (the memory
-loader, the context loader, `AgentExperienceStore`) rather than calling recall
-or store. Swapping the field to `Arc<dyn AgentMemory>` would break those
-collaborators, which need the full domain interface. The memory seam cannot be
-repointed until they move behind traits too.
-
-**3. No capability trait fits an existing call shape 1:1.** Checked all ten.
-`ContextComposer::compose_system_prompt` returns a `String`, but the turn needs
-structured `LearnedContextData` to feed its own `SystemPromptBuilder`, so
-adopting it means moving the whole prompt assembly into the adapter — the same
-work as Phase 5, not a repoint. `ToolOutcomeClassifier`'s only host consumer is
-`progress_tracing/`, which §3 **deletes** rather than moves. `subconscious` in
-`session/` is type annotations in `factory.rs` only.
-
-**4. Four adapters cannot be constructed from session state.**
-
-| Adapter | Constructor needs | Session has |
-| --- | --- | --- |
-| `AgentMemory`, `ExperienceStore` | `Arc<dyn Memory>` | yes (`memory_arc()`) |
-| `ToolOutcomeClassifier` | nothing | yes |
-| `ProgressSink` | `Sender<AgentProgress>` | yes |
-| `LearningSink` | `Vec<Arc<dyn PostTurnHook>>` | yes |
-| **`BudgetGate`, `ContextComposer`, `ModelResolver`** | **`Arc<Config>`** | **yes — the session carries `runtime_config: Option<Arc<Config>>`** |
-| **`SecurityGate`** | **`Arc<SecurityPolicy>`** + tool sets | tool sets yes, **policy no** |
-
-The `Arc<Config>` gap that used to head this chain is **closed**: the session
-field was promoted from `integration_runtime_config: Option<Config>` to
-`runtime_config: Option<Arc<Config>>` in #5396, and the same pass collapsed the
-subagent spawn path from seven ambient `Config::load_or_init()` calls to one.
-`BudgetGate`, `ContextComposer` and `ModelResolver` are therefore constructible
-today.
-
-What remains blocked is narrower than it was:
-
-> Phase 4's **repointing** still needs Phase 2 to rehome
-> `session_dual_write` / `session_shadow_reads`, which needs the parity soak,
-> and the soak needs a *shipped release* to produce data.
->
-> So §5's claim that Phase 4 "delivers most of the architectural value with
-> none of the relocation risk" holds for the **adapters**, which are done. The
-> repointing half is gated on elapsed time, not on effort.
-
-**Two further blockers surfaced in #5396's review, both crate-side** and both
-filed upstream — repointing should not proceed past them:
-
-- [`tinyagents#88`](https://github.com/tinyhumansai/tinyagents/issues/88) —
- `ProgressEvent` has no tool-completion milestone, so a host cannot report a
- tool's outcome. Tool rows would stay `running` forever; synthesising
- `success: true` would put wrong data in the timeline and the trace exporter.
-- [`tinyagents#89`](https://github.com/tinyhumansai/tinyagents/issues/89) —
- `ModelResolveRequest` carries no model pin, so a definition's exact model id
- has no route to the resolver. Per-agent pins would silently resolve to the
- workload default.
-
-> **Both are fixed upstream in
-> [`tinyagents#100`](https://github.com/tinyhumansai/tinyagents/pull/100)**,
-> awaiting merge. `ProgressEvent` gains `ToolCallFinished { run, call, success,
-> output }` and `ModelResolveRequest` gains `model_pin: Option<String>`.
->
-> Two notes for whoever does the repointing:
->
-> - **Neither type is emitted by the runtime yet.** The PR makes the seams
-> *expressible*; the agent loop still has to produce `ToolCallFinished`, and
-> the subagent runner still has to populate `model_pin` from
-> `AgentDefinition.model`. Landing #100 unblocks the adapters, it does not
-> wire them.
-> - **The `model_pin` is advisory by design.** The host decides whether it can
-> honour a pin, because the runtime has no view of credentials or provider
-> health. `OpenHumanModelResolver` should therefore validate the id against
-> configured providers rather than pass it through blind — which is the
-> behaviour §4's adapter notes already wanted and had no channel for.
-
-**21 `TODO(phase4)` markers** remain across the adapters, each naming a domain
-surface that was not reachable. They are honest gaps, not stubs pretending to
-work; the notable ones are `AgentMemory::thread_summary` (no host-authored
-per-thread prose rollup exists) and `SecurityGate::screen_input` never returning
-`Redacted` (OpenHuman can detect PII but exposes no public text-rewriting
-helper).
-
-**Phase 5 — Relocate, module family at a time.** — *3 of 7 families landed*
-Order by inbound coupling, lowest first: `artifact_offload` → `run_queue` →
-`multimodal` → `parse`/`tool_calling` (merges with DS-5b) → `subagent_runner` →
-`session/turn` → `session/{builder,runtime,types}`. Each family: move to
-`vendor/tinyagents/src/harness/`, re-export from the host adapter for one
-release, then repoint consumers.
-*Exit per family:* crate tests green; host `cargo check` both worlds; the
-family's tests live upstream.
-
-| Family | State |
-| --- | --- |
-| `artifact_offload` | **landed** — crate `harness::artifacts` (tinyagents#101), host keeps the prompt contract + two policy adapters |
-| `run_queue` | **landed** — crate `harness::run_queue` owns the FIFO mechanics; host wrapper keeps `QueueMode::{Interrupt,Parallel}` and the `QueuedMessage` payload |
-| `multimodal` | **landed** — crate `harness::multimodal` owns marker parsing, `data:` URIs, MIME detection, limits and payload rendering; host keeps the `ChatMessage` adapters, the config mapping, the proxy client, the `documents` PDF extractor and the attachment stash |
-| `parse`/`tool_calling` | not started |
-| `subagent_runner` | not started |
-| `session/turn` | blocked on Phase 2's soak |
-| `session/{builder,runtime,types}` | blocked on Phase 2's soak |
-
-> **The shape both landed families converge on**, and the template for the
-> rest: the crate owns the mechanics, the host keeps a thin wrapper holding
-> exactly the parts that are product-specific. `run_queue` keeps two enum
-> variants and a payload struct; `artifact_offload` keeps prompt text and two
-> policy adapters. Neither host module is a re-export shim — each is the
-> irreducible remainder, which is what "keep just the wiring" means in
-> practice.
->
-> **Two rules the `artifact_offload` move established**, both of which will
-> recur:
->
-> 1. **Prompt text never moves.** §6 lists OpenHuman prompt text as
-> unpublishable, and prompts name host tool ids. So the crate's pointer
-> renderer takes the read-tool name as a *parameter* rather than a constant
-> — a hard-coded tool name in a redistributed crate would put a tool some
-> other host does not have into its prompts.
-> 2. **A host policy becomes a trait pair, not an import.** `SecurityPolicy`
-> and `sanitize_text` became `ArtifactPathPolicy` / `ArtifactRedactor`. The
-> host constructor installs both every time, because the crate permits
-> `None` for each and OpenHuman never wants either — routing construction
-> through one helper is what stops a call site producing an unguarded writer
-> by omission.
-
-**Phase 6 — Collapse the seam and the adapter.**
-`src/openhuman/tinyagents/` dissolves into the host adapter layer. Delete the
-compatibility re-exports.
-*Exit:* `agent/` is the adapter layer only; parent spec's DS-0 re-export gate
-allowlist is seam-free.
-
-**Phase 7 — Exit gate.**
-Full `scripts/test-rust-with-mock.sh`, `cargo test --all-features` in both
-vendored crates, slim disabled build **and** `cargo test --lib
---no-default-features core::`, `pnpm
-rust:check`, deletion-ledger totals reconciled, architecture docs rewritten.
-
----
-
-## 6. Risks
-
-- **Inbound coupling is the real cost, not outbound.** 48 domains import
- `agent::`. Phase 5's per-family re-export window is what keeps that tractable;
- skipping it turns every family move into a 48-domain atomic commit.
-- **On-disk transcript risk (Phase 2)** is the only user-visible data risk in
- the program. It is deliberately isolated and sequenced first.
-- **`AgentProgress` is a UI contract.** It stays host-side and is produced
- through `ProgressSink`. If it drifts into the crate, the frontend timeline,
- cost footer, and citation chips break in ways unit tests will not catch.
-- **Trait-explosion.** Ten traits is the budget. If Phase 4 needs a fifteenth,
- that is a signal a seam is wrong — re-open the RFC rather than adding it.
-- **GPL/crates.io.** Publishable: traits, generic loop, tool-calling wire
- formats. Not publishable: `provider_role_for`'s `subconscious` routing, the
- `integrations_agent` override, OpenHuman prompt text, backend phrasing, key
- material. Every relocated file needs this check.
-- **≥ 80% diff-coverage gate** on a program of this size — Phases 4 and 5 touch
- hundreds of files. Check `diff-cover` per slice.
-- **Two Cargo worlds** — every crate bump regenerates root and
- `app/src-tauri` lockfiles (#3877).
-- **`RUST_MIN_STACK=16777216`** — the subagent runner's large futures already
- overflow the default stack on Apple Silicon; Phase 5's subagent move is
- exactly where that resurfaces.
-- **`GGML_NATIVE=OFF`** for local root-crate builds.
-
----
-
-## 7. Summary
-
-| | |
-| --- | --- |
-| Decision | move `agent/` into `tinyagents` (maintainer call, 2026-07-28) |
-| Enabler | the crate is already generic over `State`; 18 extension traits use the pattern today |
-| Inversion | 45 outbound domains → **~10 capability traits** |
-| Reality check | `agent/` does not empty — ~20–25k LOC stays as the host adapter (`ChatMessage`, `AgentProgress`, prompts, triage, bus, trait impls) |
-| Gating decisions | config mapping (§4.1 → Option A); durable conversation record converges on the crate **store**, not a crate-owned JSONL (§4.2, corrected 2026-08-03) |
-| Highest-value / lowest-risk phase | **Phase 4** — trait injection in place. Cuts coupling 45 → 10 without moving a file; a legitimate stopping point |
-| Highest-risk phase | **Phase 2** — on-disk transcript format, isolated and sequenced first. Was mis-specified and already ~2/3 built under #4249; parity soak started 2026-08-03 |
-| Honest cost | multi-quarter program; every phase leaves the tree green and shippable |
-
diff --git a/docs/specs/plan-memory.md b/docs/specs/plan-memory.md
deleted file mode 100644
index 2c1f297442..0000000000
--- a/docs/specs/plan-memory.md
+++ /dev/null
@@ -1,482 +0,0 @@
-# Memory Subsystem — Pluggable Provider API & TinyCortex Consolidation
-
-**Status:** proposed · **Date:** 2026-07-28 · **Scope:** `src/openhuman/memory*`, `src/openhuman/tinycortex/`, `vendor/tinycortex`
-**Depends on:** [`kernel.md`](kernel.md)
-**Supersedes (in disposition only):** `docs/tinycortex-cutover-evaluation-2026-07-28.md` §"Audit result" — see §6.1.
-
----
-
-## Amendment 2026-08-10 — the destination is `tinymemory`, not `vendor/tinycortex`
-
-This plan was written when TinyCortex was the only engine in view, so it named
-`vendor/tinycortex` as the destination for everything that moves. That is now split in two,
-because "engine-specific" and "engine-neutral" are different destinations:
-
-| Kind of code | Destination | Why |
-| --- | --- | --- |
-| TinyCortex's own storage, retrieval, tree, queue and sync internals (§6.2) | `vendor/tinycortex` — unchanged | It is the implementation of *one* engine. |
-| The contract, capability negotiation, driver admission, the conformance corpus, the shared mandatory families, and one adapter per engine | **`vendor/tinymemory`** (new submodule) | A second engine cannot be reached through a crate named after the first. |
-
-**What landed (2026-08-10).**
-
-- `tinymemory-api` — the contract, moved out of `tinycortex-api` byte-identical. §3.1's carve-out
- still describes how it was *created*; it now lives one repository over.
-- `tinymemory::registry` — driver admission, lifted out of `memory/binding.rs`. §4's driver table
- is where new ids get reserved.
-- `tinymemory::mandatory` — the three mandatory families composed once over the `Memory` storage
- trait, so a new engine inherits the four easy-to-get-wrong parts (taint routing, all-namespace
- list, scoped-recall refusal, import provenance) instead of re-deriving them.
-- `tinymemory-tinycortex` — the seam, with exhaustively-destructuring conversions.
-- `vendor/tinycortex` is pinned as a nested submodule of `tinymemory`. Adapters name their engine
- by **version requirement**, so a host's own `[patch.crates-io]` unifies everything onto one
- engine copy; a path dependency would give the host two engines with two incompatible `Memory`
- traits.
-
-**Two contracts, converted at one seam — a deliberate deviation.** `tinycortex-api` was *not*
-turned into a re-export of `tinymemory-api`. The two therefore remain distinct Rust types that
-describe the same values, and `tinymemory-tinycortex` converts between them. The cost is real and
-should be stated: a value crossing the seam is rebuilt, and the two contracts can drift. The
-mitigation is that every conversion destructures exhaustively, so a field added on either side is
-a compile error naming the field rather than a silently dropped value.
-
-The consequence for this plan: **openhuman stays on `tinycortex-api`** as its contract. §6.7's grep
-invariant is unchanged. A future phase that unifies the two contracts would re-point the host's
-~200 `tinycortex_api::` references in one mechanical pass; until then, the seam is the boundary.
-
-**Sequencing unchanged.** M8a (the `source_scope` inversion) is still the hard gate before any
-`memory_tree/retrieval` file moves, and M8b's per-module moves still go to `vendor/tinycortex`.
-This amendment changes *where the engine-neutral layer lives*, not the order in which the engine
-moves.
-
----
-
-## 1. Goals
-
-1. **Memory becomes an API, not an implementation.** The kernel owns a versioned memory contract;
- TinyCortex becomes the default *embedded driver* behind it, and a third-party backend
- (Supermemory, mem0, a self-hosted service) can be bound instead without touching kernel code.
-2. **Everything TinyCortex-specific lives in TinyCortex.** The remaining engine-shaped host
- modules and re-export shims move into `vendor/tinycortex`. The host keeps only what a
- Supermemory-only build would still need: RPC, agent tools, policy, credentials, scheduling,
- registry, adapters.
-3. **No behaviour change for the default build.** Bind `tinycortex`, and the RPC surface, agent
- tools, on-disk workspace, and parity harness are byte-identical to today.
-
-## 2. Where we are
-
-- 74k LOC across `memory` (18.3k), `memory_store` (17.4k), `memory_sync` (17.2k), `memory_tree`
- (9.9k), `memory_sources` (5.0k), `memory_diff` (2.0k), `memory_queue` (1.4k), `memory_tools`
- (1.3k), `memory_goals` (0.9k), `memory_conversations` (0.9k), `memory_search` (0.7k), plus a
- 3.2k-LOC seam at `src/openhuman/tinycortex/`.
-- The engine cutover is **complete**: TinyCortex is already the implementation authority for
- chunks, content, vectors, trees, retrieval, scoring, queue, ingest, readers, sync, diffs, goals,
- graph, conversations, and tool memory.
-- But the coupling is **static and direct**. `memory::traits` is a `pub use tinycortex::memory::{…}`;
- `memory/global.rs` hands out a concrete `MemoryClient`; `UnifiedMemory` (the ten-table
- namespace-document tier) is host-owned SQLite. There is no seam a second backend can enter, and
- ~51 controller schemas assume the full capability set is present.
-
-### What OpenClaw does, and what we take from it
-
-OpenClaw's memory is a **single slot** (`plugins.slots.memory`) with a local default (Markdown +
-sqlite-vec + FTS5 hybrid). Installing `memory-lancedb` or `@mem0/openclaw-mem0` claims the slot and
-disables the incumbent with a warning. Providers expose a small tool triple —
-`memory_recall` / `memory_store` / `memory_forget` — plus opt-in **auto-recall before the turn**
-and **auto-capture after the turn**, bounded by `recallMaxChars` / `captureMaxChars` and a context
-token budget. Ownership isolation is a storage predicate, not a post-search filter.
-
-**Adopt:** one-slot binding; the recall/store/forget core triple; auto-recall/auto-capture as
-kernel-owned lifecycle hooks; per-call character/token budgets; isolation pushed into the query.
-**Reject:** the tool triple as the *whole* contract — OpenHuman's surface is an order of magnitude
-larger (trees, diffs, goals, sources, sync, entities), which is exactly why capabilities must be
-negotiated rather than assumed. **Also reject:** provider-authored lifecycle hooks. In OpenClaw the
-plugin hooks the turn; here the kernel does, so policy cannot be bypassed by a driver.
-
----
-
-## 3. The contract: `tinycortex-api`
-
-### 3.1 Crate carve-out (the enabling move)
-
-Today the shared value types live in `tinycortex::memory`, so any driver depending on the contract
-drags in SQLite, the retrieval engine, and the job model. Split a **dependency-free** crate:
-
-```
-vendor/tinycortex/
-├── api/ # NEW crate `tinycortex-api` — serde + std + async-trait only
-│ └── src/ # value types, capability traits, Capabilities, MemoryError, CONTRACT_VERSION
-└── src/ # the engine; depends on `tinycortex-api`, re-exports it as `tinycortex::memory`
-```
-
-This is the `skills`-gate type carve-out rule (`AGENTS.md`: inert types stay ungated, stub only
-behaviour) applied one level up. Existing `tinycortex::memory::{…}` paths keep resolving via
-re-export, so the ~30 host consumers and `memory::traits` are untouched.
-
-Value types moving to the API crate verbatim: `MemoryEntry`, `MemoryCategory`, `MemoryTaint`,
-`RecallOpts`, `NamespaceSummary`, plus chunk/source/tree DTOs (`ChunkRef`, `SourceRef`,
-`TreeNodeRef`, `IngestRequest`, `IngestOutcome`, `DiffEntry`, `GoalRecord`, `ToolMemoryRecord`).
-
-> `MemoryTaint` is security-critical and fails closed to `ExternalSync`. It moves **byte-identical**
-> and keeps its dedicated seam test. Provenance semantics are contract, not implementation.
-
-### 3.2 Capability families
-
-A driver implements `MemoryProvider` plus any subset of the families it advertises:
-
-| Family | Trait | Methods (indicative) | Required? |
-| --- | --- | --- | --- |
-| `core` | `MemoryCore` | `store`, `store_with_taint`, `get`, `forget`, `list`, `namespaces` | **yes** |
-| `recall` | `MemoryRecall` | `recall(query, RecallOpts) -> Ranked<ChunkRef>` | **yes** |
-| `ingest` | `MemoryIngest` | `ingest_document`, `ingest_chat` (driver owns chunking + embedding) | no |
-| `documents` | `MemoryDocuments` | namespace-document tier: `put_doc`, `get_doc`, `query_docs` | no |
-| `tree` | `MemoryTree` | `query_source`, `drill_down`, `seal`, `cascade` | no |
-| `entities` | `MemoryEntities` | entity index + edges + hotness | no |
-| `graph` | `MemoryGraph` | kv-graph read/write | no |
-| `diff` | `MemoryDiff` | snapshot capture + change computation | no |
-| `goals` | `MemoryGoals` | goal extraction/records | no |
-| `tool_memory` | `MemoryToolMemory` | per-tool learned memory | no |
-| `sources` | `MemorySourceSink` | accept synced source items (host owns creds + schedule) | no |
-| `maintenance` | `MemoryMaintenance` | reembed, compact, consolidate ("dream"), doctor | no |
-| `portability` | `MemoryPortability` | `export(stream)`, `import(stream)` | **yes** |
-
-`core`, `recall`, and `portability` are mandatory: without them a driver is not a memory backend,
-and without `portability` a user cannot leave it. Everything else degrades per kernel spec §3.3 —
-the method is unregistered, the tool is absent, the UI hides the surface.
-
-### 3.3 Degradation map (what a minimal driver loses)
-
-| Absent capability | RPC unregistered | Agent tools absent |
-| --- | --- | --- |
-| `tree` | `memory_tree*`, retrieval drill-down | tree query/drill-down tools |
-| `diff` | `memory_diff*` | diff tools |
-| `goals` | `memory_goals*` | goal tools |
-| `documents` | doc put/get/query | doc tools |
-| `sources` | `memory_sources_sync`, `memory_sync*` | sync tools |
-
-The registration sites are already grouped per family in `src/core/all.rs` (each
-`all_memory_*_registered_controllers()` call), so this is a filter at those call sites — not a
-rewrite. Both-ways tests per family, mirroring `channels_controllers_{registered,absent}`.
-
-### 3.4 The guard (non-negotiable)
-
-`MemoryGuard<P: MemoryProvider>` wraps the bound driver and is the only handle product code ever
-receives. It enforces, in order:
-
-1. `SecurityPolicy` tier + workspace/action-root path rules;
-2. `source_scope` per-turn allowlist — **applied as a query predicate passed to the driver**, not
- as a post-filter (OpenClaw's isolation lesson; also what today's W5 seam test pins);
-3. `MemoryTaint` stamping on every write — the driver receives taint, never assigns it;
-4. redaction (`memory/util/redact.rs`) on content leaving the process for an `external` driver;
-5. egress budget + `trust_state` check for `external` drivers;
-6. char/token budgets for auto-recall/auto-capture;
-7. audit event on the bus + tracing span with `driver_id`, `capability`, `namespace`.
-
-Steps 4–5 are new and exist because "memory" is the most sensitive data in the product. An
-`external` driver bind requires an explicit `trust_state = "trusted"` and, on first bind, a
-one-time user consent recorded in config. Fail-closed: unset trust ⇒ refuse to bind, fall back to
-embedded, surface in status.
-
-### 3.5 Lifecycle hooks (kernel-owned)
-
-- **auto-recall** — before an interactive turn, the kernel calls `recall` and injects results
- under a `max_context_tokens` budget (default 2000, OpenClaw parity).
-- **auto-capture** — after a turn, the kernel decides *whether* to capture (existing
- `remember.rs` / `preferences.rs` policy) and calls `store`.
-- **maintenance tick** — the existing scheduler drives `MemoryMaintenance::consolidate` if
- advertised; the embedded driver maps it to seal/cascade/reembed.
-
-Drivers do not hook the agent loop. Same rule as `queue::run_once`: the host owns the loop, the
-engine owns one step.
-
----
-
-## 4. Drivers
-
-### 4.1 `tinycortex` — embedded default
-
-`src/openhuman/memory_adapter/embedded/` implements every family over the existing seam
-(`src/openhuman/tinycortex/`). Zero new engine logic: it is a re-shaping of the current direct
-calls into contract methods. Advertises all 13 families. This is the compatibility anchor — the
-parity harness compares it against pre-change behaviour.
-
-### 4.2 `http` — the external transport adapter
-
-`src/openhuman/memory_adapter/http/` implements every family by translating to a documented
-JSON wire contract, so a third-party backend never depends on Rust or on this repo:
-
-```
-POST /v1/handshake → { contract_version, driver_id, capabilities[] }
-POST /v1/memory/store { namespace, key, content, category, taint, session_id }
-POST /v1/memory/recall { query, namespace, limit, filters, scope_allowlist[] } → ranked[]
-POST /v1/memory/forget { namespace, key | query }
-POST /v1/memory/ingest { source_ref, content, mime, taint }
-GET /v1/memory/export → NDJSON stream
-POST /v1/memory/import ← NDJSON stream
-GET /v1/health → { status, detail }
-```
-
-Unsupported family ⇒ the endpoint is absent from `capabilities[]` and returns `501`; the adapter
-maps that to `MemoryError::Unsupported`. Auth via a keychain-resolved bearer. The handshake pins
-the contract version; a major mismatch refuses the bind.
-
-**`supermemory` reference driver** is a thin config profile over `http` (base URL, auth, field
-mapping), shipped as a worked example plus a conformance-suite run — not special-cased in code.
-
-### 4.3 `mcp` — opportunistic
-
-For backends that already speak MCP, an adapter maps the families onto MCP tool calls through the
-existing `mcp_client`. Lower priority; `http` covers the demand.
-
-### 4.4 `composite` / `mirror`
-
-Per kernel spec §3.5. `mirror` is the **migration path**: bind
-`mirror { primary = "tinycortex", secondary = "supermemory" }`, backfill via
-`export`→`import`, verify with the conformance suite, then re-bind to the secondary.
-
-### 4.5 Config
-
-```toml
-[subsystems.memory]
-driver = "tinycortex"
-
-[subsystems.memory.hooks]
-auto_recall = true
-auto_capture = true
-max_context_tokens = 2000
-recall_max_chars = 1000
-capture_max_chars = 500
-
-[subsystems.memory.drivers.supermemory]
-class = "external"; transport = "http"
-endpoint = "https://api.supermemory.ai"
-credential_ref = "keychain:supermemory"
-trust_state = "untrusted" # must be explicitly raised before bind succeeds
-```
-
-The existing `[memory]`, `[memory_tree]`, `[[memory_sources]]` blocks stay as-is and map into the
-embedded driver's options; no user-visible config break.
-
----
-
-## 5. RPC & tools (unchanged surface)
-
-Method names, params, and payloads are **unchanged** — `memory*`, `memory_tree*`, `memory_sync*`,
-`memory_sources*`, `memory_diff*`, `memory_goals*` all keep their contracts. Handlers stop calling
-`memory::global::client()` and call `memory::subsystem::guard()` instead. Two additions:
-
-- `memory_provider_status` — bound driver id, class, health, contract version, capabilities,
- last error. Drives the UI's capability-aware rendering.
-- `memory_export` / `memory_import` — provider-agnostic NDJSON portability, gated by the approval
- gate (a full memory export is a high-consequence action).
-
----
-
-## 6. Consolidation: what moves into TinyCortex
-
-### 6.1 Re-disposition vs. the 2026-07-28 cutover evaluation
-
-That evaluation asked *"is this product policy or engine logic?"* and concluded the remaining
-`memory*` modules must stay. Under the kernel criterion (kernel spec §4) the question becomes
-*"would a Supermemory-only build still need this file?"* — and several modules it retained are
-**implementation of the default driver**, which is exactly where they belong once a second driver
-is possible. Its core warning still holds and is honoured here: RPC, policy, secrets, and runtime
-composition must **not** move into the crate.
-
-### 6.2 Moves to `vendor/tinycortex`
-
-| Host module | Why it moves | Lands as |
-| --- | --- | --- |
-| `memory_store/namespace_store/*` (the ten-table tier: `memory_docs`, `graph_*`, `episodic_log`+fts, `event_log`+fts+embeddings, `conversation_segments`, `segment_embeddings`, `vector_chunks`, `user_profile`) | TinyCortex-specific SQLite schema + migrations. Supermemory has no `episodic_fts`. | `store::namespace` behind the `documents`/`graph` capabilities |
-| `memory_store/content/{wiki_git,obsidian,obsidian_registry}` | On-disk content formats of the embedded engine | `store::content::{wiki_git,obsidian}`, feature-gated |
-| `memory_store/{client,factories,kinds,traits}.rs` compatibility shims | Re-exports over crate types; the contract replaces them | deleted |
-| `memory_tree/health/`, `memory_tree/io.rs`, `summarise.rs` residue | Health/doctor of *this* engine | `tree::health`, surfaced via `MemoryMaintenance::doctor` |
-| `memory_search/*` remaining shims | Re-export layer over crate retrieval | deleted |
-| `memory_queue/{store,worker,scheduler,types}.rs` residue | Engine job model; host keeps only the tokio loop that calls `queue::run_once` | crate `queue` |
-| `memory_sources/{readers,registry,reconcile,status}.rs` | Reader/parser implementations | crate `sources` |
-| `memory_sync/{canonicalize,sources,workspace,composio}` engine parts not yet flipped | Sync engine; host keeps schedulers, creds, bus, RPC | crate `sync` (feature-gated network) |
-| `memory_diff`, `memory_goals`, `memory_conversations`, `memory_tools` store/type re-export files | Thin facades over crate modules | deleted; import `tinycortex::memory::*` directly |
-| `memory/{ingest_pipeline,tree_source,query,util/*}` engine internals | Chunking/ranking/tree policy mechanics of the embedded engine | crate `ingest`/`tree`/`retrieval` |
-
-### 6.3 Stays in the host (kernel side)
-
-`memory/{ops,schemas,schema,read_rpc,rpc_models}` · `memory/tools/*`, `memory_search/tools/`,
-`memory_tools` tool surface · `SecurityPolicy` gating, `source_scope`, `util/redact.rs` ·
-`preferences.rs`, `remember.rs`, `tree_policy.rs` (product policy over the tree, not the tree) ·
-`global.rs` → becomes the registry/bind site · `chat.rs` · credentials/keychain, Composio OAuth ·
-schedulers (`memory_sync/periodic.rs`), bus subscribers · config mapping · **new**
-`memory_adapter/` (embedded, http, mcp, composite, guard).
-
-### 6.4 How much actually moves (measured, 2026-07-28)
-
-Measured over `src/openhuman/memory*`, classifying RPC/schema/ops/tools/bus/policy files as
-kernel-side and everything else as engine:
-
-| Module | Total | Kernel-side | Engine (movable) | Tests |
-| --- | ---: | ---: | ---: | ---: |
-| `memory_store` | 17,433 | 572 | **16,861** | 5,033 |
-| `memory_sync` | 17,204 | 2,246 | **14,958** | 1,813 |
-| `memory` | 18,332 | 12,474 | 5,858 | 2,709 |
-| `memory_tree` | 9,898 | 3,549 | 6,349 | 292 |
-| `memory_sources` | 4,968 | 1,733 | 3,235 | — |
-| `memory_queue` | 1,411 | 39 | **1,372** | 37 |
-| `memory_diff` | 1,956 | 1,695 | 261 | — |
-| `memory_tools` | 1,338 | 461 | 877 | 228 |
-| `memory_goals` | 869 | 642 | 227 | — |
-| `memory_conversations` | 858 | 833 | 25 | — |
-| `memory_search` | 718 | 703 | 15 | — |
-| **Total** | **74,985** | **24,947 (33%)** | **50,038 (67%)** | 10,112 |
-
-So roughly **two thirds of the host memory tree is movable engine code**, concentrated in
-`memory_store`, `memory_sync`, `memory_tree`, and `memory_queue` — those four are 90% of the
-movable mass and are near-totally engine (`memory_queue` is 97% engine, `memory_store` 97%).
-Conversely `memory_conversations`, `memory_search`, `memory_diff`, and `memory_goals` are already
-almost pure kernel-side surface: their remaining engine content is 25–261 LOC of facade, so those
-directories effectively **collapse into shims** rather than "move".
-
-This is the answer to "can most of it move now": **yes by mass, and mostly in four directories** —
-subject to §6.5.
-
-### 6.5 The one real blocker: engine→host reach-backs
-
-Twelve movable files reach *back* into host state, so they cannot be lifted as-is. Inventory:
-
-**(a) Task-local `source_scope` read from inside retrieval — the security-relevant one.**
-`memory_tree/retrieval/{source,fast,drill_down,fetch,cover}.rs` call
-`memory::source_scope::current_source_scope()` / `chunk_source_allowed_in()` directly. The
-per-turn allowlist is a *host task-local* consumed *inside the engine*. Moving these files as-is
-either drags `source_scope` into the crate (policy in the engine — the failure mode the
-2026-07-28 cutover evaluation correctly warned about) or silently drops the allowlist.
-**Fix:** invert it — retrieval takes an explicit `scope: Option<&ScopePredicate>` parameter, and
-`MemoryGuard` populates it from the task-local at the call boundary. This is already the spec's
-stated design (§3.4 step 2: *applied as a query predicate passed to the driver, not as a
-post-filter*); it just has to land **before** the move, not after. Mechanical: five call sites,
-one signature.
-*(`memory_store/tools/raw_chunks.rs`, `memory_search/tools/{chunk_context,vector_search}.rs` also
-read the task-local, but those are agent tools — kernel-side, staying put. No change needed.)*
-
-**(b) Config/event-bus reach-backs from `memory_tree`.** ~20 files under `memory_tree/{tree,score,
-graph,health,retrieval}` import `crate::openhuman::config::` or `crate::core::event_bus`.
-**Fix:** pass the derived options in (the `MemoryConfig` mapping the seam's `config.rs` already
-does) and emit through the existing sink traits instead of the bus directly. Mechanical, but
-broader than (a) — this is the bulk of `memory_tree`'s move cost.
-
-**Already fine, no work needed:** `memory_store/safety/*` is already a thin shim over the crate
-scrubber; `namespace_store/query.rs` only *constructs* `MemoryTaint::Internal` (a type, which M0
-puts in `tinycortex-api`); `memory_sources/readers/*` only mention redaction in log comments.
-
-**Consequence for sequencing:** the M4-before-M8 rule is sharper than "all policy first". Only
-class (a) is a policy-correctness gate. Class (b) is a decoupling chore that can run per-module in
-parallel. So the move can start earlier and wider than the linear workstream table implies —
-see the revised M8 split in §8.
-
-### 6.6 The shims must stay host-owned
-
-"Shims to expose the RPC APIs" has two possible shapes, and only one is correct:
-
-- ✅ **Host-owned thin controllers over the contract.** `memory/schemas/*.rs` keeps defining the
- schema, keeps `handle_*` delegating — but delegates to `MemoryGuard<dyn MemoryProvider>` instead
- of a concrete TinyCortex path. The crate never learns that JSON-RPC exists.
-- ❌ **Crate-owned RPC exposed through a host shim.** If `tinycortex` gains schemas/handlers and
- the host merely re-exports them, the dependency boundary inverts: the reusable engine now knows
- OpenHuman's method names, error envelope, and policy vocabulary — and a second driver can no
- longer satisfy the same RPC surface, which defeats the whole point.
-
-The 51 controller schemas under `memory/schemas/` therefore **do not move**, even though they are
-thin. Thin is what a good syscall table looks like.
-
-### 6.7 Expected shape after
-
-~74k LOC of host `memory*` reduces to a kernel-side surface dominated by RPC + tools + policy +
-adapters. **Line count is not the goal and not the success metric** — the metric is that
-`grep -rn "tinycortex::" src/openhuman/ --include=*.rs` returns hits only under
-`memory_adapter/embedded/` and `src/openhuman/tinycortex/`.
-
----
-
-## 7. Conformance suite
-
-The golden-workspace parity harness that backs the TinyCortex cutover is promoted to a
-**driver conformance suite** — one test corpus, run against any driver:
-
-- **Tier 1 (mandatory families):** store/get/forget/list/namespaces round-trips, recall ranking
- sanity, taint preservation, namespace isolation, export→import fidelity.
-- **Tier 2 (per advertised family):** one scenario per family; skipped-with-reason when unadvertised.
-- **Tier 3 (policy, driver-independent):** `source_scope` allowlist honoured; out-of-scope source
- never returned; redaction applied before an `external` driver sees content; `ExternalSync` taint
- stamped on synced ingest; credential never in `Debug`/error output.
-- **Tier 4 (differential):** `mirror` mode runs the corpus against both drivers and diffs results —
- the acceptance gate for adding a new driver.
-
-`tinycortex` must pass Tiers 1–4 with results identical to pre-change. The reference `supermemory`
-profile must pass Tiers 1–3 for its advertised set.
-
----
-
-## 8. Workstreams
-
-Each ≈ one PR; the sandwich rule applies to crate-side changes (crate PR → `chore(vendor): bump
-tinycortex` → host cutover PR, host tests in the same PR for the ≥80% diff-coverage gate).
-
-| # | Workstream | Deliverable | Gate |
-| --- | --- | --- | --- |
-| **M0** | `tinycortex-api` carve-out | Dep-free crate; `tinycortex::memory` re-exports; host imports unchanged | Full suite green; `cargo tree` shows no SQLite under `tinycortex-api` |
-| **M1** | Contract definition | 13 capability traits, `Capabilities`, `MemoryError`, `CONTRACT_VERSION` | Compiles; no host wiring yet |
-| **M2** | Registry + bind | `subsystems.memory` config, `SubsystemRegistry`, bind at `CoreBuilder`, fallback + status | `memory_provider_status` returns `tinycortex`/all caps |
-| **M3** | Embedded driver | `memory_adapter/embedded/` implements all families over the existing seam | Conformance Tiers 1–2 identical to pre-change |
-| **M4** | `MemoryGuard` | Policy decorator; all product call sites re-pointed; direct-driver-call lint test | Conformance Tier 3; existing security seam tests green |
-| **M5** | Capability degradation | Filter controller registration + tool assembly by capability set; both-ways tests per family | `null` driver ⇒ memory RPC unknown-method, tools absent, core boots |
-| **M6** | HTTP adapter + wire contract | `memory_adapter/http/`, handshake, `501`→`Unsupported`, egress/trust/redaction path | Conformance Tiers 1–3 against a mock backend |
-| **M7** | Portability | `memory_export`/`memory_import` NDJSON + approval gate; `mirror` driver | Export→import round-trip; Tier 4 differential |
-| **M8a** | Reach-back inversion (§6.5) | `scope` predicate parameter through retrieval; config/bus reach-backs replaced by injected options + sink traits | Existing `source_scope` seam test green; no `crate::openhuman::` import remains in the movable set |
-| **M8b** | Bulk consolidation | The §6.2 moves — `memory_store`, `memory_sync`, `memory_tree`, `memory_queue` first (90% of the mass), one module per PR | Parity green per move; the `grep` invariant in §6.7 holds |
-| **M8c** | Facade collapse | `memory_conversations`, `memory_search`, `memory_diff`, `memory_goals` reduce to kernel-side surface; re-export files deleted | Import paths land on `tinycortex::memory::*` |
-| **M9** | Reference driver + docs | `supermemory` profile, conformance report, `gitbooks/developing/architecture/memory.md`, AGENTS.md checklist | Tiers 1–3 green for advertised set |
-
-M0–M5 land the abstraction with zero behaviour change. M6–M7 make a second backend possible.
-
-**Revised sequencing (per §6.5).** The original "M8 must not start before M4" was too coarse.
-Sharper rule:
-
-- **M8a class (a) — the `source_scope` inversion — is the hard gate.** It must land before any
- `memory_tree/retrieval` file moves, or the per-turn allowlist is dropped or dragged into the
- crate. It is five call sites and one signature; it can land immediately, in parallel with M0/M1.
-- **M8a class (b) — config/bus decoupling — is a chore, not a gate**, and can run per-module
- concurrently with M2–M5.
-- **M8b can therefore start once M8a is done for that module**, without waiting for M6/M7.
- `memory_store` (16.9k) and `memory_queue` (1.4k) have almost no reach-backs and are movable
- first; `memory_tree` (6.3k) is gated on M8a(b); `memory_sync` (15.0k) is gated on its credential
- and scheduler seams staying host.
-- **M4 (`MemoryGuard`) still gates M8c**, because the facade collapse is what re-points call sites
- off `memory::global::client()` — that is the moment enforcement either exists or doesn't.
-
----
-
-## 9. Risks
-
-| Risk | Mitigation |
-| --- | --- |
-| **Policy dropped during the move** (highest) | M4 before M8; Tier-3 conformance runs on every driver; guard is the only handle |
-| **Memory exfiltration via an external driver** | fail-closed `trust_state`, one-time consent, redaction before egress, egress budget, audit events, `null`-fallback on bind failure |
-| **Perf regression from trait indirection** | families are coarse; `async_trait` boxing on already-async I/O paths is noise; benchmark recall p50/p95 before/after in M3 |
-| **Capability explosion** | 13 families capped; adding one = contract minor bump + both-ways test |
-| **Crate split churn** | M0 is re-export-only; every existing import path keeps resolving |
-| **Feature-forwarding drift** | any new default-ON gate goes into `app/src-tauri/Cargo.toml`; `check-feature-forwarding.mjs` enforces it |
-| **Disabled-build test rot** | CI's smoke lane is `cargo check` only — run `cargo test --lib --no-default-features …` locally after every gated change |
-
----
-
-## 10. Open questions
-
-1. **Does `documents` (the namespace tier) stay mandatory in practice?** Several host surfaces
- (`store_skill_sync`, profiles, episodic log) assume it. If an external driver cannot provide it,
- do we bind a `composite` with an embedded `documents` shard, or degrade those surfaces?
- *Leaning:* composite — keep documents embedded, delegate recall/ingest. Decide in M5.
-2. **Where do embeddings live for an external driver?** If the backend embeds server-side we must
- not double-embed. *Proposal:* a capability flag `embeds_internally`; when set, the kernel skips
- the embedding provider for that path.
-3. **Multi-user / multi-workspace binding** — one bind per process, or per workspace? *Leaning:*
- per workspace, since `global.rs` already rebinds on active-user switch.
-4. **Sync ownership.** Sources/credentials/scheduling stay host, but a backend like Supermemory
- has its own connectors. Do we allow a driver to advertise `owns_sources` and let the host step
- back? Deferred past M9.
-
diff --git a/docs/superpowers/plans/2026-07-09-cursor-windsurf-harness.md b/docs/superpowers/plans/2026-07-09-cursor-windsurf-harness.md
deleted file mode 100644
index 0444ace22d..0000000000
--- a/docs/superpowers/plans/2026-07-09-cursor-windsurf-harness.md
+++ /dev/null
@@ -1,250 +0,0 @@
-# Cursor & Windsurf Harness Recognition — Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Make OpenHuman's orchestration engine recognize `cursor` and `windsurf` as harness providers so their sessions render with a first-class roster group and brand glyph instead of the "Other" catch-all.
-
-**Architecture:** Widen the single backend recognition gate (`harness_type_for()` in the Rust orchestration crate), then widen the frontend `HarnessType` union it feeds — the TypeScript type-checker forces the two UI lookup tables (`HarnessGlyph` glyph map, `TinyPlaceRoster` groups) to stay complete. No changes to ingest, pairing, relay, or attention.
-
-**Tech Stack:** Rust (`openhuman` crate, `cargo test`), TypeScript/React (`app/`, `vitest`, `tsc`).
-
-**Design doc:** `docs/superpowers/specs/2026-07-09-cursor-windsurf-harness-design.md`
-
-## Global Constraints
-
-- **Scope is recognition-only.** Do NOT create any `sdk/plugin-tinyplace/adapters/*` file or touch ingest/pairing/relay/attention. Only the recognition gate and the two UI tables it feeds.
-- **Anchor edits on exact code strings, not line numbers.** This repo has concurrent activity and line numbers drift. Every edit below quotes the exact `old` string to match.
-- **Glyph labels:** Cursor → `Cu`, Windsurf → `Ws` (two-letter, parallel to Codex's `Cx`).
-- **Glyph tones (confirmed present in `app/tailwind.config.js`):** Cursor → `bg-slate-800 text-white`; Windsurf → `bg-teal-500 text-white`.
-- **Roster order:** append Cursor then Windsurf after Gemini, before the implicit "Other" group.
-- **Provider ordering in Rust match / everywhere:** `claude`, `codex`, `gemini`, `cursor`, `windsurf`.
-- **Working branch:** `feat/cursor-windsurf-harness` (already created; the design-doc commit `2af56b1e0` is its tip). Do NOT commit on `main`. Never `git add -A`; stage only the exact paths listed.
-
----
-
-### Task 1: Rust core — widen the recognition gate
-
-**Files:**
-- Modify: `src/openhuman/hosted/orchestration/schemas.rs` (fn `harness_type_for`, its two doc comments, and the test `harness_type_only_for_known_providers`)
-
-**Interfaces:**
-- Consumes: nothing (leaf change).
-- Produces: `harness_type_for(source: &str) -> Option<String>` now returns `Some(source)` for `"cursor"` and `"windsurf"` in addition to `"claude" | "codex" | "gemini"`. This is the value that populates the `harnessType` field on the session summary consumed by the frontend (Task 2).
-
-- [ ] **Step 1: Extend the failing test**
-
-In `src/openhuman/hosted/orchestration/schemas.rs`, find the test `fn harness_type_only_for_known_providers()`. It contains these assertions:
-
-```rust
- assert_eq!(harness_type_for("claude").as_deref(), Some("claude"));
- assert_eq!(harness_type_for("codex").as_deref(), Some("codex"));
- assert_eq!(harness_type_for("gemini").as_deref(), Some("gemini"));
-```
-
-Add two lines immediately after the `gemini` assertion:
-
-```rust
- assert_eq!(harness_type_for("cursor").as_deref(), Some("cursor"));
- assert_eq!(harness_type_for("windsurf").as_deref(), Some("windsurf"));
-```
-
-Leave the existing `None` assertions (`master` / `user_created` / `orchestration`) unchanged — they guard against over-broadening.
-
-- [ ] **Step 2: Run the test to verify it fails**
-
-Run: `cargo test -p openhuman harness_type_only_for_known_providers`
-Expected: FAIL — `assertion \`left == right\` failed` with `left: None, right: Some("cursor")` (the gate doesn't recognize `cursor` yet).
-
-- [ ] **Step 3: Widen the gate**
-
-In the same file, find the function body:
-
-```rust
- matches!(source, "claude" | "codex" | "gemini").then(|| source.to_string())
-```
-
-Replace it with:
-
-```rust
- matches!(source, "claude" | "codex" | "gemini" | "cursor" | "windsurf")
- .then(|| source.to_string())
-```
-
-- [ ] **Step 4: Refresh the doc comments (same file)**
-
-There are two doc comments naming the provider set as `(claude/codex/gemini)`. Update both to `(claude/codex/gemini/cursor/windsurf)`:
-
-Doc comment above the `HarnessSession`/`source` field — find:
-```rust
- /// The emitting harness (claude/codex/gemini) when this is an external agent
-```
-Replace `(claude/codex/gemini)` → `(claude/codex/gemini/cursor/windsurf)`.
-
-Doc comment above `fn harness_type_for` — find:
-```rust
-/// windows persist the emitting harness (claude/codex/gemini) in `source` (see
-```
-Replace `(claude/codex/gemini)` → `(claude/codex/gemini/cursor/windsurf)`.
-
-- [ ] **Step 5: Run the test to verify it passes**
-
-Run: `cargo test -p openhuman harness_type_only_for_known_providers`
-Expected: PASS (`test result: ok. 1 passed`).
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add src/openhuman/hosted/orchestration/schemas.rs
-git commit -m "feat(orchestration): recognize cursor & windsurf harness providers"
-```
-
----
-
-### Task 2: Frontend — widen the harness type and its UI tables
-
-**Files:**
-- Modify: `app/src/lib/orchestration/orchestrationClient.ts` (the `HarnessType` union)
-- Modify: `app/src/components/intelligence/HarnessGlyph.tsx` (the `GLYPH` record)
-- Modify: `app/src/components/intelligence/TinyPlaceRoster.tsx` (the `HARNESS_GROUPS` list)
-- Test: `app/src/components/intelligence/HarnessGlyph.test.tsx`
-- Test: `app/src/components/intelligence/TinyPlaceRoster.test.tsx`
-
-**Interfaces:**
-- Consumes: the widened backend gate from Task 1 (a session whose `source` is `cursor`/`windsurf` now arrives with `harnessType: 'cursor' | 'windsurf'`).
-- Produces: `HarnessType` union widened to `'claude' | 'codex' | 'gemini' | 'cursor' | 'windsurf'`; `GLYPH` and `HARNESS_GROUPS` gain matching entries. No new exported functions.
-
-- [ ] **Step 1: Extend the failing tests**
-
-In `app/src/components/intelligence/HarnessGlyph.test.tsx`, the `it.each` table is:
-
-```tsx
- it.each<[GlyphKind, string]>([
- ['claude', 'C'],
- ['codex', 'Cx'],
- ['gemini', 'G'],
- ['openhuman', 'OH'],
- ])('renders the %s mark', (harness, label) => {
-```
-
-Add two rows after `['gemini', 'G'],`:
-
-```tsx
- ['cursor', 'Cu'],
- ['windsurf', 'Ws'],
-```
-
-In `app/src/components/intelligence/TinyPlaceRoster.test.tsx`, add a new test after the existing `groups instances by harness ...` test (insert before the `marks the selected instance` test):
-
-```tsx
- it('groups cursor and windsurf sessions under their own headers', () => {
- const sessions = [
- session({ sessionId: 'cu1', harnessType: 'cursor', source: 'cursor' }),
- session({ sessionId: 'ws1', harnessType: 'windsurf', source: 'windsurf' }),
- ];
- render(<TinyPlaceRoster sessions={sessions} />);
- expect(screen.getByText('Cursor')).toBeInTheDocument();
- expect(screen.getByText('Windsurf')).toBeInTheDocument();
- expect(screen.getByTestId('instance-card-cu1')).toBeInTheDocument();
- expect(screen.getByTestId('instance-card-ws1')).toBeInTheDocument();
- // Neither falls into the Other catch-all.
- expect(screen.queryByText('tinyplaceOrchestration.roster.other')).toBeNull();
- });
-```
-
-- [ ] **Step 2: Run the tests to verify they fail**
-
-Run from the `app/` directory: `pnpm test src/components/intelligence/HarnessGlyph.test.tsx src/components/intelligence/TinyPlaceRoster.test.tsx`
-Expected: FAIL — `HarnessGlyph` throws destructuring `undefined` for `GLYPH['cursor']`, and `TinyPlaceRoster` cannot find the `Cursor`/`Windsurf` headers (sessions currently land in "Other").
-
-- [ ] **Step 3: Widen the `HarnessType` union**
-
-In `app/src/lib/orchestration/orchestrationClient.ts`, find:
-
-```ts
-export type HarnessType = 'claude' | 'codex' | 'gemini';
-```
-
-Replace with:
-
-```ts
-export type HarnessType = 'claude' | 'codex' | 'gemini' | 'cursor' | 'windsurf';
-```
-
-- [ ] **Step 4: Add the glyph entries**
-
-In `app/src/components/intelligence/HarnessGlyph.tsx`, find the `GLYPH` record:
-
-```ts
-const GLYPH: Record<GlyphKind, { label: string; tone: string }> = {
- claude: { label: 'C', tone: 'bg-[#c96442] text-white' },
- codex: { label: 'Cx', tone: 'bg-content text-surface' },
- gemini: { label: 'G', tone: 'bg-ocean-500 text-white' },
- openhuman: { label: 'OH', tone: 'bg-sage-500 text-white' },
-};
-```
-
-Insert the two new entries after `gemini`:
-
-```ts
- cursor: { label: 'Cu', tone: 'bg-slate-800 text-white' },
- windsurf: { label: 'Ws', tone: 'bg-teal-500 text-white' },
-```
-
-- [ ] **Step 5: Add the roster groups**
-
-In `app/src/components/intelligence/TinyPlaceRoster.tsx`, find the `HARNESS_GROUPS` list:
-
-```ts
-const HARNESS_GROUPS: Array<{ key: HarnessType; label: string }> = [
- { key: 'claude', label: 'Claude' },
- { key: 'codex', label: 'Codex' },
- { key: 'gemini', label: 'Gemini' },
-```
-
-Add the two new groups after the `gemini` entry (before the closing `];`):
-
-```ts
- { key: 'cursor', label: 'Cursor' },
- { key: 'windsurf', label: 'Windsurf' },
-```
-
-- [ ] **Step 6: Run the tests to verify they pass**
-
-Run from the `app/` directory: `pnpm test src/components/intelligence/HarnessGlyph.test.tsx src/components/intelligence/TinyPlaceRoster.test.tsx`
-Expected: PASS (both files green; the parametrized `HarnessGlyph` cases now include `cursor`/`windsurf`).
-
-- [ ] **Step 7: Type-check the frontend**
-
-Run from the `app/` directory: `pnpm tsc --noEmit` (or the project's `typecheck` script if present — check `app/package.json`).
-Expected: PASS with no errors. This confirms the widened union left no exhaustive consumer incomplete.
-
-- [ ] **Step 8: Commit**
-
-```bash
-git add app/src/lib/orchestration/orchestrationClient.ts \
- app/src/components/intelligence/HarnessGlyph.tsx \
- app/src/components/intelligence/HarnessGlyph.test.tsx \
- app/src/components/intelligence/TinyPlaceRoster.tsx \
- app/src/components/intelligence/TinyPlaceRoster.test.tsx
-git commit -m "feat(orchestration): render cursor & windsurf harness glyphs and roster groups"
-```
-
----
-
-## Self-Review
-
-**Spec coverage:**
-- Design change 1 (widen `harness_type_for`) → Task 1 Steps 3. ✅
-- Design change 2 (Rust test) → Task 1 Steps 1–2, 5. ✅
-- Design doc-comment refresh → Task 1 Step 4. ✅
-- Design change 3 (`HarnessType` union) → Task 2 Step 3. ✅
-- Design change 4 (glyph entries, `bg-slate-800` / `bg-teal-500`) → Task 2 Step 4. ✅
-- Design change 5 (roster groups) → Task 2 Step 5. ✅
-- Design tests 6 (`HarnessGlyph.test.tsx`) → Task 2 Step 1. ✅
-- Design tests 7 (`TinyPlaceRoster.test.tsx`) → Task 2 Step 1. ✅
-- Verification (cargo test, vitest, tsc) → Task 1 Step 5, Task 2 Steps 6–7. ✅
-- Out-of-scope (no adapter, no ingest/attention change) → Global Constraints. ✅
-
-**Placeholder scan:** No TBD/TODO/"handle edge cases"; every code step shows exact strings. ✅
-
-**Type consistency:** Provider order `claude, codex, gemini, cursor, windsurf` and labels `Cu`/`Ws` are identical across the Rust match, the TS union, the glyph map, the roster groups, and both test files. ✅
diff --git a/docs/superpowers/plans/2026-07-24-identity-marketplace-seller-web-only.md b/docs/superpowers/plans/2026-07-24-identity-marketplace-seller-web-only.md
deleted file mode 100644
index 87ff802cc2..0000000000
--- a/docs/superpowers/plans/2026-07-24-identity-marketplace-seller-web-only.md
+++ /dev/null
@@ -1,212 +0,0 @@
-# Identity Marketplace Seller-Web-Only Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Replace the seller-side dead-end in the desktop Identities → Trading tab with a note pointing users to the web flow, and record that seller-side is web-only by design.
-
-**Architecture:** Additive UI only. A persistent info note at the bottom of `TradingTab` opens `https://tiny.place/identities` via the existing `openUrl()` helper (mirrors the `X402ConfirmDialog` `/fund` precedent). No SDK, core, or `invokeApiClient` changes — the tiny.place backend has no seller routes. Scoping recorded in two doc comments.
-
-**Tech Stack:** React 19 + TypeScript, Vitest + Testing Library, `@tauri-apps/plugin-opener` (via `app/src/utils/openUrl.ts`), Rust doc comment.
-
-## Global Constraints
-
-- **No i18n:** `IdentitiesSection.tsx` is entirely hardcoded English (e.g. `"Commitment submitted."` line 854, `"Purchased {name}"` line 887). New strings are hardcoded English to match. **No locale-file edits** — do NOT add `useT()` here.
-- **Web URL is a hardcoded prod constant:** `https://tiny.place/identities`. Mirrors `FUND_PAGE_URL = 'https://tiny.place/fund'` in `X402ConfirmDialog.tsx`. The tiny.place *web* frontend has no per-env base in `config.ts`.
-- **External links go through `openUrl`** from `app/src/utils/openUrl.ts` — never a raw `window.open` or `<a target="_blank">` for the CTA (the `<a>` explorer links elsewhere in the file are read-only tx links, a different case).
-- **Out of scope (do not touch):** `vendor/tinyplace/sdk/**`, `src/openhuman/tinyplace/manifest.rs`, `app/src/lib/agentworld/invokeApiClient.ts`, buy/bid/offer flows.
-- **Run commands from repo root** unless noted. The worktree root is `.claude/worktrees/fix-4920`.
-
----
-
-### Task 1: Seller "sell on tiny.place" note in the Trading tab
-
-**Files:**
-- Modify: `app/src/agentworld/pages/IdentitiesSection.tsx` (imports ~16-37; header docstring ~1-16; `TradingTab` return, insert before line 996 `</div>` that closes the outer `space-y-4`)
-- Test: `app/src/agentworld/pages/IdentitiesSection.test.tsx` (add a `describe` block; add an `openUrl` mock near the top mocks)
-
-**Interfaces:**
-- Consumes: `openUrl(url: string): Promise<void>` from `../../utils/openUrl`; existing `Button` component from `../../components/ui/Button`.
-- Produces: a rendered note with testid `sell-on-web` containing a CTA button testid `sell-on-web-cta` that calls `openUrl('https://tiny.place/identities')`.
-
-- [ ] **Step 1: Add the `openUrl` mock to the existing test file**
-
-In `app/src/agentworld/pages/IdentitiesSection.test.tsx`, directly after the existing `vi.mock('../AgentWorldShell', …)` block (ends ~line 41), add:
-
-```ts
-// External-link opener — assert the seller CTA hands off to the OS browser
-// without actually invoking Tauri.
-vi.mock('../../utils/openUrl', () => ({ openUrl: vi.fn() }));
-```
-
-And add its import next to the other imports at the top of the file (after the `IdentitiesSection` import line):
-
-```ts
-import { openUrl } from '../../utils/openUrl';
-```
-
-- [ ] **Step 2: Write the failing test**
-
-Append this `describe` block to `app/src/agentworld/pages/IdentitiesSection.test.tsx` (after the last Trading-tab describe block; reuses the file's existing `gotoTab` helper, `render`, `screen`, `userEvent`):
-
-```ts
-describe('Trading tab — seller web-only note', () => {
- test('renders the seller pointer note on the Trading tab', async () => {
- render(<IdentitiesSection />);
- await gotoTab('Trading');
- const note = await screen.findByTestId('sell-on-web');
- expect(note).toHaveTextContent(/selling a handle or responding to offers/i);
- });
-
- test('CTA opens the tiny.place identities page via openUrl', async () => {
- render(<IdentitiesSection />);
- await gotoTab('Trading');
- await userEvent.click(await screen.findByTestId('sell-on-web-cta'));
- expect(vi.mocked(openUrl)).toHaveBeenCalledWith('https://tiny.place/identities');
- });
-});
-```
-
-- [ ] **Step 3: Run the test to verify it fails**
-
-Run: `pnpm --filter openhuman-app test -- IdentitiesSection --run -t "seller web-only"`
-Expected: FAIL — `Unable to find an element by: [data-testid="sell-on-web"]`.
-
-- [ ] **Step 4: Add the `openUrl` import + web-URL constant to the component**
-
-In `app/src/agentworld/pages/IdentitiesSection.tsx`, add the import. Import order groups deeper relative paths first, so place it directly **above** `import { apiClient } from '../AgentWorldShell';` (line 33):
-
-```ts
-import { openUrl } from '../../utils/openUrl';
-```
-
-Then, immediately after the import block (before the `// ── Types ──` comment at line 39), add the constant:
-
-```ts
-// Seller-side identity actions (list a handle for sale, accept/reject an offer)
-// are web-only — the tiny.place backend exposes no seller routes and the
-// vendored SDK is a buyer-side compatibility wrapper (see #4920). We point
-// sellers at the web app instead. Hardcoded prod URL, matching the
-// `FUND_PAGE_URL` precedent in X402ConfirmDialog.tsx.
-const SELL_ON_WEB_URL = 'https://tiny.place/identities';
-```
-
-- [ ] **Step 5: Insert the note JSX in `TradingTab`**
-
-In the same file, insert the following block immediately **before** line 996 (the `</div>` that closes the outer `<div className="space-y-4">`), i.e. after the Recent Sales `</div>` at line 995:
-
-```tsx
- {/* Seller-side is web-only (#4920): no in-app list-for-sale / accept-offer
- path exists, so point sellers at the tiny.place web app. */}
- <div
- className="rounded-lg border border-line bg-surface-muted/40 p-3"
- data-testid="sell-on-web">
- <p className="text-xs text-content-muted">
- Selling a handle or responding to offers happens on tiny.place.
- </p>
- <Button
- variant="secondary"
- size="xs"
- className="mt-2"
- analyticsId="identities.sellOnWeb"
- onClick={() => void openUrl(SELL_ON_WEB_URL)}
- data-testid="sell-on-web-cta">
- Open tiny.place →
- </Button>
- </div>
-```
-
-- [ ] **Step 6: Update the header docstring to record the web-only scope**
-
-In the header docstring, extend the `Write flows are live x402:` list (ends with the "Money only moves…" sentence, ~line 12-14). Add a paragraph immediately before the closing `*/` (line 15):
-
-```text
- *
- * Seller-side actions (list a handle for sale, accept / reject an offer/bid)
- * are intentionally NOT in-app — they are web-only on tiny.place. The backend
- * exposes no seller routes and the vendored SDK is a buyer-side compatibility
- * wrapper, so the Trading tab links sellers to the web app instead (#4920).
-```
-
-- [ ] **Step 7: Run the tests to verify they pass**
-
-Run: `pnpm --filter openhuman-app test -- IdentitiesSection --run`
-Expected: PASS — the new `seller web-only` tests pass and the pre-existing IdentitiesSection tests still pass.
-
-**E2E scope (approved exception):** no desktop WDIO E2E is added for this change. The affordance is a static info note whose CTA hands off to the OS browser via `openUrl` — there is no cross-process behavior an E2E could assert beyond the unit tests above. This is a documented exception to the standard unit-and-E2E expectation; the exception is also recorded in the design spec's Testing section and in a comment on the test's `describe` block.
-
-- [ ] **Step 8: Typecheck, lint, and format**
-
-Run: `pnpm typecheck && pnpm --filter openhuman-app lint -- --fix app/src/agentworld/pages/IdentitiesSection.tsx app/src/agentworld/pages/IdentitiesSection.test.tsx && pnpm --filter openhuman-app exec prettier --write app/src/agentworld/pages/IdentitiesSection.tsx app/src/agentworld/pages/IdentitiesSection.test.tsx`
-Expected: no type errors, no lint errors, files formatted (import order may be auto-fixed).
-
-- [ ] **Step 9: Commit**
-
-```bash
-git add app/src/agentworld/pages/IdentitiesSection.tsx app/src/agentworld/pages/IdentitiesSection.test.tsx
-git commit -m "feat(tinyplace): point sellers to tiny.place web from Trading tab (#4920)"
-```
-
----
-
-### Task 2: Record web-only scope in the tinyplace core domain doc
-
-**Files:**
-- Modify: `src/openhuman/tinyplace/mod.rs` (module doc comment, after the `## Seed derivation` block ending line 26)
-
-Docs-only; no test (Rust doc comment). Folded into a single commit.
-
-- [ ] **Step 1: Add a scoping note to the module doc**
-
-In `src/openhuman/tinyplace/mod.rs`, insert this doc-comment section immediately after line 26 (`//! The seed is never logged…`) and before the blank line preceding `pub(crate) mod agent;`:
-
-```rust
-//!
-//! ## Marketplace scope (buyer-side only)
-//!
-//! The identity marketplace handlers here are **buyer-side only**: buy a
-//! listing, bid, and make an offer. Seller-side actions — listing a handle for
-//! sale and accepting / rejecting offers — are **web-only on tiny.place** (the
-//! backend exposes no seller routes). The desktop Trading tab links sellers to
-//! the web app instead. See #4920.
-```
-
-- [ ] **Step 2: Verify it compiles**
-
-Run: `GGML_NATIVE=OFF cargo check --manifest-path Cargo.toml`
-Expected: compiles (doc comment only — no code change). Warnings unrelated to this change are fine.
-
-- [ ] **Step 3: Format**
-
-Run: `cargo fmt --manifest-path Cargo.toml`
-Expected: no diff on the doc-comment lines (doc comments are not reflowed).
-
-- [ ] **Step 4: Commit**
-
-```bash
-git add src/openhuman/tinyplace/mod.rs
-git commit -m "docs(tinyplace): note identity marketplace is buyer-side only, selling is web-only (#4920)"
-```
-
----
-
-### Task 3: GitHub bookkeeping (outward-facing — CONFIRM before running)
-
-**Not code.** Do NOT run these until the user explicitly confirms editing the epic and commenting on the issue (both are outward-facing). Until then, capture them in the PR body.
-
-- [ ] **Step 1: Comment the resolution on #4920**
-
-```bash
-gh issue comment 4920 --repo tinyhumansai/openhuman --body "Resolved as **web-only by design**: the tiny.place backend exposes no seller routes and the vendored SDK is a buyer-side compatibility wrapper, so listing a handle / accepting-rejecting offers stays on the tiny.place web app. The desktop Trading tab now points sellers there instead of dead-ending. Scope recorded in \`IdentitiesSection.tsx\` and \`src/openhuman/tinyplace/mod.rs\`. See PR <PR_URL>."
-```
-
-- [ ] **Step 2: Mark #4776 §9 seller items N/A**
-
-Edit the #4776 body: change the "Sell / list a handle for sale" and "Accept / reject offer" table rows' Status to `N/A (web-only — #4920)`, and change `- [ ] Sell / list flow works` to `- [x] Sell / list flow works — N/A, web-only (#4920)`. (Manual body edit via `gh issue edit 4776 --repo tinyhumansai/openhuman --body-file -` after fetching and patching the current body, to avoid clobbering other sections.)
-
----
-
-## Self-Review
-
-- **Spec coverage:** UI affordance → Task 1 (steps 4-5). Hardcoded-English constraint → Global Constraints + Task 1 (no `useT`). Docstring scoping → Task 1 step 6 + Task 2. Test → Task 1 steps 1-3, 7. GitHub bookkeeping → Task 3. Out-of-scope items → Global Constraints. All spec sections covered.
-- **Placeholder scan:** `<PR_URL>` / `<PR_URL>` in Task 3 are intentional fill-at-runtime values for outward-facing text, not code placeholders. No code step contains TBD/TODO.
-- **Type consistency:** testids `sell-on-web` / `sell-on-web-cta` and constant `SELL_ON_WEB_URL` used identically in test (Task 1 steps 2) and component (Task 1 steps 4-5). `openUrl` signature matches `app/src/utils/openUrl.ts`.
diff --git a/docs/superpowers/plans/2026-07-30-tinyplace-feed-post-media-web-only.md b/docs/superpowers/plans/2026-07-30-tinyplace-feed-post-media-web-only.md
deleted file mode 100644
index 3e8d4a29a2..0000000000
--- a/docs/superpowers/plans/2026-07-30-tinyplace-feed-post-media-web-only.md
+++ /dev/null
@@ -1,46 +0,0 @@
-# Feed Post Media Web-Only Implementation Plan (#4924)
-
-**Goal:** Replace the text-only feed composer's missing-media gap with a note
-pointing users to tiny.place, and record that post media is web-only by design.
-Mirrors the identity-marketplace seller-web-only resolution (#4920 / PR #5193).
-
-**Architecture:** Additive UI only. A persistent note at the bottom of
-`FeedComposer` opens `https://tiny.place` via the existing `openUrl()` helper. No
-SDK, core, `manifest.rs`, or submodule changes — the tiny.place backend serves no
-post-media field. Scope recorded in two doc comments.
-
-**Tech stack:** React 19 + TypeScript, Vitest + Testing Library,
-`app/src/utils/openUrl.ts`, Rust module doc comment.
-
-## Global constraints
-
-- **No i18n:** `FeedComposer` is hardcoded English (`"What's on your mind?"`,
- `"Post"`, `"Posting…"`). New strings match — no `useT()`, no locale-file edits.
-- **Web URL is a hardcoded prod constant:** `https://tiny.place` (home = feed).
- Mirrors `SELL_ON_WEB_URL` / `FUND_PAGE_URL`.
-- **External links go through `openUrl`** — never a raw `window.open`.
-- **Out of scope (do not touch):** `vendor/tinyplace/**` (incl. the submodule
- pointer), `manifest.rs`, `invokeApiClient.ts`, the compose/like/comment flows.
-
-## Tasks
-
-- [x] **Task 1 — Composer note + CTA.** `FeedSection.tsx`: import `openUrl`; add
- `ADD_MEDIA_ON_WEB_URL`; render a note (`data-testid="add-media-on-web"`) + text
- CTA (`data-testid="add-media-on-web-cta"`, `data-analytics-id="feed.addMediaOnWeb"`)
- at the bottom of `FeedComposer` that `void openUrl(ADD_MEDIA_ON_WEB_URL)`. Header
- docstring gains a "post media is web-only" note.
-- [x] **Task 2 — Rust scope note.** `src/openhuman/tinyplace/mod.rs`: add a
- "Feed scope (post media is web-only)" doc-comment section after the marketplace
- one. Docs-only; `cargo fmt --check` verifies.
-- [x] **Task 3 — Tests.** `FeedSection.test.tsx`: mock `openUrl`; assert the note
- renders and the CTA calls `openUrl('https://tiny.place')`.
-- [x] **Task 4 — GitHub bookkeeping (outward-facing).** Done: commented the
- web-only resolution on #4924, and marked the #4776 §2 "Images / media in posts"
- item N/A (web-only) via an epic status comment (the epic body is owner-gated).
-
-## Verification
-
-- `pnpm --filter openhuman-app test` — FeedSection green (incl. 2 new cases).
-- `tsc --noEmit` clean; `eslint` no new errors; `prettier --check` clean.
-- `cargo fmt --check` clean (doc-comment-only Rust change).
-- `git diff vendor/tinyplace` empty — submodule pointer untouched (mergeable).
diff --git a/docs/superpowers/specs/2026-07-09-cursor-windsurf-harness-design.md b/docs/superpowers/specs/2026-07-09-cursor-windsurf-harness-design.md
deleted file mode 100644
index f6616b29f9..0000000000
--- a/docs/superpowers/specs/2026-07-09-cursor-windsurf-harness-design.md
+++ /dev/null
@@ -1,140 +0,0 @@
-# Design: Recognize Cursor & Windsurf as first-class harnesses
-
-> Status: **approved** — 2026-07-09. Scope locked to OpenHuman-side recognition only.
-
-## Goal
-
-Teach OpenHuman's orchestration engine to recognize `cursor` and `windsurf` as
-harness providers, so their sessions render with a proper roster group, a brand
-glyph, and a typed `harnessType` instead of falling into the generic **"Other"**
-catch-all group.
-
-This is **recognition-only**. It does not add a session-origination adapter (the
-`sdk/plugin-tinyplace/adapters/*` piece that would make a real Cursor/Windsurf
-CLI emit these sessions). See [Out of scope](#out-of-scope).
-
-## Background: how harness recognition works today
-
-A coding agent sends a `SessionEnvelopeV1` over the tiny.place Signal relay with a
-`harness.provider` field (e.g. `"codex"`). OpenHuman's orchestration ingest
-(`src/openhuman/hosted/orchestration/ingest.rs`) decrypts it and copies that field
-**verbatim** into the session's `source` — there is no provider allowlist at
-ingest (`ingest.rs:187`, `ingest.rs:213`).
-
-The single gate that decides whether a `source` is a *known* harness is
-`harness_type_for()` in `src/openhuman/hosted/orchestration/schemas.rs:276`:
-
-```rust
-fn harness_type_for(source: &str) -> Option<String> {
- matches!(source, "claude" | "codex" | "gemini").then(|| source.to_string())
-}
-```
-
-It is called when building the session summary (`schemas.rs:339`) to populate the
-`harnessType` field sent to the UI. An unrecognized `source` yields `None`, and
-the roster drops that session into the "Other" group with no glyph.
-
-On the frontend, `harnessType` keys three surfaces:
-
-- `app/src/lib/orchestration/orchestrationClient.ts:24` — the `HarnessType` union.
-- `app/src/components/intelligence/HarnessGlyph.tsx:20` — a `Record<GlyphKind, …>`
- mapping each harness to a `{ label, tone }` brand glyph.
-- `app/src/components/intelligence/TinyPlaceRoster.tsx:23` — `HARNESS_GROUPS`, the
- ordered list of roster group headers.
-
-Because `GLYPH` is a `Record<GlyphKind, …>`, widening `HarnessType` is
-**compile-forced**: the type-checker fails until every new variant has a glyph.
-
-## Data flow (unchanged by this change)
-
-```
-Cursor/Windsurf CLI → harness.provider = "cursor" | "windsurf"
- → relay → ingest.rs (source = provider, verbatim)
- → harness_type_for(source) ← THE GATE (widened here)
- → session summary { harnessType }
- → HarnessGlyph + TinyPlaceRoster group ← follows via the type
-```
-
-No change to ingest, pairing, attention, or the relay. Only the recognition gate
-and the two UI lookup tables it feeds.
-
-## Changes
-
-### Rust core — `src/openhuman/hosted/orchestration/`
-
-1. **`schemas.rs:277`** — widen the match:
- ```rust
- matches!(source, "claude" | "codex" | "gemini" | "cursor" | "windsurf")
- ```
- Refresh the `(claude/codex/gemini)` doc comments at `schemas.rs:192` and
- `schemas.rs:273` to include the new providers.
-
-2. **`schemas.rs:1113` (test)** — extend the `harness_type_for` round-trip test:
- ```rust
- assert_eq!(harness_type_for("cursor").as_deref(), Some("cursor"));
- assert_eq!(harness_type_for("windsurf").as_deref(), Some("windsurf"));
- ```
- The existing `None` cases (`master`/`user_created`/`orchestration`) stay.
-
-### Frontend — `app/src/`
-
-3. **`lib/orchestration/orchestrationClient.ts:24`**:
- ```ts
- export type HarnessType = 'claude' | 'codex' | 'gemini' | 'cursor' | 'windsurf';
- ```
-
-4. **`components/intelligence/HarnessGlyph.tsx:20`** — add two `GLYPH` entries:
- ```ts
- cursor: { label: 'Cu', tone: 'bg-slate-800 text-white' },
- windsurf: { label: 'Ws', tone: 'bg-teal-500 text-white' },
- ```
- Labels `Cu` / `Ws` parallel Codex's two-letter `Cx` and avoid colliding with
- Claude's `C` / Gemini's `G`. Tones: Cursor slate/near-black, Windsurf teal.
- **Exact tone classes to be confirmed against the palette classes actually
- available in the app** (the existing glyphs mix literal `bg-[#c96442]` and
- named `bg-ocean-500`/`bg-sage-500`); the values above are the intent, final
- classes chosen from what the Tailwind config exposes.
-
-5. **`components/intelligence/TinyPlaceRoster.tsx:23`** — append to `HARNESS_GROUPS`
- (after Gemini, before the implicit "Other"):
- ```ts
- { key: 'cursor', label: 'Cursor' },
- { key: 'windsurf', label: 'Windsurf' },
- ```
-
-### Tests
-
-6. **`components/intelligence/HarnessGlyph.test.tsx`** — add label cases
- `['cursor', 'Cu']`, `['windsurf', 'Ws']` to the existing parametrized table.
-
-7. **`components/intelligence/TinyPlaceRoster.test.tsx`** — add a session with
- `harnessType: 'cursor'` (and one `'windsurf'`), assert it groups under the
- `Cursor` / `Windsurf` header and **not** under "Other".
-
-## Testing / verification
-
-- **Rust:** `cargo test` for the orchestration schemas module (the widened
- `harness_type_for` test).
-- **Frontend:** the vitest suites for `HarnessGlyph`, `TinyPlaceRoster`, and
- `InstanceCard` (the last already exercises `harnessType`/`source`).
-- **Type-check:** widening `HarnessType` is the safety net — `tsc` fails if any
- exhaustive consumer (notably the `GLYPH` `Record`) is left incomplete.
-
-Regression posture: each new variant is asserted both in Rust (`harness_type_for`)
-and in the two UI tables' tests — failing before the change, passing after.
-
-## Out of scope
-
-- **Session origination.** A `sdk/plugin-tinyplace/adapters/cursor.mjs` /
- `windsurf.mjs` that wraps a real Cursor/Windsurf CLI and emits
- `harness.provider = "cursor" | "windsurf"` is **not** built here. Feasibility
- depends on those agents exposing a wrappable headless CLI, which is unverified.
- Until such an adapter exists, this recognition is correct but exercised only by
- tests, not live traffic. This is an intentional, separately-scoped follow-up.
-- No changes to ingest, pairing/consent, attention/unread, or the relay.
-
-## Risks
-
-- **Low.** The change is additive and type-checked end to end. The only judgment
- call is the glyph tone classes, which are cosmetic and confirmed against the
- available palette during implementation.
diff --git a/docs/superpowers/specs/2026-07-10-cursor-windsurf-adapter-spike.md b/docs/superpowers/specs/2026-07-10-cursor-windsurf-adapter-spike.md
deleted file mode 100644
index 5351c1a286..0000000000
--- a/docs/superpowers/specs/2026-07-10-cursor-windsurf-adapter-spike.md
+++ /dev/null
@@ -1,52 +0,0 @@
-# Spike: Cursor & Windsurf tiny.place adapters — feasibility
-
-> Status: **findings** — 2026-07-10. Time-boxed research spike (web, cited). Precedes any adapter code.
-> Companion to the recognition slice (`2026-07-09-cursor-windsurf-harness-design.md`), which is the prerequisite Layer 1.
-
-## Question
-
-Can **Cursor** and **Windsurf** each host the tiny.place `plugin-tinyplace` stdio MCP server *inside* their agent, be observed, and be driven headlessly for an auto-responder — i.e. can we build `adapters/cursor.mjs` and `adapters/windsurf.mjs` mirroring `adapters/codex.mjs`?
-
-## Headline
-
-**Both are _likely_ feasible as thin observe+respond adapters, contingent on the two empirical spike-tests (A and B) below.** The make-or-break capability — a headless agent CLI (the `codex exec` equivalent) — **exists for both** (Cursor `cursor-agent -p`, Devin `devin -p`). But the remaining unknowns must pass before this is a firm yes: what env actually reaches the MCP subprocess (test A) and whether an inbound DM can be surfaced into a live turn (test B). The inbound `server→live-turn` push limitation stands regardless of those tests.
-
-⚠️ **Windsurf has rebranded:** as of 2026-06-02 it is **Devin Desktop** (Cognition); **Cascade reached EOL 2026-07-01**, replaced by **Devin Local**. On-disk config paths (`~/.codeium/windsurf/mcp_config.json`) and a `windsurf` CLI carried forward, but the headless target is now the **`devin`** CLI. A "windsurf" adapter today actually targets Devin Desktop. Devin Desktop also natively speaks **ACP (Agent Client Protocol)** — a possible cleaner integration surface than a bespoke adapter.
-
-## Feasibility matrix (adapter-contract field → harness)
-
-| Contract field | Cursor | Windsurf / Devin Desktop |
-|---|---|---|
-| **MCP stdio hosting** | 🟢 `.cursor/mcp.json` (project) / `~/.cursor/mcp.json` (global); `mcpServers` {command,args,env}. **40-tool cap** (our ~20 fine). | 🟢 `~/.codeium/windsurf/mcp_config.json`; `mcpServers` {command,args,env}. Remote entries accept **`serverUrl`** (and newer builds also `url`) — moot for us since our adapter is stdio {command,args,env}. |
-| **Headless responder (CRITICAL)** | 🟢 `cursor-agent -p "<prompt>" --model <m> --force --approve-mcps --output-format json`. Model-pinnable. | 🟢 `devin -p "<prompt>" --model <m> --permission-mode bypass`. `--resume`/`--continue` for continuity. |
-| **Session-id env to MCP subprocess** | 🟡 None ambient/documented. `conversation_id` only in **hook** payload. Inject a sentinel via `mcp.json` `env`. | 🟡 None documented. Session id in **hook** payload. `DEVIN_PROJECT_DIR` set for hooks. |
-| **Workspace-dir** | 🟡 `${workspaceFolder}` interpolation into `mcp.json` `env`. | 🟡 `DEVIN_PROJECT_DIR` (hooks) / `${env:...}` injection. |
-| **Inbound push (server→live turn)** | 🔴 No async server push. Elicitation (mid-tool only) + `tools/list_changed`. Surface on next tool call or a fresh headless turn. | 🔴 Undocumented/unverified. Route inbound via **hook `additionalContext`** or an agent-polled tool. |
-| **Hooks (surfacing/observe)** | 🟢 Cursor 1.7+: `sessionStart`, `beforeSubmitPrompt`, `stop`, `pre/postToolUse`, `before/afterMCPExecution`. Payload has `conversation_id`, `workspace_roots`; env `CURSOR_PROJECT_DIR`. | 🟢 `SessionStart/End`, `UserPromptSubmit`, `Stop`, `Pre/PostToolUse`. stdin JSON; `hookSpecificOutput.additionalContext` injects live context. |
-| **Launch + MCP install** | 🟡 No per-launch MCP-config flag (open FR). Install = write/merge `mcp.json`. `cursor <dir>` / `cursor-agent --workspace`. | 🟡 No per-launch flag. Install = write `mcp_config.json`. `windsurf <dir>` opens workspace. |
-| **Detection ("am I inside X?")** | 🟡 No confirmed `CURSOR_*` in MCP child (only in hook env). Self-provision `TINYPLACE_HOST=cursor` sentinel in `mcp.json` `env`. | 🟡 No `CODEX_HOME` analogue for MCP. Self-provision sentinel. |
-
-## What this changes vs. the codex/claude adapters
-
-1. **`foregroundInject` (tmux) is dead for both** — they're GUI IDEs, not terminal panes. Inbound leans on hooks + headless turns, not tmux `send-keys`.
-2. **No async server→agent push** on either — the `inbound.push` channel (Claude's `claude/channel`) has no equivalent. Model inbound as: surface-on-next-tool-call, hook `additionalContext`, or spawn a headless `-p` turn.
-3. **Install model differs** — codex writes an *isolated home*; here `launch.prepare()` becomes *"merge our server into the well-known `mcp.json`/`mcp_config.json`"* (no per-invocation injection flag exists). Must be careful to merge, not clobber, the user's existing MCP config.
-4. **Session id** comes from the **hook payload**, not MCP env → correlating a hook's `conversation_id` to the live MCP process is the piece to prototype.
-
-## Two empirical spike-tests before writing code
-
-- **A. What env actually reaches the MCP subprocess?** Register a trivial MCP server in each IDE that dumps `process.env`; confirm whether any session/workspace var leaks (docs say no — verify).
-- **B. Inbound delivery path.** Confirm whether hook `additionalContext` (Devin) / a `stop`+`beforeSubmitPrompt` hook (Cursor) can reliably surface an inbound DM into the next turn, vs. relying on an agent-polled `inbox` tool.
-
-## Recommendation
-
-- **Both adapters are buildable today.** Proceed — but with a GUI-IDE-shaped adapter model (env-injection install, hook-based inbound, headless-`-p` responder), not a copy of codex's isolated-home/tmux model.
-- **Sequence Cursor first:** cleaner, well-documented (`cursor-agent`, hooks, 40-tool cap), no rebrand churn.
-- **Then Windsurf → target `devin`/Devin Local**, watch the churn, and evaluate the **ACP** route (Devin speaks ACP; may insulate from further rebrands and reuse ACP patterns).
-- **Naming decision (resolved → `windsurf`):** the recognition slice baked in `harness.provider = "windsurf"`; the product is now "Devin Desktop." We keep the harness key **`windsurf`** — it matches the on-disk brand that actually carried forward (`~/.codeium/windsurf/mcp_config.json`, the `windsurf` CLI shim) and keeps the recognition gate and adapter `provider` aligned with what's observable on disk. Revisit only if/when the config path itself rebrands to `devin`.
-- **Land the recognition slice (Layer 1) regardless** — it's the prerequisite; without it, a working adapter's sessions render as "Other."
-
-## Sources (selected)
-
-Cursor: `cursor.com/docs/mcp`, `cursor.com/docs/cli/headless`, `cursor.com/docs/cli/reference/parameters`, `cursor.com/docs/hooks`, `cursor.com/changelog/1-5`.
-Windsurf/Devin: `docs.devin.ai/desktop/cascade/mcp`, `docs.devin.ai/cli/reference/commands`, `docs.devin.ai/cli/extensibility/hooks/overview`, `devin.ai/blog/windsurf-is-now-devin-desktop/`, `docs.devin.ai/desktop/changelog`.
diff --git a/docs/superpowers/specs/2026-07-11-cursor-observer-findings.md b/docs/superpowers/specs/2026-07-11-cursor-observer-findings.md
deleted file mode 100644
index b7099cbbbc..0000000000
--- a/docs/superpowers/specs/2026-07-11-cursor-observer-findings.md
+++ /dev/null
@@ -1,104 +0,0 @@
-# Cursor observer prototype — empirical findings (spike-tests A & B)
-
-> Date: 2026-07-11
-> Companion to `2026-07-10-cursor-windsurf-adapter-spike.md`, which flagged two
-> empirical spike-tests (A: what env reaches the MCP subprocess; B: can an
-> inbound DM be surfaced into a live turn) as the gates before a firm feasibility
-> yes. This doc records what a throwaway prototype actually demonstrated against
-> **staging** (`https://staging-api.tiny.place`).
-
-## What was built (and then removed)
-
-A throwaway **Cursor hooks observer** — not the real adapter, just enough to
-prove the observe→stream half end-to-end:
-
-- `~/.cursor/hooks.json` wired `beforeSubmitPrompt` (user turn) and
- `afterAgentResponse` (assistant turn) to a small Node script.
-- The script normalized each turn into a tinyplace `SessionEnvelopeV1`
- (`harness.provider = "cursor"`, `scope.harness_session_id = conversation_id`)
- and sent it as a Signal-E2E DM to the running OpenHuman identity.
-- OpenHuman's orchestration ingest decrypted it, classified it as `cursor`
- (`harness_type_for`, the gate widened in the recognition slice), and rendered
- it under a **Runtime · cursor** session.
-
-All prototype artifacts (the hooks file, the observer scripts, the throwaway
-`cursorbridge`/`cursoragent` wallets, the `~/.tinyplace-cursorbridge` store) were
-removed after the demo. The shippable output is the recognition slice (PR #4775).
-
-> **Correction (2026-07-13).** A first attempt to "fix" a bundle 404 by minting
-> a slash-free tiny.place identity (PR #4779) was **closed as wrong** on review.
-> The `/keys/:cryptoId/*` relay routes are keyed on the **base58** cryptoId (no
-> `/`) and the backend already resolves both encodings, so the 404 only occurs
-> when a *client* puts the base64 `identityKey` in the URL path. Every current
-> send path already fetches by base58 (TS SDK ≥2.0.2 `deriveCryptoId`; OpenHuman
-> `resolve_recipient_to_agent_id` → `crypto_id`). The observer's 404 was a stale
-> `@tinyhumansai/[email protected]` build in the prototype, not a product defect —
-> and remapping the identity would have broken the payment/wallet coupling
-> (`signer.agent_id()` is the x402 `from` / registry `crypto_id`). Identity must
-> stay `== funded Solana wallet`; the real follow-up is bumping the plugin's SDK
-> dependency to ≥2.0.2 (see `tiny.place#213`).
-
-## Result: observe → render works ✅
-
-A **real, live Cursor chat** (a Cursor agent window open on `~/work/k8s`,
-`conversation_id = 4c17e405…`) streamed both turns into OpenHuman and rendered as
-a Cursor runtime session — with no polling, driven purely by Cursor's own hooks
-firing on each turn. This confirms the observe path the adapter needs is real:
-hooks give us `{prompt}` / `{text}` plus `conversation_id` / `workspace_roots`,
-which is enough to build the envelope the ingest already understands.
-
-### Spike-test A (env to MCP subprocess) — partially answered
-
-The observer used **hooks**, not the MCP subprocess, so it did not need the
-sanitized-env workaround. But the same run confirmed the constraint the spike
-called out: Cursor hands MCP/hook subprocesses a **sanitized environment** (only
-`HOME`/`PATH`/`SHELL`/…). The observer therefore had to inject
-`TINYPLACE_CURSOR_HOME` / `OPENHUMAN_ADDR` / `TINYPLACE_API_URL` explicitly via a
-wrapper `.sh`. **Implication for the real adapter:** its `launch.prepare()` must
-bake every env var the MCP server needs into the written `mcp.json` `env` block —
-it cannot rely on inheriting the parent shell's environment. (This matches what
-the committed `adapters/cursor.mjs` already does with its `env` sentinel.)
-
-## Gaps found (both are the *respond/inbound* half, not observe)
-
-### Gap 1 — reply address is base58↔base64 mismatched
-
-When OpenHuman tries to **reply** into the runtime session, the send fails with
-`No agent found for <id>`. This is the same base58/base64 encoding family as the
-correction above: the peer must be addressed and resolved by its **base58**
-`crypto_id`, not the **base64** `identityKey`. No new crypto is needed — the fix
-is base58 discipline on the reply/resolve boundary, and it is likely already
-closed once the prototype/plugin is on SDK ≥2.0.2 (whose send path fetches by
-`deriveCryptoId`). **Next step: re-test the reply path against a current-SDK
-plugin build before assuming any OpenHuman-side change is required.**
-
-### Gap 2 — no Cursor GUI-chat injection API
-
-Even with Gap 1 fixed, an orchestrator reply can be *delivered* to the runtime,
-but there is **no supported way to inject text back into Cursor's live GUI chat
-window**. The headless `cursor-agent -p` path can *answer* a prompt (that's the
-adapter's `responder`), but it is a separate, headless turn — it does not appear
-in the human's open Cursor chat. Surfacing an inbound DM into the *live GUI* turn
-(spike-test B) remains **unsolved** and is a research item, not a quick fix. The
-observe→render→headless-respond loop works; observe→render→*GUI-inject* does not.
-
-### First-contact ratchet desync (SDK-level, recoverable)
-
-On the very first DM between two fresh identities, the Double Ratchet can desync
-("No session for <peer>" → the recipient drops the decrypt). Recovery is
-`reset_session(<peer>, rehandshake: true)` on the emitter followed by a resend;
-after that the session is stable. This is a known SDK first-contact edge, not
-specific to the harness work, but adapter onboarding flows should expect it and
-either pre-warm the session or retry once on the first send.
-
-## Net feasibility read
-
-- **Observe → normalize → render as a Cursor runtime: proven live.** ✅
-- **Headless respond (`cursor-agent -p`): proven separately** in the adapter
- live E2E (whoami, session label `cursor:1`, staging-verified).
-- **Orchestrator → live GUI reply: blocked** on Gap 1 (encoding, fixable) and
- Gap 2 (no injection API, open research).
-
-So the recognition slice + the adapter's observe and headless-respond surfaces
-are sound; the remaining work is the reply-address encoding fix and the (harder)
-question of GUI injection.
diff --git a/docs/superpowers/specs/2026-07-24-identity-marketplace-seller-web-only-design.md b/docs/superpowers/specs/2026-07-24-identity-marketplace-seller-web-only-design.md
deleted file mode 100644
index ad566ab32a..0000000000
--- a/docs/superpowers/specs/2026-07-24-identity-marketplace-seller-web-only-design.md
+++ /dev/null
@@ -1,104 +0,0 @@
-# Design: Identity marketplace seller-side is web-only (#4920)
-
-**Date:** 2026-07-24
-**Issue:** [#4920](https://github.com/tinyhumansai/openhuman/issues/4920) — *[Tiny Place] Identity marketplace is buyer-only: no list-for-sale or accept/reject-offer path*
-**Epic:** #4776 §9 (Trading / Identities marketplace)
-
-## Problem
-
-The desktop app's identity marketplace (Agent World → Identities → Trading tab) supports
-only **buyer-side** actions: browse listings, buy, bid, and make an offer. There is no path
-to **sell** (list one's own `@handle`) and no path to **accept / reject** an incoming offer
-or bid. A user who wants to sell opens the Trading tab and finds a dead end.
-
-## Decision
-
-**Seller-side actions are web-only by design.** The tiny.place backend does not expose
-seller routes (create-listing, accept/reject-offer), and the vendored Rust SDK
-(`vendor/tinyplace/sdk/rust/src/api/marketplace.rs`) is explicitly a *"compatibility wrapper
-for marketplace endpoints used by OpenHuman"* — buyer-side only. Listing a handle and
-responding to offers happens on the tiny.place web app.
-
-This resolves #4920 not by building the full seller stack (SDK → core handler →
-`invokeApiClient` → UI), but by:
-
-1. Removing the in-app dead-end with a clear pointer to the web flow.
-2. Recording the web-only scoping decision in-repo.
-3. Marking the corresponding #4776 §9 items N/A.
-
-## Scope
-
-### In scope
-
-1. **UI affordance** — `app/src/agentworld/pages/IdentitiesSection.tsx`, Trading tab.
- Add an informational note beneath the listings / recent-sales area:
-
- > ℹ️ Selling a handle or responding to offers happens on tiny.place. **[Open tiny.place →]**
-
- - The CTA opens `https://tiny.place/identities` via `openUrl()`
- (`app/src/utils/openUrl.ts` → `tauri-plugin-opener`), mirroring the existing
- `https://tiny.place/fund` precedent in `X402ConfirmDialog.tsx`.
- - The web URL is a hardcoded production constant, matching the `/fund` precedent
- (the tiny.place *web* frontend has no per-env base in `config.ts`; only the API
- host is env-derived).
- - Strings are **hardcoded English**, matching this file's existing convention. Unlike
- sibling agentworld pages, `IdentitiesSection.tsx` is entirely un-i18n'd (its buy/commit
- banners use literal strings, e.g. `"Commitment submitted."`, `"Purchased {name}"`), and
- this passes CI (`i18n:check` / `i18n:english:check` validate locale-file parity, not
- hardcoded JSX). Introducing a single `useT()` string here would be inconsistent; a
- full-file i18n conversion is out of scope. No locale-file changes.
-
-2. **Scoping documentation**
- - Extend the `IdentitiesSection.tsx` header docstring to state that seller-side
- (list-for-sale, accept/reject offer) is **web-only by design**, with the reason.
- - Add a one-line pointer in the tinyplace domain module doc
- (`src/openhuman/tinyplace/mod.rs`).
-
-3. **Test** — co-located Vitest test asserting the Trading tab renders the seller note and
- the CTA invokes `openUrl` with `https://tiny.place/identities` (mock `openUrl`). Covers
- the new diff lines for the ≥80% changed-line coverage gate.
-
-4. **GitHub bookkeeping** (not code; done via `gh`, noted in the PR body)
- - #4776 §9: mark "Sell / list a handle for sale", "Accept / reject offer", and the
- "Sell / list flow works" checkbox as N/A, referencing #4920's resolution.
- - Comment the web-only resolution on #4920.
-
-### Out of scope (YAGNI)
-
-- Vendored SDK seller methods (`create_listing` / `accept_offer` / `reject_offer`).
-- Core `handle_tinyplace_marketplace_*` seller handlers.
-- `invokeApiClient.ts` seller methods.
-- Full i18n conversion of `IdentitiesSection.tsx` (the new strings are hardcoded English,
- matching the file).
-
-## Components & data flow
-
-```text
-Trading tab (IdentitiesSection.tsx)
- └─ SellOnWebNote ──click──▶ openUrl('https://tiny.place/identities')
- └─ tauri-plugin-opener → OS default browser
-```
-
-No core RPC, no network from the app itself — the CTA hands off to the OS browser.
-
-## Error handling
-
-`openUrl()` already handles the CEF IPC-bridge gap by falling back to `window.open` for
-http(s) URLs and logs a low-PII telemetry breadcrumb. No new error surface is introduced.
-
-## Testing
-
-- **Unit (Vitest):** render `TradingTab`, assert the seller note text is present, that the
- CTA carries the `identities.sellOnWeb` analytics id, and that clicking it calls the mocked
- `openUrl` with the expected URL.
-- No new Rust behavior → no Rust test changes.
-- **E2E: intentionally skipped.** The affordance is a static info note whose CTA hands off to
- the OS browser via `openUrl` — there is no cross-process behavior a desktop WDIO E2E could
- assert beyond the unit tests. Documented as an approved exception to the standard
- unit-and-E2E expectation for this change.
-
-## Rollback / risk
-
-Low risk: additive UI note + docstring. No behavior change to existing buy/bid/offer flows,
-and no i18n/locale files touched (strings are hardcoded English, matching the file). Revert
-is a clean removal of the note block plus its docstring note and the two unit tests.
diff --git a/docs/superpowers/specs/2026-07-30-directory-search-pagination-design.md b/docs/superpowers/specs/2026-07-30-directory-search-pagination-design.md
deleted file mode 100644
index 3bbcd5d396..0000000000
--- a/docs/superpowers/specs/2026-07-30-directory-search-pagination-design.md
+++ /dev/null
@@ -1,92 +0,0 @@
-# Directory search + pagination (Tiny Place §6)
-
-Sub-slice of the Tiny Place audit epic **#4776 §6 (Directory)**. The audit found
-`DirectorySection` "largely non-interactive": card-click→profile-modal and
-follow already landed (#4927), but **search, type filter, and pagination**
-remain unwired even though the backend + vendored SDK fully support them. This
-spec covers **search + pagination** (type filter is deliberately out of scope).
-
-## Problem
-
-`DirectorySection.tsx` fetches the whole directory once via
-`apiClient.graphql.agents()` with **no arguments**:
-
-- No way to search by handle/name, though `graphql.agents({ q })` maps `q` →
- the GraphQL `query` variable server-side (`vendor/tinyplace/.../graphql.rs`).
-- No pagination: the SDK query threads `limit`/`offset`, but the UI sends
- neither, so large directories render a single unbounded (backend-capped) page
- with no "Load more".
-
-Both gaps are **frontend-only** — the core handler
-(`handle_tinyplace_graphql_agents`) already deserializes and forwards
-`AgentQueryParams`.
-
-## Solution
-
-Rework `DirectorySection` to own a search query + offset-paginated list,
-mirroring the existing **Feed/Ledger "Load more"** pattern already in this
-directory (`FeedSection.tsx` `loadMore`, `LedgerSection.tsx` `loadMore`).
-
-### Search (server-side, debounced)
-
-- A labeled search `<input>` at the top of the section.
-- Debounce ~300ms; the debounced query drives
- `graphql.agents({ q, limit: PAGE_SIZE, offset: 0 })`.
-- Empty query = browse-all (today's behavior).
-- A query change **resets** pagination to `offset: 0` and replaces the list
- (does not append).
-
-### Pagination (offset "Load more")
-
-- `DIRECTORY_PAGE_SIZE = 24` (divides 1/2/3-column grids evenly).
-- Initial/query-change fetch: `offset: 0`. "Load more" fetches
- `offset: nextOffset` and **appends**.
-- Dedupe appended agents by `agentId` (a mutation-shifted offset must not
- produce duplicate React keys / double rows — the exact guard Feed/Ledger use).
-- End-of-list = "page shorter than `PAGE_SIZE`" (robust; no reliance on the
- optional `count` field).
-
-### State model
-
-Extend the `useDirectoryAgents` hook to accept the debounced query and own:
-accumulated `agents`, `nextOffset`, `hasMore`, `loadingMore`, `loadMoreError`.
-Keep the existing `loading` / `payment_required` / `error` / `ok` states.
-Refetch-from-zero when the query changes; append on load-more. Reentry into
-`loadMore` is guarded by disabling the button while `loadingMore`.
-
-### Types / i18n / a11y
-
-- Add `offset?: number` to the frontend `AgentQueryParams` interface
- (`invokeApiClient.ts`) — it currently declares `cursor` only; the SDK uses
- `offset`.
-- New UI text goes through `useT()` (the section is currently hardcoded; new
- strings comply with the i18n rule, existing ones are left untouched to avoid
- scope creep). New keys added to `en.ts` **and all 14 locale files**, no em
- dashes:
- `agentWorld.directory.searchLabel`, `.searchPlaceholder`, `.noResults`,
- `.loadMore`, `.loadingMore`, `.loadMoreError`.
-- Search input is labeled; the existing card keyboard-nav guard (#4927) is
- preserved.
-
-## Out of scope
-
-- Type filter (agent / human / org).
-- "Send DM" from a directory card.
-- Converting the section's pre-existing hardcoded strings to i18n.
-
-## Tests (Vitest, TDD)
-
-Extend `DirectorySection.test.tsx`:
-
-1. Typing a query calls `graphql.agents` with `{ q }` (after debounce) and
- replaces the list; offset resets to 0.
-2. "Load more" fetches the next offset and **appends**, deduping by `agentId`.
-3. A page shorter than `PAGE_SIZE` hides "Load more".
-4. Empty-results state renders for a no-match query.
-5. A failed "Load more" surfaces `loadMoreError` and keeps existing rows.
-
-## Debug logging
-
-Namespaced `debug('agentworld:directory')` already present — add entry/exit +
-field logs for: first-page fetch (`q`, limit), load-more (`offset`, received,
-fresh, hasMore), and load-more failure.
diff --git a/docs/superpowers/specs/2026-07-30-ledger-ux-filters-design.md b/docs/superpowers/specs/2026-07-30-ledger-ux-filters-design.md
deleted file mode 100644
index f738ead75f..0000000000
--- a/docs/superpowers/specs/2026-07-30-ledger-ux-filters-design.md
+++ /dev/null
@@ -1,80 +0,0 @@
-# Ledger UX — asset filter, direction filter, copy tx-id (Tiny Place §4)
-
-Sub-slice of the Tiny Place audit epic **#4776 §4 (Ledger)**. Pagination already
-landed; this adds the remaining §4 UX gaps: **asset filter**, **in/out
-direction filter**, and **copy transaction ID**. Frontend only.
-
-## Problem
-
-`LedgerSection` renders the public transaction ledger with pagination, but:
-
-- No way to filter by asset (USDC / SOL / …).
-- No way to see only incoming vs outgoing transactions.
-- The Tx ID is plain text with no copy affordance (only a "View on chain"
- explorer link).
-
-## Solution
-
-All three are client-side, over the already-loaded `transactions`. Server-side
-filtering is deliberately **not** used:
-
-- `tx.asset` may be a **symbol or a mint address** (`assets.resolveAssetSymbol`
- resolves both), so a server-side `asset` filter value can't reliably match the
- stored form.
-- Direction is **viewer-relative** (from/to vs the wallet address) — not a
- server concept for a public ledger.
-
-### Copy tx-id
-
-A copy button beside the Tx ID in the expanded detail. `navigator.clipboard
-.writeText(tx.txId)`, transient "Copied" state (~1.5s), i18n label. Degrades
-silently if the clipboard API is unavailable.
-
-### Asset filter (client-side)
-
-A `<select>` of `All` + the distinct `resolveAssetSymbol(tx.asset)` values found
-in the loaded rows. Reusing the display-side resolver guarantees the option
-labels match what rows show (no symbol/mint mismatch). Selecting one narrows the
-rendered list.
-
-### Direction filter (client-side, wallet-gated)
-
-Segmented `All / In / Out`. `myAddr` comes from `fetchWalletStatus()` (the
-Solana account address). A tx is **In** when `to === myAddr`, **Out** when
-`from === myAddr`. The control is **hidden** when no wallet address is available
-(the public ledger has no viewer-relative direction without one).
-
-### Interaction
-
-Both filters apply to the loaded `transactions` before render (memoized).
-"Load more" continues to fetch raw pages; filters re-apply to the larger set.
-When filters hide every loaded row, a distinct "no transactions match these
-filters" message renders (vs. the empty-ledger copy). This is an explicit,
-honest tradeoff: filters act on loaded rows, not the entire server ledger.
-
-## Out of scope
-
-- Wallet-balance-on-ledger, real-time updates, CSV export (other §4 items).
-- Server-side filtering.
-
-## Tests (Vitest, TDD)
-
-Extend `LedgerSection.test.tsx`:
-
-1. Copy button writes `tx.txId` to the clipboard and shows "Copied".
-2. Asset filter narrows the list to the chosen asset.
-3. Direction filter (with a mocked wallet) shows only incoming / outgoing rows.
-4. Direction control is absent when `fetchWalletStatus` returns no address.
-5. Filtering to zero rows renders the "no match" message, not the empty-ledger
- copy, and keeps the filter controls visible.
-
-## i18n
-
-New keys in `en.ts` + all 13 locales (no em dashes): `filterAsset`,
-`filterAllAssets`, `direction`, `directionAll`, `directionIn`, `directionOut`,
-`copyTxId`, `copied`, `noMatch`, `noMatchHint`.
-
-## Debug logging
-
-Reuse `debug('agentworld:ledger')`; log filter changes (asset symbol chosen,
-direction) and copy outcomes — no PII (addresses already abbreviated in logs).
diff --git a/docs/superpowers/specs/2026-07-30-tinyplace-feed-post-media-web-only-design.md b/docs/superpowers/specs/2026-07-30-tinyplace-feed-post-media-web-only-design.md
deleted file mode 100644
index fc120d78c0..0000000000
--- a/docs/superpowers/specs/2026-07-30-tinyplace-feed-post-media-web-only-design.md
+++ /dev/null
@@ -1,63 +0,0 @@
-# Design: Feed post media is web-only (#4924)
-
-Part of #4776 (Tiny Place audit) · §2 Feed · sibling of the #4920 web-only resolution (PR #5193).
-
-## Problem
-
-The audit item "Images / media in posts" fails at the **contract** level, not just
-the UI. Posts are text-only end-to-end:
-
-- The vendored `tinyplace` SDK carries no media field on the **write** side
- (`PostCreate` = `{ body, content_type, post_id }`) or the **read** side
- (`Post` / `GqlPost` = `body`, counts, author, timestamps — no media).
-- The tiny.place **backend** serves no post-media field. Verified against
- tiny.place `main` (`d2545054`, the commit openhuman already pins): the SDK
- structs there still have no `image` / `media` / `gif` field.
-- The desktop composer sends `{ body }` only (`FeedSection.tsx` →
- `feeds.createPost` → `manifest.rs` → SDK `feeds::create_post`).
-
-Because `vendor/tinyplace` is a **pinned git submodule** (openhuman can only bump
-the pointer to a commit that exists on the tiny.place remote), the media contract
-cannot be added from this repo. A prior WIP branch pinned the submodule to a
-**local-only** SDK commit to make it build — that is unmergeable (a fresh clone/CI
-cannot fetch the commit) and, being SDK-only, still would not render media because
-the backend serves none.
-
-## Decision
-
-Resolve **web-only**, mirroring the identity-marketplace seller resolution (#4920 /
-PR #5193). Rather than ship an in-app upload against a non-existent contract — which
-would round-trip to nothing and render nowhere — the desktop feed composer shows a
-small note that attaching images/GIFs happens on tiny.place, with a CTA that opens
-the web app via the existing `openUrl()` helper.
-
-## Changes
-
-1. **UI** (`app/src/agentworld/pages/FeedSection.tsx`) — additive only. A subtle
- note + text CTA at the bottom of `FeedComposer` opens `https://tiny.place` (the
- home page is the feed) through `openUrl()`. Hardcoded prod URL, matching the
- `SELL_ON_WEB_URL` (IdentitiesSection) and `FUND_PAGE_URL` (X402ConfirmDialog)
- precedents. Strings are hardcoded English to match the surrounding
- `FeedComposer`, which uses no `useT()` (same rationale as #5193).
-
-2. **Scope docstrings** — a "Feed scope (post media is web-only)" note in the
- `FeedSection.tsx` header and in `src/openhuman/tinyplace/mod.rs`, next to the
- existing marketplace web-only note.
-
-3. **Test** (`FeedSection.test.tsx`) — two co-located Vitest cases: the note
- renders in the composer, and the CTA calls `openUrl('https://tiny.place')`
- (mock `openUrl`). Covers the new diff lines for the ≥80% changed-line gate.
-
-## Out of scope (YAGNI)
-
-- Vendored SDK media fields (`PostCreate.image` / `PostMedia` / `Post.media`).
-- Core `manifest.rs` post-media handling; `invokeApiClient.ts` media params.
-- Any `vendor/tinyplace` submodule pointer bump.
-- Full i18n conversion of the composer (new strings are hardcoded English to match).
-
-## Follow-up to genuinely close in-app (tiny.place-first, not this repo)
-
-1. tiny.place backend: persist + serve a post-media field.
-2. tiny.place SDK: add media to `PostCreate` + read-side `Post` / `GqlPost`; release.
-3. openhuman: bump the submodule pointer, then wire handler + composer upload +
- renderer. Tracked under the Tiny Place epic (#4190 / #4776).
diff --git a/docs/tauri-live-profiling-brief.md b/docs/tauri-live-profiling-brief.md
deleted file mode 100644
index 89488165dd..0000000000
--- a/docs/tauri-live-profiling-brief.md
+++ /dev/null
@@ -1,85 +0,0 @@
-# Brief: Tauri live-app benchmark and profiling
-
-Audience: the next agent/session taking on desktop-app (live Tauri + CEF)
-profiling. The Rust-core library side is done and documented in
-[`library-benchmarking.md`](library-benchmarking.md); this brief covers what
-to build for the shipped desktop app, what already exists, and what to reuse.
-
-## Goal
-
-Bring the desktop app to the same standard the core now has: named,
-repeatable scenarios; fresh-process repeats with median aggregation; JSON
-results; pass/fail budget gates; and an escalation path for attribution. The
-app is a process *family* (Tauri host + CEF helpers + utility/GPU/renderer
-processes + node/python runtime children), so every measurement must be
-family-wide, not single-pid.
-
-## What already exists (reuse, do not rebuild)
-
-- **`app/src-tauri/profiling/`** — an offline Tauri process-family profiler
- (own small crate: `src/main.rs` ~813 lines, README) added in commit
- `ce6cd2291`. Start here; extend it rather than writing a new sampler.
-- **`src/openhuman/platform/proc_metrics/`** — RSS/peak/threads/CPU-ms/fds sampling
- plus `tree.rs` (descendant process-tree walker, macOS `proc_listchildpids`
- + Linux `/proc` ppid walk). The tree sampler is exactly what family-wide
- measurement needs.
-- **`scripts/profile/`** — the driver-script pattern (build → N fresh runs →
- jq medians → summary.md + gate exit code). Copy `library-bench.sh`'s shape
- for an `app-bench.sh`.
-- **JSON schema v2** (`library-profile` output) — reuse the field names
- (`baseline`/`settled`/`peak_rss_kib`/`checkpoints[]`/`budget`) so existing
- aggregation and future CI tooling work on both suites.
-- **Env-var conventions** — `OPENHUMAN_PROFILE_*` knobs, `HOLD_SECS`-style
- inspection points.
-
-## Prior findings to build on (2026-07-21 session)
-
-| Finding | Number |
-| --- | ---: |
-| Full desktop process family | 1,207-1,440 MiB |
-| CEF prewarm cost | ~86 MiB (disable/short-lived candidate) |
-| spaCy cost | ~146 MiB (lazy-init candidate) |
-| Rust core share of the family | ~40-50 MiB |
-
-The gap between the ~50 MiB core and the ~1.2-1.4 GiB family is the entire
-story: CEF/renderer processes, prewarm policy, spaCy, and shell-side polling.
-
-## Suggested scenarios
-
-1. **cold-boot** — launch to interactive UI; family RSS + wall time,
- checkpointed (host start, core ready, CEF first frame, UI route mounted).
-2. **idle-drift** — 10-30 min idle; family RSS + CPU sampled continuously.
- This is where scanner polling, heartbeat, accessibility probes, and
- `osascript` probes show up (keep them event-driven per prior findings).
-3. **chat-turn-e2e** — one full chat turn through the real UI (drive via CDP
- on the CEF debug port or the Appium harness in `openhuman/e2e/`); compare
- against the core-only `agent-turn` baseline to attribute shell overhead.
-4. **webview-cycle** — open/close provider webviews (N cycles); CEF child
- process lifecycle, leak check on repeat.
-5. **prewarm-matrix** — CEF prewarm on/off × spaCy on/off, reproducing and
- pinning the prior session's ~86/~146 MiB findings as a regression gate.
-6. **overlay-surfaces** — mascot/notch/companion windows up vs down.
-
-## Method notes
-
-- Family enumeration: union of the Tauri host's descendant tree (use
- `proc_metrics::tree`) plus CEF helper processes, which may re-parent —
- match by bundle path/name as `app/src-tauri/profiling` already does.
-- Sum-RSS double-counts shared CEF framework pages across helpers; on macOS
- record `footprint` output alongside ps-style sums (the instances driver
- in `scripts/profile/library-instances.sh` shows the pattern and caveat
- wording); on Linux use PSS.
-- Drive the UI mechanically, not by hand: CDP against CEF (`:19222` per the
- e2e harness) or the WDIO/Appium specs. Every scenario must run
- unattended.
-- Gate suggestion: family budget per scenario (e.g. cold-boot ≤ X MiB,
- idle-drift slope ≈ 0), same PASS/FAIL summary style as
- `library-fleet.sh`.
-
-## Definition of done
-
-- `scripts/profile/app-bench.sh` (or equivalent) running the scenarios
- above unattended with median aggregation and gates.
-- Baselines recorded in a doc table (like `library-benchmarking.md`).
-- The prewarm/spaCy findings converted from one-off observations into
- standing regression gates.
diff --git a/docs/the-tet.png b/docs/the-tet.png
deleted file mode 100644
index cb5ace1249..0000000000
Binary files a/docs/the-tet.png and /dev/null differ
diff --git a/docs/tinyagents-drift-ledger.md b/docs/tinyagents-drift-ledger.md
deleted file mode 100644
index 7a0696e562..0000000000
--- a/docs/tinyagents-drift-ledger.md
+++ /dev/null
@@ -1,293 +0,0 @@
-# TinyAgents Drift Ledger
-
-**Purpose.** The TinyAgents migration spans `inference`, `tools`, and
-`agent_orchestration`, while the OpenHuman host will keep evolving. This ledger
-records the baseline used for the port plan and tracks which host-side drift must
-be upstreamed, retained, or deleted before each phase cuts over.
-
-- **DRIFT -> tinyagents PR** - generic engine behavior absent from the crate; port
- upstream before deleting the host copy.
-- **HOST-OWNED** - OpenHuman product policy, RPC, config, credentials, UI, local
- runtime, or integration glue. No upstream action.
-- **CONSOLIDATE / DELETE** - duplicate host implementation already covered by
- TinyAgents primitives; delete only after the seam proves the crate-backed path.
-- **CLOSED** - resolved by a submodule/version bump or a completed cutover.
-
-> **Gate rule:** no phase deletes host code until every open row for that phase
-> is either upstreamed and bumped, reclassified host-owned, or covered by a
-> crate-backed seam test.
-
-## Anchors
-
-| Thing | Value |
-| --- | --- |
-| Host repo | `tinyhumansai/openhuman` |
-| Host branch | `feat/tinyagents-provider-cleanup` |
-| Host audit base | `5b8a9f269` (`upstream/main`, 2026-07-22) |
-| Active plan | `docs/tinyagents-migration-plan-2026-07-22.md` |
-| TinyAgents submodule | `vendor/tinyagents` -> `tinyhumansai/tinyagents` |
-| Phase 0 target | `v1.6.0` / `e72036d847b589044aa9a4add1b34544b92a293d` |
-| Current host pin | `v2.1.0` / `2583fcc` (vendored tag; root requirement `2.1`) |
-| Verification PR | [openhuman#4769](https://github.com/tinyhumansai/openhuman/pull/4769) — Motion A + Motion B checkpoint. **CI fully green** (`PR CI Gate` + `Rust Core Coverage` + fmt/clippy); 14,437 Rust tests pass. First full CI verification of this branch. |
-
-## Baseline Snapshot
-
-Recorded from `docs/tinyagents-port-plan` after the Phase 0 version alignment
-work started. Counts include Rust files only.
-
-| Host module | Rust files | LOC | Test fns | Plan disposition |
-| --- | ---: | ---: | ---: | --- |
-| `src/openhuman/inference/` | 116 | 53,023 | 1,101 | Provider consolidation and small generic ports |
-| `src/openhuman/tools/` | 94 | 38,553 | 877 | Tool model reconciliation, then builtin family ports |
-| `src/openhuman/agent/orchestration/` | 64 | 25,769 | 262 | Sub-agent lifecycle consolidation onto TinyAgents graph/orchestration |
-| `src/openhuman/agent/tinyagents/` | 25 | 15,219 | 101 | Host seam; shrinks but remains OpenHuman-owned |
-
-## Phase 0 Drift Rows
-
-| # | Area | Status | Evidence / action |
-| --- | --- | --- | --- |
-| P0-1 | Version skew: host required `tinyagents = 1.5.0` while the intended engine baseline was `v1.6.0` | **CLOSED** | Phase 0 first aligned the host to `v1.6.0`; the current Phase 1 host pin is now `v1.7.1` in root `Cargo.toml`, both lockfiles, and `vendor/tinyagents` (`3e81e493`). |
-| P0-2 | `ToolCompleted` outcome was reconstructed through OpenHuman's `ToolFailureMap` side channel | **CLOSED** | `src/openhuman/agent/tinyagents/observability.rs` consumes TinyAgents 1.6 `duration_ms`, `output_bytes`, and `error`; `ToolFailureMap` now only preserves OpenHuman's richer classified failure and legacy fallback fields. |
-| P0-3 | TinyAgents 1.6 event constructor shape changed for local observability tests | **CLOSED** | Local constructors in `src/openhuman/agent/tinyagents/observability.rs` include `ModelCompleted.started_at_ms` and the expanded `ToolCompleted` fields. |
-| P0-4 | `invoke_stream` adoption in `src/openhuman/agent/tinyagents/mod.rs` | **CLOSED** | TinyAgents PR [tinyagents#21](https://github.com/tinyhumansai/tinyagents/pull/21) shipped context-preserving `invoke_stream_in_context` in `v1.7.0`; follow-up PR [tinyagents#28](https://github.com/tinyhumansai/tinyagents/pull/28) made that stream `Send` and shipped in `v1.7.1`. `OpenHumanTinyAgentModel::invoke` now drives `invoke_stream_in_context` when progress streaming is enabled, consuming terminal `AgentStreamItem`s while the existing `EventSink` bridge continues to mirror progress. Local validation for #28 in the submodule: `cargo fmt --check`; `timeout 180s cargo clippy --all-targets -- -D warnings`; `timeout 120s cargo test invoke_stream_in_context_stream_is_send`; `timeout 120s cargo test invoke_stream_in_context_unsubscribes_channel_listener`. GitHub release run `28729225952` passed TinyAgents format, clippy, tests, package, tag, and crates.io publish for `v1.7.1`. |
-| P0-5 | SHA-256 prompt fingerprint / prompt-cache drift guard | **CLOSED** | `src/openhuman/agent/tinyagents/middleware.rs` now stamps `PromptCacheSegmentMiddleware` segment ids and `ModelRequest::prompt_fingerprint` with SHA-256 over canonical JSON. Tool-cache identity includes the full serialized `ToolSchema` list, not just tool names, matching TinyAgents 1.6 `PromptBuilder::fingerprint` expectations. Added `prompt_cache_segments_fingerprint_full_tool_schema` as the local regression guard. |
-| P0-6 | Idempotent redaction middleware vs `journal.rs` double-redaction | **CLOSED** | Audit found no OpenHuman install of TinyAgents `RedactionMiddleware`. Model-facing tool output is scrubbed once by `CredentialScrubMiddleware`; durable event persistence is separately wrapped by `journal.rs` `RedactingSink` over `openhuman_redaction_secrets()`. These protect different surfaces, so there is no crate/host double-redaction seam to collapse in Phase 0. |
-
-## Phase 1 Drift Rows
-
-| # | Area | Status | Evidence / action |
-| --- | --- | --- | --- |
-| P1-1 | `SchemaCleanr` provider schema normalization | **CLOSED** | TinyAgents PR [tinyagents#20](https://github.com/tinyhumansai/tinyagents/pull/20) shipped in `v1.7.0`. Host `src/openhuman/tools/schema.rs` now re-exports `tinyagents::harness::tool::{CleaningStrategy, SchemaCleanr, GEMINI_UNSUPPORTED_KEYWORDS}`, keeping the old OpenHuman import path stable while deleting the in-tree implementation. Local TinyAgents validation before merge: `cargo fmt --check`; `timeout 180s cargo clippy --all-targets -- -D warnings`; `timeout 120s cargo test schema_`. |
-| P1-2 | `current_time` / `resolve_time` builtin tool pilot | **RELEASED / HOST WRAPPER RETAINED** | TinyAgents PR [tinyagents#22](https://github.com/tinyhumansai/tinyagents/pull/22) shipped in `v1.7.0` with optional `tools` feature exports. Host wrappers remain in place until Phase 2 reconciles `ToolResult`, permission, access, and timeout semantics enough to adopt crate builtin tools. Local TinyAgents validation before merge: `cargo fmt --check`; `timeout 240s cargo clippy --features tools --all-targets -- -D warnings`; `timeout 180s cargo test --features tools time_`. |
-| P1-3 | `model_context.rs` generic context-window patterns | **CLOSED** | TinyAgents PR [tinyagents#23](https://github.com/tinyhumansai/tinyagents/pull/23) shipped in `v1.7.0`. Host `context_window_for_model` now checks OpenHuman tier aliases and the cost catalog first, then delegates generic raw-model fallback to `tinyagents::harness::model::context_window_for_model_id`. Local TinyAgents validation before merge: `cargo fmt --check`; `timeout 180s cargo clippy --all-targets -- -D warnings`; `timeout 120s cargo test context_window_patterns_cover_common_provider_families`; `timeout 120s cargo test o1_o3_context_patterns_require_segment_boundaries`. |
-| P1-4 | `error_classify.rs` generic provider failure classifiers | **RELEASED / HOST CALL-SITE PENDING** | TinyAgents PR [tinyagents#24](https://github.com/tinyhumansai/tinyagents/pull/24) shipped in `v1.7.0` with `harness::retry::{ProviderFailureClass, classify_provider_failure, classify_provider_error, structured_http_status, parse_retry_after_ms}` and shared OpenAI retryability classification. Host retry/failure call-site swaps remain pending because OpenHuman-specific session, billing-envelope, and backend phrase rules stay host-side. Local TinyAgents validation before merge: `cargo fmt --check`; `timeout 180s cargo clippy --all-targets -- -D warnings`; `timeout 120s cargo test provider_failure`; `timeout 120s cargo test structured_http_status`; `timeout 120s cargo test retry_after_parser_accepts_integer_float_and_space_separators`; `timeout 120s cargo test classify_provider_error_reads_structured_error_fields`. |
-| P1-5 | First-class reasoning channel host cutover | **CLOSED** | TinyAgents `v1.6.0` already carries typed reasoning via `ContentBlock::Thinking`, `ContentBlock::RedactedThinking`, `MessageDelta::reasoning`, and stream reconstruction that preserves thinking blocks. OpenHuman now writes new non-streaming `reasoning_content` into `ContentBlock::Thinking` instead of `ProviderExtension`, while still reading legacy `ProviderExtension` reasoning from persisted transcripts and continuing to echo `ChatMessage::extra_metadata` for provider replay. Local validation: `cargo fmt --check` passed; two targeted `cargo test --lib --manifest-path Cargo.toml ...` attempts for the new conversion tests timed out during host test compilation before executing, so runtime verification is deferred to GitHub runners. |
-| P1-6 | Git-worktree `WorkspaceIsolation` provider | **RELEASED / HOST WRAPPER RETAINED** | TinyAgents PR [tinyagents#25](https://github.com/tinyhumansai/tinyagents/pull/25) shipped in `v1.7.0`. OpenHuman's wrapper remains for global event-bus emissions, `OutsideWorkspace`, and host policy mapping; adapter deletion waits for a focused wrapper-thinning pass. Local TinyAgents validation before merge: `cargo fmt --check`; `timeout 180s cargo clippy --all-targets -- -D warnings`; targeted worktree tests for create/list/status/diff/remove plus overlap and sanitize filters. |
-| P1-7 | Tool display metadata and timeout semantics | **RELEASED / HOST TRAIT RETAINED** | TinyAgents PR [tinyagents#26](https://github.com/tinyhumansai/tinyagents/pull/26) shipped in `v1.7.0`. Host `ToolPolicy` projection now fills the new `ToolRuntime.timeout` field, but OpenHuman's `Tool` trait still owns richer legacy display/timeout semantics until the Phase 2 tool model reconciliation. Local TinyAgents validation before merge: `cargo fmt --check`; `timeout 180s cargo clippy --all-targets -- -D warnings`; `timeout 120s cargo test display_`; `timeout 120s cargo test tool_policy_deserializes_without_display_metadata`; `timeout 120s cargo test timeout_policy_uses_richer_timeout_semantics`. |
-| P1-8 | Model-layer inversion: host callers still name `Box<dyn Provider>` / call `create_chat_provider` instead of the crate `ChatModel` | **IN PROGRESS** | `create_chat_model(...) -> Arc<dyn ChatModel<()>>` exists (`inference/provider/factory.rs:922`) as a zero-behavior-change shim wrapping the existing provider stack via `ProviderModel` (`tinyagents/model.rs`, built only in `factory.rs::chat_model_from_provider`). Baseline at branch point: ~7 runtime `create_chat_provider` call sites and 25 non-test files outside `inference/provider/` still name `dyn Provider` (incl. the seam `tinyagents/{mod,model,routes}.rs`, which legitimately keep it). **Done:** one-shot callers migrated — cron model-id resolve (`cron/scheduler.rs`), accessibility vision-locate (`accessibility/{automate,vision_click}.rs`); both Cargo worlds green. `agent_meetings/summary`, `memory/chat`, `learning/linkedin_enrichment`, `memory_tree`, `subconscious` runtime paths already on `create_chat_model`. **Deferred (own slice):** `tinyflows/caps.rs` (round-trips tool_calls + reasoning into a JSON envelope — needs seam converter helpers exposed). (`src/bin/inference_probe.rs` was also deferred; the debug bin has since been deleted.) |
-| P1-9 | Harness turn path (`Agent`/`AgentTurnRequest`) carries `Arc<dyn Provider>`, not a crate `ChatModel` | **BLOCKED ON DESIGN — one coupled refactor** | Investigation finding: the plan's Buckets 2–4 (routing/channels, agent harness, subagent runner) are **not independently landable** — `Provider` flows end-to-end: producers (`channels/runtime/dispatch/processor.rs` → `AgentTurnRequest.provider`; `agent/harness/session/builder/factory.rs` → `Agent.provider`; `subagent_runner/ops/provider.rs`) → `agent/bus.rs` / `harness/graph.rs::run_channel_turn_via_graph` → seam `build_turn_models(provider: Arc<dyn Provider>, …)` (`tinyagents/mod.rs:1139`). The channel graph reads Provider-trait capability methods before building the model: `supports_native_tools`, `supports_vision`, `effective_context_window` (**async**), `telemetry_provider_id`. `ProviderModel::profile()` already carries tool_calling / image_in / streaming / context-window, so a `ChatModel`-accepting `build_turn_models` is feasible — but the **async context-window resolution** and **telemetry id** must be re-homed (into the factory at ChatModel construction, or passed as params). Net: one atomic change across ~30 files (incl. ~10 test files) on the live channel/session turn path — must land as its own reviewed PR with streaming/cost/multimodal behavior-parity testing (the flagged regression surface: #4460 thread_id task-locals, $0-turn cost, tool timeline). `routing/provider.rs::IntelligentRoutingProvider` stays a `Provider` impl (provider-stack member, Phase-3 → `ModelRegistry`); it gets wrapped via `chat_model_from_provider` at the producer boundary. **BLOCKER (found while executing):** the harness cannot hold `Arc<dyn ChatModel>` in Phase 1 as the plan assumed. `build_turn_models` needs the raw `Provider` for (a) workload-route projection — `routes::build_route_models(provider: &Arc<dyn Provider>)` re-instantiates a `ProviderModel` per tier alias with distinct model strings + per-route `with_vision`/`with_reasoning` flags, which a single baked `ChatModel` cannot re-alias — and (b) the separate-error-slot summarizer. The crate `ChatModel` trait exposes no `as_any`/downcast, so the `Provider` cannot be recovered from an `Arc<dyn ChatModel>`. Therefore the true harness inversion is gated on **Phase 3** (replace `RouterProvider`/route-projection with the crate `ModelRegistry`), an upstream `vendor/tinyagents` change — not host-only. Achievable host-only step instead: wrap the harness-held `Arc<dyn Provider>` in a seam-owned newtype (e.g. `tinyagents::TurnModelSource`) so no `agent/` code names the `Provider` trait and all Provider handling is confined to the seam + factory, making the Phase-3 swap seam-local. **PROGRESS:** `docs/tinyagents-phase3-router-registry-design.md` records the corrected premise (router→registry already crate-wired in `assemble_turn_harness`; no upstream gap; work is host-only Motion A). `TurnModelSource` (pub seam type) landed + `TurnModels` extended with `provider_id`/`context_window`/`native_tools`/`supports_vision`. **Channel/bus turn path fully migrated** (commit `30c7dfd92`): `AgentTurnRequest.provider → turn_model_source`; `run_channel_turn_via_graph` reads caps off the built crate models; channels/triage producers wrap at the bus boundary; lib + the 3 bus integration tests green; zero behavior change. **Subagent-runner path migrated** (commit `8db888712`): `agent_graph::AgentTurnRequest.provider → turn_model_source`; `run_subagent_via_graph` takes the source (reads vision/native-tool caps + telemetry id off the built models, resolves context window via the source); `SubagentCheckpoint` cap-hit summary now runs on a crate `ChatModel` (via `TurnModelSource::build_summarizer`) instead of `provider.chat`; runner wraps its resolved `subagent_provider` at both dispatch sites. Core lib green; changed files clean under `--lib --tests`; zero behavior change. **Agent session path migrated** (commit `9112330b9`): `Agent`/`AgentBuilder`, `ParentExecutionContext`, and `ChatTurnGraph` hold a `TurnModelSource`/built `TurnModels`; core builds the tiered model set up front (reads vision off it), `ParentExecutionContext` carries the source, and the streaming cap-hit checkpoint keeps `provider.chat` via a `source.provider()` escape hatch (crate `ChatModel::invoke` has no delta sink). Extract tool migrated (commit `6106ced83`). **Motion A is structurally complete:** no agent-harness struct (`Agent`, `AgentBuilder`, `ParentExecutionContext`, `ChatTurnGraph`, both `AgentTurnRequest`s) holds `Arc<dyn Provider>`; both Cargo worlds green; zero behavior change. `TurnModelSource` gained `is_local_provider()` + a `provider()` escape hatch used only at seam-boundary resolution sites. **Remaining `dyn Provider` in `agent/` (Motion B, not Motion A):** provider-*resolution/build* boundaries that construct a provider to wrap into a source — `session/builder/factory.rs` (`create_chat_provider`/`create_routed_provider`), `subagent_runner/ops/provider.rs::resolve_subagent_provider` (kept `Arc<dyn Provider>` to avoid churning its 9 unit tests), `tools/delegate.rs`, `triage/routing.rs`, and the builder `.provider()/.provider_arc()` setters — plus test files. These vanish when Motion B registers crate-native `providers::openai` clients directly. Pre-existing full-`--tests` breakage in unrelated modules (config load, web, ollama, sandbox, reliable_tests, memory) is untouched and orthogonal. |
-
-## Motion B — Provider-Build Cutover (crate-native `ChatModel` construction)
-
-The closure rows below supersede older deferred/pending prose retained later in
-this section as investigation history.
-
-| # | Area | Status | Evidence / action |
-| --- | --- | --- | --- |
-| P1-10 | Wire-equivalent BYOK cloud slugs | **CLOSED** | [openhuman#4780](https://github.com/tinyhumansai/openhuman/pull/4780) routed eligible slugs to crate-native `OpenAiModel`. |
-| P1-11 | OpenAI/Codex/custom cloud slugs | **CLOSED** | [openhuman#4782](https://github.com/tinyhumansai/openhuman/pull/4782) completed the configured cloud-slug client cutover, including Responses API construction. |
-| P1-12 | Host workload routing | **CLOSED** | [openhuman#4783](https://github.com/tinyhumansai/openhuman/pull/4783) adopted crate `ModelRouter` for fallback and capability decisions. |
-| P1-13 | Crate-native registered turn models / `compatible*.rs` deletion | **CLOSED** | [openhuman#4784](https://github.com/tinyhumansai/openhuman/pull/4784) moved the hot turn path and deleted the former `compatible*.rs` cluster. The collapsed `legacy_provider.rs` facade and the broader legacy `Provider` stack remain WP-1 deletion work; see the deletion ledger. |
-| P1-14 | Legacy `run_turn_engine` and `OPENHUMAN_AGENT_GRAPH_*` escape hatches | **CLOSED BEFORE AUDIT** | WP-3 verified that both session and subagent production paths call the TinyAgents seam unconditionally. No engine definition or env read remains; only historical parity comments and stale migration prose named the retired implementation. |
-
-## WP-2 Consolidation Audit
-
-| # | Area | Status | Evidence / action |
-| --- | --- | --- | --- |
-| WP2-1 | `routing/` parallel provider/health stack | **CLOSED / DELETED** | Repository-wide reference audit found no caller outside the module; the live route already uses crate `ModelRouter`. Deleted the unreachable stack and kept the crate-backed seam. |
-| WP2-2 | `tool_timeout/` vs crate `harness::tool::ToolTimeout` | **HOST-OWNED** | The crate type is declarative per-tool metadata (`Inherit`/`Unbounded`/`Millis`) and has no process-global setting or execution store. OpenHuman owns persisted-config and `OPENHUMAN_TOOL_TIMEOUT_SECS` precedence, live UI updates, bounds/grace semantics, and the `tokio::time::timeout` around adapted host tools. The seam already projects host timeout policy into crate `ToolRuntime`; no upstream gap or duplicate engine remains. |
-| WP2-3 | `model_council/` ensemble | **CLOSED / DELETED** | The generic fan-out already used `tinyagents::graph::parallel::map_reduce`; upstream subsequently removed the unreachable product council and registry surfaces during dead-code cleanup. |
-| WP2-4 | `tool_status/` failure classification | **HOST-OWNED** | The types are serialized into OpenHuman threads/UI and the classifier consumes OpenHuman security markers, product retry categories, and user-facing remediation copy. TinyAgents owns raw tool outcomes; the host mapping is deliberately downstream product policy. |
-
-## WP-5 Parallel Fan-Out And Worktree Ownership Audit
-
-| Surface | Status | Ownership / exit evidence |
-| --- | --- | --- |
-| `orchestration/worktree.rs` git plumbing — `BaseRef`, `WorktreeStatus`, `create`/`list`/`status`/`diff_summary`/`remove`, `detect_overlaps`, `sanitize_run_id` | **CLOSED / DELETED** | Near-verbatim twins of `tinyagents::harness::workspace::git` (`detect_overlaps` and `detect_worktree_overlaps` matched down to the `BTreeSet` dedupe; the two error enums carried identical message strings). Deleted and re-exported under the historical OpenHuman names, so RPC schemas, tools and tests are unchanged. 618 → 242 LOC. The RPC wire shape is pinned by `worktree_status_serializes_with_stable_camel_case_keys`, written and passing **before** the swap and again after; the crate carries the identical `sanitize_run_id` test already. |
-| `OpenHumanWorktreeIsolation` (was `GitWorktreeIsolation`) | **HOST-OWNED** | Wraps the crate provider to add the two things that are OpenHuman's rather than every host's: the `openhuman.worktree:{agent}:{run_id}` policy-id convention, and `DomainEvent::Workspace{Prepared,Cleanup}` on the global bus. |
-| `enforce_workspace_path` + `WorkspacePathError` | **HOST-OWNED (currently uncalled)** | Descriptor-policy gate that publishes `DomainEvent::WorkspaceViolation`. A repository-wide search finds no caller; it is retained because removing a public fail-closed gate is a separate judgement from this migration, and is recorded here so the next reader does not have to rediscover it. Split off `WorktreeError` (now the crate's git error) since it is about descriptor policy, not git. |
-| Shared-workspace claim arbitration — `ownership_file_paths` path validation, `paths_overlap`, the serial-claim accumulator | **CLOSED / CRATE ADOPTED** | Upstreamed as `tinyagents::graph::parallel::claims` (`WorkspaceClaim`, `plan_shared_workspace_dispatch`, `parse_relative_claim_paths`, `paths_overlap`). `prepare_spawn_parallel_tasks_from_defs` is now two passes: OpenHuman policy admits or rejects, then one planner call arbitrates every admitted claim in input order. Behaviour parity is the gate, and `spawn_parallel_agents_tests.rs` passes **unedited** across the cutover; three assertions pinning the mixed-batch dispatch sequence, disjoint-ownership admission, and directory containment were added before it. |
-| `files:` ownership syntax, rejection copy, `shared_workspace_write_capable_tools`, `definition_visible_tool_permissions`, `ParallelTaskRejectionKind`, `integrations_agent` toolkit rule, subagent allowlist | **HOST-OWNED** | Product policy and user-facing phrasing. The crate returns `ClaimConflict` as data specifically so the `isolation="worktree"` remedy sentence stays here; `shared_workspace_conflict_message` renders it. |
-| `annotate_stale_parent_reads`, `overlap_warnings_for_results` | **HOST-OWNED** | The first reads OpenHuman `file_state` task-locals with no crate analogue; the second is `serde_json` shaping over the crate's overlap detector. Host projection over a crate primitive, not duplication. |
-| `run_spawn_parallel_workers` serial-then-parallel execution | **HOST-OWNED (deliberate)** | The crate contributes the *plan*, not the scheduler. Today the host serializes the whole batch when any worker needs serializing; a crate-side executor running only the claimed workers serially would be a **narrower** guarantee than what ships. Keeping execution host-side keeps the diff to "who computed this decision", which is exhaustively unit-testable. |
-| `tinyagents/subagent_graph.rs` no-op pipeline skeleton | **CLOSED / DELETED** | Six nodes whose bodies only pushed their own name onto a `Vec`, compiled and executed on **every** sub-agent spawn from `ops/runner.rs`. A scaffold for a per-phase cutover that WP-5 concluded should not happen (see below). Deleted with its call site and its `topology.rs` export. |
-| `extract_tool.rs` bounded fan-out | **CLOSED / CRATE ADOPTED** | Hand-rolled `buffer_unordered(3)` plus a manual index-tag-and-re-sort, replaced by `map_reduce` with `FailurePolicy::BestEffort`, which returns outcomes in input order. The per-chunk provider error stays the fan-out's *item* rather than its error, so one failed chunk still drops with a warning instead of aborting its siblings. |
-| `harness/subagent_runner/` (7,471 LOC) — **directory-level verdict, not file-level** | **HOST-OWNED — do not relocate** | Its own module docs call it the OpenHuman *build pipeline*, and that is accurate: definition lookup, tier gating, archetype prompt assembly, toolkit filtering, sandbox narrowing, the deterministic memory fast path, Composio resolution, artifact offload, transcript persistence. The generic contract it would map onto already exists as `harness::host::HostCapabilities` (`ContextComposer` / `DefinitionRegistry` / `SecurityGate` / `ModelResolver`) and is unused by the host. The open question is therefore whether OpenHuman should *implement those traits*, not whether to move this code across the GPL boundary — a separate design-gated package. **Exception, resolved:** `subagent_runner/handoff.rs` was a 287-line near-verbatim twin of `tinyagents::harness::handoff` (exported ungated at `vendor/tinyagents/src/harness/mod.rs:23`) and has been collapsed to a ~66-line shim re-exporting the crate module under the historical OpenHuman names; only the host-only `OPENHUMAN_TEST_HANDOFF_THRESHOLD_TOKENS` resolution stays host-side, passed as the crate's explicit `threshold_tokens` parameter. Zero call-site edits. |
-
-## WP-5 Detached Lifecycle Ownership Audit
-
-| Surface | Status | Ownership / exit evidence |
-| --- | --- | --- |
-| Process-local detached task map, ownership checks, status receivers, cancellation tokens, abort handles, terminal sweep, steering lookup | **CLOSED / CRATE ADOPTED — tinyagents#75** | TinyAgents #75 merged as `d548657`; the canonical vendored pointer `4358efe` includes its `DetachedTaskRegistry`. OpenHuman calls the crate registry for snapshots, wait/timeout, owned and trusted steering, per-task/thread/global cancellation, and soft-cap cleanup. Distinct lock-poison errors are propagated by the crate. All 17 focused host tests pass. |
-| Durable detached task lifecycle | **HOST PROJECTION ON CRATE STORE** | OpenHuman maps product `SubagentStatus` into crate `OrchestrationTaskStatus` and owns the store's on-disk location; this is durable product projection, not executor ownership. (Store *selection* itself has since moved to the crate — see the `TaskStoreRegistry` row below, which supersedes the earlier wording of this one.) |
-| Per-workspace store selection + durable→memory fallback (`DetachedTaskStore` enum, `TASK_STORES` map, `open_task_store`) | **CLOSED / CRATE ADOPTED** | Upstreamed as `TaskStoreRegistry` + `open_jsonl_task_store_or_memory`. Opening a second store over one append log gives two writers with independently replayed state, so the caching is part of the contract, not an optimization. The 12-arm delegating `TaskStore` impl is deleted; the fallback ladder is ported exactly (a `create_dir_all` failure degrades to memory just as an unreadable log does — a read-only workspace must stay able to spawn work). Lock poisoning is now typed (`TaskStoreRegistryError`) rather than `.expect()`ed. All 17 focused `running_subagents` tests pass unedited. |
-| Boot-time orphan reconciliation state machine | **CLOSED / CRATE ADOPTED** | `reconcile_orphaned_tasks` owns which statuses are live and which terminal state each takes (`CancelRequested` → cancelled, other live → failed), and captures per-task transition failures rather than aborting — a record racing to terminal between listing and transition is expected. The reason is passed as a closure, so `"sub-agent orphaned by core restart (was \`running\`)"` and the `publish_subagent_failed` lifecycle event stay host-side. Already wired at `core/jsonrpc.rs`. |
-| `REGISTRY_SOFT_CAP` (256) | **HOST-TUNED CRATE POLICY — no action** | The sweep is crate-owned: the constant is passed into `DetachedTaskRegistry::new`, which performs it. Only the number is OpenHuman's. Recorded because an earlier scoping pass mistook it for a host-side duplicate. |
-| Detached task metadata, RPC/UI delivery, `RunQueue` fallback | **HOST-OWNED** | Agent/session/thread/workspace metadata, cancellation notices, background delivery, trusted desktop RPC, and compatibility steering are OpenHuman product surfaces. The fallback can shrink independently after live crate-steering parity, but does not block generic registry deletion. |
-
-TinyAgents #75 is merged and the temporary integration gitlink has been
-replaced by canonical upstream commit `4358efe`.
-
-## WP-5 Middleware Ownership Audit
-
-The earlier seam snapshot counted 17 middleware types. The audit found 18: the
-tool-exposure shadow was added after that snapshot. The crate-backed
-`SchemaGuardMiddleware` cutover below reduces the current file to 17 again.
-`TurnContextMiddleware` is an installer/config bundle rather than another hook
-implementation and is not counted. A middleware may be deleted only after its
-crate replacement and host cutover are both verified.
-
-| Middleware | Status | Ownership / exit evidence |
-| --- | --- | --- |
-| `TranscriptSnapshotMiddleware` | **HOST-OWNED** | Mirrors partial crate transcripts into OpenHuman's persisted `ChatMessage` DTO so failed sub-agent runs remain ingestible. |
-| `OpenHumanToolExposureShadowMiddleware` | **TRANSITIONAL / PARITY-GATED** | Exercises crate allowlist/contextual selection in shadow against the host registry. Delete with the host precompute only after divergence telemetry proves parity; do not flip from this audit alone. |
-| `HandoffMiddleware` | **HOST-OWNED** | Implements integrations-agent progressive disclosure through OpenHuman's `ResultHandoffCache` and `extract_from_result` contract. |
-| `PromptCacheSegmentMiddleware` | **HOST SEAM** | Projects OpenHuman's stable system/tool-cache boundaries and SHA-256 identity into the crate `PromptCacheGuardMiddleware`; the actual drift guard is crate-owned. |
-| `ToolOutputMiddleware` | **HOST-OWNED** | Applies host artifact persistence, TokenJuice compaction, byte caps, and the OpenHuman payload summarizer. |
-| `ApprovalSecurityMiddleware` | **HOST-OWNED** | Calls the global OpenHuman approval gate, redacts args, and records product audit rows. Generic crate approval cannot replace this product/security decision. |
-| `CliRpcOnlyMiddleware` | **HOST-OWNED** | Enforces OpenHuman `ToolScope` at the autonomous-agent boundary. WP-4 defines the complete Agent/CLI/RPC scope matrix. |
-| `CredentialScrubMiddleware` | **HOST-OWNED** | Uses OpenHuman's credential detector and scrubs model context, errors, raw JSON, and persisted host surfaces. Crate redaction protects a different generic boundary. |
-| `ToolPolicyMiddleware` | **HOST-OWNED** | Enforces args-aware channel permission ceilings, generated-tool provenance, and OpenHuman policy decisions. Static crate `ToolPolicy` remains metadata and a generic fail-closed layer. |
-| `ToolOutcomeCaptureMiddleware` | **HOST-OWNED** | Projects final capped results and classified failures into OpenHuman tool-call records/UI state. |
-| `ArgRecoveryMiddleware` | **UPSTREAM READY — tinyagents#71** | PR #71 adds `NormalizeThenReturnToolError` and admission-time normalization with preservation regressions. Delete after the merged crate policy is vendored and the host config selects it. |
-| `SchemaGuardMiddleware` | **CLOSED / DELETED** | TinyAgents 2.1 already provides `InvalidArgsPolicy::ReturnToolError`. The host now selects it and deleted pre-validation, synthetic schema-valid arguments, the pending map, and the tool-wrap short circuit. The policy regression and all 18 `agent_harness_e2e` tests pass. PR #71 is only needed to absorb the remaining normalization middleware. |
-| `MemoryProtocolMiddleware` | **HOST-OWNED** | Enforces OpenHuman's read/dedupe/write/index memory protocol and product tool names. |
-| `CostBudgetMiddleware` | **HOST PROJECTION** | TinyAgents `BudgetMiddleware` already runs in shadow; this wrapper maps OpenHuman billing-envelope USD/token accounting and halt summaries. Thin only when crate usage is sufficient for every host provider. |
-| `RepeatedToolFailureMiddleware` | **CRATE-BACKED / HOST PROJECTION** | Detection uses crate `NoProgressTracker`; the wrapper owns OpenHuman retry taxonomy, polling exemptions, steering, and user-facing halt summary. No duplicate generic tracker remains to upstream. |
-| `RepeatProgressMiddleware` | **CLOSED / CRATE-BACKED — tinyagents#72** | PR #72 merged and is included in canonical pointer `4358efe`. The host duplicate `StreakGuard`, thresholds, and streak accounting are deleted; the remaining thin adapter builds OpenHuman signatures/polling exemptions and maps the crate `SuccessfulRepeatTracker` verdict to the host halt summary and steering pause. All 51 focused middleware tests pass. |
-| `ImageAwareMessageTrimMiddleware` | **UPSTREAM READY — tinyagents#73** | PR #73 makes crate trimming image/token-policy aware. Delete after vendoring and proving host context-window regressions against the crate middleware. |
-
-The three upstream PRs are independently mergeable and green at the time of
-this audit. Their remaining host deletions stay pending because OpenHuman still
-vendors an earlier TinyAgents revision.
-
-Motion A confined all `Provider` handling to the seam + factory. Motion B
-replaces the *construction* of host `Provider`s with crate-native
-`ChatModel`s at each build boundary, so `compatible*.rs` can eventually be
-deleted. The factory keeps both paths in parallel until every construction
-site is crate-backed (the migration's scaffold → flip → delete pattern).
-
-| Site | Crate-native builder | Status |
-| --- | --- | --- |
-| Managed OpenHuman backend (common path: chat turns, memory/learning/meeting summaries) | `factory::make_openhuman_backend_model` → `OpenHumanBackendModel` (dynamic JWT + `thread_id` + billing envelope bridged onto crate `OpenAiModel`) | **CUT OVER** — `create_chat_model_with_model_id` routes it (commit `7e98c1b39`); test-provider override still wins. |
-| Wire-equivalent BYOK cloud slug (Anthropic / None / plain-Bearer, no codex-oauth, no `/v1/responses`) | `factory::try_create_cloud_slug_chat_model` → `crate_openai::make_crate_openai_chat_model` | **CUT OVER (conservative subset)** — `create_chat_model` routes these crate-native after the managed + local short-circuits. Resolution is shared via `resolve_cloud_slug` (the legacy `make_cloud_provider_by_slug` was refactored onto it, so eligible slugs resolve **identically**; only the wire client differs). The same `enforce_local_only_inference` + `verify_session_active` gate runs first. Covers the common non-OpenAI BYOK providers (DeepSeek, Groq, Mistral, xAI, …) via the crate wire the managed backend already proves. |
-| `openai` / codex + custom-proxy cloud slugs | crate-native via `try_create_cloud_slug_chat_model` | **CUT OVER** — the flip now covers **every** configured cloud slug except the managed `OpenhumanJwt` entry. Codex OAuth → crate `OpenAiModel` on the Responses API (`with_responses_api_primary` + account/originator headers + user-agent + `client_version` query + `max_output_tokens` omitted), enabled by the crate `/v1/responses` port ([tinyagents#51](https://github.com/tinyhumansai/tinyagents/pull/51)). Non-codex `openai` + custom slugs → crate Chat Completions (the legacy 404 → `/v1/responses` **fallback** is not replicated — chat completions is their primary path). Host pin `8e57665` = #49 toggles + #51 Responses, with #50 reverted (#52) so loopback stays retryable. **Live per-provider validation deferred to a dedicated tinyagents run.** |
-| Local runtimes (Ollama/LM Studio/MLX/OMLX/local-openai) | `factory::try_create_local_runtime_chat_model` → `crate_openai::make_crate_local_runtime_chat_model` (native tools + vision forced off; `num_ctx` baked as `{"options":{"num_ctx":N}}`) | **CUT OVER** — `create_chat_model_with_model_id` routes local runtimes crate-native (after the managed short-circuit). The flip **re-runs the same gate** the `Provider` path applies (`enforce_local_only_inference` + `verify_session_active`), so it cannot bypass privacy mode or the session requirement. Temperature rides the per-call `ModelRequest` (parity with managed). **Loopback error handling defers to upstream:** an upstream merge (`b709a993…`/`04ffc029…`) replaced the earlier `..._offline_trips_halt_guard` test with `cron_agent_job_short_loopback_send_error_stays_retryable` — i.e. an offline local provider now **stays retryable** (it may be transiently starting up). So the transient cron `{e:#}` cause-chain surfacing + the `is_non_retryable` loopback fast-fail were reverted, and the host stays pinned at `7c6e81a` (before [tinyagents#50](https://github.com/tinyhumansai/tinyagents/pull/50) `error_source_chain`) so the crate-native local error does not surface the `connection refused` errno the classifier would trip on. #50 remains a good crate improvement but is deliberately **not consumed** here to keep loopback retryable. |
-| Bespoke (managed backend, `claude_code`, `claude_agent_sdk`, `openai_codex`) | stay host `ChatModel` impls | **HOST-OWNED** — subprocess / `/v1/responses` / query-param auth have no crate equivalent; never route through `crate_openai`. |
-
-**Crate dependency landed:** [tinyagents#49](https://github.com/tinyhumansai/tinyagents/pull/49)
-adds `OpenAiModel::{with_native_tool_calling, with_vision, with_default_provider_options}`
-+ a pure `merge_provider_options` (baked defaults merged under per-call
-options; a non-object override passes through so validation still rejects it).
-Merged onto crate `v1.8.0` main as `7c6e81a`; crate tests: 61 openai unit tests
-pass (55 + v1.8.0's #45/#46); `cargo fmt --check` clean. Host pin `7c6e81a`.
-
-**Motion A deferred-test debt (found via PR #4769 CI):** Motion A renamed
-`ParentExecutionContext.provider → turn_model_source` (+ the `AgentBuilder`
-field) but ~8 `agent_orchestration`/`harness` **test** modules still built the
-struct with the old field. Because no PR existed pre-#4769, this was never
-CI-tested; the lib-test target (`cargo test --lib`) did not compile, which would
-fail CI `rust-core-coverage`. Fixed by wrapping each site in
-`TurnModelSource::new(provider)` and correcting the `AgentBuilder` field access.
-**Behavior-level test failures (5, surfaced once the suite compiled): all stale
-tests, no code regression.** Motion A's "zero behavior change" holds for the
-actual runtime contract — the failing tests were written against pre-migration
-internals and were never CI-run:
-
-- `bus_turn` / `run_subagent` *surfaces_provider_error* — the crate-owned retry
- (`RunPolicy.retry` max 3, mirroring the old `ReliableProvider`) rides a
- single-shot `ScriptedProvider::failing` through to its empty-queue default `Ok`.
- Fix: `always_fail` field so the mock fails **persistently** (all 3 attempts) —
- a genuinely-down provider still surfaces its error.
-- `agent_large_round25` extraction — `extract_from_result` now runs its per-chunk
- extraction through the crate `ChatModel` (`build_summarizer().invoke()`, commit
- `6106ced83`), not the legacy `chat_with_system`; 6 chunk calls hit `chat` and
- drained the agent-turn queue. Fix: route extraction calls (detected by the
- extraction system prompt) to the fixed result in the mock's `chat`.
-- `inference…user_state_edges` — expected an unknown model to collapse to
- `reasoning-v1`; the managed backend forwards it verbatim (#4598). Fix: assertion.
-- `cron…local_provider_offline_trips_halt_guard` — the **one code fix**:
- `run_agent_job` surfaced `raw` as `e.to_string()` (outer message only), dropping
- the `connection refused (os error N)` cause the halt-guard classifier needs.
- Changed to `{e:#}` (full anyhow chain).
-
-**BYOK cloud-slug cutover — deferred to Phase 3 (deliberate).** The host
-`make_cloud_provider_by_slug` Bearer branch (where the common cloud providers —
-openai, deepseek, groq, mistral, … — live) layers on `/v1/responses` fallback,
-`openai-codex` OAuth headers, user-agent, query params, and
-`with_responses_api_primary`. The crate `OpenAiModel` speaks Chat Completions
-only, so the Bearer path cannot flip without a crate `/responses` port. The only
-crate-native-eligible cloud slugs today are the **rare** None-auth / Anthropic-auth
-branches, and even those carry `supports_responses_fallback = true`. Flipping just
-that sliver would (a) split cloud routing across two clients for marginal coverage
-and (b) touch real-billing paths the ledger requires **per-provider wire-parity
-validation** for — validation that needs a live cloud test environment this box
-cannot provide. So the BYOK cloud cutover stays with **Phase 3 (provider
-consolidation)**: it lands together with the crate `/responses` support + the
-router → crate `ModelRegistry` migration, where the whole cloud surface moves
-coherently. `compatible*.rs` (host `OpenAiCompatibleProvider`) therefore remains —
-it still serves every Bearer cloud slug, `openai_codex`, and the `create_chat_provider`
-callers that have not moved to `create_chat_model` — and cannot be deleted until
-Phase 3 completes.
-
-## `agent/learning/` Ownership Audit
-
-No prior row covered this domain (~29 files, ~6.6k production lines excluding
-`*_tests.rs`), which left the question re-derived from scratch on every pass.
-
-| Surface | Status | Ownership / exit evidence |
-| --- | --- | --- |
-| Ambient personalization cache, stability detector, candidate producers, `PROFILE.md` rendering, LinkedIn enrichment, transcript ingestion (`src/openhuman/agent/learning/`) | **HOST-OWNED** | The runtime-learns-nothing boundary is already drawn upstream: `vendor/tinyagents/src/harness/host/learning_sink.rs` states "The runtime itself learns nothing … what counts as a lesson, where it is stored, whether it is redacted first — is host policy and stays host-side," and OpenHuman implements that seam at `src/openhuman/agent/tinyagents/host/learning_sink.rs`. `vendor/tinymemory/crates/tinymemory-bus/src/learning.rs` separately declines to own the stability formula by name. |
-| Structural blocker on porting the stability formula onto `tinymemory-api` | **HOST-OWNED (one-package rule, not a dependency cycle)** | No cargo cycle exists — `tinymemory-api` depends only on `tinymemory-bus` plus leaf crates (`vendor/tinymemory/crates/tinymemory-api/Cargo.toml:47-52`). The real blocker: `tinymemory` vendors `tinyagents` as its own submodule (`vendor/tinymemory/vendor/tinyagents`), `tinymemory-api` is unpublished (no `source` entry in `Cargo.lock`), and adding it as a second path dependency here would make `FacetClass` two incompatible types under cargo's package identity rules — the same trap documented for `tinytools` in the root `CLAUDE.md`. |
-| `TurnSummary::tools_invoked` names-only | **UPSTREAM GAP (tinyagents issue, not a host move)** | `vendor/tinyagents/src/harness/host/learning_sink.rs:91` types it `Vec<String>` — no arguments, no result. `ToolTrackerHook` (`src/openhuman/agent/learning/tool_tracker.rs`) and `AgentExperienceCaptureHook` (`src/openhuman/agent/experience/capture.rs`) silently self-disable on the crate-driven turn path because they need call arguments/results to do anything. File upstream; do not attempt a host workaround that reconstructs the missing data. |
-
-## Phase 3 — RouterProvider → crate registry (host-only)
-
-Per `docs/tinyagents-phase3-router-registry-design.md` §1, Phase 3 is **host-only**
-— the crate `ModelRegistry` projection is already wired in `assemble_turn_harness`,
-so there is **no upstream gap** (this corrects the earlier "upstream-gated" reading
-of P1-9). Two sub-motions:
-
-- **P3-A** (harness holds `TurnModels`, not `Provider`): effectively complete —
- `agent/harness/graph.rs` holds the seam `TurnModelSource` (names no `Provider`
- trait) and `TurnModels` carries the `provider_id`/`context_window`/`native_tools`/
- `supports_vision` accessors; the per-turn route re-projection that needs the raw
- `Provider` is confined inside the seam newtype.
-- **P3-B** (registered tier models become crate-native, deletes `compatible*.rs`):
- the hot turn path still builds `ProviderModel`-over-`Provider` via
- `build_turn_models`/`build_route_models`. Cutting it to crate-native tiered
- models from config is the remaining work.
-
-| Step | Status | Evidence |
-| --- | --- | --- |
-| Crate high-level router | **DONE** | [tinyagents#54](https://github.com/tinyhumansai/tinyagents/pull/54) `registry::router::{ModelRouter, WorkloadRoute}` (merged `4fc8cd8`) — declarative workload-tier table (alias→model, `CapabilitySet` gate, same-family fallbacks) filling the long-declared `ComponentKind::Router`; holds no models, no I/O. |
-| Host adopts `ModelRouter` for fallback + capability | **CLOSED** | [openhuman#4783](https://github.com/tinyhumansai/openhuman/pull/4783) made `tinyagents/routes.rs::OH_WORKLOAD_ROUTER` authoritative for fallback and required capabilities. |
-| Registered tier models become crate-native | **CLOSED** | [openhuman#4784](https://github.com/tinyhumansai/openhuman/pull/4784) completed the P3-B hot-path client swap and deleted the former `compatible*.rs` cluster. Residual `ProviderModel` and the collapsed legacy facade are tracked separately in WP-1. |
-
-## Host Validation Notes
-
-Local host validation is intentionally bounded because full suites are deferred
-to GitHub runners. `cargo fmt --check` passed after the v1.7.1 host changes.
-Targeted `timeout 240s cargo test --lib --manifest-path Cargo.toml schema_`
-and `timeout 240s cargo test --lib --manifest-path Cargo.toml context_window`
-timed out during host compilation before executing the filtered tests. A bounded
-`timeout 240s cargo check --lib --manifest-path Cargo.toml` first exposed the
-non-`Send` stream cutover issue and the new `ToolRuntime.timeout` field; after
-filling `ToolRuntime.timeout`, TinyAgents `v1.7.1` closed the stream `Send`
-blocker and the host re-applied the `invoke_stream_in_context` cutover. A fresh
-bounded `timeout 240s cargo check --lib --manifest-path Cargo.toml` then timed
-out before completion with warning output only and no post-cutover compiler
-error emitted before the cap.
-
-## Phase Gates
-
-| Phase | Gate rows | Status |
-| --- | --- | --- |
-| Phase 0 - version alignment | P0-1, P0-2, P0-3, P0-4, P0-5, P0-6 | **CLOSED** |
-| Phase 1 - quick upstream ports | SchemaCleanr, error classification, model context, reasoning channel, worktree isolation, display metadata, time tools | **PARTIAL HOST CUTOVER** |
-| Phase 2 - tool model and builtin families | ToolResult structure, permission model, ToolAccess, edit tracking, filesystem/network/time tools | **NOT STARTED** |
-| Phase 3 - provider consolidation | OpenAI-compatible client cutover and crate router adoption | **CLIENT CUTOVER CLOSED; LEGACY STACK REMOVAL IN WP-1** |
-| Phase 4 - orchestration consolidation | TaskStore/SteeringRegistry lifecycle, status vocabulary, session durability | **NOT STARTED** |
-| Phase 5 - workflow/team generic slices | Validation/scheduling slice evaluation | **NOT STARTED** |
-| Phase 6 - cleanup and docs | Transitional shim deletion and architecture docs | **NOT STARTED** |
-
-## Closing Procedure
-
-1. For a **DRIFT -> tinyagents PR** row, branch inside `vendor/tinyagents`, port
- the generic change with crate-native tests, merge/release upstream, then bump
- the host submodule and version pin together.
-2. For a **HOST-OWNED** row, document the boundary and keep the logic in
- OpenHuman behind the seam.
-3. For a **CONSOLIDATE / DELETE** row, add or update the seam proof first, cut the
- live path to TinyAgents, then delete the duplicate host implementation.
-4. Update this ledger in the same host PR that closes or reclassifies a row.
diff --git a/docs/tinyagents-full-migration-plan/99-deletion-ledger.md b/docs/tinyagents-full-migration-plan/99-deletion-ledger.md
deleted file mode 100644
index 1b41634b71..0000000000
--- a/docs/tinyagents-full-migration-plan/99-deletion-ledger.md
+++ /dev/null
@@ -1,42 +0,0 @@
-# TinyAgents migration deletion ledger
-
-This ledger records host-side removals required by
-[`tinyagents-migration-plan-2026-07-22.md`](../tinyagents-migration-plan-2026-07-22.md).
-A row moves to `DELETED` only after its crate-backed replacement and the named
-parity evidence are in place. Generic code moved into `vendor/tinyagents` must
-also name its upstream PR before the host copy is removed.
-
-| Work package | Host artifact | Preconditions / replacement | Status | Evidence |
-| --- | --- | --- | --- | --- |
-| WP-1 | `inference/provider/router.rs` + tests | Crate `ModelRouter` owns live routing | DELETED | `fcd3f3331`; #4783 adopted the router; root `cargo check` green |
-| WP-1 | `inference/provider/reliable.rs` + tests | Crate retry/fallback owns every model call | DELETED | `fcd3f3331`; crate retry/fallback plus root `cargo check` green |
-| WP-1 | Legacy compatible raw-coverage trio | Wire parity retained against crate `OpenAiModel` | DELETED | `4750defb0`; all 14 `inference_provider_e2e` tests green |
-| WP-1 | `inference/provider/legacy_provider.rs` and `compatible` alias | Every OpenAI-compatible slug uses crate `OpenAiModel` | DELETED | #4780/#4782/#4784 plus native wire/SSE parity tests; root check and raw-coverage target compile green |
-| WP-1 | `inference/provider/traits.rs` + tests | No `impl Provider`; remaining host bridge data types live in `provider/types.rs` | DELETED | `rg 'impl Provider' src` empty; factory unit suite 173 passed |
-| WP-1 | `tinyagents/model.rs::ProviderModel` / `MaxTokensModel` | Tier and bespoke models are direct `ChatModel`s | DELETED | `rg ProviderModel src` empty; tinyagents unit suite 127 passed |
-| WP-1 | `tinyagents/convert.rs` message conversion | Runtime uses crate `Message`; durable JSONL/thread DTO conversion belongs beside agent persistence; retain tool-schema conversion until WP-4 | REHOMED | Message adapter and tests moved to `agent/message_convert.rs`; `tinyagents/convert.rs` is tool-schema-only; root check green |
-| WP-1 | `inference/provider/crate_provider.rs` | No legacy `Provider` consumer needs the reverse adapter | DELETED | `rg 'impl Provider' src` empty; root `cargo check --lib` green |
-| WP-1 | `inference/provider/{auth_error_registry,resolved_route,temperature,thread_context}.rs` | Host state/policy lives outside the legacy provider abstraction | REHOMED | `4ce6ca726`, `59871c8ab`, `6cb17f91e`, `07f675ba3`; root `cargo check` and focused auth-registry tests green |
-| WP-2 | `routing/` parallel implementation | Generic decisions use crate `ModelRouter`; no live consumer remained | DELETED | Repository-wide reference audit found the module self-contained; #4783 owns live routing; root check green |
-| WP-2 | `tool_timeout` implementation | No deletion: crate `ToolTimeout` is per-tool metadata, while the host owns global config/env state and enforces the adapter deadline | HOST-OWNED | Execution-path audit; timeout precedence/deadline tests |
-| WP-2 | `model_council/` and `council_registry/` | Crate `parallel::map_reduce` already owned generic ordered fan-out; the product surface had no live consumer | DELETED | Crate-backed execution audit followed by upstream dead-code cleanup |
-| WP-2 | `tool_status/` | OpenHuman security markers, serialized UI/persistence taxonomy, retry categories, and remediation copy | HOST-OWNED | Consumer audit; classifier/type unit tests |
-| WP-3 | legacy `run_turn_engine` and graph escape hatches | All regression assertions exercise the crate turn path | ALREADY DELETED | Audit found no engine definition or runtime env read; session and subagent paths call TinyAgents unconditionally. Removed the stale runner comment. |
-| WP-4 | host tool trait/adapter artifacts selected by design | Approved tool-model decision preserves security and ungated result types | DESIGN GATE | Successor design document |
-| WP-5 | `SchemaGuardMiddleware` | TinyAgents `InvalidArgsPolicy::ReturnToolError` owns recoverable schema-invalid admission | DELETED | Policy regression + 18 `agent_harness_e2e` tests green; 232 net host lines removed in the cutover commit |
-| WP-5 | generic seam middlewares | Equivalent crate middleware released and adopted | PARTIAL | `SchemaGuard` deleted; TinyAgents #72 repeat tracker adopted and host duplicate accounting deleted (51 focused middleware tests green); `ArgRecovery` still awaits TinyAgents #71. Per-middleware drift rows remain authoritative. |
-| WP-5 | detached subagent registry mechanics | Crate `DetachedTaskRegistry` + `TaskStore`/`SteeringRegistry` own generic process-local lifecycle | CLOSED | TinyAgents #75 merged as `d548657` and canonical pointer `4358efe` contains it; OpenHuman commits `3fc769828` + `29908675f`; 17 focused `running_subagents` tests green. Host retains durable projection, product metadata, RPC, and `RunQueue` fallback. |
-| WP-5 | `agent/progress_tracing.rs` and `progress_tracing/langfuse.rs` | C4 S2-S6 gates pass; journal projection is self-sufficient | BLOCKED | One-release shadow parity and C4 §5 gate |
-| WP-5 | `agent/session_db/` (store, run ledger, types) | Generic session history; only host coupling was `config.workspace_dir` | UPSTREAMED | Now `tinyagents::session`; entry points take `&Path`. 34 tests moved intact; DB path and `session_db`/`run_ledger` RPC namespaces unchanged. Host keeps `schemas.rs` only |
-| WP-5 | `agent/harness/session/transcript.rs` | No deletion: durable `session_raw` on-disk format, `.md` companion rendering, display read, and usage rollups are product surface | HOST-OWNED | 2026-07-28 design §4 Option A. `SessionTranscriptHistory` implements crate `ChatHistory` over it, so the harness talks to the trait while OpenHuman owns the format. Zero on-disk change. S4 landed the turn path on OpenHuman-side supertraits (`SessionHistory::append_turn` for writes, `SessionTranscriptRead::read_session` + `SessionHistoryLocator` for reads) — the crate trait cannot carry `request_id`/`turn_usage`/`TranscriptMeta`, nor return `tool_calls` losslessly. Measured ledger ≈ −15/+90 LOC; the spec's "~400 LOC removed" is struck |
-| WP-5 | `agent/harness/session/turn_checkpoint.rs` | No deletion: built on `ChatMessage`, the versioned on-disk record WP-1 settled as host-owned | HOST-OWNED | Replacing it with crate `Message` would change existing users' data. Only design §4 Option B reopens this |
-| WP-5 | #4249 JSONL↔store session mirror — `agent/session_import/live.rs`, `Agent::maybe_shadow_read_session_store` / `maybe_dual_write_session_store` (`session/turn/session_io.rs`), the `StoreRegistry` registration in `agent/tinyagents/mod.rs`, the two `session_dual_write` / `session_shadow_reads` `AgentConfig` flags, and `config/migrations/enable_session_shadow_reads.rs` (~565 prod LOC) | The one genuine parallel session-persistence implementation in the tree, over crate `Store`/`AppendStore` rather than `ChatHistory` | BLOCKED | Gated on #4249's own Phase-2 parity soak (#5396 flipped `session_shadow_reads` default-ON with a config migration). **Not** the 2026-07-28 design's S5 soak — that one compares free-function reads against trait reads. Retire as a #4249 phase-3 item once parity is declared |
-| WP-5 | `agent/harness/session/migration.rs` | No deletion: zero host imports, but migrates *OpenHuman's* layout — hardcodes `session_raw`, `sessions`, `state/migrations/session_layout_v1.done`, keyed to release 0.53.4 | HOST-OWNED | Design §5 S1 check performed, not assumed: generic code for a host-specific format |
-| WP-5 | `agent/harness/subagent_runner/handoff.rs` | Crate `tinyagents::harness::handoff` owns the progressive-disclosure cache, placeholder renderer, and content-hygiene helpers | DELETED | 287 → ~66-line shim re-exporting the crate module under the historical OpenHuman names; zero call-site edits. The host shim resolves `OPENHUMAN_TEST_HANDOFF_THRESHOLD_TOKENS` and passes it as the crate's explicit `threshold_tokens` parameter. Host: `cargo fmt --check`, `cargo check --lib` (product features and `--no-default-features`), 11,622 lib tests green. `vendor/tinyagents`: fmt, `clippy -D warnings`, 1,802 tests green |
-| WP-5 | `inference/provider/types.rs::build_tool_instructions_text` | Crate `tinyagents::harness::tool::prompt_tool_instructions` owns the markdown tool-use instructions block | DELETED | 33 lines removed; one call site (`mcp/server/tools/dispatch.rs`) repointed. Model-facing prompt copy changed two words ("may emit" vs "may use", "After execution" vs "After tool execution"). Host: `cargo fmt --check`, `cargo check --lib` (product features and `--no-default-features`), 11,622 lib tests green. `vendor/tinyagents`: fmt, `clippy -D warnings`, 1,802 tests green |
-| WP-5 | `agent/tinyagents/delegation.rs` | Crate `tinyagents::graph::delegation` owns the generic delegation graph | REHOMED | 1,524 → ~190 lines; ~888 production + ~636 test lines moved to new upstream `graph::delegation`. The host copy was not zero-coupled — it reached `super::observability` by a relative path — so the crate's `DelegationConfig` gained an optional `event_sink`, letting the host wrapper still attach `GraphTracingSink`. Host: `cargo fmt --check`, `cargo check --lib` (product features and `--no-default-features`), 11,622 lib tests green. `vendor/tinyagents`: fmt, `clippy -D warnings`, 1,802 tests green |
-| WP-5 | `agent/orchestration/ops.rs` dead half | Crate `tinyagents::graph::orchestration::DetachedTaskRegistry` owns the live half | DELETED / REHOMED | ~255 dead lines deleted; remainder re-pointed onto the crate registry (697 → 574 lines). Host `AgentStatus` replaced by crate `OrchestrationTaskStatus`; `DomainEvent::AgentOrchestrationClosed` removed as unconstructable (`rg AgentOrchestrationClosed src` empty). Accepted behaviour change: the crate's `wait` prunes terminal entries, so a child can be waited on once. Host: `cargo fmt --check`, `cargo check --lib` (product features and `--no-default-features`), 11,622 lib tests green. `vendor/tinyagents`: fmt, `clippy -D warnings`, 1,802 tests green |
-
-Deletion totals are reconciled in WP-6 after all rows are terminal. The
-original projection is approximately 30k host LOC deleted and 12–15k generic
-LOC upstreamed; measured totals, not the estimate, are authoritative.
diff --git a/docs/tinyagents-full-migration-plan/C4-journal-progress-parity-plan.md b/docs/tinyagents-full-migration-plan/C4-journal-progress-parity-plan.md
deleted file mode 100644
index ee79d7bd5d..0000000000
--- a/docs/tinyagents-full-migration-plan/C4-journal-progress-parity-plan.md
+++ /dev/null
@@ -1,200 +0,0 @@
-# C4 — Journal-backed progress projection & `progress_tracing` deletion
-
-Status: execution plan (2026-07-04), written after a ground-truth code map of
-both the OpenHuman progress surface and the vendored crate observability
-primitives. This is the actionable plan for the C4 workstream's July 2026
-continuation notes, and it is the gated prerequisite for **S6 below** —
-deleting the `ProviderDelta` bridge and `progress_tracing`.
-
-## 1. Corrected architecture (what the map found)
-
-- **There is no crate `SpanCollector`.** The only span state machine is
- OpenHuman's `SpanCollector` in `src/openhuman/agent/progress_tracing.rs`
- (1272 lines). The crate does **not** build spans — it journals raw
- `AgentObservation`s and lets exporters project.
-- **The journal/status/persistence stack already exists and is attached to
- every run.** `run_turn_via_tinyagents_shared`
- (`src/openhuman/agent/tinyagents/mod.rs:420`) mints a run id, seeds the `EventSink`
- with it, and `attach_turn_journal` (`src/openhuman/agent/tinyagents/journal.rs:304`)
- installs `StoreEventJournal` (over `JsonlAppendStore`) via a
- `JournalSink → RedactingSink → FanOutSink`, plus a durable `FileStatusStore`.
- Every run already durably records the crate `AgentEvent` stream as
- `AgentObservation`s.
-- **Two producers of `AgentProgress`:**
- - Crate path: `OpenhumanEventBridge` (`src/openhuman/agent/tinyagents/observability.rs:464`)
- maps `AgentEvent` → `AgentProgress` live (stateful: iteration cursor,
- subagent `scope`, `tool_names` recovery, display labels, failure class).
- - Legacy path: `session/tool_progress.rs` `TurnProgress` +
- `spawn_delta_forwarder` maps engine callbacks + `ProviderDelta` →
- `AgentProgress` (the **Step-5 deletion target**, 253 lines).
-- **`SpanCollector` consumes `AgentProgress`** (the bridge *output*), while the
- journal captures the `AgentEvent` *input*. The web progress bridge
- (`channels/providers/web/progress_bridge.rs:157`) is a side-observer of the
- `AgentProgress` channel: `collector.record(&event, now)` per event, then
- `collector.finish()` + `export_run_trace(config, spans)` at loop exit.
-- **Langfuse is exported twice, in two data models.**
- `progress_tracing/langfuse.rs` (825 lines) hand-rolls a `TraceSpan`→Langfuse
- ingestion batch; the crate `observability/langfuse/` already builds the same
- batch from `&[AgentObservation]` (`LangfuseClient::send_observations`,
- `build_ingestion_batch`). Same proxy path, same `207` handling.
-
-## 2a. BLOCKER found during S1 (2026-07-04): the mapping is not journal-replayable
-
-The S1 attempt to extract a pure `event_to_progress` revealed that the live
-`OpenhumanEventBridge` mapping **depends on live side-channels absent from the
-journal**, so "parity by construction via journal replay" (§2 below) does
-**not** hold as written:
-
-- **`ToolCompleted`** (`observability.rs:745`): the crate event
- `ToolCompleted { call_id, tool_name, started_at_ms, input, output }` carries
- **no outcome**. `success` / `elapsed_ms` / `output_chars` / failure class are
- read from `self.failure_map`, a `call_id → (ok, failure, elapsed, chars)` map
- populated by `ToolOutcomeCaptureMiddleware` — not journalled.
-- **`record_usage`** (`observability.rs:298`): drains `usage_carry` (the model
- adapter's provider `UsageInfo` FIFO) to restore **charged USD**, cache-creation
- and context-window tokens the crate `Usage` drops. Not journalled.
-
-A journal-only projection therefore yields structurally-correct spans with
-**degraded attributes** (assumed-success tools, zero durations/sizes, `$0`
-cost) — which cannot pass the S3/S5 parity gate.
-
-### Corrected prerequisite — S0: make the journal self-sufficient (crate work)
-
-Before any journal projection can hit parity, the enriching data must live in
-the journalled `AgentEvent`s, not in OpenHuman side-channels:
-
-1. **Enrich `AgentEvent::ToolCompleted`** in the crate with the outcome:
- `success: bool`, `duration_ms`, `output_bytes` (and an optional structured
- failure), populated in `tools.rs::finish_tool_call` from the `ToolResult`
- and the `started_at_ms` it already tracks. OpenHuman's bridge then reads them
- from the event; `failure_map`/`ToolOutcomeCaptureMiddleware` shrink to the
- product-specific `ToolFailureClass` mapping (or that too moves onto the
- event). This is a V-series crate PR (additive event fields).
-2. **Usage accounting**: decide whether charged-USD/provider-cost belongs on a
- crate event (e.g. a `provider_cost`/`cache_creation` extension on
- `UsageRecorded`/`Usage`) or stays a documented, accepted OpenHuman-only trace
- attribute filled at export time from the status/cost store rather than the
- live side-channel. (The cost roll-up is already persisted per-run; the trace
- can read it from there instead of `usage_carry`.)
-3. Only after S0 does §2's "reuse the mapping" become true by construction.
-
-**Sequencing impact:** S0 (crate event enrichment) is now the first slice and
-gates S1→S2. It is separate crate work that should be PR'd upstream like V1/V2.
-The remaining S1–S6 below stand, rebased on S0.
-
-## 2. The parity-preserving approach (valid only after S0)
-
-Reproduce the span tree **by construction**, not by re-deriving it:
-
-> Replay journal `AgentObservation`s → `AgentProgress` using the *same* mapping
-> the live bridge uses → fold through the *existing* `SpanCollector`.
-
-Concretely:
-
-1. **Extract the bridge mapping into a pure, reusable function**
- `event_to_progress(event: &AgentEvent, state: &mut BridgeState, scope) -> Vec<AgentProgress>`
- (state = iteration cursor + `tool_names` + scope). The live
- `OpenhumanEventBridge::on_event` becomes a thin driver over it (refactor, **no
- behavior change** — guarded by the existing bridge tests). This makes the
- AgentEvent→AgentProgress mapping a single source of truth.
-2. **Journal projection**
- `spans_from_observations(ctx: TraceContext, obs: &[AgentObservation]) -> Vec<TraceSpan>`:
- fold each observation through `event_to_progress` into `AgentProgress`, feed a
- fresh `SpanCollector::record(...)` stamped with `obs.ts_ms`, then `finish()`.
- Because it reuses `SpanCollector`, span-shape parity is guaranteed for every
- `AgentProgress` variant the journal can produce.
-3. **Parity harness** (`progress_tracing`'s `tests.rs` is the oracle): drive a
- representative synthetic run and assert
- `spans_from_observations(journal)` == `SpanCollector` fed the live
- `AgentProgress`. Cover: multi-iteration turn, tool calls (success + failed +
- unknown-tool recovery), model-call generation spans w/ usage & reasoning &
- cache-creation, nested sub-agents, cost roll-up.
-
-### Parity gaps to resolve (AgentProgress with no journal `AgentEvent` source)
-
-`SpanCollector` ignores streaming/content deltas for spans
-(`progress_tracing.rs:1076`), so `TextDelta`/`ThinkingDelta`/`ToolCallArgsDelta`
-**do not affect span parity** — safe to drop on replay. The variants that *do*
-carry span data but have no direct `AgentEvent`:
-
-| AgentProgress | Span effect | Journal source | Resolution |
-| --- | --- | --- | --- |
-| `TurnContent{prompt, reply}` | root span `input`/`output` (gated on `capture_content`) | `ModelCompleted.input/output` present in journal but shaped differently | project root i/o from `ModelStarted`/`ModelCompleted` payloads, or emit a journalled content event |
-| `TaskBoardUpdated` | none (no span) | n/a | ignore for spans |
-| `SubagentAwaitingUser` | subagent span attr | partial (`SubAgentStarted/Completed` only) | accept minor attr gap or add a crate event (V6) |
-| `TurnCostUpdated` | root usage roll-up | `UsageRecorded`/`CostRecorded` in journal | project from those (already in bridge) |
-
-Document any accepted gap in the parity test as an explicit, reviewed
-exception.
-
-## 3. Langfuse swap (separable, lower-risk slice)
-
-Replace `progress_tracing/langfuse.rs::push_spans` with the crate
-`LangfuseClient::proxy(...).send_observations(trace_cfg, &obs)` reading the run's
-journal. Parity test: assert the crate batch matches the existing batch shape
-for a fixture run (trace-create + per-observation generation/span/event,
-`usageDetails`/`costDetails`, `207` handling, content gating from
-`agent_tracing.capture_content`). This deletes ~825 lines independently of the
-span-projection slice.
-
-## 4. Sequenced slices (each: code + tests + green build; deletions gated)
-
-0. **S0 — enrich crate `AgentEvent::ToolCompleted`** with `duration_ms` /
- `output_bytes` / `error` so the journal is self-sufficient for tool outcomes
- (§2a). **DONE** — tinyagents#18 (branch `feat/tool-completed-outcome`,
- 933 tests green). Also enriches the crate Langfuse tool span. Merge + gitlink
- bump precede S1. (Usage/charged-USD accounting — §2a item 2 — is still open:
- fill it at export time from the persisted per-run cost store rather than the
- `usage_carry` side-channel.)
-1. **S1 — extract `event_to_progress`** (pure mapping) + make the live bridge a
- driver over it. No behavior change; existing bridge/`observability` tests are
- the gate. *No deletion.*
-2. **S2 — `spans_from_observations`** journal projection + parity harness vs
- `SpanCollector`. **IN PROGRESS** — additive projection module now covers the
- single-agent spine, S0 tool outcomes, root `TurnContent` from captured model
- I/O, and sub-agent lifecycle/scoped child tool/model spans. Remaining known
- gap: per-call charged USD/cache-creation is still zero until export-time cost
- store reconciliation lands.
-3. **S3 — flip the web progress bridge** to build spans from the journal at run
- end (`spans_from_observations`) instead of the live `AgentProgress`
- side-observer; keep the old path behind a shadow-compare for one release
- (log divergences), matching the C1 `session_shadow_reads` pattern. **STARTED**
- — the web bridge now keeps live export as-is and logs a structural
- journal-projection shadow comparison keyed by the durable journal run id.
-4. **S4 — Langfuse swap** to the crate exporter (§3). **STARTED** — when the
- web bridge can read a durable run journal for S3 shadow comparison, the
- remote `share_usage_data` push now sends those `AgentObservation`s through
- the crate `LangfuseClient`; live spans remain the local tracing sink and
- fallback until S3 shadow parity is release-proven. The OpenHuman wrapper also
- injects aggregate `run.total` usage/cost from the durable run ledger so
- journal-backed Langfuse export preserves the top-level cost signal while
- per-call charged USD awaits a journal-native event. Later delete
- `progress_tracing/langfuse.rs` (~825 + tests).
-5. **S5 — delete `progress_tracing.rs` + `SpanCollector`** once S3 shadow shows
- no divergence for one release **and** journal projection parity holds (the
- §5 gate). Tick the deletion ledger (~2k incl. tests).
-6. **S6 (= V3 Step 5)** — with `AgentProgress` now a journal projection, delete
- the legacy `ProviderDelta` bridge in `session/tool_progress.rs` (253) and the
- `spawn_delta_forwarder`, since the crate event path is the only producer.
-
-## 5. Gates
-
-- `progress_tracing` delete: **C4 shadow parity (S3) for one release AND V3
- projection parity.** Langfuse (S4) may land earlier (independent shape parity).
-- Approval/security/redaction boundaries unchanged: the journal path already
- runs through `RedactingSink` (`journal.rs:327`); the projection must not
- re-introduce raw prompt/PII into spans beyond what `capture_content` already
- gates.
-
-## 6. Key file references
-
-Producer/bridge: `tinyagents/observability.rs:464` (`OpenhumanEventBridge`),
-`tinyagents/journal.rs:304` (`attach_turn_journal`), `tinyagents/mod.rs:420`
-(`run_turn_via_tinyagents_shared`). Span machine:
-`agent/progress_tracing.rs` (`SpanCollector:307`, `record:686`, `finish:1087`,
-`export_run_trace:1254`), driven at
-`channels/providers/web/progress_bridge.rs:157`. Crate foundation:
-`harness/observability/{mod,types}.rs` (`HarnessEventJournal:156`,
-`StoreEventJournal`, `JournalSink:581`, `AgentObservation:40`),
-`harness/observability/langfuse/`. Parity oracle:
-`agent/progress_tracing/tests.rs` (1169 lines).
diff --git a/docs/tinyagents-inference-migration-plan.md b/docs/tinyagents-inference-migration-plan.md
deleted file mode 100644
index 56502a267e..0000000000
--- a/docs/tinyagents-inference-migration-plan.md
+++ /dev/null
@@ -1,172 +0,0 @@
-# Migrating `src/openhuman/inference/` onto `vendor/tinyagents/`
-
-**Status:** superseded on 2026-07-22 by
-[`tinyagents-migration-plan-2026-07-22.md`](tinyagents-migration-plan-2026-07-22.md).
-This document is retained as historical model-layer design detail; its pins,
-status, and present-tense inventory are not current.
-**Relates to:** #4249 (tinyagents migration),
-`docs/tinyagents-migration-plan-2026-07-22.md`,
-`docs/tinyagents-full-migration-plan/`, and
-`docs/tinyagents-drift-ledger.md`.
-**tinyagents audit anchor:** 1.7.1. See the superseding plan for the active pin.
-
----
-
-## 1. Why
-
-The agent loop already runs on tinyagents; `run_turn_via_tinyagents_shared` drives every turn. But the **model layer underneath it is still entirely in-house**: the harness reaches a crate `ChatModel` only through the `ProviderModel` adapter (`src/openhuman/agent/tinyagents/model.rs`), which wraps openhuman's own `Box<dyn Provider>` stack from `src/openhuman/inference/provider/` — ~29.6k lines that re-implement what tinyagents 1.7 now ships natively:
-
-| openhuman (`inference/provider/`, etc.) | tinyagents 1.7 equivalent |
-| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
-| `Provider` trait, `ChatMessage`/`ChatRequest`/`ChatResponse`/`ProviderDelta` (`traits.rs`) | `harness::model::{ChatModel, ModelRequest, ModelResponse, ModelStream, ModelStreamItem}` + `harness::message::*` |
-| `compatible*.rs` (~15 files: OpenAI-compat client, SSE streaming, parse, dump, repeat, timeout) | `harness::providers::openai` (convert / sse / transport / types) — serves every OpenAI-compatible endpoint |
-| `reliable.rs` retry/backoff wrapper | `harness::retry::{RetryPolicy, FallbackPolicy, RateLimiter, is_retryable}` |
-| `router.rs` `RouterProvider` hint-table multi-model routing | `harness::model::ModelRegistry` (per-depth model resolution) |
-| `model_context.rs` context-window table | `MODEL_CONTEXT_PATTERNS` fallback + `registry::ModelCatalog` (offline snapshot: windows, pricing, capability flags) |
-| `error_classify.rs` / `error_code.rs` (retryability, HTTP status parsing) | `harness::retry::is_retryable` + `harness::model::ProviderError` |
-| provider-string → provider construction (`factory.rs`, partially) | `harness::providers::{ProviderKind, ProviderSpec}` factory (`ProviderKind::infer`, `Compatible`) |
-| embeddings dispatch (`ops.rs` → local/cloud) | `harness::embeddings` traits (+ openai impl) |
-| `provider/openai_codex.rs`, `openhuman_backend.rs`, `claude_agent_sdk/` | no equivalent — stay as host `ChatModel` impls |
-
-Maintaining both stacks means every fix (streaming edge case, retry policy, context-window entry, provider quirk) lands twice, and the adapter seam (`ProviderModel` + `ThinkingForwarder` + usage-carry plumbing) exists only to translate between two isomorphic type systems. Since `vendor/tinyagents` is our own crate (same GPL-3.0 license, same org), host-agnostic gaps get **upstreamed into the crate**; only genuinely openhuman-specific glue stays.
-
-**End state:** the crate's `ChatModel`/`ModelRequest` is the native model interface everywhere in openhuman; `inference/` keeps only host concerns (RPC surface, config, local runtime management, voice, OAuth, `/v1` endpoint); `ProviderModel` and the entire `Provider` trait stack are deleted.
-
-### Blast radius
-
-- 170 files outside `inference/` import `openhuman::inference`; 151 import `inference::provider` specifically. Top consumers: agent harness/session/tools/triage, `context`, `voice`, `routing`, `memory_tree`, `learning`, `channels`, `embeddings`, `subconscious`, `threads`, `migrations`, `config/schema`.
-- Module sizes: `provider/` ≈ 29.6k lines, `local/` ≈ 13.7k, `voice/` + `http/` + `openai_oauth/` ≈ 4.4k, root files ≈ 5.5k. Only `provider/` + parts of the root files migrate; the rest stays.
-
----
-
-## 2. Disposition map
-
-### Migrates (replaced by crate, or upstreamed into crate)
-
-| Component | Destination | Notes |
-| --- | --- | --- |
-| `provider/traits.rs` — `Provider` trait + request/response/delta types | **delete**, use crate `ChatModel` + message types | The big inversion (Phase 1). `UsageInfo` → crate `Usage` (see gap G1 on USD/cached tokens). |
-| `provider/compatible*.rs` — OpenAI-compat client | **delete**, use crate `providers::openai` | Gap audit first (Phase 2): request-dump debugging, repeat-detection, per-request timeout, BYOK auth styles. |
-| `provider/reliable.rs` | **delete**, use crate `RetryPolicy` (+ `FallbackPolicy`) | Also resolves the known double-retry (reliable.rs *and* harness-level retry both fire today). |
-| `provider/router.rs` (`RouterProvider`) | **delete**, use crate `ModelRegistry` | Hint table (`reasoning-v1`, `agentic-v1`, …) becomes registry aliases. |
-| `model_context.rs` (`context_window_for_model`) | **upstream** entries into crate `ModelCatalog` snapshot / `MODEL_CONTEXT_PATTERNS`; host keeps a thin lookup that prefers config overrides | Crate catalog also carries pricing + capability flags — feeds the cost tracker. |
-| `provider/error_classify.rs`, `error_code.rs` | **delete**, use crate `is_retryable` / `ProviderError` | Upstream any status-classification the crate misses. |
-| `provider/temperature.rs` (`@<temp>` suffix) | host parses the suffix in the factory; value rides `ModelRequest` params | Grammar stays host-side; the plumbing type goes away. |
-| `provider/config_rejection.rs`, `billing_error.rs` | **split**: generic classification upstreamed as crate error kinds; openhuman semantics (Sentry demotion, budget messaging) stay as a host classifier over `TinyAgentsError` | |
-| `provider/factory.rs` | **shrinks, stays**: resolves openhuman provider strings (`openhuman`, `cloud`, `ollama:<model>`, `<slug>:<model>[@temp]`) + config + credentials → crate `ProviderSpec`/`Arc<dyn ChatModel>` | This is the host↔crate boundary after migration. `BYOK_INCOMPLETE_SENTINEL` stays. |
-| `provider/ops.rs` (`list_configured_models`, SessionExpired publishing) | **stays**, retargeted to crate types | SessionExpired needs an auth-failure signal from the crate client (gap G3). |
-| embeddings dispatch | crate `harness::embeddings` traits (seam `tinyagents/embeddings.rs` already exists — finish it) | Local (Ollama) embedding stays a host impl of the crate trait. |
-| `provider/thread_context.rs`, `resolved_route.rs`, `auth_error_registry.rs` | **re-home** into `src/openhuman/agent/tinyagents/` (they're seam concerns, not provider concerns) | `thread_context` task-locals already consumed by `model.rs`. |
-
-### Stays in `inference/` (host concerns, out of scope for the crate)
-
-- **RPC surface**: `schemas.rs`, `ops.rs`, `local/schemas.rs` — all `inference.*` controllers, legacy aliases.
-- **Local runtime management** (`local/`): Ollama/LM Studio detect/spawn/adopt, Whisper/Piper install, download progress, model artifacts, context floor. The *chat client* to Ollama/LM Studio migrates to crate `ProviderKind::Ollama`/`Compatible`; process lifecycle stays.
-- **`voice/`**: STT/TTS inference impls (whisper-cpp bindings, Piper) — not LLM-shaped; unchanged.
-- **`openai_oauth/`**: Codex OAuth PKCE + encrypted token store (credentials domain integration).
-- **`http/`**: the `/v1/chat/completions` OpenAI-compat *server* endpoint. (Later option: crate 1.3+ has OpenAI-compat runtime model listing; revisit after Phase 5.)
-- **`device.rs`, `presets.rs`, `model_ids.rs`, `paths.rs`, `parse.rs`**: hardware profiles, preset tiers, config-derived model-id resolution, artifact paths.
-- **`sentiment.rs`**: stays as a host op, but its model call is rewritten onto `ChatModel` (+ crate structured output) in Phase 6.
-- **Bespoke providers** (`openhuman_backend.rs` session-JWT managed backend, `claude_agent_sdk/` subprocess, `openai_codex.rs` OAuth-token compat variant): stay in-repo, reimplemented as crate `ChatModel` impls (Phase 4).
-
----
-
-## 3. Known crate gaps to close first (upstream work in `vendor/tinyagents`)
-
-Verified against 1.7.1 source; re-audit at Phase 0 since the crate moves fast.
-
-- **G1 — Usage fidelity**: crate `Usage` has no `charged_amount_usd` and needs verifying for cache-read/cache-write token fields. The $0-cost-turn bug (fixed host-side via `cost::catalog::estimate_cost_usd`) shows exactly what breaks when this is lossy. Either upstream optional cost/cached fields on `Usage`, or keep host-side estimation keyed off the crate `ModelCatalog` pricing.
-- **G2 — Tool-call start metadata**: crate `ToolDelta` carries `call_id`/`content` but no `tool_name`; the UI timeline's tool-start event is still forwarded out-of-band (`model.rs` forwarder). Upstream `tool_name` on the first `ToolDelta` (or a dedicated start item) so the forwarder can die with `ProviderModel`.
-- **G3 — Auth-failure signal**: openhuman publishes `DomainEvent::SessionExpired` when a chat attempt fails auth. The crate client must classify 401/expired distinctly (as a `ProviderError` kind) so the host factory can hook it without string-sniffing.
-- **G4 — Request dump / wire observability**: `compatible_dump.rs` writes raw request/response dumps for debugging. Upstream a transport-level hook (or confirm the crate's observability exporters cover it) before deleting.
-- **G5 — Per-request timeout policy**: `compatible_timeout.rs` semantics vs. what the crate transport exposes. Upstream a per-call timeout on `ModelRequest`/`ProviderSpec` if missing.
-- **G6 — BYOK auth styles**: the authoritative provider catalog
- (`src/openhuman/config/schema/cloud_providers.rs`) supports multiple
- `AuthStyle`s (headers etc.). Confirm crate `ProviderSpec` can express every
- style in the catalog; upstream what's missing.
-- **G7 — Repeat-output guard**: `compatible_repeat.rs` (degenerate-repetition detection). Decide: upstream as an optional stream guard, or accept the loss (note #4463 already tracks deleted repeat guards).
-
-Upstream flow: change in `vendor/tinyagents` (submodule working tree) → PR to `tinyhumansai/tinyagents` → publish → bump the crates.io pin in **both** Cargo worlds (root + `app/src-tauri`) and the submodule ref in lockstep. Nothing in openhuman may depend on unpublished vendored-only API at a merge point.
-
----
-
-## 4. Phases
-
-Each phase compiles green in both Cargo worlds, keeps ≥80% diff coverage, and lands as its own PR-sized slice. Provider-string grammar, RPC names, and observable UI behavior (streaming, cost footer, tool timeline) are parity-locked throughout.
-
-### Phase 0 — Inventory & gap re-audit
-- Enumerate every consumer of `Provider` / `ChatRequest` / `ChatResponse` / `ChatMessage` outside `inference/` (151 files) and bucket them: (a) goes through the seam already, (b) direct one-shot `provider.chat(...)` callers (learning, memory, subconscious, sentiment, triage…), (c) type-only imports.
-- Re-verify §3 gaps against current crate HEAD; file crate issues; update
- `vendor/tinyagents/docs/sdk-gaps.md`.
-- Golden-transcript capture: record request/response wire dumps for the BYOK catalog matrix + Ollama + openhuman backend on the current stack, as fixtures for Phase 2 parity.
-
-**Exit:** disposition table confirmed per-file; crate gap PRs filed.
-
-### Phase 1 — Model-layer inversion (the pivot)
-- Introduce `create_chat_model(...) -> Arc<dyn ChatModel>` in `factory.rs` alongside `create_chat_provider`, initially wrapping the existing stack via `ProviderModel` (zero behavior change).
-- Migrate consumers bucket-by-bucket from `Box<dyn Provider>` to `Arc<dyn ChatModel>`: one-shot callers first (they use `chat()` once — mechanical: `ChatRequest` → `ModelRequest::new(...)`), then the seam (`run_turn_via_tinyagents_shared` takes the model directly — delete the wrap at the call sites), then streaming consumers.
-- Keep a temporary reverse adapter (`ChatModel` → `Provider`) only if a consumer can't move in one slice; delete it before phase exit.
-
-**Exit:** no caller outside `inference/provider/` names the `Provider` trait; `ProviderModel` is constructed in exactly one place (factory).
-
-### Phase 2 — OpenAI-compatible client swap
-- Behind the factory, construct crate `providers::openai` clients (via `ProviderSpec`) instead of `CompatibleProvider` for: BYOK slugs, Ollama, LM Studio, the `cloud` slug.
-- Parity-test against Phase 0 golden dumps: request shape (tools JSON, temperature, multimodal blocks), SSE streaming (text, reasoning, tool-arg deltas), usage extraction, error mapping. Note recent regression surface: tool-calling defaults to JSON with P-Format opt-in (9b84f9684) — the crate path must honor the same default.
-- Delete `compatible*.rs` (15 files, the bulk of the 29.6k lines) once all construction sites are switched.
-
-**Exit:** no `compatible*.rs` left; wire parity fixtures green; `pnpm test:rust` + `json_rpc_e2e` green.
-
-### Phase 3 — Reliability, routing, model metadata
-- Replace `ReliableProvider` layering (`session/builder/factory.rs` re-layered it in the P1 parity fix) with crate `RetryPolicy` at the client level; audit and remove the double-retry.
-- Replace `RouterProvider` with `ModelRegistry`: abstract tier names (`reasoning-v1`, `coding-v1`, …) become registry entries resolved per call; `provider_for_role`/workload resolution feeds the registry instead of building a router provider.
-- Upstream openhuman's context-window table entries into the crate `ModelCatalog` snapshot; `context_window_for_model` becomes a host shim: config override → catalog → crate pattern fallback. Wire catalog pricing into `cost::catalog` (replacing the hand-rolled rate table, or seeding it).
-
-**Exit:** `reliable.rs`, `router.rs`, `model_context.rs` deleted; retry fires exactly once per layer by design.
-
-### Phase 4 — Bespoke providers as `ChatModel` impls
-- Rewrite `openhuman_backend.rs` (managed backend, session JWT + SessionExpired publishing via G3), `openai_codex.rs` (Codex OAuth token source over the crate openai client), and `claude_agent_sdk/` (subprocess protocol) as direct `ChatModel` implementations in their current homes.
-- Local runtime: `local/` keeps process lifecycle; its chat/vision/embed entrypoints call crate clients pointed at the local base URL.
-
-**Exit:** `Provider` trait has zero implementations → delete `traits.rs` and the trait itself.
-
-### Phase 5 — Seam shrink
-- Delete `ProviderModel`, `ThinkingForwarder` remnants, `ProviderUsageCarry`, and the `ChatMessage`↔crate-message conversion layer in `tinyagents/convert.rs` (the harness now receives crate types natively).
-- Re-home `thread_context.rs` / `resolved_route.rs` / `auth_error_registry.rs` into `src/openhuman/agent/tinyagents/`.
-- `inference/provider/` collapses to: `factory.rs` (string grammar → `ChatModel`), bespoke impls, host error classifier, `ops.rs`, `schemas.rs`.
-
-**Exit:** `src/openhuman/agent/tinyagents/model.rs` deleted; adapter inventory test updated.
-
-### Phase 6 — One-shot inference ops onto the crate
-- `sentiment.rs`, `should_react`, `summarize`, vision prompts, triage-style single calls: rewrite onto `ChatModel` + crate structured output (`harness/structured`) instead of hand-rolled parse (`parse.rs` shrinks or dies).
-- Embeddings: finish `tinyagents/embeddings.rs` — cloud via crate openai embeddings, local as a host impl of the crate trait; `LocalAiEmbeddingResult` maps from crate types.
-
-**Exit:** no ad-hoc prompt/parse loops outside the crate surface.
-
-### Phase 7 — Cleanup, docs, deletion ledger
-- Update `inference/README.md`,
- `gitbooks/developing/architecture/agent-harness.md`, and the authoritative
- provider catalog in `src/openhuman/config/schema/cloud_providers.rs`; add
- deletions to `docs/tinyagents-full-migration-plan/99-deletion-ledger.md`;
- refresh `docs/tinyagents-drift-ledger.md`.
-- Remove dead re-exports from `inference/mod.rs`; keep temporary `pub use` shims only where a follow-up PR is already open.
-- Sweep for stale doc-comments naming `Provider`/`CompatibleProvider`.
-
----
-
-## 5. Risks & gotchas
-
-- **Wire-format regressions are silent until a provider hiccups.** The compat client encodes years of quirk handling (SSE edge cases, malformed tool-arg fragments, providers that omit usage). Mitigation: Phase 0 golden dumps + per-provider live smoke tests gated on env keys, run against the real BYOK matrix before each deletion.
-- **Cost accounting**: the event bridge + `record_unobserved_turn_usage` fallback were hard-won ($0-turn bug). Any `Usage` shape change must keep cached-token and USD flow intact end-to-end (dashboard + footer).
-- **Streaming UI parity**: tool-start events (G2) and post-hoc reasoning still ride the out-of-band forwarder; deleting it before the crate gap closes breaks the tool timeline.
-- **Two Cargo worlds**: root and `app/src-tauri` pin tinyagents independently — every crate bump lands in both lockfiles plus the submodule ref, same commit.
-- **Vendored-crate discipline**: the path patch means local vendor edits silently take effect; CI and other clones need the submodule at the matching ref. Never merge openhuman code that requires unpublished crate API.
-- **Sentry noise contract**: `ops.rs` deliberately demotes provider/user-config failures to `warn!`. The new host classifier over `TinyAgentsError` must preserve `expected_error_kind` behavior or Sentry floods.
-- **Test serialization**: everything runs under `inference_test_guard()` (process-global mutex over the runtime singleton + config); new tests must too.
-- **Open regressions in the same area** (#4451–#4469, esp. #4460 streamed calls losing thread_id task-locals, #4463 repeat guards): coordinate so this migration doesn't re-break or mask those fixes; thread-context task-locals move in Phase 5 — verify #4460's fix survives the re-home.
-- **`/v1` server endpoint** reuses provider types for its request/response DTOs (`http/types.rs`) — it must keep its external wire shape while internals switch to crate types.
-
-## 6. Explicit non-goals
-
-- No change to the `inference.*` RPC surface, provider-string grammar, or the Settings > AI preset catalog UX.
-- No migration of `local/` process management, `voice/` STT/TTS engines, `openai_oauth/` flows, or `device`/`presets`/`paths` — they are not LLM-driven in the crate's sense.
-- No sub-agent execution changes (P5 of the harness migration already declined crate `SubAgentTool`).
diff --git a/docs/tinyagents-migration-plan-2026-07-22.md b/docs/tinyagents-migration-plan-2026-07-22.md
deleted file mode 100644
index 5efc5d1e59..0000000000
--- a/docs/tinyagents-migration-plan-2026-07-22.md
+++ /dev/null
@@ -1,492 +0,0 @@
-# TinyAgents Migration — Current-State Audit & Consolidated Plan (2026-07-22)
-
-**Status:** audit + plan (supersedes the stale status/phasing in
-`tinyagents-port-plan.md`, `tinyagents-inference-migration-plan.md`, and
-`tinyagents-phase3-router-registry-design.md`; the drift ledger
-`tinyagents-drift-ledger.md` remains the row-level ledger but its anchors are
-behind — see §2).
-**Scope:** move the remaining generic inference + agent-framework code from
-`src/openhuman/` down into the vendored `tinyagents` crate
-(`vendor/tinyagents`), delete the in-tree duplicates, migrate/retire the
-affected tests, and clean up every dangling doc/code reference left behind by
-earlier phases.
-**Method:** fresh four-way audit of (1) the crate surface, (2)
-`src/openhuman/inference/`, (3) the agent domains + the
-`src/openhuman/agent/tinyagents/` seam, (4) the existing docs/tests — all against the
-working tree at `main` (`5b8a9f269`, 2026-07-22).
-
-**Execution status:** active on `feat/tinyagents-provider-cleanup`.
-WP-0 discovered and corrected an additional cross-crate constraint: once the
-vendored manifest honestly reports 2.1, `tinyflows` must also require
-TinyAgents 2.1 or Cargo resolves a second 1.9 copy and splits trait identity.
-The deletion ledger is
-[`tinyagents-full-migration-plan/99-deletion-ledger.md`](tinyagents-full-migration-plan/99-deletion-ledger.md).
-
----
-
-## 1. Executive summary
-
-The migration is **much further along than any existing doc records**, and the
-remaining work is now well-bounded:
-
-- The agent loop has run on `tinyagents` since #4249/#4399; the drift ledger's
- Phase 0 rows are all CLOSED and Phase 1 is mostly closed.
-- Since the docs were last touched, PRs **#4769, #4780, #4782, #4783, #4784**
- landed the model-layer inversion: the managed backend, wire-equivalent BYOK
- slugs, and openai/codex/custom slugs are all crate-native `ChatModel`s; the
- crate `ModelRouter` is adopted; and **`compatible*.rs` is already deleted**
- (collapsed into a single `legacy_provider.rs` facade).
-- What remains falls into six work packages (§5): finish the model-layer
- cutover and delete the legacy `Provider` stack (~9–10k LOC); record that the
- legacy `run_turn_engine` was already retired; consolidate `routing/`, `tool_timeout/`,
- `tool_status/`, `model_council/` onto crate primitives; reconcile the tool
- model (the one genuinely design-gated package); shrink the seam; and a
- housekeeping package (version-pin reconciliation + broken-link cleanup) that
- should go **first** because the current pin state is misleading.
-
-Nothing in this plan touches the CEF shell, the frontend, or the compile-time
-feature gates; the crate stays impossible to gate away (26+ domains consume it).
-
----
-
-## 2. Ground truth: version pins (WP-0 reconciled)
-
-| Fact | Value | Where |
-| --- | --- | --- |
-| Host requirement | `tinyagents = { version = "2.1", features = ["sqlite"] }` | root `Cargo.toml:107` |
-| Path override | `[patch.crates-io] tinyagents = { path = "vendor/tinyagents" }` | `Cargo.toml:677` |
-| Historical fork patch | Removed in WP-0; TinyCortex now declares crates.io `2.1`, so the existing host path patch unifies its dependency too | root and Tauri manifests; TinyCortex #121 |
-| Vendored crate | `version = "2.1.0"`, tag `v2.1.0` / `2583fcc`, edition 2024, GPL-3.0-only | `vendor/tinyagents/Cargo.toml`, gitlink |
-| Included since the audit | `bytes` bump (#59), **`BarrierRelief` graph fan-in primitive (#62)**, v2.0/v2.1 release commits | submodule history |
-| TinyFlows requirement | `tinyagents = "2.1"`; prevents Cargo resolving a second 1.9 crate | `vendor/tinyflows/Cargo.toml` |
-| TinyCortex requirement | `tinyagents = "2.1"`; its repo-local patch serves standalone development while host patches select the canonical copy | `vendor/tinycortex/Cargo.toml` |
-| Drift ledger | Current pin `v2.1.0` / `2583fcc` | `docs/tinyagents-drift-ledger.md` §Anchors |
-
-WP-0 bumped the gitlink to the released v2.1.0 manifest, regenerated both Cargo
-worlds, removed the unused fork-source patch, and aligned TinyFlows and
-TinyCortex to 2.1. Before those transitive alignments, correct dependency
-resolution introduced separate TinyAgents 1.9 and nested-path 2.0 packages;
-the lockfiles now prove the root, TinyFlows, and TinyCortex all use the one
-vendored 2.1 package.
-
----
-
-## 3. What the crate ships (v2.1.0)
-
-Full module map from the crate audit; the items relevant to the remaining work:
-
-- **Model layer:** `harness::model::{ChatModel<State>, ModelRegistry, ProviderError}`
- (`vendor/tinyagents/src/harness/model/types.rs:524,563,450`),
- `MODEL_CONTEXT_PATTERNS` context-window table (`model/mod.rs:51`).
-- **OpenAI-compatible client:** `harness::providers::openai::{OpenAiModel, AuthStyle,
- ReasoningTagExtraction}` with SSE streaming, the `/v1/responses` API + codex
- knobs (#51), configurable auth styles/static headers (#44), temperature
- suppression (#47), `merge_system_into_user` (#48), prompt-guided tool calling
- for non-native models (#55), stream→JSON fallback (#56), and the whole #57
- local-model hardening wave (inline `<think>` extraction, 400-degrade of
- `tool_choice`/`json_object`, malformed tool-call recovery). This is the
- replacement for everything `legacy_provider.rs` still does.
-- **Retry/fallback/error classification:** `harness::retry::{RetryPolicy,
- FallbackPolicy, ProviderFailureClass, classify_provider_failure, is_retryable}`
- (`harness/retry/types.rs:28`, `retry/mod.rs:170,396`) — already wired into the
- crate's transport and SSE paths.
-- **Routing:** `registry::router::{ModelRouter, WorkloadRoute}` (#54) — adopted
- host-side by #4783; plus `registry::catalog::ModelCatalog` (windows, pricing,
- capability flags, offline snapshot at
- `docs/modules/registry/model-catalog.snapshot.json`).
-- **Tools:** `harness::tool::{Tool<State>, ToolSchema}` + schema validation
- (`harness/tool/types.rs:344`, `tool/schema.rs`), `ToolTimeout`, tool-policy
- middleware (`harness/middleware/library/tool_policy.rs`).
-- **Subagents/orchestration:** `harness::subagent::{SubAgent, SubAgentSession,
- SubAgentTool}`, `graph::orchestration::{TaskStore, SteeringRegistry,
- OrchestrationTool, InMemoryTaskStore, JsonlTaskStore}`,
- `graph::subagent_node`, `graph::parallel::map_reduce`, and (post-bump)
- `BarrierRelief` fan-in.
-- **Embeddings:** provider implementations ported at HEAD (#58 — `openai`,
- `cohere`, `voyage`, `ollama`, `cloud`, rate-limit/retry-after helpers).
-- **Observability:** harness + graph journals/status stores, `JsonlSink`,
- `RedactingSink`, Langfuse client with nested run trees (#53).
-- **Also present:** summarization (`Summarizer`, `CompressionFailurePolicy`),
- steering, workspace isolation, response cache, cost/usage accounting
- (parses `cached_tokens`), graph checkpointing (SQLite via the `sqlite`
- feature the host enables), and offline `MockModel`/testkit conventions.
-
-~25 public traits are the extension points; the seam already implements 11 of
-them (§4.3).
-
----
-
-## 4. Audit: what remains host-side
-
-### 4.1 `src/openhuman/inference/` — 112 files, ~46.5k LOC
-
-The model-layer inversion (#4727 "Motion B") is scaffolded and mostly cut over,
-but the legacy `Provider` stack is still present and **still the default
-construction path** in places:
-
-**Still-duplicating cluster (delete in WP-1):**
-
-| File | LOC | State |
-| --- | --- | --- |
-| `provider/traits.rs` (+`traits_tests.rs`) | 779 + 501 | The `Provider` trait + `ChatMessage`/`ChatRequest`/`ChatResponse`/`ProviderDelta`/`UsageInfo`. Still central; ~10 impls remain. |
-| `provider/reliable.rs` (+`reliable_tests.rs`) | 952 + 1,228 | Retry/backoff `Provider` wrapper. Crate `RetryPolicy` covers it; the interactive turn path already stopped wrapping in `ReliableProvider` (`tinyagents/mod.rs:122`). |
-| `provider/router.rs` (+`router_tests.rs`) | 310 + 524 | `RouterProvider` hint-table routing. Crate `ModelRouter` adopted by #4783; this is the residual legacy path. |
-| `provider/legacy_provider.rs` | 343 | The collapsed remnant of the 15 `compatible*.rs` files (`provider/mod.rs:14` aliases `pub use legacy_provider as compatible;`). Superseded by crate `OpenAiModel` once WP-1 flips the default. |
-| `provider/error_classify.rs` + `error_code.rs` | 1,001 + 349 | Split (WP-1): generic retryability/status classification → crate `classify_provider_failure`; openhuman semantics (Sentry demotion, budget messaging, `config_rejection.rs`, `billing_error.rs`) stay as a host classifier layered on crate errors. |
-| `provider/crate_provider.rs` | 327 | `CrateBackedProvider` — the **temporary reverse adapter** (crate `ChatModel` → legacy `Provider`). Deleted last, when no consumer needs `Provider`. |
-
-**Crate-native scaffolding already in place (finish in WP-1):**
-
-- `provider/crate_openai.rs` (347) — host `AuthStyle` → crate `OpenAiModel`
- builder; self-described "**Status: scaffolding**" — complete and unit-tested
- but **not yet the factory default**. Flipping it (with per-provider wire
- parity validation) is the gating step.
-- `provider/openhuman_backend_model.rs` (325) — managed backend as crate
- `ChatModel` (cut over; coexists with the legacy `openhuman_backend.rs` twin,
- which can go once nothing constructs it).
-- `provider/factory.rs` (2,850) — the host↔crate boundary; already returns
- `Arc<dyn ChatModel<()>>` via `create_chat_model*`, but bespoke slugs still
- route "→ a `ProviderModel` over the host provider" (`factory.rs:1458-1511`).
-- `model_context.rs` — already falls through to the crate table
- (`context_window_for_model_id`, `model_context.rs:77`); keeps host config
- overrides. Done; keep the thin shim.
-- `ops.rs`, `local/ops.rs`, `http/server.rs` already build crate
- `ModelRequest`/`Message` types.
-
-**Seam concerns mis-housed under `provider/` (re-home in WP-1):**
-`temperature.rs` (261), `thread_context.rs` (120), `resolved_route.rs` (113),
-`auth_error_registry.rs` (166).
-
-**Host-owned, stays (no action):** all of `local/` (~14k — Ollama/LM Studio/
-Whisper/Piper runtime + installers + service admin), `voice/` (~2.4k),
-`openai_oauth/` (~1.5k), `http/` (0.7k `/v1` server), `provider/ops/` (RPC),
-bespoke `Provider`/`ChatModel` impls (`claude_code/` ~2.7k,
-`claude_agent_sdk/`, `openai_codex.rs`, `openhuman_backend*.rs`), and the root
-host files (`schemas.rs`, `presets.rs`, `model_ids.rs`, `paths.rs`, `parse.rs`,
-`sentiment.rs`, `device.rs`).
-
-**Blast radius:** 187 files import `openhuman::inference`; 158 import
-`inference::provider` (grown from the old plan's 170/151). Top consumers:
-`agent/harness/session/tests.rs` (33 hits), `core/observability.rs` (31),
-`tinyagents/mod.rs` (15), `web_chat/web_errors.rs`, `routing/factory.rs`,
-`agent/harness/subagent_runner/ops/{graph,runner}.rs`, `voice/`, `flows/ops.rs`,
-`config/ops/model.rs`, `channels/context.rs`.
-
-### 4.2 Agent domains
-
-| Domain | Files / LOC | Disposition |
-| --- | --- | --- |
-| `agent/` | 144 / 66.9k | **Mostly stays** (product brain). 37 files already crate-backed. WP-3 verified that `session/turn/core.rs` is the product turn-preparation shell and `subagent_runner/ops/graph.rs` unconditionally calls `run_turn_via_tinyagents_shared`; the legacy loops and runtime escape hatches were removed before this audit. Heaviest coupling in the tree (config=31, memory=20, event_bus=13 files). |
-| `agent_orchestration/` | 64 / 27.9k | Engine already on `tinyagents::graph` (workflow runs, teams, delegation, `map_reduce`); what remains is the product layer (ledgers, RPC). Residual upstream item: detached-subagent `TaskStore` lifecycle — WP-5. 25 files crate-backed. |
-| `routing/` | 8 / 2.7k | **Deleted in WP-2.** A repository-wide reference audit found no consumer outside the module; #4783's crate `ModelRouter` already owns the live path, so retaining the nominally host-specific health/provider files would preserve an unreachable parallel stack. |
-| `model_council/` + `council_registry/` | 8 / 1.7k | **Deleted after WP-2 audit.** Generic fan-out already used crate `parallel::map_reduce`; upstream dead-code cleanup removed the remaining unreachable product and registry surfaces. |
-| `tool_timeout/` | 1 / 316 | **HOST-OWNED.** TinyAgents `harness::tool::ToolTimeout` is declarative per-tool metadata; it has no process-global value to receive OpenHuman config. This module owns UI/config + env precedence and the actual `tokio::time::timeout` deadline used by the host-tool adapter — WP-2 audit closed. |
-| `tool_status/` | 3 / 0.7k | **HOST-OWNED.** Its serialized UI/persistence taxonomy, OpenHuman security markers, retry categories, and user-facing remediation copy are product semantics. TinyAgents tool outcomes remain the generic execution input — WP-2 audit closed. |
-| `tools/` | 98 / 40.9k | The `Tool` trait + `ToolSpec` mechanics (`traits.rs:255`), `schema.rs`, `policy.rs`, `orchestrator_tools.rs`, `user_filter.rs` are framework-shaped; all of `tools/impl/*` + RPC (`schemas.rs` 985, `ops.rs` 1,407) are product. **Design-gated** (port-plan §2 blockers still apply) — WP-4. Note: `ToolResult`/`ToolContent` are re-exported from `skills::types` (~236 consumer files) — moving those types is the highest-blast-radius single step in the whole migration and must be its own slice. Security coupling: 49 files. |
-| `tool_registry/` | 7 / 1.8k | Read-only cross-surface discovery + RPC. Stays. |
-| `agent_registry/`, `agent_experience/`, `agent_memory/`, `agent_tool_policy/`, `agentbox/`, `orchestration/` | — | All host/product (definitions-as-data, RPC controllers, marketplace HTTP, remote-brain client — `orchestration/` talks to the hosted backend, not the local crate). Stay. `agent_tool_policy` overlaps crate `tool_policy` middleware mechanically but encodes host channel-permission policy — stays, mechanism may thin post-WP-4. |
-
-### 4.3 The seam — `src/openhuman/agent/tinyagents/` (25 files, ~17.1k LOC)
-
-The seam is healthy: 23/25 files use the crate; it implements `Middleware`
-(13×), `ToolMiddleware` (4×), `ModelMiddleware` (3×), `ChatModel` (2×),
-`Summarizer`, `Tool`, `EventListener` (2×), `PayloadSummarizer`,
-`HarnessStatusStore`, `EmbeddingModel`, and `GraphEventSink`. Post-migration it
-**shrinks but remains host-owned**. Specific shrink targets:
-
-- **`model.rs`: `ProviderModel` is deleted.** The former `convert.rs` was split:
- tool-schema conversion remains as the 34-line WP-4 seam, while durable-message
- conversion moved to `agent/message_convert.rs`. The execution audit found that
- `ChatMessage` is OpenHuman's versioned JSONL/thread persistence record (including
- message ids and product metadata), not a duplicate provider request type;
- replacing it directly with the crate enum would change existing on-disk data.
-- **`middleware.rs` (4,702):** the WP-5 audit records all 18 concrete types
- found at audit time (the tool-exposure shadow was added after the 17-type
- snapshot) in `docs/tinyagents-drift-ledger.md`. `SchemaGuard` is now deleted
- in favor of TinyAgents 2.1 `InvalidArgsPolicy::ReturnToolError`, leaving 17.
- `ArgRecovery` overlaps crate #45/#71 normalization. `RepeatProgress` now uses
- the merged #72 crate tracker; only the thin OpenHuman signature/exemption and
- halt-projection adapter remains. Upstream the generic ones; host-policy ones
- (ApprovalSecurity, CredentialScrub, CliRpcOnly, MemoryProtocol, CostBudget)
- stay — WP-5.
-- `routes.rs` `UsageCarry`/`FallbackObserver` thin out as usage/fallback become
- fully crate-native.
-
-### 4.4 Broken/dangling references (resolved in WP-0)
-
-WP-0 retargeted SDK-gap references to
-`vendor/tinyagents/docs/sdk-gaps.md`, made the provider schema
-`src/openhuman/config/schema/cloud_providers.rs` authoritative, created
-`docs/tinyagents-full-migration-plan/99-deletion-ledger.md`, replaced the
-phantom numbered-plan links with this plan's WP-5/C4 sections, and retargeted
-the TinyCortex analogy to this current audit. The three historical plans now
-carry explicit superseded banners.
-
-### 4.5 Test inventory (what moves, dies, or stays)
-
-- **Dies with WP-1** (bound to the legacy `Provider` stack):
- `provider/traits_tests.rs` (501), `reliable_tests.rs` (1,228),
- `router_tests.rs` (524) — these define 10+ mock `impl Provider` doubles.
- `factory_tests.rs` (3,149) shrinks and retargets to `ChatModel` construction.
- In `tests/raw_coverage/`: the three `inference_compatible_*` files (~2.2k
- LOC) are pinned to the deleted wire client — retire or rewrite the still-
- meaningful assertions against `OpenAiModel` via wiremock.
-- **Retargets:** `tests/inference_provider_e2e.rs` (568, wiremock-based —
- OpenAI-compat chat/streaming, Anthropic auth headers, temperature
- suppression, Ollama `/v1`) — keep the scenarios, point them at the crate-
- native factory path; these become the **wire-parity gate** for flipping the
- default.
-- **Moves upstream (as crate tests, offline `MockModel` convention):** parity
- coverage for anything upstreamed in WP-2/WP-5 (routing policy/quality,
- council graph, middleware behaviors). The crate's CI is
- fmt → clippy (`-D warnings`, both feature sets) → build → `cargo test` +
- `--all-features`, no network.
-- **Stays host-side:** seam tests (`tinyagents/tests.rs` 799 + 19 inline),
- `tests/agent_harness_e2e.rs` (130 KB), `tests/json_rpc_e2e.rs` (576 KB),
- `agentbox_e2e`, `orchestration_*`, `embeddings_rpc_e2e`,
- `ollama_lifecycle_e2e`, `openai_oauth/flow_tests.rs`, all `local/*_tests`,
- and the `raw_coverage` family except the compatible trio.
-- **Runner impact:** `scripts/test-rust-with-mock.sh:52` had a stale comment
- advertising removed `OPENHUMAN_AGENT_GRAPH_*` escape hatches. WP-3 removes
- that documentation; the runner behavior itself was already crate-only.
-
----
-
-## 5. The plan — six work packages
-
-Ordering rationale: WP-0 is pure hygiene and unblocks honest review of
-everything else; WP-1 is the largest deletion and already 80% scaffolded;
-WP-2/WP-3 are independent of each other and of WP-1's tail; WP-4 is the only
-design-gated package; WP-5 is opportunistic shrink; WP-6 is the exit gate.
-Every WP follows the repo's standing rules: failing-before/passing-after
-regression tests, small validated commits on a feature branch per submodule,
-drift-ledger rows updated before deletions (the ledger's gate rule stays in
-force).
-
-### WP-0 — Version + docs housekeeping (no behavior change)
-
-1. Bump `vendor/tinyagents` submodule to tag `v2.1.0` (fast-forward; picks up
- `BarrierRelief` #62 and the bytes bump). Regenerate root and
- `app/src-tauri` lockfiles. `cargo check` both worlds +
- the slim disabled build (`--no-default-features`) per repo convention.
-2. Update `tinyagents-drift-ledger.md` Anchors (pin row → v2.1.0; add rows
- closing out #4780/#4782/#4783/#4784 which the ledger still lists as
- pending/deferred; mark the Phase-3 "compatible*.rs remains" text CLOSED).
-3. Stamp superseded-by banners on `tinyagents-port-plan.md`,
- `tinyagents-inference-migration-plan.md`,
- `tinyagents-phase3-router-registry-design.md` pointing here (keep them —
- their disposition tables and gap lists are still the reference detail).
-4. Fix the §4.4 broken references, create the deletion ledger, and replace the
- phantom numbered-plan references with real WP-5/C4 anchors.
-5. Remove the stale fork-source patch after verifying that no dependency uses
- it. Align TinyCortex's nested path dependency through a crates.io `2.1`
- declaration plus its repo-local development patch, so the host's canonical
- path patch produces one trait identity (TinyCortex #121).
-
-**Exit:** `Cargo.toml`, submodule, lockfiles, and ledger all agree on one
-version; zero dangling `docs/tinyagents*` references (`grep -rn` clean).
-
-### WP-1 — Finish the model-layer cutover; delete the legacy `Provider` stack
-
-The continuation of #4727 Motion B / drift-ledger P1-8/P1-9. Slices:
-
-1. **Flip the factory default** to `crate_openai.rs` construction for every
- OpenAI-compatible slug. Gate: the retargeted `inference_provider_e2e.rs`
- wire-parity suite (§4.5) green against the crate path, per provider family
- (managed, BYOK, ollama/lm-studio local, codex/responses).
-2. **Route bespoke providers as `ChatModel`s** — `claude_code`,
- `claude_agent_sdk`, `openai_codex`, `openhuman_backend` get direct
- `ChatModel` impls (the pattern `openhuman_backend_model.rs` already
- proves), removing the last `factory.rs:1458-1511` `ProviderModel` wraps.
- Delete the legacy `openhuman_backend.rs` twin when nothing constructs it.
-3. **Error-taxonomy split:** generic classification call sites move to crate
- `classify_provider_failure`/`ProviderError`; `error_classify.rs` shrinks to
- the openhuman-semantic layer (`config_rejection`, `billing_error`, Sentry
- demotion). Upstream any status codes the crate misclassifies (drift-ledger
- rows, then crate PR + version bump).
-4. **Delete, in dependency order:** `router.rs` → `reliable.rs` →
- `legacy_provider.rs` (+ the `as compatible` alias in `provider/mod.rs:14`)
- → `provider/traits.rs` → seam `ProviderModel`/`MaxTokensModel`
- (`tinyagents/model.rs`) → the reverse adapter `crate_provider.rs` last.
- Re-home the durable transcript adapter beside the agent persistence DTO;
- retain only tool-schema conversion in the seam until WP-4. Each deletion is its own commit with its test
- fallout (§4.5) handled in the same commit.
-5. **Consumer sweep:** migrate the 187 importing files to crate types
- (`Message`, `ModelRequest`, `Usage`, `TinyAgentsError`). Mechanical for
- most; the hot spots are `core/observability.rs`, `web_chat/web_errors.rs`,
- `voice/`, `flows/ops.rs`, `config/ops/model.rs`.
-6. **Re-home** `temperature.rs`, `thread_context.rs`, `resolved_route.rs`,
- `auth_error_registry.rs` out of `provider/` into the seam (or the factory
- module) so `provider/` ends as: factory + bespoke models + ops/RPC.
-
-**Exit criteria:** no `impl Provider` anywhere; `grep -rn "ProviderModel"
-src/` empty; `inference/provider/` ≤ ~8k LOC (from ~15.9k + tests);
-`inference_provider_e2e` + `agent_harness_e2e` + full
-`scripts/test-rust-with-mock.sh` green. Estimated net deletion: **~9–10k LOC**
-(code + dead tests).
-
-### WP-2 — Consolidate parallel implementations onto crate primitives
-
-Independent, individually shippable slices:
-
-1. **`routing/` → `registry::router` — complete by deletion.** The execution
- audit found the entire module self-contained: no production or test caller
- outside `routing/` constructed its provider or consumed its health signals.
- #4783's crate `ModelRouter` already owns live workload routing, so WP-2
- removed the unreachable parallel stack and its self-tests.
-2. **`tool_timeout/` — HOST-OWNED (audit closed).** The similarly named crate
- `ToolTimeout` is per-tool policy metadata, not a global timeout store or
- executor. OpenHuman must retain config/env precedence, live UI updates,
- seconds clamping, grace handling, and the adapter's hard deadline. The seam
- already projects host policy into crate `ToolRuntime`; there is no duplicate
- crate implementation to delete.
-3. **`model_council/` — complete by deletion.** Generic member fan-out already
- ran through `tinyagents::graph::parallel::map_reduce`; upstream dead-code
- cleanup removed the remaining unreachable council and registry product
- surfaces.
-4. **`tool_status/` — HOST-OWNED (audit closed).** The classifier is tied to
- OpenHuman security markers, serialized thread/UI types, retry categories,
- localized-copy keys, and remediation language. TinyAgents owns generic tool
- outcomes; mapping those outcomes into product status remains in the host.
-
-**Exit: complete.** `routing/`, `model_council/`, and `council_registry/` are
-deleted; timeout and status are explicitly HOST-OWNED. Ledger rows record the
-audit evidence.
-
-### WP-3 — Retire the legacy turn engine
-
-**Audit result: complete before this plan was written.** The filenames cited by
-the initial audit survived, but their legacy engines did not:
-
-1. `session/turn/core.rs` performs OpenHuman turn preparation and calls the
- TinyAgents session path; it contains no `run_turn_engine` definition.
-2. `subagent_runner/ops/graph.rs` documents the removed `run_inner_loop` /
- `run_turn_engine` and unconditionally calls `run_turn_via_tinyagents_shared`.
-3. No runtime or test code reads `OPENHUMAN_AGENT_GRAPH_*`; only this plan and a
- stale test-runner comment mentioned those names. The stale comment is now
- removed.
-
-**Exit satisfied:** one TinyAgents turn engine; source and scripts contain no
-`OPENHUMAN_AGENT_GRAPH_*` reference. Historical/parity comments mentioning the
-former engine remain intentionally as provenance, not executable branches.
-
-### WP-4 — Tool-model reconciliation (design-gated; do not start on autopilot)
-
-The openhuman `Tool` trait (`tools/traits.rs:255`) vs crate `Tool<State>`
-unification. The port-plan §2 design blockers still stand, plus two audited
-constraints:
-
-- `ToolResult`/`ToolContent` live in `skills::types` as the deliberately
- ungated type carve-out consumed by ~236 files (MCP, runtime_node, every Tool
- impl). Any move must preserve that carve-out property (inert, dep-free,
- compiled in all feature combinations) — either the types move **into the
- crate** and `skills::types` re-exports them, or they stay and the crate
- bridge continues via `SharedToolAdapter`.
-- `tools/` has the tree's heaviest security coupling (49 files) — execution
- gating (`classify_command`, approval, sandbox) must stay host-side
- regardless of where the trait lives.
-
-Recommended shape: a short design doc (successor to the port-plan §2 list)
-deciding (a) trait unification vs permanent adapter, (b) the
-`ToolResult`/`ToolContent` home, (c) `ToolScope::AgentOnly` gating (deferred
-"Phase 2" per `traits.rs:14-19`) — then slices. Until then, the
-`SharedToolAdapter` seam is cheap and correct; **do not delete it
-prematurely.**
-
-The proposed decision is recorded in
-[`tinyagents-tool-model-decision-2026-07-23.md`](tinyagents-tool-model-decision-2026-07-23.md).
-It selects a permanent ownership-boundary adapter, keeps the host's structured
-result types in the always-compiled carve-out while preserving them through
-TinyAgents `raw`, and defines the required scope-enforcement matrix. WP-4 code
-changes remain gated on explicit approval of that proposal.
-
-### WP-5 — Seam shrink + orchestration lifecycle upstreaming
-
-1. Middleware audit (§4.3): per-middleware ledger rows; `SchemaGuard` is deleted
- through the existing crate invalid-args policy. TinyAgents #72 is merged and
- `RepeatProgress` now delegates generic streak accounting to the crate
- `SuccessfulRepeatTracker`; the host duplicate guard and thresholds are
- deleted, while the thin product adapter remains. `ArgRecovery` still awaits
- the #71 crate equivalent; keep host-policy middlewares.
-2. Detached-subagent lifecycle: move the generic detached-run registry
- mechanics (`agent_orchestration/running_subagents.rs`,
- `subagent_control.rs`) onto crate `TaskStore`/`SteeringRegistry` fully;
- host keeps ledgers + RPC. This restores the lifecycle consolidation intent
- recorded by the earlier audit without relying on a phantom design doc.
- **Cutover implemented:** TinyAgents PR
- [#75](https://github.com/tinyhumansai/tinyagents/pull/75) adds the generic
- ownership-aware `DetachedTaskRegistry`; OpenHuman now delegates snapshots,
- waits, steering lookup, cancellation/abort, terminal sweeping, and lock-error
- handling to it. The host retains durable `TaskStore` projection, product
- metadata, RPC, and the `RunQueue` compatibility fallback. All 17 focused
- `running_subagents` tests pass. TinyAgents #75 merged as `d548657`, and the
- canonical vendored pointer `4358efe` includes it, closing the generic
- lifecycle cutover.
-3. Finish the C4 journal-progress-parity plan (S2–S6): journal-backed progress
- projection, then delete `agent/progress_tracing.rs` (1,272) +
- `progress_tracing/langfuse.rs` (825) in favor of crate observability —
- respecting the recorded S2a replayability blocker.
-
-### WP-6 — Exit gate
-
-- Full suite: `scripts/test-rust-with-mock.sh` (all targets incl.
- `raw_coverage_all`), `cargo test --all-features` in `vendor/tinyagents`,
- slim disabled build + `cargo test --lib --no-default-features core::` (repo standing rule), `pnpm rust:check`.
-- Deletion ledger totals reconciled against the port-plan's projection
- (~30k deleted / ~12–15k upstreamed).
-- Docs: `inference/README.md`, `gitbooks/developing/architecture/
- {agent-harness,orchestration,flows-on-tinyagents}.md` updated to the
- post-cutover reality; drift ledger phases marked CLOSED; this plan stamped
- done.
-
----
-
-## 6. Risks and standing gotchas
-
-- **Wire parity is the whole risk in WP-1.** The legacy client accumulated
- provider quirks for years; the crate's #44–#57 wave was built to match them,
- but the flip must be gated on the wiremock parity suite per provider family,
- not on unit tests. Keep `CrateBackedProvider` as the rollback seam until the
- parity suite has soaked on `main`.
-- **GPL/crates.io boundary:** tinyagents is publicly redistributed — only
- genuinely generic code moves down; no product policy, backend phrasing as
- API, or key material (port-plan rule, still in force).
-- **Usage fidelity (old gap G1):** verify crate `Usage` carries the
- USD/cached-token fields the cost tracker needs before deleting
- `UsageInfo`; `routes.rs` `UsageCarry` is the current compensator.
-- **`RUST_MIN_STACK=16777216`** in the mock runner exists because of the
- subagent runner's large futures — deep-graph changes in WP-3/WP-5 can
- resurface stack overflows on Apple Silicon (see
- `composio_list_tools_stack_overflow_regression` test).
-- **Whisper/GGML on Apple Silicon:** any `cargo` validation of the root crate
- locally needs `GGML_NATIVE=OFF` (unrelated to this migration but will bite
- every WP's validation loop).
-- **Two Cargo worlds:** every vendor bump must update both the root and
- `app/src-tauri` lockfiles (until the workspace convergence tracked in
- #3877).
-
----
-
-## 7. Quick reference — disposition of every audited module
-
-| Module | Verdict |
-| --- | --- |
-| `inference/provider/{traits,reliable,router,legacy_provider,crate_provider}.rs` | DELETE (WP-1) |
-| `inference/provider/{error_classify,error_code}.rs` | SPLIT: generic → crate; host semantics stay (WP-1) |
-| `inference/provider/{crate_openai,openhuman_backend_model,factory}.rs` | KEEP — becomes the host↔crate boundary (WP-1 finishes) |
-| `inference/provider/{temperature,thread_context,resolved_route,auth_error_registry}.rs` | RE-HOME to seam (WP-1) |
-| `inference/{local,voice,http,openai_oauth}/`, `provider/ops/`, bespoke providers, root host files | STAYS |
-| `tinyagents/model.rs` (`ProviderModel`) | DELETED (WP-1) |
-| `tinyagents/convert.rs` message layer | RE-HOMED to `agent/message_convert.rs`; durable JSONL/thread compatibility is product-owned. Tool-schema conversion remains for WP-4. |
-| `tinyagents/middleware.rs` generic middlewares | UPSTREAM case-by-case (WP-5) |
-| `tinyagents/` remainder (seam) | STAYS, shrinks |
-| `agent/` legacy `run_turn_engine` + escape hatches | ALREADY DELETED; WP-3 corrected the stale audit and runner documentation |
-| `agent/` remainder, `agent_registry/`, `agent_experience/`, `agent_memory/`, `agent_tool_policy/`, `agentbox/`, `orchestration/`, `tool_registry/` | STAYS (product/host) |
-| `routing/` | DELETED; #4783 crate router already owned the only live path (WP-2) |
-| `tool_timeout/` | HOST-OWNED: config/env state + hard-deadline enforcement; crate timeout is metadata only (WP-2 closed) |
-| `tool_status/` classification | HOST-OWNED: OpenHuman UI/security/recovery taxonomy (WP-2 closed) |
-| `model_council/`, `council_registry/` | DELETED after crate-backed fan-out audit and upstream dead-code cleanup (WP-2 closed) |
-| `tools/` trait mechanics | DESIGN-GATED (WP-4) |
-| `tools/impl/*`, all `schemas.rs` RPC controllers | STAYS |
-| `agent_orchestration/` detached-run mechanics | UPSTREAM to `TaskStore` (WP-5) |
-| `agent/progress_tracing*` | DELETE after C4 S2–S6 (WP-5) |
diff --git a/docs/tinyagents-phase3-router-registry-design.md b/docs/tinyagents-phase3-router-registry-design.md
deleted file mode 100644
index d52c1578f4..0000000000
--- a/docs/tinyagents-phase3-router-registry-design.md
+++ /dev/null
@@ -1,140 +0,0 @@
-# Phase 3 — RouterProvider → crate ModelRegistry: design & ground truth
-
-**Status:** superseded on 2026-07-22 by
-[`tinyagents-migration-plan-2026-07-22.md`](tinyagents-migration-plan-2026-07-22.md).
-Phase 3's client cutover landed in #4783/#4784; this document is retained as
-historical design rationale, not current status. Grounded in a full read of both the crate
-(`vendor/tinyagents/src/harness/model`, `harness/agent_loop`, `harness/retry`,
-`registry/`) and the host seam (`src/openhuman/agent/tinyagents/{mod,routes,model}.rs`,
-`inference/provider/{router,factory}.rs`).
-**Relates to:** `docs/tinyagents-inference-migration-plan.md` (Phase 3),
-`docs/tinyagents-drift-ledger.md` (P1-9), issue #4249.
-
----
-
-## 1. The premise correction (important)
-
-The plan framed Phase 3 as "implement RouterProvider → crate ModelRegistry in
-`vendor/tinyagents`." **Investigation shows the registry migration is already
-done at the seam, and the crate already does everything the host router needs —
-there is no hard upstream gap.** Specifically, `assemble_turn_harness`
-(`tinyagents/mod.rs:1240-1353`) already:
-
-- Registers the primary and every workload-tier route into the crate
- `ModelRegistry` (`harness.register_model(name, model)`; primary via
- `set_default_model`).
-- Wires cross-route fallback as a **crate** `RunPolicy.fallback =
- routes::route_fallback_policy(model)` — traversed natively by
- `agent_loop::invoke_model_resolving`.
-- Gates vision via the crate: `RequiredCapabilitiesMiddleware` stamps
- `image_in` onto the `ModelRequest`, and the crate's `resolve_request` filters
- named candidates by `ModelProfile::satisfies`.
-- Emits the `FallbackSelected` parity event via `FallbackObserverMiddleware`.
-
-The two things the crate *lacks* (per the crate audit) are **not needed** by the
-host:
-
-- **Capability-based *selection*** (scan the registry for a capable model): the
- host never does this — the **caller picks the tier** upstream
- (`subagent_runner/ops/graph.rs` sets `model = vision-v1` for image turns); the
- middleware only *validates/enforces*, it doesn't select.
-- **Capability-aware *fallback***: the host's fallback chains are hand-built to
- be capability-safe (`routes::same_family_fallbacks`: `vision-v1 → []`; the
- same-family text alternates are all text-capable), so the crate's
- non-capability-filtered `next_after` is benign here.
-
-**Conclusion:** RouterProvider is *already* projected onto the crate registry.
-What remains is host-side, and needs no crate release.
-
-## 2. What actually survives (the real remaining work)
-
-`RouterProvider` (`inference/provider/router.rs`) survives only as the **per-call
-BYOK alias resolver *inside* the wrapped `Provider`** — at dispatch it maps a
-tier alias (`reasoning-v1`, …) → concrete `(provider, model)` (issue #2079: raw
-aliases 400 on OpenAI/DeepSeek). The registered tier models are still
-`ProviderModel`s that wrap this host `Provider`. So the harness holds a
-`Provider` for exactly one reason: **`build_turn_models` builds the per-turn
-primary + routes + summarizer `ProviderModel`s from one `Provider` handle**
-(`tinyagents/mod.rs:1139-1175`, `routes::build_route_models`).
-
-Two independent motions remain, in priority order:
-
-### Motion A — Harness holds crate `ChatModel`s (this Phase; host-only)
-Move `build_turn_models` construction from the harness turn path
-(`agent/harness/graph.rs::run_channel_turn_via_graph`, session turn path) to the
-**producer/factory boundary**, so `agent/` holds crate model types, not
-`Provider`. The harness turn path today reads four `Provider` methods before
-building — all are already available without the trait:
-
-| harness reads today | crate-native source |
-| --- | --- |
-| `provider.supports_native_tools()` | `TurnModels.primary.profile().tool_calling` |
-| `provider.supports_vision()` | `…profile().modalities.image_in` |
-| `provider.effective_context_window(model).await` | resolved at build time → `…profile().max_input_tokens` |
-| `provider.telemetry_provider_id()` | new `TurnModels.provider_id: String` |
-
-So `TurnModels` becomes the unit the harness holds. Design points:
-
-1. **Extend `TurnModels`** with `provider_id: String` and small accessors
- (`native_tools()`, `supports_vision()`, `context_window()`) reading
- `primary.profile()`. Removes every raw-`Provider` read in the harness graph.
-2. **New factory entry** `inference::provider::factory::create_turn_models(
- role_or_model, config, temperature) -> anyhow::Result<TurnModels>`: builds the
- `Provider` internally (existing `create_chat_provider` path), resolves the
- async `effective_context_window`, computes `telemetry_provider_id`, and calls
- the seam `build_turn_models`. All `Provider` naming stays in
- `inference/provider/` + the seam.
-3. **Lifecycle:** `build_turn_models` is per-`(provider, model)`; the harness
- builds a fresh `TurnModels` per turn today. Keep that — the producer builds
- `TurnModels` at turn-request assembly (channels processor, session turn entry,
- subagent runner) instead of the harness graph doing it. `error_slot` stays
- per-turn (correct — it recovers *this* turn's provider error).
-4. **Type swap:** `AgentTurnRequest.provider: Arc<dyn Provider>` → carries the
- built `TurnModels` (+ the `model`/`provider_name` it already has);
- `Agent`/`AgentBuilder.provider` likewise. `run_channel_turn_via_graph` /
- session `turn/graph.rs` receive `TurnModels`, read caps via the accessors, and
- pass it straight to `run_turn_via_tinyagents_shared` (which already takes
- `TurnModels`). `IntelligentRoutingProvider` stays a `Provider` impl
- (provider-stack member); the factory wraps it before `build_turn_models`.
-
-Exit: no `agent/` file names the `Provider` trait; `ProviderModel` built only in
-the seam (`model.rs` / `build_turn_models`), reached only via the factory entry.
-Zero behavior change (same `ProviderModel`s, same registry/fallback wiring).
-
-### Motion B — Registered models become crate-native (later; the big LOC win)
-Replace `ProviderModel` wrappers with crate `providers::openai` clients built
-from config (BYOK slugs, Ollama/LM Studio base URLs), registering per-tier
-clients directly so `RouterProvider`'s per-call alias resolution disappears
-(each tier is its own registered client). This is inference-plan **Phase 2**
-(client swap, deletes `compatible*.rs`) + the remainder of Phase 3, and keeps the
-bespoke providers (managed backend, claude-code, codex) as host `ChatModel`
-impls (Phase 4). Out of scope for Motion A; unblocked by it.
-
-## 3. Optional crate nicety (not required)
-If we later want capability-*aware* fallback (so a hand-built chain isn't the
-only safety net), the one-line crate change is to re-apply `model_eligible`
-to `FallbackPolicy::next_after` targets in `invoke_model_resolving`
-(`vendor/tinyagents/src/harness/agent_loop/model_call.rs:186-204`). File as a
-separate small upstream PR only if Motion B introduces capability-divergent
-fallback chains. Not needed for Motion A.
-
-## 4. First implementation slice (Motion A)
-1. `TurnModels`: add `provider_id` + `native_tools()/supports_vision()/context_window()` accessors (seam-internal; behavior-neutral).
-2. `create_turn_models(...)` factory entry (wraps `create_chat_provider` +
- async context-window resolve + `build_turn_models`).
-3. Cut `run_channel_turn_via_graph` to take `TurnModels` and read caps via
- accessors (delete the 4 raw-provider reads); channel producer
- (`channels/runtime/dispatch/processor.rs`) builds `TurnModels` via the factory
- and puts it on `AgentTurnRequest`.
-4. Repeat for the session turn path + subagent runner; swap `Agent.provider`.
-5. Update tests to build `TurnModels`/crate `MockModel` instead of hand-rolled
- `Provider` impls.
-6. Verify: both Cargo worlds green; `json_rpc_e2e`; streaming/cost/tool-timeline
- parity on a mock-backend turn (the #4460 / $0-turn / tool-timeline hazards).
-
-## 5. Verification & parity locks (unchanged from the plan)
-Provider-string grammar, `inference.*` RPC, tier alias set, fallback ordering
-(single same-family alternate; vision primary-only), the once-per-logical-call
-FIFO usage push (charged-USD-over-estimate precedence, graceful degradation), and
-the `FallbackSelected` event must all be preserved. These are already crate-wired
-— Motion A only moves *where the models are built*, not how they route.
diff --git a/docs/tinyagents-port-plan.md b/docs/tinyagents-port-plan.md
deleted file mode 100644
index ffba1fcde9..0000000000
--- a/docs/tinyagents-port-plan.md
+++ /dev/null
@@ -1,246 +0,0 @@
-# TinyAgents Port — Plan & Audit (inference / tools / agent_orchestration)
-
-**Status:** superseded on 2026-07-22 by
-[`tinyagents-migration-plan-2026-07-22.md`](tinyagents-migration-plan-2026-07-22.md).
-This document is retained as historical design detail; its version pins,
-phase status, and present-tense file inventory are not current.
-**Anchor precedent:** the TinyAgents harness migration (#4249 / #4399 / #4473) and the TinyCortex memory migration plan (`docs/tinycortex-memory-migration-plan.md`).
-**Target:** move the genuinely framework-shaped parts of `src/openhuman/inference/`, `src/openhuman/tools/`, and `src/openhuman/agent/orchestration/` down into the `tinyagents` crate (vendored git submodule at **`vendor/tinyagents`**, `https://github.com/tinyhumansai/tinyagents`), and delete the in-tree duplicates in favor of crate primitives.
-
----
-
-## 0. Ground truth (as audited)
-
-### 0.1 Sizes and shape
-
-| Host module | LOC (approx) | Role |
-| --- | --- | --- |
-| `src/openhuman/inference/` | ~53,000 (121 files) | Provider trait + OpenAI-compatible wire client, factory/routing, local runtime (Ollama/LM Studio/Whisper/Piper), voice, OAuth, RPC surface |
-| `src/openhuman/tools/` | ~38,500 | `Tool` trait + metadata model, schema cleaning, generated-tool admission, ~200-tool registry assembly, `impl/` families (filesystem, system, browser, computer, network, presentation), RPC surface |
-| `src/openhuman/agent/orchestration/` | ~25,800 | Product control plane over sub-agents: in-memory session, detached-run registry, workflow runs, agent teams, command center, worktree isolation, RPC/tools surface |
-| `src/openhuman/agent/tinyagents/` (the seam) | ~15,200 (25 files) | Adapters implementing tinyagents traits over openhuman services — where all ported code plugs back in |
-
-**TinyAgents** (sibling repo, v1.7.1, edition 2024, GPL-3.0-only, published to crates.io) already provides: `harness/` (`ChatModel`, `Tool<State>`, agent loop, middleware, retry/fallback, usage/cost, cache, embeddings + vector store, summarization, steering, `SubAgent`/`SubAgentSession`/`SubAgentTool`, observability journals, `WorkspaceIsolation`, testkit), `graph/` (durable typed graphs, checkpointers incl. SQLite, recursion policy, `map_reduce`, `orchestration::TaskStore`/`SteeringRegistry`, topology export), `registry/`, and the `.rag`/`.ragsh` languages. ~30 public traits are the extension points.
-
-**License:** both repos are GPL-3.0 — moving code down is license-clean. But tinyagents is publicly redistributed on crates.io, so only genuinely generic code moves (no product policy, backend phrases as load-bearing API, or keys).
-
-### 0.2 The single most important audit finding
-
-**Most of the "bulky" code is not portable — it is a parallel implementation of things tinyagents already ships.** The heavy clusters duplicate crate primitives rather than extend them:
-
-| openhuman (in-tree) | tinyagents (already shipped) |
-| --- | --- |
-| `inference/provider/traits.rs` (`Provider`, `ChatMessage`, `ChatResponse`, `UsageInfo`) | `harness/model/` (`ChatModel`, `ModelRequest/Response`), `harness/usage/` (field-for-field) |
-| `inference/provider/compatible*.rs` (~6.6k + 4.9k tests) | `harness/providers/openai/` (same 9-provider OpenAI-compat fan-out) |
-| `inference/provider/reliable.rs` (retry wrapper) | `harness/retry/` + `middleware/library/resilience.rs` — `reliable.rs`'s own module doc says it is "slated for removal once the tinyagents crate owns retry/fallback" and pins retry to 1 attempt |
-| `tools/traits.rs` `Tool` trait / `ToolSpec` / flat-Vec registry | `harness/tool/` `Tool<State>` / `ToolSchema` / deduping `ToolRegistry` |
-| `agent_orchestration/ops.rs` `AgentOrchestrationSession` + `running_subagents.rs` | `graph/orchestration/` `TaskStore` + `SteeringRegistry` + `harness/subagent/` `SubAgentSession` |
-| `inference/provider/router.rs` tier routing | `harness/middleware` fallback + `registry/` `ModelCatalog` |
-
-So the correct plan has **three motions**, not one:
-
-1. **Consolidate (delete in favor of the crate)** — the duplication above. This is where nearly all of the LOC reduction comes from.
-2. **True ports (net-new upstream)** — a short list of clean, generic pieces tinyagents lacks (§2).
-3. **Stays in openhuman** — RPC/controllers, config/credentials/policy glue, local runtime + voice, product tools, UI surfaces (§3).
-
-### 0.3 Version status
-
-**Phase 0 closed:** the host branch first aligned `vendor/tinyagents` to
-`v1.6.0` and closed the baseline seam fallout: `ToolCompleted` outcome
-projection, SHA-256 prompt-cache fingerprinting, and the redaction-layer audit.
-
-**Phase 1 partial cutover:** TinyAgents `v1.7.1` is tagged at
-`3e81e493`, and the host now pins both lockfiles plus `vendor/tinyagents` to
-that release. `SchemaCleanr` is crate-backed through the stable OpenHuman
-import path; `model_context.rs` delegates generic raw-model hints to
-`tinyagents::harness::model::context_window_for_model_id` after checking
-OpenHuman tier aliases and the cost catalog; and the observed run path now
-drives `invoke_stream_in_context`, whose `Send` stream fix shipped in
-[tinyagents#28](https://github.com/tinyhumansai/tinyagents/pull/28).
-
-### 0.4 Contribution workflow (same convention as tinycortex)
-
-Engine changes are made **inside `vendor/tinyagents`**, committed on a branch there, PR'd against `tinyhumansai/tinyagents`, released, then the host bumps the submodule SHA + version pin in a standalone `chore(vendor): bump tinyagents — <summary> (tinyagents#<PR>)` commit. Host PRs never contain engine source edits. tinyagents house rules apply to upstreamed code: `types.rs`/`test.rs`/`mod.rs` module discipline, centralized `lib.rs` re-exports, ≥80% coverage, tiny dependency tree (no new default deps; anything heavy goes behind a cargo feature), offline tests via `MockModel` (network tests are `live_*` and key-gated).
-
----
-
-## 1. Target ownership split
-
-### 1.1 Moves to / consolidates into TinyAgents
-
-| Host code | Motion | tinyagents destination |
-| --- | --- | --- |
-| `inference/provider/error_classify.rs` (777 L, 35 tests, extracted for this purpose in #4249) | port | `harness/retry/` classification (or `harness/providers/` error module) |
-| `inference/model_context.rs` pattern table (minus OH tier/cost-catalog arms) | port | `harness/model/` `ModelProfile`/context metadata |
-| `inference/parse.rs` (`sanitize_inline_completion`, zero deps) | port (low priority) | text post-process util |
-| `inference/provider/compatible*.rs` + `reliable.rs` + `router.rs` | **delete** after cutover to `harness/providers/openai` + `retry`/`resilience` + registry routes | n/a (crate already has it) |
-| `tools/schema.rs` `SchemaCleanr` (+ `schema_tests.rs`, zero deps) | port | provider adapters (per-provider JSON-Schema cleaning — genuine gap) |
-| `tools/traits.rs` display/metadata morsels: `humanize_tool_name`, `context_detail_from_args`, `display_label`/`display_detail`, `ToolTimeout` semantics | port (additive) | `harness/tool/` (`ToolRuntime`/policy metadata) |
-| `tools/generated.rs` admission/provenance model | align (don't duplicate) | `registry/capability` + `registry/component` |
-| `tools/impl/filesystem/` (file_read/write/edit_file/apply_patch/grep/glob/list_files/read_diff) | port (behind a `tools` feature) | new `harness/tools/` builtin family, `Tool<State>`-native |
-| `tools/impl/system/{current_time,resolve_time}.rs` | port (first movers — nearly pure) | same builtin family |
-| `tools/impl/network/{http_request,web_fetch,curl,url_guard}.rs` (SSRF guard is 842 L of largely pure logic) | port | same builtin family |
-| `tools/impl/system/{shell,node_exec,npm_exec}.rs` | port later (multi-seam: SecurityPolicy, NodeBootstrap, sandbox, tool_timeout) | same builtin family, gated on §4 blockers |
-| `agent_orchestration/worktree.rs` (617 L — already an impl of tinyagents' `WorkspaceIsolation`; one `publish_global` seam) | port | `harness/workspace/` git-worktree isolation provider |
-| `agent_orchestration/ops.rs` (`AgentOrchestrationSession`) + `running_subagents.rs` (1.9k L) | **delete** in favor of `graph::orchestration::TaskStore` + `SteeringRegistry` + `SubAgentSession`; route the live control path through the crate (today only re-exported, per seam `orchestration.rs:23-33`) | n/a |
-| `agent_orchestration/types.rs` `AgentStatus` vocabulary | reconcile into `OrchestrationTaskStatus` (two parallel status enums today) | `graph/orchestration/types` |
-| `agent_orchestration/workflow_runs/` phase-DAG validation + `agent_teams/` dependency-DAG/atomic-claim/quality-gate logic | evaluate upstreaming the *validation/scheduling slices* as graph extensions; durability (`session_db::run_ledger`) and RPC stay host-side | `graph/` |
-| Reasoning-content channel (historically smuggled via `ContentBlock::ProviderExtension`; host now writes `ContentBlock::Thinking` for new messages and only reads legacy `ProviderExtension` from persisted transcripts — seam `convert.rs`) | **largely done** — the crate's first-class typed reasoning channel (`ContentBlock::Thinking`) is live per Phase 1.4 / ledger P1-5 | `harness/message/` |
-
-### 1.2 Stays in OpenHuman (product policy, I/O, surfaces)
-
-- **All RPC surfaces**: `inference/{ops,schemas}.rs`, `provider/ops*`, `tools/schemas.rs`, `agent_orchestration/*_schemas.rs`, `subagent_control.rs`, `command_center/`, `worktree_schemas.rs`. JSON-RPC method names and payload shapes must not change.
-- **Provider resolution & auth**: `provider/factory.rs` (provider-string grammar), `openhuman_backend.rs`, `openai_codex.rs`, `claude_code/`, `claude_agent_sdk/`, `openai_oauth/`, `thread_context.rs`, backend billing-envelope parsing (`openhuman.usage.*` / `openhuman.billing.*`).
-- **Local runtime & voice** (~17k L): all of `inference/local/` (Ollama/LM Studio admin, Whisper/Piper install + engines), `voice/`, `device.rs`+`presets.rs`+`model_ids.rs`+`paths.rs` (device→tier product policy), `sentiment.rs`, `http/` (OpenAI-compat serving surface). tinyagents has no local-runtime provisioning and should not grow one now. (`device.rs` is technically portable — zero openhuman deps — but only valuable if tinyagents ever grows local provisioning; skip.)
-- **Tool product surface**: `tools/ops.rs` registry assembly (~200 registrations over ~50 domains), `user_filter.rs` (UI-toggle families), `orchestrator_tools.rs`, `local_cli.rs`, `impl/computer/` (macOS CGEvent/AX), `impl/presentation/`, network app integrations (gitbooks, gmail_unsubscribe, mcp_setup).
-- **Orchestration product plane**: all `agent_orchestration/tools/*` (openhuman `Tool` impls re-pointed at crate primitives), `subagent_events.rs` + `run_ledger_finalize.rs` (event-bus bridges), `background_{completions,delivery}.rs` (chat idle-delivery UX), `pairing*` (tiny.place consent), `parent_context/` (DI bootstrap), `session_db::run_ledger` durability.
-- **The seam itself** (`src/openhuman/agent/tinyagents/`) — it shrinks as duplication is deleted, but the `ChatModel`/`Tool`/middleware/journal adapters remain openhuman's integration layer.
-
----
-
-## 2. Blockers to resolve before tool ports (design decisions)
-
-These are API mismatches the current seam bridges **lossily**; porting tools natively forces a decision on each:
-
-1. **`ToolResult` shape** — openhuman uses MCP-style content blocks + `markdown_formatted`; tinyagents uses flat string `content` (the seam always sets `raw: None`, discarding structure). Proposal: add an optional structured-content field (or `raw` population convention) to tinyagents' `ToolResult` so ported tools stop losing block structure.
-2. **`PermissionLevel` (5 ordered levels, with per-call `*_with_args` overrides) vs `ToolSideEffects` booleans** — today `Write`/`Execute`/`Dangerous` all collapse to `writes_files` + `WorkspaceAccess::Any`, and per-call gating is dropped. Proposal: extend `ToolPolicy` with an ordered permission level and an optional per-call classifier hook, or accept the boolean model and encode levels host-side only (document the loss).
-3. **`SecurityPolicy` is the universal seam** across all of `impl/` (path/command/host gating). tinyagents models the same concept as `ToolAccess`/`SandboxMode`/`WorkspaceDescriptor`; the `security_for_tool_context` shims in `impl/{filesystem,system}/mod.rs` already bridge workspace roots. Ported tools must depend **only** on the crate-side abstractions; openhuman injects its `SecurityPolicy` behind them. This likely means growing `ToolAccess` (e.g. trusted roots, command classification hook) — design this once, before the first filesystem tool moves.
-4. **`file_state` edit-tracking** (filesystem family) — either port a minimal read-before-write tracker into the crate tools or leave tracking host-side via middleware.
-5. **Status vocabulary** — `AgentStatus` (Pending/Running/Waiting/Completed/Failed/Cancelled/Closed) vs `OrchestrationTaskStatus` (…/Awaiting/Timeout). Pick the crate vocabulary, map host wire compat in the RPC layer.
-
----
-
-## 3. Step-by-step plan
-
-Each phase is a coherent PR set: tinyagents PR(s) → release/tag → host `chore(vendor): bump` → host cutover PR. Every phase ends green on both CI lanes (tinyagents `ci.yml`; host fast lane + release lane).
-
-### Phase 0 — Version alignment & baseline (no behavior change)
-
-1. **Done:** bump `vendor/tinyagents` to **v1.6.0** and the host requirement `1.5.0` → `1.6.0` (both root and `app/src-tauri` manifests; keep the `[patch.crates-io]` path entries).
-2. **Done:** fix seam fallout from the bump: SHA-256 prompt fingerprint vs the seam's KV-cache drift guard (`tinyagents/middleware.rs`), idempotent `RedactionMiddleware` vs `journal.rs` double-redaction, adopt `ToolCompleted` outcome fields in `observability.rs` (retire `ToolFailureMap` reconstruction). The context-preserving `invoke_stream` host path is now closed by the `Send` stream follow-up released in TinyAgents `v1.7.1`.
-3. Record a baseline: LOC per module, test counts, and the duplication map (§0.2) as the drift ledger for this migration (mirroring `docs/tinycortex-drift-ledger.md`).
-4. **Exit:** host builds and full release lane passes on tinyagents 1.6.0 with zero in-tree deletions yet. The host has since moved on to the Phase 1 `v1.7.1` partial cutover.
-
-### Phase 1 — Quick wins upstream (small tinyagents PRs, no host deletions)
-
-Land these as separate small PRs against tinyagents (each with its ported tests re-expressed in crate conventions):
-
-1. `SchemaCleanr` (+ its 15-test suite) → provider-layer schema cleaning. Zero-dep, highest value/effort ratio. **Status:** released in TinyAgents `v1.7.0`; host `tools/schema.rs` re-exports the crate implementation so existing import paths keep working.
-2. `error_classify.rs` classifiers → retry/HTTP-error classification (strip openhuman-backend phrase matches into a host-side extension table; keep the generic HTTP/status logic). **Status:** released in TinyAgents `v1.7.0`; host retry/failure call-site swaps remain pending because OpenHuman-specific backend phrase and billing-envelope rules must stay host-side.
-3. `model_context.rs` pattern-match table (substring-vs-segment matching, incl. the o1/o3 regression guard) → `ModelProfile` context resolution. OH tier aliases and cost-catalog arms stay host-side. **Status:** released in TinyAgents `v1.7.0`; host now delegates generic fallback lookup to the crate after checking tiers and the OpenHuman cost catalog.
-4. First-class **reasoning channel** on `AssistantMessage` → delete the `ProviderExtension` smuggling in seam `convert.rs`. **Status:** closed for new messages: TinyAgents `v1.6.0` provides typed thinking blocks, and the host now writes `reasoning_content` to `ContentBlock::Thinking` while retaining legacy `ProviderExtension` reads.
-5. Git-worktree `WorkspaceIsolation` provider from `agent_orchestration/worktree.rs` (+ `worktree_tests.rs`, which exercises real git repos — fits the crate's offline test policy). The single `publish_global` event becomes a host-side wrapper. **Status:** released in TinyAgents `v1.7.0`; OpenHuman's wrapper stays for event-bus emissions, `OutsideWorkspace`, and host policy mapping until a safer adapter pass.
-6. Tool display metadata (`humanize_tool_name`, `display_label`/`display_detail`, `ToolTimeout` semantics) → `harness/tool/`. **Status:** released in TinyAgents `v1.7.0`; host adjusted `ToolRuntime.timeout`, but the OpenHuman `Tool` trait still owns richer legacy metadata until Phase 2 reconciles the tool model.
-7. `current_time` / `resolve_time` as the first two builtin tools (pilot for the `tools` feature layout). **Status:** released in TinyAgents `v1.7.0` behind the optional `tools` feature; host wrappers stay until the Phase 2 tool model reconciliation adopts crate builtins.
-8. **Exit:** TinyAgents `v1.7.1` tagged and host bumped. `SchemaCleanr`, generic model-context lookup, reasoning, and the context-preserving observed stream path are crate-backed; worktree/time/error-classification/display APIs are available but host deletion waits for their adapter/model reconciliation steps.
-
-### Phase 2 — Tool model reconciliation + builtin tool families
-
-1. Resolve §2 blockers 1–4 as a tinyagents design PR (ToolResult structure, permission model, `ToolAccess` extension, edit tracking).
-2. Port `impl/filesystem/` (8 generic tools) natively onto `Tool<State>` behind a `tools` cargo feature, depending only on `ToolAccess`/`WorkspaceDescriptor`. Port inline tests + `git_operations`/`run_tests` siblings where generic.
-3. Port `impl/network/{http_request,web_fetch,curl,url_guard}` (SSRF guard first — it is mostly pure).
-4. Host cutover: `tools/ops.rs` registers the crate builtins (wrapped with openhuman `SecurityPolicy` injected behind `ToolAccess`); delete the in-tree implementations; `user_filter.rs` table re-points at crate tool names (watch the `web_search`→`"web_search_tool"` name-drift risk).
-5. Defer `shell`/`node_exec`/`npm_exec` to a follow-up within this phase — they need the command-classification hook (`classify_command`/`gate_decision` stays host-side; the crate exposes the hook).
-6. `generated.rs`: re-target `GeneratedTool` onto the crate `Tool<State>` + align admission/provenance with `registry/capability` instead of a parallel mechanism.
-7. **Exit:** filesystem + network + time tools live in tinyagents with their tests; host `impl/` shrinks by ~10k L; `tool_policy_from_openhuman_tool` lossy mapping replaced by the reconciled model.
-
-### Phase 3 — Provider consolidation (deletion, not porting)
-
-The endgame of #4249's Workstream 11:
-
-1. Cut the live chat path over from `Provider::chat`/`compatible*.rs` to `harness/providers/openai` via the seam's `ProviderModel` — provider-by-provider, behind the existing route projection (`routes.rs`).
-2. Un-wrap `ReliableProvider` and restore crate-owned retry (`RunPolicy` retry is currently pinned to 1 attempt at seam `mod.rs:117-120` precisely because of the double-retry hazard).
-3. Move the openhuman-backend billing/usage envelope parsing into the backend provider adapter (host-side `ChatModel` impl), not the generic wire client.
-4. Delete: `compatible*.rs` (~6.6k L), `reliable.rs` (909 L, self-declared dead-in-waiting), `router.rs` (route via registry `ModelCatalog`), legacy `StreamChunk`/`stream_chat_*` streaming surface in `traits.rs` (superseded by `ProviderDelta`, itself superseded by crate streaming).
-5. `compatible_tests.rs` (4,851 L / 207 tests — the richest suite in the domain): re-express the *behavioral* cases (SSE edge cases, tool-arg normalization, reasoning round-trip) against `providers/openai` fixtures upstream; keep host-side only the backend-envelope tests.
-6. `Provider` trait stays temporarily as the host-side seam for factory/local/claude-code providers, now thin; evaluate retiring it entirely once all consumers are `ChatModel`.
-7. **Exit:** one wire client (the crate's); `inference/provider/` reduced to factory + app-specific providers + ops/RPC.
-
-### Phase 4 — Orchestration consolidation
-
-1. Route the detached sub-agent control plane through `graph::orchestration` for real: replace `running_subagents.rs`'s bespoke registry/steer/abort/ownership machinery with `TaskStore` + `SteeringRegistry` (+ upstream anything missing: ownership enforcement, soft-cap sweep — evaluate as crate PRs). The seam's `orchestration.rs` stops being a partial re-export.
-2. Replace `AgentOrchestrationSession` (`ops.rs`, 679 L) with crate `SubAgentSession` + `TaskStore`; consumers (`workflow_runs/engine.rs`, `agent_teams/runtime.rs`) move onto the crate API.
-3. Unify status vocabularies (§2.5); host RPC keeps wire compat via mapping.
-4. ~~Reconcile `subagent_sessions/` (durable reusable sessions) with crate `JsonlTaskStore`/checkpoint reuse instead of a parallel JSON store.~~ **Premise wrong (2026-08-30 audit):** `subagent_sessions/` is not a parallel task store. It is a reuse-selector directory keyed on ~8 product dimensions (`SubagentSessionSelector`, `subagent_sessions/types.rs:37-45`: `parent_session`, `parent_thread_id`, `agent_id`, `toolkit`, `model`, `sandbox_mode`, `action_root`, `task_key`) holding host `ChatMessage` transcripts, with a reusability status (`DurableSubagentStatus` — `Running`/`Idle`/`AwaitingUser`/`Failed`/`Closed`, `types.rs:8-32`) that has no crate counterpart. The crate's `JsonlTaskStore` (`vendor/tinyagents/src/graph/orchestration/store.rs`) is a durable task-status append log, an orthogonal concept. Reclassified **HOST-OWNED** — no reconciliation needed.
-5. ~~Thin `spawn_parallel_graph.rs` further into the seam ...; fix the two-spawn-path inconsistency (worktree diff results threaded in one path, hardcoded empty in the other — `ops.rs:559-562`).~~ **Stale/resolved (2026-08-30 audit):** the line reference is stale and the inconsistency is gone. Only `spawn_parallel_graph.rs::create_spawn_parallel_worktree` (currently ~lines 318-407) calls `worktree::OpenHumanWorktreeIsolation::new(...).prepare(...)`; every other spawn path inherits a descriptor and correctly reports `worktree_path: None` (`tools/dispatch.rs`, `tools/spawn_async_subagent.rs`, `tools/continue_subagent.rs`), which is the correct behavior, not a bug. Item resolved; no further action.
-6. Harden the `steering_forwarder.rs` (#4456) 50 ms poll-loop coupling upstream: give `SteeringHandle`/`RunQueue` bridging a first-class crate-side lifecycle instead of an abort-on-drop guard.
-7. **Exit:** one sub-agent lifecycle (the crate's); `agent_orchestration/` reduced to product tools, event bridges, ledger, RPC.
-
-### Phase 5 — Workflow/team generic slices (optional, evaluate after Phase 4)
-
-1. Upstream the **validation** slices: workflow phase-DAG structural/cycle validation (`workflow_runs/{types,ops}`), ~~team dependency validation + atomic CAS claim + quality-gate state machine (`agent_teams/ops.rs`)~~ — as `graph/` extensions if they generalize cleanly; otherwise leave host-side. Durability (`session_db::run_ledger`) and `command_center/` stay host-side regardless. **The atomic CAS claim + quality-gate state machine is DONE (2026-08-30 audit):** `vendor/tinyagents/src/session/run_ledger/ops.rs` owns `claim_agent_team_task` (line 935), `complete_agent_team_task` (line 1040), and `evaluate_completion_gate` (line 1157), with tests in `run_ledger/test.rs`. The host (`src/openhuman/agent/orchestration/agent_teams/ops.rs`) retains only delegation wrappers (`claim_task` at line 181 calls `run_ledger::claim_agent_team_task`; `complete_task` at line 325 calls `run_ledger::complete_agent_team_task`).
-2. `*_topology()` exports already funnel through seam `topology.rs::all_graph_topologies` — keep that pattern for anything upstreamed.
-
-### Phase 6 — Cleanup & docs
-
-1. Delete transitional shims (`ToolAdapter` test-only wrapper, `subagent_graph.rs` no-op skeleton once the graph path is the real one, `retrieve_tool_output` vs tokenjuice duplication).
-2. Update `gitbooks/developing/architecture/agent-harness.md`, `orchestration.md`, module READMEs, and `about_app` if user-facing behavior shifted.
-3. Final LOC/coverage ledger vs the Phase 0 baseline.
-
----
-
-## 4. Test migration strategy
-
-- **Port with the code (self-contained suites):** `schema_tests.rs` (15 fns), `generated_tests.rs` (24 fns), `error_classify` inline (35 tests), `model_context` inline, `parse.rs` inline (11), `worktree_tests.rs` (real-git, offline), filesystem/network tool inline suites, `policy.rs` inline. Re-express in tinyagents conventions: co-located `test.rs`, offline `MockModel`, `testkit` doubles, `e2e_*.rs` for integration, `live_*.rs` (key-gated) only where a real endpoint is essential.
-- **Re-express behaviorally (harness-bound):** `compatible_tests.rs` (207 tests) → crate `providers/openai` fixture tests; `reliable_tests.rs` (26) → crate retry/resilience tests (most already exist — diff first, port the gaps).
-- **Stay host-side:** `factory_tests.rs` (150), `ops_tests.rs` suites everywhere, `user_filter`/`orchestrator_tools` inline, all `agent_orchestration` harness-dependent suites (`engine_tests`, `runtime_tests`, `spawn_parallel_agents_tests`, `tools_e2e_tests`), all `/tests/*_e2e.rs` whole-app harnesses. These keep guarding the host wiring after cutover — they are the regression net for each deletion phase.
-- **Coverage gates:** tinyagents expects ≥80%; host PR lanes gate ≥80% on changed lines. Cutover PRs that mostly *delete* code should still touch the seam with tests proving the crate-backed path preserves behavior (golden transcripts via `MockModel` scripts are the cheap way).
-
----
-
-## 5. Bugs, gaps, and improvements found during the audit
-
-Fix-in-place candidates (independent of the port; several become moot as phases delete their hosts):
-
-**inference/**
-- `presets.rs:200-205` — `recommend_tier` ignores its RAM input and always returns `MVP_MAX_TIER`; misleading dead logic (its own test asserts the non-scaling). Either implement scaling or rename/strip the parameter.
-- `provider/traits.rs:734` — default `stream_chat_with_history` hardcodes `provider_name = "unknown"`, yielding the useless diagnostic `"unknown does not support streaming"`.
-- `provider/traits.rs` — two parallel streaming abstractions coexist (`StreamChunk`/`stream_chat_*` legacy vs `ProviderDelta`); the legacy surface is near-dead and scheduled for deletion in Phase 3.
-- `provider/reliable.rs` — live wrapper that no longer retries (pinned to one attempt); dead-code-in-waiting.
-- `provider/factory.rs:404` — `NO_MODEL_CONFIGURED_ANCHOR` correctness depends on a string literal matched by a separate classifier in `provider/ops.rs:19`; fragile cross-file coupling.
-
-**tools/**
-- `tools/ops.rs` — `all_tools_with_runtime` takes 12 positional args (`#[allow(clippy::too_many_arguments)]`; the thin `all_tools` shim forwards 9); a builder is overdue. The `Vec<Box<dyn Tool>>` container doesn't dedupe (a test exists *because* of this); the crate's `ToolRegistry` fixes it structurally.
-- `tools/traits.rs:15` — `ToolScope::AgentOnly` is a dead variant; `ToolCategory::Workflow` is pinned to wire `"skill"` (documented tech-debt to resolve before porting the type).
-- `tools/traits.rs:367-372` — `is_concurrency_safe` is advisory-only (harness runs tools serially); tinyagents 1.6 has concurrent independent tool calls — adopting it makes the flag real.
-- `orchestrator_tools.rs:38-41,87-89` — dead `SpawnWorkerThreadTool` registration (pending #1624); mis-attached doc-comment at lines 592-603 describes a different test than the one it precedes.
-- `user_filter.rs:168-188` — `skill_manage` and `workflow_manage` families carry identical `rust_names` (deliberate alias, duplication footgun); `web_search` → `"web_search_tool"` name mapping is drift-prone against the `search` domain.
-- ~~`impl/network/polymarket*` — a large app integration under the "cross-cutting families only" `impl/` rule.~~ Resolved by deletion: the Polymarket surface and its `prediction-markets` feature were removed outright.
-- Seam `tools.rs` — `tool_policy_from_openhuman_tool` silently drops `category`, `scope`, and all `*_with_args` per-call gating (§2.2).
-
-**agent_orchestration/**
-- `ops.rs:138-168` — `message_agent` records metadata only and never injects into the running loop; a real functional hole that `agent_teams/runtime.rs` and `command_center` inherit.
-- `subagent_control.rs` — the `SteerError::NotOwned` arm is unreachable on the trusted RPC `steer_control` path (which performs no parent-ownership check), but the variant is **not dead**: the agent-tool `running_subagents::steer` path enforces ownership and returns it (guarded by `steer_rejects_cross_parent_and_unknown`). Real RPC-path enforcement is deferred to Phase 4 (`SteeringRegistry` ownership consolidation).
-- `ops.rs:559-562` — in-memory session path hardcodes `worktree_path: None, changed_files: []` on completion even for worktree-isolated workers (inconsistent with `spawn_parallel_graph`).
-- `delegation.rs:120-127` — human-approval interrupt permanently disabled; the durable interrupt path in the seam is wired but unreachable until a review surface exists.
-- Two parallel status enums (`AgentStatus` vs `OrchestrationTaskStatus`) — latent drift hazard (§2.5).
-- Process-wide `OnceLock<Mutex<…>>` singletons in `background_completions`/`background_delivery`/`running_subagents` serialized through `TEST_ENV_LOCK` in tests — the crate favors injected stores; Phase 4 removes most of them.
-
-**seam (`src/openhuman/agent/tinyagents/`)**
-- `mod.rs:117-120` — retry pinned to 1 attempt (Workstream 11 debt; resolved in Phase 3).
-- `orchestration.rs:23-33` — bridge is re-export-only; live control path still on `RunQueue` (resolved in Phase 4).
-- `retriever.rs:14-27` — crate `Retriever`/`InMemoryVectorStore` built but unused on the live path (dead-until-swap; out of scope here, note for the memory migration).
-- `steering_forwarder.rs` (#4456) — abort-on-drop guard papering over a fragile poll-loop coupling; harden upstream (Phase 4.6).
-- `middleware.rs` — prompt-cache drift detection duplicated between seam and crate `PromptCacheGuardMiddleware`, with differing fingerprints until the 1.6.0 bump (Phase 0).
-
----
-
-## 6. Risks & mitigations
-
-| Risk | Mitigation |
-| --- | --- |
-| Behavioral drift cutting `compatible*.rs` over to crate providers (SSE edge cases, tool-arg normalization, backend envelope) | Provider-by-provider cutover behind the route projection; port the 207-test behavioral suite upstream *before* deleting; keep backend-envelope parsing host-side |
-| Double-retry / retry semantics during Phase 3 transition | Keep the 1-attempt pin until `ReliableProvider` is un-wrapped in the same PR that enables crate retry |
-| Lossy tool-metadata mapping ossifying (permissions, MCP blocks) | §2 design decisions land as a tinyagents PR **before** any tool family moves |
-| tinyagents is public crates.io GPL code | Audit each upstream PR for product policy/backend phrase coupling; backend-specific classifiers stay host-side as extension tables |
-| Version skew between submodule pin, crates.io version req, and upstream tags | Every bump is a standalone `chore(vendor)` commit pinning tag + version together; never float the submodule |
-| The two-Cargo-world topology (root crate vs Tauri shell, #3877) means two lockfiles to bump | Bump both manifests in the same `chore(vendor)` commit; CI full lane validates both |
-| Big-bang deletion breaking the fast PR lane's changed-file coverage gate | Phase PRs pair each deletion with seam tests exercising the crate-backed path |
-
----
-
-## 7. Expected outcome (rough accounting)
-
-- **Deleted from host:** `compatible*.rs` + tests (~11.5k), `reliable.rs` + tests (~2k), `router.rs` (~0.8k), orchestration session + detached registry + parallel-graph thinning (~4–5k), tool families moved (~10k incl. tests), misc (streaming legacy, shims) — **~30k LOC** leaves the host across Phases 1–4.
-- **Added to tinyagents:** builtin tools (feature-gated), schema cleaning, error classification, reasoning channel, worktree isolation, context-window table, orchestration hardening — **~12–15k LOC** upstream, most of it accompanied by ported tests.
-- **Unchanged:** RPC wire surface, local AI runtime, voice, provider factory grammar, product tool catalog, run ledger, UI.
diff --git a/docs/tinyagents-tool-model-decision-2026-07-23.md b/docs/tinyagents-tool-model-decision-2026-07-23.md
deleted file mode 100644
index 4d14e75d35..0000000000
--- a/docs/tinyagents-tool-model-decision-2026-07-23.md
+++ /dev/null
@@ -1,139 +0,0 @@
-# TinyAgents tool-model decision
-
-**Status:** proposed at the WP-4 design gate; implementation requires explicit
-approval.
-
-This document resolves the choices left open by
-`docs/tinyagents-port-plan.md` section 2. It deliberately does not authorize a
-trait rewrite or builtin-tool port by itself.
-
-## Decision summary
-
-| Question | Decision |
-| --- | --- |
-| One tool trait everywhere? | No. Use native `tinyagents::Tool<State>` for generic crate tools and retain OpenHuman's `Tool` for product tools. `SharedToolAdapter` is the permanent boundary between them. |
-| Where do `ToolResult` and `ToolContent` live? | Keep the MCP-style types in OpenHuman's always-compiled `skills::types`. Preserve them losslessly in TinyAgents `ToolResult::raw`; keep `content` as the model-facing rendering. |
-| How is `ToolScope::AgentOnly` enforced? | Enforce scope at every exposure boundary: `All` everywhere, `AgentOnly` only in autonomous agent registries, and `CliRpcOnly` only in explicit CLI/RPC registries. Reject an out-of-scope direct invocation as well as hiding it from discovery. |
-| Who owns security decisions? | OpenHuman. TinyAgents policy metadata is descriptive and provides generic fail-closed checks; OpenHuman still performs args-aware permission, approval, command, path, sandbox, credential, and external-effect gating. |
-
-## 1. Trait boundary
-
-OpenHuman should not mechanically migrate its roughly 200 product and
-integration tools onto the generic crate trait. Its trait carries product
-contracts that the crate does not: args-aware permission and approval,
-generated-tool provenance, UI scope/category, markdown rendering, and
-host-configured deadlines. Flattening these into static `ToolPolicy` fields is
-lossy and risks bypassing security checks.
-
-Instead:
-
-- New or ported generic builtins implement `tinyagents::Tool<State>` in the
- crate.
-- Product, RPC, dynamic integration, MCP, and OS-specific tools continue to
- implement OpenHuman `Tool`.
-- `SharedToolAdapter` remains the supported host-to-harness boundary. Rename it
- only if a clearer public integration name is useful; do not delete it as
- migration debris.
-- Add the inverse adapter only when an upstream builtin must be exposed through
- OpenHuman CLI/RPC. It must preserve the same scope and security gates as a
- native host tool.
-
-This is convergence by ownership, not by forcing unrelated tools through one
-trait.
-
-## 2. Result ownership and lossless conversion
-
-`skills::types::{ToolResult, ToolContent}` is an inert, dependency-light wire
-type used by MCP, Node/Python runtimes, persisted surfaces, and nearly every
-host tool. Moving it would create a large feature-gate and serialization blast
-radius for no execution benefit. It remains compiled with the `skills` feature
-both on and off.
-
-The bridge must stop discarding structure:
-
-1. Render `OpenHuman ToolResult::output_for_llm(true)` into TinyAgents
- `ToolResult::content`.
-2. Serialize the complete OpenHuman result into TinyAgents `ToolResult::raw`,
- including `content`, `is_error`, and `markdownFormatted`.
-3. Populate TinyAgents `error` when the host result reports `is_error`, without
- changing the structured `raw` value.
-4. For a crate-native tool exposed back to a host surface, prefer a recognized
- OpenHuman-result envelope in `raw`; otherwise map a JSON `raw` value to
- `ToolContent::Json` and textual `content` to `ToolContent::Text`.
-
-The envelope is versioned by its existing serde field names; no duplicate
-`ToolContent` enum should be added to TinyAgents. Tests must cover mixed text
-and JSON blocks, markdown, tool-reported errors, and the fallback for a
-crate-native raw JSON value.
-
-## 3. Scope semantics
-
-`ToolScope` is host product policy and stays out of the crate. Its enforced
-matrix is:
-
-| Scope | Agent model | Explicit CLI/RPC |
-| --- | ---: | ---: |
-| `All` | yes | yes |
-| `AgentOnly` | yes | no |
-| `CliRpcOnly` | no | yes |
-
-Filtering discovery is necessary but insufficient. The final dispatcher must
-repeat the check so a caller cannot invoke a hidden tool by name. Rejections
-must use the existing host policy/error shape and must not execute the tool.
-
-The first implementation slice should inventory agent, CLI, JSON-RPC, Node,
-Rhai, MCP, and generated-tool entrypoints, then add table-driven tests for the
-matrix at each shared registry/dispatcher boundary. Until that inventory is
-green, `AgentOnly` remains documented as unenforced and no tool should rely on
-it as a security boundary.
-
-## 4. Security and access mapping
-
-`ToolPolicy` remains useful registry metadata, but it cannot replace
-OpenHuman's live policy:
-
-- Static host permission maps conservatively into TinyAgents side-effect and
- access metadata.
-- Args-aware `permission_level_with_args`, `external_effect_with_args`, and
- generated-tool policy run at call time in host middleware before execution.
-- `classify_command`, approval, workspace-internal fail-closed checks,
- `trusted_roots`, and sandbox selection remain host-owned.
-- Per-call timeout resolution remains in the adapter until TinyAgents accepts a
- dynamic timeout hook without duplicating enforcement.
-- File read-before-write tracking remains host middleware. It is not part of a
- generic tool result or policy type.
-
-Filesystem builtins may move only when their crate implementation depends on
-`WorkspaceDescriptor`/`ToolAccess` and the host can inject its stricter path
-checks. Shell, Node, and package execution remain deferred until the crate has
-an application-supplied command-classification/gating hook.
-
-## 5. Implementation slices after approval
-
-1. **Lossless result bridge:** populate and round-trip `ToolResult::raw`; add
- focused adapter tests. No registry changes.
-2. **Scope enforcement:** audit exposure/invocation boundaries and enforce the
- matrix with table-driven tests. No trait changes.
-3. **Native builtin registration seam:** add a host wrapper for selected
- crate-native time tools, proving bidirectional result and policy mapping.
-4. **Filesystem pilot:** upstream/cut over one read-only tool using injected
- workspace policy and edit-tracking middleware where applicable.
-5. **Broader ports:** proceed family by family. Product tools remain behind the
- permanent adapter.
-
-Each slice is independently revertible. Do not combine the 236-file result-type
-consumer graph with a tool-family port.
-
-## 6. Acceptance criteria
-
-- No structured host result is lost at the TinyAgents boundary.
-- `AgentOnly` and `CliRpcOnly` are both hidden and rejected outside their
- allowed surfaces.
-- Existing OpenHuman approval, args-aware permission, sandbox, and path checks
- remain authoritative.
-- Generic crate tools can be registered without implementing the host trait
- directly.
-- Builds with `--no-default-features` retain the OpenHuman result types and
- compile.
-- `SharedToolAdapter` remains until all host product tools cease to exist,
- which is not a goal of this migration.
diff --git a/docs/tinycortex-api-gap-audit.md b/docs/tinycortex-api-gap-audit.md
deleted file mode 100644
index 2cf269eae0..0000000000
--- a/docs/tinycortex-api-gap-audit.md
+++ /dev/null
@@ -1,180 +0,0 @@
-# TinyCortex API Gap Audit (Phase 0.2)
-
-**Status (2026-07-22):** Historical gap inventory for the completed engine
-cutover. Counts and source anchors below describe the audit base; unresolved
-host consolidation work, including G1 re-homing and sync dedupe, is tracked in
-`tinycortex-migration-plan-2026-07-22.md`.
-
-**Purpose.** Map every host call site into the engine-mapping modules
-(`memory_store`, `memory_tree`, `memory_queue`, and the long tail) onto a TinyCortex
-public API. Where no crate API covers a host need, record a **gap** — each gap becomes a
-`tinycortex` issue/PR (engine-side) or an explicit host-adapter decision, and gates the
-workstream that touches it.
-
-Anchors: host `7850cf363` · tinycortex `d1a8c7be` (v0.1.1). Crate API surface inventoried
-from `vendor/tinycortex/src/memory/**` (`pub` traits/fns/types, verbatim signatures).
-
-## Call-site volume (host → engine, external references only)
-
-External refs = uses of `memory_<mod>::…` from host code **outside** that module.
-
-| Engine module | External refs | Maps to crate | Coverage |
-| --- | --- | --- | --- |
-| `memory_store` | 454 | `store/`, `chunks/` | High — see per-API below |
-| `memory_tree` | 169 | `tree/`, `retrieval/`, `score/` | High (gaps G3, G5) |
-| `memory_queue` | 42 | `queue/` | High (drift D2) |
-| `memory_sources` | 35 | `sources/` | Full (local readers only) |
-| `memory_conversations` | 24 | `conversations/` | Full (drift D1) |
-| `memory_tools` | 12 | `tool_memory/` | Full |
-| `memory_diff` | 11 | `diff/` | Full |
-| `memory_archivist` | 9 | `archivist/` | Full |
-| `memory_goals` | 6 | `goals/` | Full |
-| `memory_search` | 1 | `retrieval/`, `score/` | tools stay host |
-| `memory_entities` | 0 | `entities/` | Full |
-| `memory_graph` | 0 | `graph/` | Derive-on-read (gap G2) |
-
-Highest-traffic `memory_store` sub-APIs (external): `chunks::store` (152), `chunks::types`
-(93), `trees::types` (54), `create_memory` (31), `trees::store` (27), `profile` (26),
-`types` (19), `content` (19), `content::compose` (14), `content::paths` (10),
-`content::read` (9), `content::atomic` (8), `content::raw` (7). All of `chunks::*`,
-`trees::*`, `content::*`, `profile` map to crate re-exports (`chunks::…`, `tree::…`,
-`store::content::…`, `config::WeightProfile`). `create_memory` is host glue (see below).
-
-## Seam-trait roster (the W1 adapter targets — all present in crate)
-
-The crate exposes every seam the plan expects, plus more. Host implements these:
-
-| Trait | Path | Host adapter (W1) |
-| --- | --- | --- |
-| `EmbeddingBackend` | `store/vectors/embedding.rs:32` | `tinycortex/embeddings.rs` over `openhuman::embeddings` *(amended: bridged to `tinyagents::harness::embeddings::EmbeddingModel` in W-EMB, plan §8.2)* |
-| `Embedder` (retrieval/summarise) | `score/embed.rs:28` | same seam file |
-| `ChatProvider` | `score/extract/llm.rs:70` | `tinycortex/chat.rs` over `memory::chat` / `inference` |
-| `Summariser` (bucket-seal, structured) | `tree/summarise.rs:70` | `tinycortex/chat.rs` |
-| `Summariser` (time-tree, string) | `tree/runtime/engine.rs:29` | **divergent — see G6** |
-| `EntityExtractor` (regex + LLM) | `score/extract/composite.rs:16` | `tinycortex/chat.rs` (LLM variant) |
-| `QueueDelegates` | `queue/handlers.rs:96` | `tinycortex/queue_driver.rs` |
-| `TreeJobSink` | `ingest/types.rs:15` | `tinycortex/ingest.rs` |
-| `TreeLeafSink` | `archivist/sink.rs:44` | `tinycortex/ingest.rs` |
-| `SnapshotItemSource` | `diff/source.rs:28` | host diff adapter |
-| `EntityOccurrenceIndex` | `graph/types.rs:44` | host graph adapter |
-| `SelfIdentity` | `store/entity_index/store.rs:25` | host identity registry |
-| `GoalsGenerator` | `goals/reflect.rs:57` | `tinycortex/chat.rs` |
-| `SourceReader` | `sources/readers/mod.rs:1732` | local readers only *(amended: live-sync readers join the crate in W-SYNC, plan §8)* |
-| `SyncEventSink` *(new, W-SYNC)* | `sync/traits.rs` (planned) | `tinycortex/sync_sink.rs` → `MemorySyncStage` bus events |
-| `SkillDocSink` *(new, W-SYNC)* | `sync/traits.rs` (planned) | forwards to `MemoryClient::store_skill_sync` (host-retained unified tier) |
-| `ConversationEventBus` / `ChannelEventHandler` | `conversations/bus.rs:106/95` | host `memory_conversations/bus.rs` (translate to `DomainEvent`) |
-
-Config seam: `MemoryConfig{workspace, embedding: EmbeddingConfig{dim,model,strict},
-tree: TreeConfig{input_token_budget,output_token_budget,summary_fanout,flush_age_secs},
-retrieval: RetrievalConfig{default_profile}, sync_budget: SyncBudgetConfig}` +
-`WeightProfile{graph,vector,keyword,freshness}` — all `pub` with the exact fields the W1
-`config.rs` adapter maps `Config` onto.
-
----
-
-## Gaps (each → tinycortex issue/PR or explicit host-adapter decision)
-
-### G1 — Raw SQLite connection escape hatch (`sqlite_conn()`) — **HARD, high blast radius**
-
-- **Host:** two trait methods return a live handle:
- `memory/traits.rs:277` and `memory_store/memory_trait.rs:458`
- `fn sqlite_conn(&self) -> Option<Arc<Mutex<Connection>>>`. ~312 references to
- `sqlite_conn`/`raw_conn`/`with_connection` across the host.
-- **Crate:** deliberately omits it (`traits.rs:3-6`). Offers instead a **scoped** accessor
- `chunks::with_connection(config, |conn| …)` (`chunks/mod.rs:217`) over the cached handle;
- `conn_cache()` is private.
-- **Decision (W2):** do **not** upstream a handle-getter (it breaks the crate's connection-cache
- invariants). Instead: (a) migrate host internal raw-SQL sites to `chunks::with_connection`
- during W3; (b) keep `sqlite_conn()` as a **host-side extension trait** over the crate store for
- the transition, shrinking to zero as sites migrate. Track residual call sites in the deletion
- ledger. **Gates W2/W3.**
-
-### G2 — Graph relation-edge persistence (E2GraphRAG accumulation) — **HARD**
-
-- **Host:** `memory_store/namespace_store/{graph,query}.rs` persist and query co-occurrence
- / LLM-triple relations; `NamespaceMemoryHit.supporting_relations: Vec<GraphRelationRecord>`
- is populated at retrieval.
-- **Crate:** persists the **entity occurrence index** at persist time
- (`score::persist_score`/`persist_score_tx`, `score/mod.rs:847-906`) but **does not write
- co-occurrence graph edges** — docstring `score/mod.rs:843-846`: *"Co-occurrence graph edges
- (OpenHuman's E2GraphRAG accumulation) are not written here."* The `graph` module **derives**
- edges on read from the occurrence index (`graph/query.rs`, "owns no state, performs no
- writes"). `GraphRelationRecord` exists as a type but nothing in the crate writes it.
-- **Decision (W6/W7):** verify whether derive-on-read reproduces the host's persisted-relation
- retrieval (`supporting_relations`) with parity. If yes → host relation store stays host
- (namespace doc/graph store is explicitly host per plan §1); if the crate must own accumulation
- → upstream a relation-persist path. **Gates W6/W7.** Parity-critical for retrieval output.
-
-### G3 — Seal-time embedding — **MEDIUM (parity timing)**
-
-- **Host:** computes summary embeddings around seal (`memory_tree/tree/bucket_seal.rs`,
- `memory_tree/score/embed/*`, `set_summary_embedding`).
-- **Crate:** `bucket_seal.rs:21` / `tree/mod.rs:22` list "seal-time embedding" as **not ported**;
- `seal_one_level` computes labels but never embeds. Summary embedding runs later via the queue's
- `reembed_batch` delegate. The `mem_tree_summary_embeddings` sidecar + setters exist.
-- **Decision (W5):** confirm retrieval parity on freshly-sealed summaries — if the host embeds at
- seal but the crate defers to the queue, a summary is momentarily unembedded until the worker
- drains. Either drive an embed job at seal from the host queue driver, or upstream seal-time
- embedding. **Gates W5.**
-
-### G4 — Post-seal notification sink (for host `wiki_git` mirror) — **SOFT**
-
-- **Host:** `6395f642e` wired a seal-time hook in `bucket_seal.rs` to commit summary markdown to
- the git-backed `wiki_git` mirror (host-retained, per the drift ledger).
-- **Crate:** no observer/sink trait for seal events — but `append_leaf` / `cascade_all_from` /
- `TreeFactory::seal_now` **return `Vec<String>` of sealed summary ids**. The host can drive
- `wiki_git` from the returned ids without a callback.
-- **Decision (W3/W5):** no crate change required; the host queue driver calls `wiki_git` after each
- seal using returned ids. Record as a seam-wiring task, not an upstream gap. Revisit only if a
- push-notification is later wanted.
-
-### G5 — Tree health / doctor (storage-degraded state machine) — **SOFT (host-retained)**
-
-- **Host:** `memory_tree/health/*` (`mark_storage_degraded`/`clear_storage_degraded`, degraded
- flag), consumed by `memory/tools/doctor.rs` and fed by the D2 host-FS classifier.
-- **Crate:** defers tree health/doctor entirely (`tree/mod.rs:20`); only `Memory::health_check()
- -> bool`. Queue uses its own `JobFailure` (no storage-degraded machine).
-- **Decision (W5):** **host-retained** (like `wiki_git`). `memory_tree::health` stays host; the D2
- predicate (queue classifier) upstreams, its Sentry-once + degraded-flag consumers stay host.
-
-### G6 — Two divergent `Summariser` traits — **MEDIUM (ambiguity)**
-
-- Crate has **two** traits named `Summariser`: `tree/summarise.rs:70` (structured batch fold —
- `summarise(&[SummaryInput], &SummaryContext) -> SummaryOutput`) used by bucket-seal, and
- `tree/runtime/engine.rs:29` (string in/out — `summarise(Option<&str>, &str) -> String`) used by
- the markdown time-tree runtime. They are distinct contracts with the same name.
-- **Decision (W1/W5):** the host seam must implement **both**. Flag for possible upstream
- unification (rename one, e.g. `TimeTreeSummariser`) to reduce confusion — non-blocking. Note
- which tree path OpenHuman actually drives (bucket-seal SQLite trees vs markdown time-tree) so we
- don't wire a dead seam.
-
-### Non-gaps (expected host glue — no crate change)
-
-| Host API | Refs | Disposition |
-| --- | --- | --- |
-| `memory_store::create_memory` / `create_memory_with_local_ai` (`factories.rs:297,322`) | 31 | Host glue building `UnifiedMemory`. Crate has no `UnifiedMemory`/`MemoryClient` (by design). **W3 re-implements these factories over `tinycortex::store` + `chunks`, keeping the host-facing `MemoryClient` API stable.** Not a crate gap. |
-| `memory_store::profile` (`unified::profile`) | 26 | Maps to `config::WeightProfile` (fields `graph/vector/keyword/freshness`, `by_name`). |
-| `memory_store::fts` / keyword search | 7 | Crate provides `retrieval::keyword_relevance` + `hybrid_score` (not SQLite FTS5). **Verify keyword-recall parity in W5** (behavioral, not a missing API). |
-| Namespace document/graph store | — | Explicitly host-retained per plan §1 until/unless upstreamed (ties to G2). |
-
----
-
-## Gap → workstream gate summary
-
-| Gap | Severity | Gates | Resolution path |
-| --- | --- | --- | --- |
-| G1 escape hatch | High | W2/W3 | Migrate to `with_connection`; host extension trait for transition |
-| G2 graph relations | High | W6/W7 | Parity check derive-on-read; upstream persist iff needed |
-| G3 seal-time embedding | Medium | W5 | Drive embed at seal from host queue driver, or upstream |
-| G4 seal notification | Soft | W3/W5 | Drive `wiki_git` from returned sealed ids (no crate change) |
-| G5 tree health/doctor | Soft | W5 | Host-retained |
-| G6 two `Summariser` traits | Medium | W1/W5 | Implement both; optional upstream rename |
-
-**No hard gap blocks W1 (seam scaffolding) or W4 (queue, only drift D2).** W3 is gated by G1;
-W5 by G3/G6; W6/W7 by G2. These are recorded here and mirrored in the spec's deletion ledger.
-
-**Amendment 2026-07-09 (plan §8):** the crate's sync data model (`SourceKind::Composio`,
-`SyncBudgetConfig`, the TOML source registry with `upsert_composio_source` /
-`memory_sync_defaults_for_toolkit`) — previously host-consumed only — becomes **engine-consumed by
-W-SYNC**: the crate's own sync engine reads the registry and enforces the budget. New seam traits
-`SyncEventSink` / `SkillDocSink` land with W-SYNC.1 (see roster above); no other new gaps.
diff --git a/docs/tinycortex-cutover-evaluation-2026-07-28.md b/docs/tinycortex-cutover-evaluation-2026-07-28.md
deleted file mode 100644
index bc02a52286..0000000000
--- a/docs/tinycortex-cutover-evaluation-2026-07-28.md
+++ /dev/null
@@ -1,68 +0,0 @@
-# TinyCortex Memory Cutover Evaluation (2026-07-28)
-
-## Decision
-
-The memory engine cutover is complete. TinyCortex is the implementation
-authority for chunks, content and vector primitives, trees, retrieval, scoring,
-queue jobs, ingest, source readers, sync pipelines, diffs, goals, graph
-primitives, conversations, and tool memory.
-
-The remaining `src/openhuman/memory*` modules must not be moved wholesale. They
-are product adapters or compatibility paths, not a second memory engine:
-
-- RPC schemas and controller registration
-- agent tools and `SecurityPolicy` enforcement
-- source-scope and redaction policy
-- credentials, scheduling, and event-bus bridges
-- the host-owned namespace/document store
-- wiki-git and Obsidian product surfaces
-- process lifecycle and the global memory singleton
-
-Moving those concerns into TinyCortex would reverse the established dependency
-boundary by teaching the reusable engine about OpenHuman RPC, policy, secrets,
-and runtime composition.
-
-## Audit result
-
-The audit covered `src/openhuman/memory/`, every `memory_*` domain, the
-`src/openhuman/memory/tinycortex/` seam, and `vendor/tinycortex/src/memory/`.
-
-| Host area | Disposition |
-| --- | --- |
-| `memory_store::{chunks,content,vectors,kv,entities,trees,safety}` | TinyCortex-backed compatibility and host glue |
-| `memory_tree::{tree,retrieval,score}` | TinyCortex-backed compatibility plus RPC, CLI, health, and bus glue |
-| `memory_queue` | TinyCortex queue, driven by the host worker lifecycle |
-| `memory_sync` | TinyCortex sync engine plus host credentials, schedules, projections, RPC, and events |
-| `memory_diff`, `memory_goals`, `memory_conversations` | TinyCortex engine types/operations plus host tools, RPC, or bus glue |
-| `memory_sources` | Host source registry and RPC over TinyCortex readers |
-| `memory_tools` | TinyCortex tool-memory store/types plus host prompt hooks and agent tools |
-| `memory_store::namespace_store` | Host-owned; intentionally outside TinyCortex |
-| `memory`, `tinycortex` | Product orchestration and the engine adapter seam; retained |
-
-No second store, retrieval engine, queue engine, or sync-provider engine remains
-on the live host path. The large host line counts are dominated by retained
-product surfaces and their tests; line count alone is not evidence of engine
-duplication.
-
-## Cleanup executed
-
-The unused `memory_tools::types` facade file was removed. `memory_tools` now
-re-exports the crate-owned types and store directly at its existing domain-level
-API. Its private `store` module retains only the host constructor so `mod.rs`
-remains export-focused; prompt integration, the capture hook, and agent tools
-also stay host-owned.
-
-Other small re-export modules remain where they preserve heavily used import
-paths such as `memory_queue::types`, `memory_sources::types`,
-`memory_tree::retrieval::types`, and `memory_store::trees::types`. Removing
-those files would create broad source churn without changing runtime ownership.
-
-## Guardrails
-
-- New generic memory behavior belongs in `vendor/tinycortex`.
-- OpenHuman may add adapters, policy, RPC, tools, lifecycle, and product
- projections, but must not fork TinyCortex engine logic.
-- Persisted format parity tests in `openhuman::memory::tinycortex::parity` remain the
- cutover guard for existing workspaces.
-- `MemoryTaint`, redaction, and source-scope behavior remain security-sensitive
- review points.
diff --git a/docs/tinycortex-drift-ledger.md b/docs/tinycortex-drift-ledger.md
deleted file mode 100644
index de5366dc86..0000000000
--- a/docs/tinycortex-drift-ledger.md
+++ /dev/null
@@ -1,166 +0,0 @@
-# TinyCortex Drift Ledger (Phase 0.1)
-
-**Purpose.** The `tinycortex` port was taken at a point in time; the OpenHuman host
-engine has continued to evolve since. This ledger enumerates every host commit that
-touched an engine-mapping memory module after the port line, and classifies each as:
-
-- **DRIFT → tinycortex PR** — a real engine behavior change absent from the crate; must be
- re-applied upstream (submodule PR against `tinyhumansai/tinycortex`) before that module cuts over.
-- **HOST-OWNED** — the change lives in a layer that stays in OpenHuman (RPC, agent tools,
- event bus, embedding *compute*, live sync). No upstream needed.
-- **HOST-RETAINED (crate excludes)** — an engine-adjacent feature the crate *deliberately*
- does not own (declared in its own module docs). Stays host; may imply a **seam gap** (see
- the API gap audit).
-- **ALREADY PRESENT** — the change is already in the crate (port captured it).
-
-> **Gate rule (plan §2/§6):** no module cuts over while its drift ledger row is open.
-> A row is *closed* when its DRIFT items are merged upstream and the submodule SHA is bumped,
-> or when the item is reclassified HOST-OWNED / HOST-RETAINED / ALREADY PRESENT.
-
-## Anchors
-
-| Thing | Value |
-| --- | --- |
-| Host repo | `tinyhumansai/openhuman` |
-| Host audit SHA | `7850cf363559bcbb7ba688cbc4fccdb6bd9ce754` (`main`, 2026-07-04) |
-| TinyCortex submodule | `vendor/tinycortex` → `tinyhumansai/tinycortex` |
-| TinyCortex audit SHA | `d1a8c7be2babc8fff7a72ed93861f459f3d6fa58` |
-| TinyCortex historical cutover SHA | `a8e10f7dd8ebdb9b0905e1380fefcc6bf5a65207` — audit SHA **+ #59** (native-dep alignment, §0.4) **+ #63/#64** (D2/D1 drift ports) merged |
-| **TinyCortex reviewed gitlink (2026-07-22)** | `daaaf6ba5f02635c08deae2b2b2ed7fcc8c06b6a` — includes OpenHuman #4794/#4820/#4863-era crate work; upstream currently has no tags |
-| **TinyCortex migration branch (current)** | `7b4b115` — TinyAgents 2.1 dependency alignment, standalone patch configuration, and corrected sync ownership docs |
-| TinyCortex crate version | `0.1.1` |
-| **Port line (derived)** | **after 2026-06-25, before 2026-06-28** (see below) |
-
-> **Execution status (2026-07-10). Drift closure COMPLETE — all rows CLOSED.**
-> The submodule is pinned at `a8e10f7`. **D3 CLOSED** (folded into #59);
-> **D2 CLOSED** — merged as **tinycortex#63** (`is_host_io_error`, `e352435`);
-> **D1 CLOSED** — merged as **tinycortex#64** (rank-before-materialize, `a8e10f7`).
-> Host gitlink bumped `33dda94 → a8e10f7` (`chore(vendor): bump tinycortex …
-> (tinycortex#63, #64)`). With every drift row closed, **W4** (queue) and **W7**
-> (conversations) are now unblocked per the gate rule. D4 (memory_sync corpus,
-> W-SYNC) remains its own separate track.
-
-> **Consolidation status (2026-07-22): D1–D4 CLOSED.** D1–D3 remain closed.
-> D4 was re-audited against the crate sync implementation and the live host
-> dispatch path. The host schedulers, credentials, RPC, source-scope/redaction
-> policy, product task normalizers, and event-bus adapters remain host-owned.
-
-### How the port line was located
-
-The port commits in `vendor/tinycortex` are all dated **2026-06-29**, but that is the date the
-*port* was authored, not the host state it captured. The line was pinned by **content**, not date:
-
-- **≥ 2026-06-25 is captured.** Host `feat(memory_diff): back change ledger with git instead of
- SQLite` (`040e6e20d`, 06-25) replaced the SQLite `mem_diff_read_markers` table with a git-backed
- ledger. The crate's `diff/` uses the **git-backed** `ledger.get_read_marker(...)`
- (`vendor/tinycortex/src/memory/diff/diff.rs:98`, `ledger.rs`) — i.e. the post-06-25 shape. So the
- port base includes the 06-25 memory_diff work.
-- **< 2026-06-28 for engine features.** Host `feat(memory): track summary-only wiki git history`
- (`6395f642e`, 06-28) added `memory_store/content/wiki_git/`. The crate has **no** `wiki_git` file
- anywhere — but see the reclassification below: the crate *deliberately* excludes it, so this is not
- proof of a stale base, it is a declared boundary.
-
-Net: only commits after 2026-06-25 that touch engine-mapping modules are drift candidates, and each
-was verified against crate content individually below.
-
----
-
-## Drift candidates (verified individually against crate content)
-
-Scan: `git log --since=2026-06-20 -- src/openhuman/memory/store memory_tree memory_queue memory_diff
-memory_goals memory_entities memory_graph memory_archivist memory_conversations memory_sources`,
-then per-commit file lists intersected with engine-mapping modules, then content-diffed against
-`vendor/tinycortex`.
-
-### DRIFT → needs tinycortex PR
-
-| # | Host commit | Module | Change | Crate state (verified) | Upstream target |
-| --- | --- | --- | --- | --- | --- |
-| D1 | `007a99b62` (06-30) `perf(memory_conversations): rank before cloning hits in cross-thread search` | `memory_conversations/inverted_index.rs` | Rank matches on cheap borrowed keys (`(doc_id:u32, matched:usize, created_at:&str)`), truncate to `limit`, **then** materialize the KB-sized `CrossThreadHit`. Order-equivalent to score ranking. | ✅ **CLOSED.** Ported + merged as **tinycortex#64** (`a8e10f7`): the rank-before-materialize refactor + `ranks_by_score_then_recency_before_truncating` test. Was pre-fix clone-then-rank at the port line. | — (closed) |
-| D2 | `d7bee77e3` (06-30) `fix(memory-queue): classify host-FS I/O errors to stop the tree_jobs Sentry flood` | `memory_queue/worker.rs` | Adds `is_host_io_error(&anyhow::Error) -> bool` classifying **persistent** host-FS failures (EIO/ENOSPC/EROFS) distinct from transient SQLite busy/I-O, so the worker backs off and reports Sentry **once** instead of ~10k events/50min (Sentry CORE-RUST-19J). | ✅ **CLOSED.** Ported + merged as **tinycortex#63** (`e352435`): the `is_host_io_error` predicate + 2 unit tests (EIO/ENOSPC/EROFS × typed/context/text; negatives). **Predicate only** — the Sentry-once emission and `mark_storage_degraded` flag stay host-owned (see D2-host below). | — (closed) |
-| D3 | `c43f79641` (07-03) (within TinyAgents migration) | `memory_store/vectors/store.rs` | `count()` reads `COUNT(*)` as `i64` and converts via `usize::try_from(...).context(...)` instead of `row.get::<usize>` directly — robustness against platform `usize`/`i64` mismatch. | ✅ **CLOSED.** Present at `vendor/tinycortex/src/memory/store/vectors/store.rs:371–384` (`usize::try_from(count).context(...)`) — folded into #59's `usize`→`i64`/`try_from` rusqlite-0.40 sweep and merged. | — (closed) |
-
-**Drift rows: D1, D2 (predicate), D3** — the only three engine behavior changes since the port line,
-all small and independent, **now all CLOSED** (gitlink `a8e10f7`).
-
-- D1 gates **W7** (long tail — conversations). ✅ **CLOSED** — merged as tinycortex#64.
-- D2 gates **W4** (queue). ✅ **CLOSED** — merged as tinycortex#63.
-- D3 gates **W3** (store + chunks). ✅ **CLOSED** — already in the crate via #59.
-
-### HOST-OWNED — same commits, layers that stay in OpenHuman (no upstream)
-
-| Host commit | File(s) | Layer | Why host |
-| --- | --- | --- | --- |
-| `0304d145f` (07-03) | `memory/tools/store.rs`, `memory/tools/forget.rs` | Agent tools | Tool contract/prompt text; agent tools stay host (plan §1). |
-| `7bf18562a` (06-30) | `memory/read_rpc/{types,vault}.rs` | RPC read surface | `read_rpc` stays host; JSON-RPC surface. |
-| `f84eec533` (06-30) | `memory_conversations/bus.rs` | Event bus | `bus.rs` = `EventHandler` impls, host-owned by canonical module shape. |
-| `6edaa77b1` (06-29) | `memory_tree/score/embed/openai_compat.rs` | Embedding **compute** | Network-calling embedding backend; the crate abstracts compute behind `EmbeddingBackend` and "never makes a network call". Wires into the W1 `embeddings.rs` seam. |
-| `d7bee77e3` (06-30) [D2-host] | `memory_tree/health/{mod,doctor}.rs` (`mark_storage_degraded`/`clear_storage_degraded`), `memory_tree/tree/rpc.rs` | Health signal + RPC | Degraded-state flag + Sentry wiring + doctor RPC. Crate defers tree health entirely (see gap audit); this is the host-side consumer of D2's predicate. |
-| `c43f79641` (07-03) | `memory_search/{vector,tools}/*`, `memory_sync/composio/*` | Agent tools / live sync | Import-path churn from the TinyAgents cutover + live-sync; not engine semantics. |
-
-### HOST-RETAINED — crate deliberately excludes (not drift)
-
-| Host commit | File(s) | Crate declaration |
-| --- | --- | --- |
-| `6395f642e` (06-28) `feat(memory): track summary-only wiki git history` | `memory_store/content/wiki_git/` (mod + tests, ~690 LOC), plus a seal-time hook in `memory_tree/ingest.rs` + `memory_tree/tree/bucket_seal.rs` | `vendor/tinycortex/src/memory/store/content/mod.rs:19–20`: *"The Obsidian-vault registry (`content::obsidian*`) and the git-backed wiki mirror (`content::wiki_git`) pull host config and git surfaces beyond this."* The crate explicitly leaves `wiki_git` **and** `obsidian*`/`obsidian_registry` host-side (host `memory_store/content/mod.rs:17,18,23`). |
-
-**Reclassification note (important).** At first pass this looked like drift (feature absent from crate).
-It is **not** — the crate's own content module doc names `content::wiki_git` and `content::obsidian*` as
-host surfaces it does not own. So `wiki_git`, `obsidian`, `obsidian_registry` join `memory_sync` as
-**host-retained** parts of an otherwise-moving module. **Consequence:** the seal-time hook that
-`6395f642e` wired into `bucket_seal.rs` has **no counterpart callback in the crate's `bucket_seal`**
-(`vendor/tinycortex/src/memory/tree/bucket_seal.rs` exposes no post-seal sink). That is tracked as an
-**API gap** (a `TreeJobSink`-style "summary sealed" callback the host implements to drive `wiki_git`),
-not as drift. See `tinycortex-api-gap-audit.md`.
-
----
-
-## Per-module drift status (the gate table)
-
-| Engine module | Maps to crate | Open drift | Gates workstream | Status |
-| --- | --- | --- | --- | --- |
-| `memory_store` (chunks, content, vectors, kv, entity_index, safety) | `store/`, `chunks/` | **D3** (vectors count guard) ✅ closed via #59. `wiki_git`/`obsidian*` host-retained (not drift). | W3 | **CLEAR** (D3 closed) |
-| `memory_tree` (tree, retrieval, score, summarise) | `tree/`, `retrieval/`, `score/` | none (health/rpc/embed-compute are host-owned) | W5 | **CLEAR** |
-| `memory_queue` | `queue/` | **D2** (predicate) — ✅ merged tinycortex#63 | W4 | **CLEAR** (D2 closed) |
-| `memory_conversations` | `conversations/` | **D1** (rank-before-clone) — ✅ merged tinycortex#64 | W7 | **CLEAR** (D1 closed) |
-| `memory_diff` | `diff/` | none (git-ledger captured) | W7 | **CLEAR** |
-| `memory_entities` | `entities/` | none | W7 | **CLEAR** |
-| `memory_graph` | `graph/` | none | W7 | **CLEAR** |
-| `memory_goals` | `goals/` | none | W7 | **CLEAR** |
-| `memory_archivist` | `archivist/` | none | W7 | **CLEAR** |
-| `memory_sources` (registry + local readers) | `sources/` | none | W7 | **CLEAR** |
-| `memory_tools` (engine part) | `tool_memory/` | none | W7 | **CLEAR** |
-| `memory_search` (`vector`, `scoring` engine parts; `tools` are host) | `retrieval/`, `score/` | none (churn only) | W5 | **CLEAR** (classify tools vs engine in W5) |
-
-**Summary:** 3 drift rows total, **all CLOSED** — **D3** via #59, **D2** via tinycortex#63,
-**D1** via tinycortex#64; gitlink now `a8e10f7`. No engine drift remains open; **W4 and W7 are
-unblocked**. Nothing else drifted. `memory_search` is a mixed module not in the plan's move table —
-its `tools/` stay host (agent tools), its `vector`/`scoring` are engine (W5) — flagged for the gap audit.
-
-## D4 — memory_sync corpus (2026-07-09 reclassification, W-SYNC)
-
-The plan's §8 amendment moved the generic sync engine into the crate, so the
-blanket **HOST-OWNED "live sync"** classification above is superseded for
-engine-mapping sync code. The crate port landed in `0333d10` and is the path
-called by `memory_sync::composio::run_connection_sync` and the default
-`ComposioProvider::sync` implementation.
-
-| # | Host commit | Files in corpus | Note |
-| --- | --- | --- | --- |
-| D4.1 | `c43f79641` (07-03) | `composio/providers/{sync_state,traits}.rs` | ✅ **CLOSED.** Import churn only; persistence and provider dispatch are implemented by the `SyncStateStore` seam and crate dispatcher. |
-| D4.2 | `27b00b539` (07-05) | `sources/rebuild.rs` | ✅ **CLOSED.** Test-only parity cleanup; no engine semantic delta. |
-| D4.3 | `653e6e143` (07-06) | `memory_sources/sync.rs` (+312) | ✅ **CLOSED.** Crate `sync/workspace.rs` updates changed items and prunes vanished items through `LocalDocumentSink::delete`; covered by workspace sync tests. |
-| D4.4 | `e456b7799` (07-07) | `memory_sources/{rpc,sync}.rs`, `canonicalize/email.rs`, `composio/providers/{gmail/post_process,notion/source,orchestrator}.rs`, `sources/github.rs` | ✅ **CLOSED.** Generic provider fetch/pagination/canonical memory records are in the crate port; orchestration, product task normalization, action-result presentation, and RPC fixes are host policy by design. |
-
-**Gate result:** D4 is **CLOSED**. Gmail's Composio 413 mitigation is additionally
-present in crate commit `ba9e12e` (25-message fetch pages). Host-retained parts
-(schedulers, bus subscribers, RPC wrappers, keychain/OAuth, action tools and
-product task/profile projections) remain HOST-OWNED.
-
-## Closing the ledger (procedure)
-
-For each open row:
-1. Branch in `vendor/tinycortex`, port the change (impl + test), PR against `tinyhumansai/tinycortex`.
-2. Merge upstream; bump the submodule in a standalone host commit
- `chore(vendor): bump tinycortex — <what> (tinycortex#<n>)`, keeping the `[dependencies]` pin in lockstep.
-3. Flip the row to **CLOSED** here; only then may the gated workstream cut over.
diff --git a/docs/tinycortex-memory-migration-plan.md b/docs/tinycortex-memory-migration-plan.md
deleted file mode 100644
index 36e0bcd0e8..0000000000
--- a/docs/tinycortex-memory-migration-plan.md
+++ /dev/null
@@ -1,268 +0,0 @@
-# TinyCortex Memory Migration — Plan & Audit
-
-**Status:** Historical execution plan. W1–W8 and the engine test port are landed
-(OpenHuman #4794/#4820); persona/coding-session ingest followed in #4863. The
-remaining consolidation work is tracked in
-[`tinycortex-migration-plan-2026-07-22.md`](tinycortex-migration-plan-2026-07-22.md).
-**Anchor precedent:** the TinyAgents harness migration (#4249 / #4399 / #4473 and follow-ups).
-**Target:** migrate large portions of the OpenHuman memory subsystem onto the `tinycortex` crate, vendored as a git submodule at **`vendor/tinycortex`** (`https://github.com/tinyhumansai/tinycortex`).
-
-> **Amendment 2026-07-09 (§8 — W-SYNC + W-EMB).** The original seam contract kept live sync
-> (`memory_sync/`) host-side and TinyCortex strictly network-free. That boundary is **revised**:
-> TinyCortex becomes all-encompassing of the sync modules (Composio toolkit sync included) behind an
-> optional `sync` cargo feature, and embeddings are inherited from `tinyagents::harness::embeddings`.
-> Sections §1/§3 below are the original contract, kept for history; where they conflict with §8,
-> **§8 wins**.
-
----
-
-## 0. Ground truth (as audited)
-
-### 0.1 What exists today
-
-**Host memory subsystem** (in-tree, all still live):
-
-| Host module | LOC (approx) | Role |
-| --- | --- | --- |
-| `src/openhuman/memory/` | ~20,700 (79 files) | Orchestration/policy layer: `Memory` trait, RPC ops/schemas, agent tools, ingest orchestrator, sync lifecycle, preferences, source-scope task-locals, redaction |
-| `src/openhuman/memory/store/` | ~32,800 | Storage: `UnifiedMemory`/`MemoryClient`, chunks DB, content store, vectors, KV, safety |
-| `src/openhuman/memory/tree/` | ~25,300 | Summary trees, retrieval, scoring, health |
-| `src/openhuman/memory/sync/` | ~30,700 | Live sync: Composio, MCP, OAuth, pollers |
-| `memory_queue`, `memory_sources`, `memory_diff`, `memory_goals`, `memory_entities`, `memory_graph`, `memory_archivist`, `memory_tools`, `memory_search` | ~20k combined | Engine long tail |
-
-**TinyCortex** (`vendor/tinycortex`, crate `tinycortex` v0.1.1, MIT, single crate, ~49,500 lines under `src/memory/`): an **already-completed port** of the engine layers — `store/` (content markdown + YAML, SQLite vectors, KV, entity_index, safety), `chunks/`, `tree/`, `queue/`, `retrieval/`, `score/`, `ingest/` (canonicalize/extract/pipeline), `conversations/`, `archivist/`, `diff/`, `sources/` (local readers only), `entities/`, `graph/`, `goals/`, `tool_memory/`. Its git history is explicitly "port X from OpenHuman" commits, and its types (`MemoryEntry`, `MemoryCategory`, `MemoryTaint`, `RecallOpts`, `NamespaceSummary`, the `Memory` trait) are wire-compatible with the host's `memory::traits`.
-
-**Wiring already pre-staged:**
-- `.gitmodules` has `vendor/tinycortex` → `tinyhumansai/tinycortex`.
-- Root `Cargo.toml` `[patch.crates-io]` block includes `tinycortex = { path = "vendor/tinycortex" }` (same mechanism as tinyagents: crates.io version pin + path patch). `app/src-tauri/Cargo.toml` has a matching path entry.
-- CI (`test-reusable.yml`, `build-ci-image.yml`, release workflows) already checks out submodules recursively. **No new CI plumbing needed.**
-
-**Gap:** zero `.rs` files in `src/` import `tinycortex`. There is no `[dependencies] tinycortex = "0.1"` entry activating the patch. The host still runs entirely on the in-tree engine, which has continued to evolve since the port was taken.
-
-### 0.2 TinyCortex's declared boundary (the seam contract)
-
-TinyCortex deliberately does **not** own (per its own module docs):
-- Live sync / polling / OAuth / network source readers (Composio, GitHub, RSS, web) — only `folder` and `conversation` local readers ship.
-- RPC schemas, event bus, CLI, agent-tool surfaces.
-- LLM and embedding **compute** — abstracted behind `EmbeddingBackend`, `score::extract::ChatProvider`, `tree::summarise::Summariser` traits ("never makes a network call").
-- A tokio worker pool — the host drives the queue via `queue::run_once` / `drain_until_idle`.
-- The namespace document/graph store and the Composio identity registry.
-
-This boundary is the migration contract: **engine in TinyCortex, product policy + I/O + surfaces in OpenHuman** — exactly mirroring the tinyagents split (generic runtime in the crate; prompts, security, RPC compat, UX in the host).
-
-### 0.3 Submodule contribution workflow (how engine changes are made)
-
-TinyCortex lives at **`vendor/tinycortex`** as a git submodule. Any change to engine code — whether by a human or by an LLM agent — is made **inside the submodule**, committed on a branch there, and raised as a **PR against `tinyhumansai/tinycortex`**. Once merged, the host repo bumps the submodule pointer in a standalone `chore(vendor): bump tinycortex — <summary> (tinycortex#<PR>)` commit, keeping the `[dependencies]` version pin in lockstep (same convention as `chore(vendor): bump tinyagents` commits citing `tinyagents#11` etc.). Host-side PRs never contain engine source edits; they only move the submodule SHA.
-
----
-
-## 1. Target ownership split
-
-### Moves to TinyCortex (delete from host after cutover)
-
-| Host module | TinyCortex counterpart | Notes |
-| --- | --- | --- |
-| `memory_store/` (chunks, content, vectors, kv, entity_index, safety) | `store/`, `chunks/` | Largest single win (~33k LOC) |
-| `memory_tree/` (tree, retrieval, score, summarise) | `tree/`, `retrieval/`, `score/` | Host keeps `tree_policy.rs` flavour constants |
-| `memory_queue/` | `queue/` | Host keeps the tokio worker loop that drives it |
-| `memory/ingest_pipeline.rs` internals | `ingest/` | Host keeps the thin entry points (`ingest_chat`, `ingest_document_with_scope`) as adapters |
-| `memory_diff/`, `memory_entities/`, `memory_graph/`, `memory_goals/`, `memory_archivist/`, `memory_sources/` (registry + local readers), `tool_memory` engine, `conversations` engine | same-named modules | Long tail |
-| `memory/traits.rs` core types | `tinycortex::memory::{Memory, MemoryEntry, MemoryCategory, MemoryTaint, RecallOpts, NamespaceSummary, …}` | Host re-exports from the crate so 30+ consumer sites keep compiling unchanged |
-
-### Stays in OpenHuman (product policy, I/O, surfaces)
-
-- **All RPC surfaces**: `memory/ops/`, `memory/schemas/`, `memory/schema/`, `memory/read_rpc/`, `rpc_models.rs` (controller framework types `ControllerSchema`/`RpcOutcome` are host-only). JSON-RPC method names and payload shapes must not change.
-- **Agent tools**: `memory/tools/` and `memory/query/` (`Tool`/`ToolResult` impls, `SecurityPolicy` gating) — they become thin wrappers over crate retrieval primitives.
-- **Live sync**: all of `memory_sync/` (Composio/MCP/OAuth/pollers), `memory/sync.rs` lifecycle + event-bus stage events. *(Superseded by §8: the sync engine moves to the crate; only schedulers, credentials/OAuth, bus bridges, and RPC wrappers stay host.)*
-- **Process glue**: `memory/global.rs` singleton + background queue worker; `memory/source_scope.rs` tokio task-locals; `memory/chat.rs` (LLM adapter over `openhuman::inference`); embeddings provider wiring.
-- **Policy/UX**: `preferences.rs`, `remember.rs`, `tree_policy.rs`, `util/redact.rs`, config mapping (`Config` → `tinycortex::MemoryConfig`).
-- **Namespace document/graph store** (until/unless deliberately upstreamed — TinyCortex explicitly excludes it today).
-
-### The adapter seam: `src/openhuman/memory/tinycortex/`
-
-New sibling module mirroring `src/openhuman/agent/tinyagents/`, holding every impl of a TinyCortex trait over an OpenHuman service:
-
-- `embeddings.rs` — `impl tinycortex EmbeddingBackend` over `openhuman::embeddings` (dim/model/signature from `Config`).
-- `chat.rs` — `impl ChatProvider` + `impl Summariser` over `memory::chat::build_chat_provider` / `inference::provider`.
-- `queue_driver.rs` — tokio worker loop calling `queue::run_once`/`drain_until_idle`, owned by `memory/global.rs`, with event-bus progress emission and Sentry hooks (host-side, since TinyCortex dropped its scheduler).
-- `config.rs` — `Config` → `MemoryConfig` (workspace roots, `EmbeddingConfig`, `TreeConfig`, `WeightProfile`, `SyncBudgetConfig`) with `tree_policy.rs` flavour overlays.
-- `ingest.rs` / `seal.rs` — `TreeJobSink`, seal observer, and host state bridges.
-- `sync.rs` — sync persistence/policy plus translation into host `DomainEvent`s (the crate stays bus-free).
-- `mod.rs` — facade re-exports (`pub use tinycortex::memory::{…}`) so the rest of the host imports through one seam, plus module-doc explaining the boundary (the tinyagents seam's `mod.rs` header is the template).
-
----
-
-## 2. Phase 0 — Audit & baseline (before any cutover)
-
-This phase produces documents and upstream issues only; it is the gate for everything after.
-
-**0.1 Drift audit.** The port in TinyCortex was taken at a point-in-time; the host engine has since received changes (perf waves, bug fixes). For each host module → crate module pair in the table above, diff behavior and enumerate host commits since the port SHA that must be re-applied upstream. Output: a per-module drift ledger (`host commit → tinycortex PR needed / already present / obsolete`). This is the highest-risk unknown in the whole migration — **nothing cuts over until its module's drift ledger is closed.**
-
-**0.2 API gap audit.** Enumerate every host call site into `memory_store`/`memory_tree`/`memory_queue`/long-tail modules (the internal sibling graph: ~25 uses of `memory_store::chunks`, 6 of `trees`, etc.) and map each to a TinyCortex public API. Output: gap list, each gap becoming a `tinycortex` issue/PR (e.g. the known gaps: graph edge accumulation at persist time, seal-time embedding, `seal_document_subtree` follow-ups, tree health/doctor — `memory/tools/doctor.rs` wraps `memory_tree::health`, which the crate defers).
-
-**0.3 Data-format parity audit.** Existing user workspaces must open unchanged after cutover. Verify byte/schema compatibility for: chunks.db SQLite schema + migrations, jobs table, tree tables, vector table encoding (packed f32), markdown content store paths + YAML frontmatter, entity markdown, git diff-ledger layout, deterministic chunk IDs. Output: a parity checklist with a fixture-based verification harness design (golden workspace snapshot opened by both engines, compared). Any mismatch is an upstream fix, not a host workaround.
-
-**0.4 Toolchain baseline.** Add `tinycortex = { version = "0.1" }` under `[dependencies]` (activating the existing `[patch.crates-io]` override); align `rusqlite` versions between host and crate (both must link one bundled SQLite); check edition (crate is 2021), feature flags, and that **both Cargo worlds** (root crate and `app/src-tauri`) compile with the dep active; confirm `GGML_NATIVE=OFF` macOS builds. Verify the release workflows' submodule-init covers `vendor/tinycortex` (the tinyagents wave needed +5-line fixes there).
-
-**0.5 Type-unification decision.** Host `memory::traits` types and crate types are wire-compatible twins. Decide: host re-exports crate types (preferred — one source of truth, 30+ consumer sites unchanged via `pub use`), vs. keeping host types + `From` conversions (fallback if serde/API divergence is found in 0.3). Special care: `MemoryTaint` is **security-critical provenance** (fails closed to `ExternalSync`, drives external-effect-tool gating) — its semantics, serde representation, and fail-closed defaults must be proven identical before re-exporting.
-
-**0.6 Spec doc.** Write `docs/tinycortex-migration-spec.md` version-anchored to exact reviewed SHAs (host + tinycortex), with the ownership lists above, the drift/gap/parity ledgers, and a **deletion ledger** skeleton (every legacy file, with preconditions for deletion) — coordinated with `docs/tinyagents-migration-plan-2026-07-22.md`; the TinyCortex deletion ledger lives in §2 of the spec.
-
----
-
-## 3. Cutover workstreams (Phase 1–8)
-
-Per the tinyagents rules: **adapter first → prove parity → flip ownership → delete legacy**, deletion mandatory and enumerated per step. Ordering follows the engine's dependency graph (storage first, surfaces last). Within every workstream, **implementation lands first, tests second** (see §5).
-
-**W1 — Seam scaffolding.** Create `src/openhuman/memory/tinycortex/` with the adapters in §1 (config, embeddings, chat/summariser, queue driver, sinks, bus bridge, facade). No behavior flips yet; adapters are constructed and unit-verified against the crate's inert defaults. *Deliverable: crate is linked, adapters compile, `MemoryConfig` derived from real `Config`.*
-
-**W2 — Types & trait cutover.** `memory/traits.rs` becomes re-exports of `tinycortex` types (per 0.5 decision). All 30+ external consumers (`agent/harness`, `learning`, `channels/runtime`, `subconscious`, `threads`, …) compile unchanged through the re-export. `sqlite_conn()` escape hatch on the host trait is reviewed: either upstreamed or kept as a host-side extension trait.
-
-**W3 — Store + chunks.** Flip `memory_store` internals (`UnifiedMemory`/`MemoryClient` re-implemented over `tinycortex::store` + `chunks`), keeping the host-facing `MemoryClient` API stable so `global.rs` and all RPC ops are untouched. Delete legacy `memory_store` engine files. *Gate: 0.3 parity harness green on a golden workspace.*
-
-**W4 — Queue.** `memory_queue` → `tinycortex::queue`, driven by the seam's tokio worker. Job payload/schema parity from 0.3. Delete `memory_queue`.
-
-**W5 — Tree + retrieval + score.** `memory_tree` → `tinycortex::{tree, retrieval, score}`. Host `memory/query/*` tools and `read_rpc/*` re-point to crate primitives (`query_source`, `drill_down`, `cover_window`, `fetch_leaves`, `search_entities`, MMR/hybrid scoring). `tree_source/registry.rs` wraps the crate registry; `tree_policy.rs` stays host. `source_scope` enforcement point re-verified (retrieval must still respect the per-turn allowlist — this is a security surface). Delete `memory_tree`.
-
-**W6 — Ingest.** `memory/ingest_pipeline.rs` + `memory/ingestion/` re-pointed to `tinycortex::ingest` + `score::extract` (LLM extraction via the seam's `ChatProvider`). The namespace document/graph store path stays host-side unless deliberately upstreamed (explicit decision in this workstream). `ingest_chat`/`ingest_document_with_scope` keep their signatures — 11 call sites (learning, agent harness, archivist) unchanged.
-
-**W7 — Long tail.** `memory_diff`→`diff`, `memory_entities`→`entities`, `memory_graph`→`graph`, `memory_goals`→`goals`, `memory_archivist`→`archivist`, `memory_sources` registry/local readers→`sources`, tool-memory engine→`tool_memory`, conversation storage→`conversations`. Each is small and independent; each deletes its legacy module on flip. `memory_sync` engine parts **move via W-SYNC (§8)** — the original "does not move" rule is superseded.
-
-**W8 — Test port + parity sweep + deletion-ledger close-out.** See §5. Ends with: deletion ledger fully executed, `gitbooks/developing/architecture.md` + a new `architecture/memory.md` seam doc written (the durable post-plan documentation, as `agent-harness.md` was for tinyagents), `AGENTS.md`/`CLAUDE.md` module tables updated, and the spec doc archived.
-
-### Sequencing note
-
-W3–W5 are the risky core (user data on disk). W1–W2 can land quickly; W6–W7 parallelize after W5. Expect the real-world shape to match tinyagents: one or two substantial cutover-wave PRs plus a long tail of small parity-fix PRs — budget for that tail explicitly.
-
----
-
-## 4. Git / PR / submodule workflow
-
-- **Branching:** all work on feature branches off `upstream/main` (never on `main`), small focused commits, explicit `git add <paths>` (never `-A`), one workstream ≈ one PR against `tinyhumansai/openhuman`.
-- **Engine changes → submodule PRs:** any modification to engine code (drift re-application, gap-filling, parity fixes) is committed inside `vendor/tinycortex` on a branch and PR'd to `tinyhumansai/tinycortex`. This applies equally to human contributors and LLM agents: *change the submodule, raise the PR from there.* Host PRs consume merged engine changes via `chore(vendor): bump tinycortex — <what> (tinycortex#<n>)` commits.
-- **Version lockstep:** keep the `[dependencies] tinycortex = "<version>"` pin in lockstep with the submodule tag; publish tinycortex to crates.io at each milestone so non-vendored consumers resolve (identical to the tinyagents `1.5.0` + patch pattern).
-- **Interleaving:** a typical workstream is a sandwich — (a) tinycortex PR(s) closing that module's drift/gap ledger, (b) host `chore(vendor)` bump, (c) host cutover PR (adapter flip + legacy deletion), (d) host test PR/commits. CI already handles recursive submodule checkout on all build/test lanes.
-
----
-
-## 5. Testing strategy — implementations first, tests second
-
-Ordering rule for this migration: **within each workstream, the implementation (adapter + cutover + deletion) lands first; the test work follows as the second slice.** Tests are not skipped — they are sequenced after the implementation is proven to compile and pass the *existing* suites. Concretely:
-
-1. **Slice A (impl):** adapters + cutover + legacy deletion. Gate: `cargo check` both worlds, existing crate-level integration tests (`tests/memory_roundtrip_e2e.rs`, `tests/raw_coverage/memory_tree_sync_deep_raw_coverage_e2e.rs`, etc.) still green — these exercise the public `openhuman::memory::` surface and act as the built-in parity harness for every flip.
-2. **Slice B (tests):** port and extend the test estate for the new boundary:
- - **Engine-internal tests move upstream.** The host's `#[path]`-included sibling tests (`ops_tests.rs` pattern) that poke engine internals migrate into `vendor/tinycortex` as crate tests (via tinycortex PRs), following the crate's own `*_tests.rs` sibling convention.
- - **Host keeps boundary tests:** RPC schema/handler tests, tool gating tests, seam adapter tests (config mapping, embedding signature, taint fail-closed, source-scope enforcement), and the E2E files under `tests/`.
- - **Test-harness re-plumbing** is its own task: `GLOBAL_MEMORY_TEST_LOCK`, `ensure_shared_memory_client`, and `config::TEST_ENV_LOCK` are host globals the sibling tests depend on; upstreamed tests need crate-local fixtures instead.
-3. **Coverage gate reality check:** PR CI enforces ≥80% diff coverage on changed lines, and host coverage tooling does not count tests living in the vendored crate. So "tests second" means *second slice of the same PR* (impl commits, then test commits, one PR) for host-side changes — not a separate later PR — or the coverage gate blocks the merge. Pure-deletion diffs and the seam re-export shims are the low-coverage-risk parts; the seam adapters need their host-side unit tests in the same PR.
-4. **W8 parity sweep (last):** golden-workspace fixture opened by pre- and post-migration builds (read-side comparison of recall/retrieval/tree output), full `pnpm test:rust` + JSON-RPC E2E + the memory-related `tests/*_e2e.rs` matrix, plus a manual upgrade test on a real developer workspace.
-
----
-
-## 6. Risk register
-
-| Risk | Severity | Mitigation |
-| --- | --- | --- |
-| **Engine drift** since the tinycortex port (host perf/bug fixes not upstream) | High | Phase 0.1 drift ledger is a hard gate per module; no cutover with an open ledger |
-| **On-disk format divergence** (SQLite schemas, chunk IDs, vault layout) breaking existing user workspaces | High | Phase 0.3 golden-workspace parity harness; upstream fixes only, never host shims |
-| **`MemoryTaint` / `source_scope` security semantics** silently weakened across the boundary | High | Dedicated seam tests for fail-closed taint and scope enforcement; treated as security review items in W2/W5 |
-| **Blast radius** of `memory::traits` (30+ sites), `global` (25), `chat` (~20), `redact` (12) | Medium | Re-export strategy keeps import paths stable; `redact`/`chat`/`global` never move |
-| **rusqlite / dependency version skew** (two bundled SQLites, two Cargo worlds) | Medium | Phase 0.4 alignment before any dep activation; watch `app/src-tauri` lockfile too |
-| **Coverage gate vs. vendored tests** (host CI can't count crate-side tests) | Medium | Host-side seam/boundary tests in the same PR as impl (§5.3) |
-| **Sibling `#[path]` tests bound to private internals** won't move cleanly | Medium | Explicit test-port slice per workstream; crate-local fixtures replace host globals |
-| **Queue driver behavior change** (crate has no scheduler; host loop replaces tokio pool + Sentry hooks) | Medium | W4 keeps worker cadence/backoff/error-reporting parity; verbose `[memory]`-prefixed logging per repo logging rules |
-| **Namespace doc/graph store ambiguity** (crate excludes it) | Low | Explicit keep-host decision in W6; revisit upstreaming later |
-| **Long parity tail** (tinyagents needed ~15 follow-up PRs) | Expected | Budget the tail; isolate each parity fix as a small scoped PR, engine fixes via submodule PRs |
-
----
-
-## 7. Definition of done
-
-- `memory_store`, `memory_tree`, `memory_queue`, `memory_diff`, `memory_entities`, `memory_graph`, `memory_goals`, `memory_archivist`, engine parts of `memory_sources`/`memory_tools`/conversations deleted from `src/openhuman/`; deletion ledger fully checked off.
-- Host memory code = policy/surfaces only: `memory/` (RPC, tools, sync lifecycle, preferences, scope, redact, global) + `src/openhuman/memory/tinycortex/` seam + `memory_sync/`.
-- All engine logic served by `tinycortex` at a tagged, crates.io-published version, submodule pinned in lockstep.
-- JSON-RPC method names/payloads unchanged; existing user workspaces open and recall identically (golden-workspace parity green).
-- Full suites green on both CI lanes; gitbooks/AGENTS.md updated; spec + ledgers archived.
-- **(Amended)** `memory_sync/` engine deleted from the host per §8 (W-SYNC); host retains only
- schedulers, credentials/OAuth, event-bus bridges, and RPC wrappers. `src/openhuman/inference/embeddings/`
- provider impls deleted per §8 (W-EMB); embeddings served by `tinyagents::harness::embeddings`.
-
----
-
-## 8. Amendment (2026-07-09) — sync-inclusive scope + embeddings inheritance
-
-Decisions (confirmed with the maintainer): TinyCortex becomes **all-encompassing of the sync
-modules**; "Composio-related skills syncing" = the per-toolkit memory-sync providers
-(`memory_sync/composio/providers/{gmail,slack,github,notion,linear,clickup}`); **full network in
-crate** behind a cargo feature; Composio API key via env var + config field (host still resolves
-from the `composio-direct` keychain slot in production); a **mocked + live test pair** gates the
-Composio sync port; embeddings **fully inherited from TinyAgents**.
-
-### 8.1 Revised seam contract — W-SYNC
-
-**Moves into TinyCortex** (new cargo feature `sync`, off by default so the default build stays a
-pure, network-free library):
-
-| Host source | Crate destination |
-| --- | --- |
-| `memory_sync/traits.rs` (`SyncPipeline`/`SyncOutcome`/`SyncPipelineKind`) | `src/memory/sync/traits.rs` (init/tick take `&MemoryConfig` + a `SyncContext`) |
-| `memory_sync/composio/providers/*` (all 6 toolkits + registry, orchestrator, sync_state, catalogs, user_scopes) | `src/memory/sync/composio/providers/*` |
-| New Composio HTTP client (modeled on `src/openhuman/integrations/composio/client.rs`, minus keychain) | `src/memory/sync/composio/client.rs` — **direct** (BYO key → backend.composio.dev) and **proxied** (base_url + bearer; OpenHuman-backend default) modes |
-| `memory_sync/canonicalize/` | merged into the crate's existing `ingest/canonicalize` |
-| `memory_sync/workspace/` scan logic (not the timers) | `src/memory/sync/workspace.rs` |
-| `memory_sync/sources/{audit,rebuild}.rs` | `src/memory/sync/{audit,rebuild}.rs` |
-| `memory_sync/sync_status/` SQL | `src/memory/sync/status.rs` (chunk schema lives in the crate) |
-| `memory_sources/sync.rs::sync_source` dispatcher + `reconcile.rs::ensure_composio_sources` | `src/memory/sync/dispatch.rs` |
-
-**Stays host-side:** scheduler loops (`composio/periodic.rs`, `workspace/periodic.rs`, file
-watcher — crate exposes `sync::tick_all`/`tick_pipeline(id)`, host owns tokio timers, same pattern
-as `queue::run_once`); credentials/OAuth (keychain slot `composio-direct`, RPC
-`composio.{get_mode,set_api_key,clear_api_key}`, connection lifecycle); event bus (new
-**`SyncEventSink`** trait in the crate, host adapter `src/openhuman/memory/tinycortex/sync_sink.rs`
-translates to `MemorySyncStage` bus events); RPC wrappers (`memory/ops/sync.rs`,
-`memory/schemas/sync.rs`, `memory_sources/rpc.rs` — JSON-RPC names/payloads unchanged); the
-UnifiedMemory writeback path via a new **`SkillDocSink`** trait (providers call
-`MemoryClient::store_skill_sync`, which writes the host-retained namespace-document tier — the
-crate must not depend on that tier); MCP transport (MCP pipeline stays host through W-SYNC.3).
-
-**Config/key:** crate gains `SyncConfig { budget, composio: Option<ComposioSyncConfig> }` with
-`ComposioSyncConfig { mode: Direct|Proxied, base_url, api_key: Option<SecretString>, bearer_token,
-entity_id }`; `api_key` falls back to the `COMPOSIO_API_KEY` env var (tests only — the app resolves
-from keychain and injects). `SecretString` redacts `Debug`/`Display` and skips serialization.
-
-**Tests (gate):** (a) `vendor/tinycortex/tests/composio_sync_mock.rs` — wiremock-backed gmail
-pipeline test, always-on in crate CI (pagination, cursor advance, taint = `external_sync`,
-idempotent second tick, `SkillDocSink` capture, 401 without key leakage); (b)
-`vendor/tinycortex/tests/composio_sync_live.rs` — `#[ignore]`, runs when `COMPOSIO_API_KEY` is set,
-direct-mode gmail sync with structural assertions, budget-capped (~5 records).
-
-**Ordering:** W-SYNC slots **after W6, before W7** (providers write through crate ingest; queue
-jobs through crate queue). Phases: **W-SYNC.1** scaffolding (feature + config + client + traits +
-gmail provider) → **W-SYNC.2** remaining providers + workspace/audit/rebuild/status → **W-SYNC.3**
-host flip (delete `memory_sync` bodies; wire adapters/schedulers/RPC wrappers) → **W-SYNC.4**
-cleanup (dedupe the agent-tools Composio client, remove `composio/{bus,periodic,providers}.rs`
-shims, decide MCP).
-
-**Drift:** the HOST-OWNED "live sync" classification in the drift ledger is superseded — see the
-ledger's **D4** entry.
-
-### 8.2 Embeddings inherited from TinyAgents — W-EMB
-
-`tinyagents::harness::embeddings` becomes the canonical embeddings module:
-
-- **W-EMB.1 (tinyagents PR):** extend `EmbeddingModel` with `name()`/`model_id()`/`signature()`
- (default **byte-identical** to the host format `provider={name};model={model_id};dims={dims}` —
- parity P10 / #1574); port host providers (`ollama`, `cohere`, `voyage`, `cloud`, `noop`) +
- `rate_limit.rs`/`retry_after.rs` into `harness::embeddings::providers/*`; merge host `openai.rs`
- into the existing `OpenAiEmbeddingModel`.
-- **W-EMB.2 (tinycortex PR):** add a `tinyagents` dependency; bridge/replace `EmbeddingBackend`
- with `tinyagents::harness::embeddings::EmbeddingModel` (re-export or blanket impl).
-- **W-EMB.3 (host PR):** dual submodule bump; `src/openhuman/memory/tinycortex/embeddings.rs` constructs
- tinyagents providers from `Config`; delete `src/openhuman/inference/embeddings/` provider impls; keep
- `factory.rs` (thin), `rpc.rs`, `schemas.rs`, catalog + config wiring host-side; signature-parity
- seam tests in the same PR.
-
-W-EMB is independent of W-SYNC and may run in parallel; land W-EMB.2 **before** the W-SYNC.3 flip
-so `SyncContext` is defined against the tinyagents trait once. New risk: `tinycortex → tinyagents`
-crate coupling — version bumps move in lockstep in both `[patch.crates-io]` blocks (root +
-`app/src-tauri`).
diff --git a/docs/tinycortex-migration-plan-2026-07-22.md b/docs/tinycortex-migration-plan-2026-07-22.md
deleted file mode 100644
index 91d52a3b49..0000000000
--- a/docs/tinycortex-migration-plan-2026-07-22.md
+++ /dev/null
@@ -1,417 +0,0 @@
-# TinyCortex Migration — Current-State Audit & Consolidated Plan (2026-07-22)
-
-**Status:** **DONE** on `feat/tinycortex-migration-2026-07-22`.
-[CI Full run 29925645209](https://github.com/senamakel/openhuman/actions/runs/29925645209)
-is green, including the final gate and every Linux, macOS, and Windows desktop
-shard
-(companion to `tinyagents-migration-plan-2026-07-22.md`;
-supersedes the *status/phasing* in `tinycortex-memory-migration-plan.md`,
-`tinycortex-migration-spec.md`, `tinycortex-api-gap-audit.md`, and
-`tinycortex-parity-checklist.md` — those docs' ownership splits, gap lists, and
-parity dimensions remain the reference detail. `tinycortex-drift-ledger.md`
-stays the row-level ledger but its anchors are stale — see §2).
-**Scope:** finish moving the remaining generic memory-engine code from
-`src/openhuman/` into the vendored `tinycortex` crate (`vendor/tinycortex`),
-delete the in-tree duplicates and staging code, migrate/retire the affected
-tests, and clean up every dangling doc/code reference.
-**Method:** fresh four-way audit — (1) the crate surface, (2) the core memory
-domains, (3) the periphery + the `src/openhuman/memory/tinycortex/` seam, (4) the
-docs/tests/git history — against the working tree at `main` (`5b8a9f269`,
-2026-07-22).
-
----
-
-## 1. Executive summary
-
-**The engine migration is essentially done and the docs don't know it.** All
-five `docs/tinycortex-*` docs self-describe a "W1–W2 landed; W3 partial" state,
-but git shows the full W-track landed: W1 seam (#4526), W2 type re-export
-(#4529), the W3 chunk-store cutover chain (#4532–#4559), W4 queue flip
-(#4781), W5 vector+scoring (#4790), the W7 long-tail shims (#4785–#4789),
-**engine-migration completion (#4794)**, **engine test port into the crate
-(#4820)**, and post-completion feature work (persona/coding-session ingest
-#4863) on top. The drift ledger's D1–D3 rows are all CLOSED.
-
-What remains is not "migrate the engine" but five bounded packages (§5):
-
-1. **Housekeeping** — the pin/tag story is broken (crate has *no git tags*
- despite the Cargo.toml comment demanding tag-lockstep), the host CI vendor
- suite omits the `persona` feature the host enables, and there are ~8
- broken/stale references including a seam module doc naming files that were
- never created.
-2. **Delete `memory_store/unified/`** — the explicitly "staging for removal"
- tier (~5k LOC + ~3.7k test LOC), gated by the G1 `sqlite_conn()` escape
- hatch.
-3. **W-SYNC completion** — `memory_sync/` (17.7k LOC, the largest remaining
- host mass) still runs the host provider pipelines while the crate now ships
- a full `memory::sync` Composio engine; the D4 ledger rows gate the flip.
-4. **Embedding-provider dedupe** — host `embeddings/` adapters and
- `memory_tree/score/embed/` providers now duplicate what
- `tinyagents::harness::embeddings` ships since tinyagents #58 (this package
- lands in **tinyagents**, not tinycortex — the crates split the job).
-5. **Shim retirement + funnel decision** — the compatibility shims left behind
- by W3–W7, and a policy call on the fact that domains import
- `tinycortex::memory::*` directly while the seam's re-export facade has
- **zero** consumers.
-
----
-
-## 2. Ground truth: pins, versions, and discrepancies (fix first)
-
-| Fact | Value | Where |
-| --- | --- | --- |
-| Host requirement | `tinycortex = { version = "0.1", features = ["git-diff", "persona", "sync"] }` | root `Cargo.toml:116` |
-| Path override | `[patch.crates-io] tinycortex = { path = "vendor/tinycortex" }` | `Cargo.toml:682` |
-| Vendored crate | `0.1.1`, edition 2021, **MIT** (not GPL — unlike tinyagents), repo `tinyhumansai/tinycortex` | `vendor/tinycortex/Cargo.toml` |
-| Submodule HEAD | `daaaf6ba` (`heads/main`, dependabot-era, ~50+ commits past every SHA the docs cite) | `git submodule status` |
-| Tags | **none exist** — `git describe --tags` fails; yet host `Cargo.toml:115` says "Keep the version pin in lockstep with the submodule tag" | submodule |
-| Docs' claimed pin | gitlink `a8e10f7` (exists in history, long since passed) | drift ledger / spec anchors |
-| Nested dep | tinycortex requires `tinyagents = { version = "2", path = "vendor/tinyagents" }`, **its own nested submodule pinned at v2.0.0** | `vendor/tinycortex/Cargo.toml:69` |
-| Host tinyagents req | `2.1` | root `Cargo.toml:107` |
-| Fork patch | `[patch."https://github.com/senamakel/tinyagents"]` exists *for tinycortex's sake* ("temporarily pins the embedding API port while tinyagents #58 is pending" — #58 is now merged at the tinyagents submodule HEAD) | `Cargo.toml:685-691` |
-| Host CI vendor suite | `cargo test --manifest-path vendor/tinycortex/Cargo.toml --features git-diff,sync` — **omits `persona`**, which the host enables | `.github/workflows/ci-lite.yml:859` |
-
-Version skew summary: three different tinyagents expectations (host `2.1`,
-tinycortex `2`, nested submodule `2.0.0`) resolve only via path patches. The
-tinyagents plan's WP-0 (bump `vendor/tinyagents` to v2.1.0) should be executed
-together with bumping tinycortex's *nested* `vendor/tinyagents` so both crates
-share one trait identity at one version, after which the `senamakel` patch
-block and its "temporarily pins" comment can likely be retired.
-
----
-
-## 3. What the crate already ships
-
-`tinycortex 0.1.1` exposes a single `memory` module — the engine "ported from
-OpenHuman" — with features `tokio`, `git-diff` (git2-backed `memory::diff`),
-`providers-http` (reqwest embedding/LLM providers, host does **not** enable),
-`sync` (live Composio + workspace-scan engine), `persona` (doc-06 persona
-distillation). Modules: `store` (content/vectors/kv/entity_index/safety+PII),
-`chunks`, `sources` (+readers), `score` (embed/extract/signals), `tree`
-(+runtime, bucket/document seal, flavoured trees), `queue` (SQLite job queue +
-tokio runtime), `retrieval` (hybrid search, MMR, rerank), `entities`, `graph`,
-`goals`, `tool_memory`, `conversations`, `archivist`, `ingest`
-(canonicalize→chunk→score→tree), `diff`, `sync` (composio
-clickup/github/linear/notion/slack/gmail), `providers`, `persona`
-(readers for claude_code/codex/git history), `fsutil`.
-
-Host-facing extension points (~20 public traits) with the seam's current
-implementations in parentheses: `Memory`, `MemoryStore`, `EmbeddingBackend` +
-`Embedder` (`SeamEmbedder`), `ChatProvider` (`SeamChatProvider`), `Summariser`
-(`HostSummariser`), `SealObserver` + seal-time `Embedder` bridge (`seal.rs`),
-`TreeJobSink` (`HostTreeJobSink`), `QueueDelegates` (`HostQueueDelegates`),
-`SourceReader`, `SelfIdentity`, `EntityOccurrenceIndex`, `SnapshotItemSource`,
-`GoalsGenerator`, `ConversationEventBus`/`ChannelEventHandler`,
-`PersonaStateStore`, and the sync seams `SyncStateStore` / `SyncEventSink` /
-`SkillDocSink` / `LocalDocumentSink` / `ExternalSourceReader` / `SyncPipeline`
-/ `ActionExecutor` / `IncrementalSource` (`sync.rs`, `HostSyncAdapter`).
-
-The crate consumes `tinyagents::harness::embeddings::{EmbeddingModel,
-format_embedding_signature}` in `store/vectors/embedding.rs` — that is the
-whole tinyagents dependency (the W-EMB decision made real by tinyagents #58).
-
-Crate CI: fmt, clippy `-D warnings`, build+test `--all-features`, doc build
-with warnings denied, plus a per-feature matrix (`core`, `tokio`, `git-diff`,
-`sync`, all). Offline by convention; Composio/live tests are wiremock-mocked or
-env-key-gated.
-
----
-
-## 4. Audit: what remains host-side
-
-### 4.1 Per-domain state (crate-backed file counts via `use tinycortex::`)
-
-| Domain | Files / LOC | Crate-backed | State |
-| --- | --- | --- | --- |
-| `memory/` | 69 / 18.0k | 3 | Orchestration + policy + RPC layer (by design "no SQLite here"). Predominantly host: `read_rpc/`, `schema*/`, `rpc_models`, agent tools, sync orchestration, tree *policy*. Stays, minus shim cleanup. |
-| `memory_store/` | 54 / 17.7k | 15 | Sub-stores flipped to crate (chunks, content, vectors, kv, entities, trees, safety/PII per W3/W7 markers). **`unified/` (~5k + ~3.7k tests) is README-marked "Staging for removal"** — documents/query/segments/events/profile await per-kind flips. `factories.rs` (config/provider selection) stays host. |
-| `memory_tree/` | 47 / 10.3k | 16 | Largest crate-backed surface; engine parts delegate. Host keeps RPC (`tree/rpc.rs` 1,387, `retrieval/rpc.rs`), CLI, bus subscriber, `health/` doctor (G5, host-retained by decision), and `score/embed/` **providers** (~1.9k — see WP-3). |
-| `memory_queue/` | 7 / 1.4k | 2 | W4 flipped: `worker.rs` delegates claim→dispatch→settle to `tinycortex::memory::queue::run_once` via `HostQueueDelegates`; per-kind handlers deleted. Host keeps worker pool, scheduler tick, `scheduler_gate` throttle, SQLite glue. Done, minus the `memory::jobs` re-export shim. |
-| `memory_search/` | 8 / 0.8k | 2 | W5 flipped: `scoring.rs`/`vector/mmr.rs` are near-empty shims over crate `WeightProfile`/`retrieval::mmr`. Host keeps the three agent tools. Done. |
-| `memory_tools/` | 9 / 1.4k | 3 | W7 flipped: types/store/prompt are shims over `tool_memory::{types,store,render}`. Host keeps `capture.rs` (`PostTurnHook`) + put/list tools. Done. |
-| `memory_archivist/` | 1 / 44 | 1 | Pure W7 shim over `memory::archivist`. Done. |
-| `memory_conversations/` | 2 / 0.9k | 2 | W7 shim over `memory::conversations`; host keeps `bus.rs` event-bus glue (+ a `tinychannels` legacy-message conversion). Done. |
-| `memory_diff/` | 7 / 2.0k | 11 uses | W7 flipped: engine crate-owned; host keeps RPC/tools + `DomainEvent::MemoryDiff*` publishing. Done. |
-| `memory_goals/` | 6 / 0.9k | 4 uses | W7 flipped: types/store crate-owned (byte-identical `MEMORY_GOALS.md`); host keeps agent wiring. Done. |
-| `memory_sources/` | 16 / 5.0k | 12 uses | Product registry (config-persisted connectors) with crate readers underneath. Host by design. |
-| `memory_sync/` | **73 / 17.7k** | 5 uses | **The largest remaining mass.** Host Composio provider pipelines (gmail/slack/github/notion/linear/clickup) still run host-side while the crate's `memory::sync` ships the same provider engine. W-SYNC seam (`sync.rs`, 679) is landed; the host flip (W-SYNC.3) has not happened. See WP-2. |
-| `embeddings/` | 13 / 3.1k | **0** | Bridges **tinyagents** (9 files), not tinycortex. Post-#58, the host per-provider adapters duplicate crate `harness::embeddings` providers. See WP-4. |
-| `agent_memory/`, `subconscious/` (memory parts), `learning/` (memory parts) | — | 0 | Host product consumers of the memory stack; no crate duplication. Stay. |
-
-Consumer counts (host memory tiers are deeply embedded and *stay* host, so
-these are context, not deletion blockers): `memory::` 166 files,
-`memory_store::` 132, `memory_tree::` 67, `memory_queue::` 18,
-`memory_tools::` 11, `memory_search::` 3.
-
-### 4.2 The seam — `src/openhuman/memory/tinycortex/` (11 files, ~3.2k LOC)
-
-`config.rs`, `embeddings.rs`, `chat.rs`, `summariser.rs`, `ingest.rs`,
-`seal.rs`, `sync.rs` (679), `queue_driver.rs` (1,007), `persona.rs` (446),
-`parity.rs` (`#[cfg(test)]` format pins), `mod.rs`. Healthy and intentionally
-host-owned. Two findings:
-
-- **The seam is not the funnel.** `mod.rs` re-exports crate types
- (`MemoryEntry`, `MemoryTaint`, `RecallOpts`, …) as the intended
- type-unification funnel, but **zero** files import `crate::…::tinycortex::`
- re-exports — every memory domain imports `tinycortex::memory::*` directly.
- Either convention works; pick one and record it (WP-5). Direct crate imports
- are simpler and match how `tinyagents` is consumed; if so, shrink the facade
- instead of promoting it.
-- **Stale internal doc:** `mod.rs:28-30` names sibling adapters `sinks.rs` and
- `bus.rs` that were never created (their roles landed as
- `ingest.rs`/`seal.rs`/`sync.rs`). `queue_driver.rs:21-26` still says "This
- brick is additive: nothing is flipped yet" — the flip landed in #4781.
-
-Coupling is bidirectional by design (seam reaches back into
-`memory_store`/`memory_tree`/`memory_sync` to do host work inside crate
-callbacks); not a defect, but `queue_driver.rs`'s 11 host imports will thin as
-WP-1/WP-3 shims retire.
-
-### 4.3 Broken/dangling references (resolved in WP-0)
-
-| Resolved issue | Resolution |
-| --- | --- |
-| Missing TinyAgents companion-spec link | Replaced with the existing July 22 migration plan. |
-| Missing standalone deletion-ledger link | Replaced with §2 of the TinyCortex migration spec. |
-| Wrong agent-harness documentation path | Pointed at the architecture subdirectory. |
-| Never-landed golden-workspace generator | Removed after the post-cutover parity decision descoped synthetic pre-cutover fixtures. |
-| Wrong raw-coverage test path | Corrected to the `tests/raw_coverage/` location. |
-| Stale line anchors `Cargo.toml:82`, `src/openhuman/mod.rs:130` | `tinycortex-migration-spec.md` §0.4 (actual: `Cargo.toml:116`, `mod.rs:140`) |
-| Never-created seam sibling names | Replaced with the adapters that actually landed. |
-| Developer-specific absolute path in crate docs | Replaced with repository-relative paths. |
-
-Also stale-in-place: all five docs' status headers (pre-#4794), the drift
-ledger's pin anchors, and the crate migration doc's claim that "TinyCortex
-will not own memory sync" (superseded by the plan's §8 sync-inclusive
-amendment and the crate's shipped `sync` module — the *scheduler/credentials/
-RPC* stay host, the *engine* is crate; restate the boundary in one place).
-
-### 4.4 Test inventory
-
-- **In-crate (done):** engine coverage was ported by #4820; the crate runs its
- own suite offline (wiremock Composio mock; live tests env-gated). W8's CI
- wiring exists: `ci-lite.yml:859` runs the vendor suite on submodule-pointer
- changes — **but with `--features git-diff,sync` only; `persona` is untested
- in host CI while enabled in the host build.**
-- **Dies with WP-1:** `memory_store/unified/*_tests.rs` (~3.7k LOC:
- `documents_tests` 1,275, `query_tests` 1,000, `profile_tests` 763,
- `segments_tests` 393, `events_tests` 287) go with the unified tier; port any
- still-unique assertions to the per-kind crate backends first.
-- **Retargets with WP-2:** the memory_sync suites (389 inline tests across 35
- files + provider `*_tests.rs`: github 655, gmail 301+354, slack 180, linear
- 172, clickup 155, notion 119) — post-flip, provider *engine* behavior is
- crate-tested; host keeps orchestration/bus/config tests. Integration:
- `memory_sync_pipeline_e2e.rs` (570), `memory_golden_parity_e2e.rs` (275),
- `raw_coverage/memory_sync_*` retarget to the crate-backed path.
-- **Golden parity harness:** comparators 1 & 5 green; 2/3/4 TODO;
- `frontmatter_parity` Layer-1 asserter pending; fixture generator script
- missing. Decide finish-vs-descope in WP-0 (post-cutover, parity pins matter
- mainly for `MemoryTaint`/on-disk stability — keep those, consider dropping
- the rest).
-- **Stays host:** `json_rpc_e2e.rs` memory sections, `memory_sources_e2e`
- (837), `memory_tree_summarizer_e2e` (583), `memory_roundtrip_e2e`,
- `memory_graph_sync_e2e`, `memory_fast_retrieve_e2e`, `autocomplete_memory_e2e`,
- `memory_artifacts_e2e`, the 15 `raw_coverage/memory_*` modules, and all
- subconscious/learning suites.
-
----
-
-## 5. The plan — five work packages
-
-Same conventions as the tinyagents companion plan: WP-0 first (hygiene,
-unblocks honest review), then largely independent packages; drift-ledger rows
-before deletions; failing-before/passing-after regression tests; small
-validated commits on feature branches per submodule.
-
-### WP-0 — Version/tag + CI + docs housekeeping (no engine behavior change)
-
-1. **Establish the tag discipline the Cargo comment promises:** tag
- `vendor/tinycortex` (e.g. `v0.1.1` at the current release point, or cut
- `v0.2.0` at HEAD), and record the bump workflow the plan prescribed
- (`chore(vendor): bump tinycortex …` — zero such commits exist in host
- history). Alternatively amend the comment to describe reality
- (main-tracking submodule). Either is fine; the current state (comment
- demands tags, none exist) is the worst option.
-2. **Align the nested tinyagents:** when the tinyagents plan's WP-0 bumps
- `vendor/tinyagents` to v2.1.0, bump `vendor/tinycortex/vendor/tinyagents`
- in lockstep and update tinycortex's `tinyagents = "2"` if needed; then
- evaluate retiring the `[patch."…senamakel/tinyagents"]` block and its
- obsolete "while tinyagents #58 is pending" comment (#58 is merged).
-3. **Close the persona CI hole:** add `persona` to the vendor-suite features
- in `.github/workflows/ci-lite.yml:859` (and confirm the crate's own
- feature-matrix covers `persona`, which today it does not list either).
-4. **Docs refresh:** update the five docs' status headers to post-#4794/#4820
- reality; update drift-ledger anchors (pin `daaaf6ba`+tag, note #4794/#4820/
- #4863); document the `persona` feature + seam (currently invisible in all
- five docs); restate the sync ownership boundary once (engine=crate,
- scheduler/credentials/RPC/bus=host) and fix the crate-side migration doc's
- contradictory "will not own sync" line + its absolute local path.
-5. **Fix the §4.3 broken references**, including the two code-adjacent ones:
- correct the seam module inventory and the queue-driver's stale pre-flip
- description.
-6. **Golden-parity decision:** finish comparators 2/3/4 + `frontmatter_parity`
- + the fixture script, **or** descope to the security-relevant pins
- (`MemoryTaint` byte-identity, chunk/vector on-disk format) with the
- decision recorded in the parity checklist.
-
-**Exit:** pins/tags/CI/docs agree with the tree; `grep` for the phantom paths
-comes back clean.
-
-### WP-1 — Retire `memory_store/unified/` (the "staging for removal" tier)
-
-1. Inventory the five remaining unified facets (documents, query, segments,
- events, profile — ~5k LOC) against their per-kind crate backends; flip
- callers facet-by-facet (the W3 sub-store pattern, already proven for
- chunks/content/vectors/kv/entities/trees/safety).
-2. The blocker is **G1** (`sqlite_conn()` escape hatch, ~312 refs at audit
- time): re-audit the current count, then either land the crate-side access
- the gap audit sketched or explicitly re-scope G1 to the host-retained
- namespace-document tables and record it.
-3. Decide the fate of the 10-table host-retained `UnifiedMemory`
- namespace-document tier: keep host (spec's standing decision) but move it
- out of `unified/` into a clearly-named home so "staging for removal" can
- actually be removed.
-4. Tests: port unique assertions from the ~3.7k LOC of `unified/*_tests.rs`
- to per-kind backends (crate-side where engine behavior, host-side where
- glue), then delete with the code.
-
-**Exit:** `memory_store/unified/` gone or reduced to the renamed host tier;
-`memory_store/` ≈ 9–10k LOC of glue + host tier; `memory_roundtrip_e2e` +
-`memory_golden_parity_e2e` + full mock-suite green.
-
-### WP-2 — W-SYNC.3: flip `memory_sync/` onto the crate sync engine
-
-The seam (`sync.rs`: `ExternalSourceReader`, `SkillDocSink`,
-`LocalDocumentSink`, `SyncStateStore`, `SyncEventSink`) is landed; the crate
-ships the Composio engine incl. per-provider modules. Remaining:
-
-1. Close the **D4.1–D4.4** drift rows (ledger requires this before the flip).
-2. Flip provider-by-provider (gmail first — the crate already carries the
- Gmail 413-page fix #73), keeping host-side: scheduler/periodic trigger,
- credentials, `config.toml` source registry (`memory_sources/`), event-bus
- publishing (`ChannelMessageReceived` et al.), RPC/status surface, and
- redaction/`source_scope` gating.
-3. Dedupe post-processing: host `providers/*/post_process*` vs crate provider
- modules — upstream generic normalization, keep host product policy.
-4. Tests per §4.4: engine behavior moves to crate suites (wiremock Composio),
- host keeps orchestration/bus/e2e; `memory_sync_pipeline_e2e` retargets.
-
-**Exit:** `memory_sync/` shrinks from 17.7k toward ~6–8k LOC of
-orchestration/product glue; D4 rows CLOSED; no duplicated provider parsing.
-
-### WP-3 — Embedding-provider dedupe (lands in *tinyagents*, coordinated here)
-
-Two host clusters now duplicate `tinyagents::harness::embeddings` (post-#58:
-openai/cohere/voyage/ollama/cloud + rate-limit/retry-after):
-
-1. `src/openhuman/inference/embeddings/` adapters (`openai/voyage/cohere/ollama/
- cloud_adapter.rs`, `provider_trait.rs`) → construct crate
- `EmbeddingModel`s directly; host keeps `rpc.rs` (1,479), `schemas.rs`,
- `catalog.rs`, `factory.rs` (config/BYOK selection, #4056 dimension
- gating).
-2. `memory_tree/score/embed/{openai_compat,ollama,cloud,factory}.rs` (~1.9k)
- → same crate models via the seam's `SeamEmbedder`/`EmbedderBridge`.
-
-Because tinycortex consumes the same `EmbeddingModel` trait, this single
-change serves both crates — it is the concrete payoff of the W-EMB decision.
-Sequence after WP-0's tinyagents version alignment.
-
-**Exit:** one embedding-provider implementation per provider across the
-workspace; `embeddings_rpc_e2e` (822) + `ollama_embeddings_fallback_e2e` (234)
-green against the crate-backed path.
-
-### WP-4 — Shim retirement + funnel decision
-
-1. **Funnel policy:** adopt direct `tinycortex::memory::*` imports as the
- convention (matches reality and the tinyagents precedent), shrink the seam
- `mod.rs` facade to the types host code genuinely re-brands
- (`MemoryTaint` stays pinned by parity tests) — or the reverse; either way,
- record it in the spec and stop carrying both.
-2. Retire compatibility shims whose consumers can move: `memory_tree/tools.rs`
- (points at `memory`), `memory_store/trees` legacy paths, the
- `memory_queue`→`memory::jobs` re-export, `memory_archivist` (44-line shim —
- move its 2 call sites and delete the domain), and the W5/W7 near-empty
- shims once import counts hit zero (`memory_search/scoring.rs`,
- `vector/mmr.rs`, `memory_tools/{types,store}.rs`).
-3. Thin `queue_driver.rs` (1,007) as WP-1 removes its `memory_store`
- reach-backs.
-
-**Exit:** shim count measurably down (each deletion = one commit with its
-import-migration); seam ≤ ~2.5k LOC; no module whose entire body is a
-re-export except deliberate facades recorded in the spec.
-
-### WP-5 — Exit gate
-
-- Full suite: `scripts/test-rust-with-mock.sh` (incl. the 15
- `raw_coverage/memory_*` modules), vendor suite
- `cargo test --manifest-path vendor/tinycortex/Cargo.toml --features
- git-diff,sync,persona`, slim disabled build (`--no-default-features`
- — memory domains are ungated but the standing repo rule applies),
- `pnpm rust:check`.
-- Drift ledger: D4 CLOSED; new rows for every WP-1/WP-2 deletion; the spec's
- §2 deletion-ledger skeleton filled in with actuals.
-- Docs: the five tinycortex docs + `src/openhuman/memory*/README.md` files +
- `gitbooks/developing/architecture.md` reflect the post-flip reality; this
- plan stamped done.
-
-### Execution record (2026-07-22)
-
-| Package | Result |
-| --- | --- |
-| WP-0 | TinyAgents unified at 2.1 across OpenHuman, TinyCortex, and TinyFlows; obsolete fork patch removed; TinyCortex CI covers `persona`; docs and phantom references repaired. TinyCortex intentionally tracks reviewed upstream commits rather than nonexistent tags. |
-| WP-1 | G1 count is zero. The ten-table namespace/document product tier is host-owned, so the complete `unified/` directory was renamed to `namespace_store/` instead of deleted as engine duplication. Its 153 targeted tests pass. |
-| WP-2 | The live default path was already TinyCortex-backed. D4 is CLOSED; dead Gmail duplicate removed; remaining provider task/profile projections explicitly classified as product policy. Provider tests pass (301). |
-| WP-3 | Concrete provider transports deduplicated into TinyAgents. The memory tree now uses a thin `ProviderEmbedder`; Ollama's 8k context/batch and missing-model guidance moved upstream before the host client was deleted. TinyAgents embedding tests pass (38); host library check passes. |
-| WP-4 | Archivist, search scoring/MMR, tool-memory type/store, tree-tool, jobs-alias, and unused seam type facades retired. Direct crate imports are canonical. Seam production code is 2,229 LOC (below the 2.5k exit target). |
-| WP-5 | Local focused validation is recorded above; the slim `--no-default-features` build also passes. [CI Full run 29925645209](https://github.com/senamakel/openhuman/actions/runs/29925645209) is green: core quality and full tests, TinyCortex, Tauri, frontend, mock-backend Rust E2E, Playwright, three desktop builds, every launched desktop shard, and the final gate. Two first-attempt Linux jobs ended without uploaded logs; rerunning only failed jobs passed the Linux build, Rust integration suite, and all eight Linux shards. |
-
----
-
-## 6. Risks and standing gotchas
-
-- **`MemoryTaint` is security-critical.** The type is proven byte-identical
- host↔crate and fails closed to `ExternalSync`; the parity pins in
- `tinycortex/parity.rs` are the regression guard — whatever WP-0 decides
- about the golden harness, **keep these**.
-- **Redaction and `source_scope` gating stay host.** WP-2 must not let crate
- sync code become a path around host redaction or the source allowlist —
- review the `SyncEventSink`/`LocalDocumentSink` implementations for every
- provider flipped.
-- **On-disk compat:** chunk/vector formats, `MEMORY_GOALS.md` byte-identity,
- and the P5 fresh-DB divergence (3 legacy inline-embedding columns in
- `mem_tree_chunks`) — migrations of user data must be forward-only and
- tested against a pre-migration workspace fixture.
-- **MIT vs GPL:** tinycortex is MIT (tinyagents is GPL-3.0) — moving host code
- *down* into tinycortex relicenses it; fine for our own code, but keep the
- "no product policy / no keys / nothing openhuman-branded as API" rule, and
- don't move anything derived from GPL-only sources into the MIT crate.
-- **Two Cargo worlds + nested submodule:** vendor bumps now touch up to three
- lockfiles (root, `app/src-tauri`, and tinycortex's own) and two submodule
- pointers (`vendor/tinycortex`, `vendor/tinycortex/vendor/tinyagents`). CI
- clones with `submodules: recursive` for the vendor suite — verify after any
- bump.
-- **Event-bus surface:** `memory_sync` publishes 7 distinct `DomainEvent`
- variants; the WP-2 flip must keep publishing them from host callbacks (the
- crate has no event bus by design).
-
----
-
-## 7. Quick reference — disposition of every audited module
-
-| Module | Verdict |
-| --- | --- |
-| `memory_store/unified/` | DELETE after per-kind flips; host tier re-homed (WP-1) |
-| `memory_store/` sub-stores, `factories.rs` | DONE (crate-backed) / STAYS (host glue) |
-| `memory_sync/` provider engines | FLIP to crate `memory::sync` (WP-2) |
-| `memory_sync/` scheduler, bus, RPC, credentials | STAYS |
-| `embeddings/` per-provider adapters | REPLACE with `tinyagents::harness::embeddings` models (WP-3) |
-| `embeddings/` rpc/schemas/catalog/factory | STAYS |
-| `memory_tree/score/embed/` providers | REPLACE via seam + crate models (WP-3) |
-| `memory_tree/` engine files | DONE (crate-backed); RPC/CLI/bus/health STAY |
-| `memory_queue/`, `memory_search/`, `memory_tools/`, `memory_diff/`, `memory_goals/`, `memory_conversations/` | DONE — retire residual shims when import counts reach zero (WP-4) |
-| `memory_archivist/` | DELETE the 44-line shim after moving 2 call sites (WP-4) |
-| `memory/` (orchestration/RPC/tools/tree-policy) | STAYS |
-| `memory_sources/` | STAYS (product registry over crate readers) |
-| `agent_memory/`, `subconscious/`, `learning/` | STAYS (consumers, no duplication) |
-| Seam `src/openhuman/memory/tinycortex/` | STAYS, shrinks; fix stale module docs (WP-0), thin `queue_driver.rs` (WP-4) |
-| Golden-parity harness | FINISH or DESCOPE by decision (WP-0); `MemoryTaint`/format pins KEEP |
diff --git a/docs/tinycortex-migration-spec.md b/docs/tinycortex-migration-spec.md
deleted file mode 100644
index 131557c89b..0000000000
--- a/docs/tinycortex-migration-spec.md
+++ /dev/null
@@ -1,215 +0,0 @@
-# TinyCortex Memory Migration — Spec (Phase 0.5 / 0.6)
-
-**Status:** Post-engine-cutover reference. W1–W8 and the crate-owned engine test
-port landed in OpenHuman #4794/#4820, with persona/coding-session ingest in
-#4863. The remaining host consolidation is tracked by
-[`tinycortex-migration-plan-2026-07-22.md`](tinycortex-migration-plan-2026-07-22.md).
-This document retains the ownership contract and deletion ledger detail.
-
-**Companion plan:** [`tinycortex-memory-migration-plan.md`](tinycortex-memory-migration-plan.md)
-**Ledgers:** [`tinycortex-drift-ledger.md`](tinycortex-drift-ledger.md) ·
-[`tinycortex-api-gap-audit.md`](tinycortex-api-gap-audit.md) ·
-[`tinycortex-parity-checklist.md`](tinycortex-parity-checklist.md)
-
-## Version anchors
-
-| Repo | SHA | Note |
-| --- | --- | --- |
-| `tinyhumansai/openhuman` | `7850cf363559bcbb7ba688cbc4fccdb6bd9ce754` | host audit base (`main`, 2026-07-04) |
-| `tinyhumansai/tinycortex` | `d1a8c7be2babc8fff7a72ed93861f459f3d6fa58` | crate audit base (v0.1.1) |
-| `tinyhumansai/tinycortex` | `33dda943053e61ef585fc39647cf1854344b6323` | audit base **+ #59** (native-dep alignment, §0.4) merged |
-| `tinyhumansai/tinycortex` | `a8e10f7dd8ebdb9b0905e1380fefcc6bf5a65207` | historical cutover gitlink — **+ #63/#64** (D2/D1 drift closure) merged |
-| `tinyhumansai/openhuman` | `5b8a9f269` | 2026-07-22 consolidation audit base |
-| `tinyhumansai/tinycortex` | `daaaf6ba5f02635c08deae2b2b2ed7fcc8c06b6a` | 2026-07-22 reviewed gitlink; no upstream tags exist, so the host tracks reviewed main commits |
-| `tinyhumansai/tinycortex` | `7b4b115` | current migration branch: TinyAgents 2.1 alignment + corrected ownership docs |
-
-Port line (derived by content, §0.1): **after 2026-06-25, before 2026-06-28** for engine features.
-
----
-
-## 0.5 — Type-unification decision
-
-**Decision: host re-exports the crate types** (`pub use tinycortex::memory::{…}` from
-`memory/traits.rs`), the preferred option in the plan. One source of truth; 30+ consumer sites keep
-their import paths through the re-export. Rationale confirmed by 0.3 (wire-compatible on disk) and the
-`MemoryTaint` proof below. Fallback (host types + `From` conversions) is **not** needed — no
-serde/API divergence was found.
-
-### MemoryTaint — security-critical, proven identical (required before re-export)
-
-`MemoryTaint` drives external-effect-tool gating (a tainted subconscious turn must refuse
-`external_effect` tools). Its serde form, db strings, and fail-closed default were compared
-byte-for-byte:
-
-| Property | Host (`memory/traits.rs:25`) | Crate (`types.rs:26`) | Match |
-| --- | --- | --- | --- |
-| Variants | `Internal` (`#[default]`), `ExternalSync` | `Internal` (`#[default]`), `ExternalSync` | ✅ |
-| serde | `snake_case` | `snake_case` | ✅ |
-| `as_db_str` | `internal` / `external_sync` | `internal` / `external_sync` | ✅ |
-| `from_db_str` unknown | → `ExternalSync` (fail-closed) | → `ExternalSync` (fail-closed) | ✅ |
-
-The **more restrictive** taint is the default and the unknown-decode target on both sides — the
-fail-closed-to-`ExternalSync` invariant is preserved. Re-exporting `MemoryTaint` from the crate does
-not weaken provenance. A dedicated seam test (W2) pins this: unknown db string → `ExternalSync`,
-`Default::default()` → `Internal`, and round-trip of both db strings.
-
-### `sqlite_conn()` escape hatch (W2 sub-decision)
-
-The host `Memory` trait's `sqlite_conn()` (gap G1) is **not** part of the re-exported crate trait.
-Keep it as a **host-side extension trait** during the transition; migrate internal raw-SQL callers to
-`tinycortex::memory::chunks::with_connection` in W3; drive the residual count to zero in the deletion
-ledger. Re-export covers the data types (`MemoryEntry`, `MemoryCategory`, `MemoryTaint`, `RecallOpts`,
-`NamespaceSummary`, `GraphRelationRecord`, `RetrievalScoreBreakdown`, `NamespaceMemoryHit`, …) and the
-`Memory` trait's async CRUD surface; the escape hatch stays host until W3 retires it.
-
----
-
-## 0.4 — Toolchain baseline (result)
-
-| Check | Result |
-| --- | --- |
-| Crate edition | 2021 (matches host) ✅ |
-| `[patch.crates-io] tinycortex = { path = "vendor/tinycortex" }` | pre-staged in **both** worlds (root + `app/src-tauri`) ✅ |
-| CI submodule checkout | recursive on all build/test lanes; covers `vendor/tinycortex` ✅ (verify release lanes in W1, as tinyagents needed) |
-| **rusqlite alignment** | ✅ **resolved & merged (#59).** Crate was pinned `0.32` (bundled), host pins `=0.40.0` (bundled). Two `links = "sqlite3"` = hard Cargo error. Fixed in #59 (bump to `0.40` + `usize`→`i64`/`try_from` — the same sweep that closed drift **D3**). |
-| **git2 alignment** | ✅ **resolved & merged (#59).** Crate was pinned `0.19`, host `0.21` (vendored-libgit2). Two `links = "git2"`. Fixed in #59 (bump to `0.21` + API deltas: `Tag::message`, `StringArray::Iter`, `Buf::as_str`). |
-| Crate compiles with aligned deps | ✅ `cargo check --all-targets` clean; 38 diff/checkpoint tests pass. |
-| **Host root world compiles with dep active** | ✅ `cargo check --manifest-path Cargo.toml --lib` **exit 0** with `tinycortex = "0.1"` active (`Cargo.toml:116`) + submodule at `33dda94`. **No `multiple packages link to native library` error** — one bundled SQLite + one libgit2 confirmed. **Now landed** (post-#59-merge): the `[dependencies]` line and gitlink are committed on the working branch, not reverted. Re-verified 2026-07-09. |
-| Host `app/src-tauri` world | to verify in W1 (separate Cargo world / lockfile). |
-| `GGML_NATIVE=OFF` macOS ARM | to verify on a macOS runner in W1 (no macOS host here). |
-
-**Activation landed (post-#59).** The native-dep alignment merged upstream as **#59** and the host
-gitlink was bumped to `33dda94`, so — per the submodule rule (bump only to a **merged** SHA) — W1's
-activation is now in place: `[dependencies] tinycortex = "0.1"` is active in the root world
-(`Cargo.toml:116`), the seam (`src/openhuman/memory/tinycortex/`) is wired (`src/openhuman/mod.rs:140`), and
-`cargo check --lib` is **exit 0**. Remaining §0.4 follow-ups: the `app/src-tauri` world and the
-`GGML_NATIVE=OFF` macOS-runner check still verify in W1 (see rows above).
-
----
-
-## 1. Ownership split (canonical, refined by the audits)
-
-### Moves to TinyCortex (delete from host after cutover)
-
-| Host module | Crate counterpart | Substrate tables that move |
-| --- | --- | --- |
-| `memory_store/{chunks,content(core),vectors,kv,entity_index,safety}` | `store/`, `chunks/` | `mem_tree_chunks`, `mem_tree_chunk_embeddings(+reembed_skipped)`, `vectors`, `kv_global`, `kv_namespace`, `store_meta`, `mem_tree_entity_index`, `mem_tree_entity_edges`, `mem_tree_entity_hotness`, `mem_tree_ingested_sources`, `mcp_writes`, `legacy_marker` |
-| `memory_tree/{tree,retrieval,score,summarise}` | `tree/`, `retrieval/`, `score/` | `mem_tree_trees`, `mem_tree_summaries(+embeddings,+reembed_skipped)`, `mem_tree_buffers`, `mem_tree_score` |
-| `memory_queue/` | `queue/` | `mem_tree_jobs` |
-| `memory/ingest_pipeline.rs` internals | `ingest/` | — |
-| `memory_diff`, `memory_entities`, `memory_graph`(engine), `memory_goals`, `memory_archivist`, `memory_sources`(registry + local readers), `memory_tools`(engine), `memory_conversations`(engine), `memory_search`(`vector`,`scoring`) | same-named crate modules | — |
-| `memory/traits.rs` core types | `tinycortex::memory::{…}` (re-export) | — |
-
-### Stays in OpenHuman (product policy, I/O, surfaces)
-
-- **RPC surfaces:** `memory/{ops,schemas,schema,read_rpc}`, `rpc_models.rs`. Method names/payloads unchanged.
-- **Agent tools:** `memory/tools/`, `memory/query/`, `memory_search/tools/`, `memory_tools`(tool surface) — thin wrappers over crate retrieval + `SecurityPolicy` gating.
-- **Live sync (amended 2026-07-09, plan §8 / W-SYNC):** the sync **engine** (pipelines, per-toolkit
- Composio providers + HTTP client, canonicalize, sync_state, audit/rebuild, sync_status query,
- dispatcher) **moves to the crate** behind an optional `sync` cargo feature. The crate's
- "never makes a network call" invariant becomes **feature-scoped**: the default build stays
- network-free; the `sync` feature adds an HTTP Composio client whose credentials are injected by
- the host. Host retains: scheduler loops (tick-driven crate, like `queue::run_once`),
- credentials/OAuth (keychain `composio-direct`), event-bus bridges via a new **`SyncEventSink`**
- seam trait, RPC wrappers (`memory/{ops,schemas}/sync.rs`, `memory_sources/rpc.rs`), and the
- UnifiedMemory writeback via a new **`SkillDocSink`** seam trait. MCP transport stays host.
-- **Process glue:** `memory/global.rs` singleton + queue worker; `memory/source_scope.rs` task-locals; `memory/chat.rs`; embeddings provider wiring. *(Amended, plan §8 / W-EMB: the provider **implementations** in `src/openhuman/inference/embeddings/` migrate upstream into `tinyagents::harness::embeddings` — trait gains `name`/`model_id`/`signature` byte-pinned to `provider={name};model={model};dims={dims}` (P10) — and tinycortex bridges `EmbeddingBackend` to that trait; the host keeps factory/config/RPC wiring only.)*
-- **Policy/UX:** `preferences.rs`, `remember.rs`, `tree_policy.rs`, `util/redact.rs`, config mapping.
-- **Host-retained `UnifiedMemory` namespace-document tier** (0.3 key finding) — the 10 tables that
- coexist in the shared DB but **do not move**: `memory_docs`, `graph_global`, `graph_namespace`,
- `episodic_log` (+ `episodic_fts` + triggers), `event_log` (+ `event_fts`, `event_embeddings`,
- triggers), `conversation_segments`, `segment_embeddings`, `vector_chunks`, `user_profile`.
- These live in `memory_store/namespace_store/{init,fts5,events,segments,profile}.rs` and remain host — the
- crate is the **primitive substrate**, not a drop-in for the whole DB.
-- **Content-store host surfaces the crate explicitly excludes:** `content::wiki_git`,
- `content::obsidian`, `content::obsidian_registry`.
-
-### The adapter seam: `src/openhuman/memory/tinycortex/` (W1, mirrors `src/openhuman/agent/tinyagents/`)
-
-**W1 seam files** (all against seam traits already present in the crate, §0.2):
-`embeddings.rs` (`EmbeddingBackend`/`Embedder`), `chat.rs` (`ChatProvider`/`Summariser`×2/
-`EntityExtractor`/`GoalsGenerator`), `queue_driver.rs` (`QueueDelegates` + tokio worker loop +
-Sentry/bus), `config.rs` (`Config`→`MemoryConfig`), `sinks.rs` (`TreeJobSink`/`TreeLeafSink`/
-`SnapshotItemSource`/`EntityOccurrenceIndex`), `sync.rs` (sync outcomes → `DomainEvent`),
-`mod.rs` (adapter namespace + compatibility re-exports + boundary doc). New
-engine consumers import `tinycortex::memory::*` directly; the seam owns
-implementations rather than serving as a second type funnel. All 17 W1 seam
-traits confirmed present (§0.2).
-
-**Later seam additions (amended 2026-07-09):**
-
-- **W-EMB rebridge** — `embeddings.rs` is re-pointed from `openhuman::embeddings` to
- `tinyagents::harness::embeddings::EmbeddingModel` (crate bridges `EmbeddingBackend` to that trait,
- plan §8.2 / gap-audit roster). Seam file stays; its backing implementation moves upstream.
-- **W-SYNC seam file** — `sync_sink.rs` adds the host adapters for **two new crate traits** landing
- with W-SYNC.1 (not among the 17 above; they do not exist in the crate at the Phase-0 SHA):
- `SyncEventSink` (→ `MemorySyncStage` bus events) and `SkillDocSink` (→
- `MemoryClient::store_skill_sync`, the host-retained namespace-document tier). See plan §8.1 and the
- gap-audit roster.
-
----
-
-## 2. Deletion ledger
-
-Every legacy engine file is deleted only when its module's **drift row is closed**, its **gaps are
-resolved**, and the **golden-workspace parity harness is green** for its flip. Counts from the host
-audit SHA.
-
-| Legacy module | Files (test files) | Deletes in | Preconditions |
-| --- | --- | --- | --- |
-| `memory_store/` | 66 (11) | W3/WP-1 | drift **D3** closed; gap **G1** migrated completely (zero `sqlite_conn()` call sites at the 2026-07-22 audit); parity P3/P5/P11/P12 green; namespace tier re-homed to `namespace_store/` as host-retained |
-| `memory_tree/` | 65 (7) | W5 | gaps **G3** (seal-embed), **G6** (2× Summariser) resolved; `source_scope` allowlist re-verified; parity P7/P11 green; `health/` + `tree_policy.rs` kept host (G5) |
-| `memory_queue/` | 10 (1) | W4 | drift **D2** closed (predicate upstreamed); job payload_json parity (P4/P9); host worker loop + Sentry/degraded wiring kept host |
-| `memory_conversations/` | 7 (1) | W7 | drift **D1** closed; `bus.rs` kept host |
-| `memory_diff/` | 7 (0) | W7 | git-ledger parity (P9) green |
-| `memory_entities/` | 3 (0) | W7 | parity P8 green |
-| `memory_graph/` | 3 (0) | W7 | gap **G2** resolved (derive-on-read parity vs host-retained `graph_*`) |
-| `memory_goals/` | 7 (0) | W7 | seam `GoalsGenerator` wired |
-| `memory_archivist/` | 6 (0) | W7 | `TreeLeafSink` seam wired |
-| `memory_sources/` | 16 (0) | W7 / W-SYNC | registry + local readers move (W7); `sync.rs` dispatcher + `reconcile.rs` move in W-SYNC; `rpc.rs` kept host |
-| `memory_sync/` (engine) | — | **W-SYNC.3** | drift **D4** closed; W6 landed (crate ingest live); mocked + live Composio test pair green; sync-status parity green; schedulers/bus/RPC/keychain kept host |
-| `src/openhuman/inference/embeddings/` (provider impls) | — | **W-EMB.3** | tinyagents provider port merged; signature parity (P10) green; `factory.rs`(thin)/`rpc.rs`/`schemas.rs`/catalog kept host |
-| `memory_tools/` | 10 (1) | W7 | engine → `tool_memory/`; tool surface kept host |
-| `memory_search/` | 8 (0) | W5 | `vector`/`scoring` → crate `retrieval`/`score`; `tools/` kept host |
-| `memory/ingest_pipeline.rs` internals | (thin entry points kept) | W6 | `ingest_chat`/`ingest_document_with_scope` signatures unchanged; 11 call sites untouched |
-
-### 2026-07-22 consolidation actuals
-
-| Package | Actual result |
-| --- | --- |
-| WP-1 namespace tier | `memory_store/unified/` removed and re-homed byte-for-byte as `memory_store/namespace_store/`; G1 re-audit found zero `sqlite_conn()` call sites. The retained ten-table product store explains why total `memory_store` remains 17.7k LOC rather than the plan's speculative 9–10k target. |
-| WP-2 sync | The default provider `sync()` and `run_connection_sync` already call the TinyCortex engine. Deleted the dead host Gmail sync parser; renamed GitHub/Notion/Linear/ClickUp product projections from `sync.rs` to `normalization.rs`. D4.1-D4.4 are CLOSED. The retained 17.2k LOC is schedulers, bus/RPC, action tools/catalogs, credentials, profiles, post-processing, and product task projections; 6.9k LOC is provider catalogs/tools/normalization/profile/RPC alone. |
-| WP-3 embeddings | Deleted host OpenAI, Cohere, Voyage, general Ollama, memory-tree cloud, and memory-tree Ollama provider implementations (746 production LOC) plus their obsolete 828-line raw-coverage suite. Provider transport now has one implementation in TinyAgents; OpenHuman retains selection and credential/privacy adapters. |
-| WP-4 shims | Deleted `memory_archivist`, `memory_search::{scoring,vector}`, `memory_tools::{types,store}`, `memory_tree::tools`, and the `memory::jobs` alias. Removed the unused TinyCortex type facade; direct `tinycortex::memory::*` imports are the convention. The seam is 2,229 pre-test LOC. |
-
-**Kept host (never deleted):** `memory/{ops,schemas,schema,read_rpc,tools,query,tree_source,
-ingestion,util}`, `memory/{global,source_scope,chat,sync,preferences,remember,tree_policy,rpc_models,
-traits(→re-exports)}.rs`, `memory_sync/`'s host-retained shell only (schedulers `periodic.rs`,
-`bus.rs` subscribers, RPC registration — the engine moves in W-SYNC, plan §8), `memory_store/namespace_store/*` (the namespace-document
-tier), `memory_store/content/{wiki_git,obsidian,obsidian_registry}`, `memory_tree/health/`, and the
-new `src/openhuman/memory/tinycortex/` seam.
-
-## 3. Workstream order (one workstream ≈ one host PR)
-
-W1 seam scaffolding → W2 types/trait re-export → W3 store+chunks → W4 queue → W5 tree+retrieval+score
-→ W6 ingest → **W-SYNC** (sync engine + Composio client, plan §8) → W7 long tail → W8 test-port +
-golden parity sweep + deletion-ledger close-out. **W-EMB** (embeddings inheritance from tinyagents,
-plan §8.2) runs in parallel; W-EMB.2 must land before the W-SYNC.3 flip.
-
-Each risky workstream is a sandwich (plan §4): (a) tinycortex PR(s) closing that module's drift/gap
-ledger, (b) host `chore(vendor): bump tinycortex`, (c) host cutover PR (adapter flip + legacy
-deletion + host-side tests in the same PR for the ≥80% diff-coverage gate).
-
-## 4. Security review items (must have dedicated seam tests)
-
-1. **`MemoryTaint` fail-closed to `ExternalSync`** — proven identical (0.5); pin with a W2 seam test.
-2. **`source_scope` per-turn allowlist** — must survive the W5 retrieval cutover; the retrieval
- primitives (`query_source`/`query_topic`/`drill_down`) run inside the host's task-local scope, and
- a W5 seam test must assert an out-of-allowlist source is not returned.
-3. **Composio credential handling (W-SYNC)** — the crate holds the key only as a redacted
- `SecretString` (`Debug`/`Display` masked, serialization skipped); production resolution stays in
- the host keychain (`composio-direct`), the `COMPOSIO_API_KEY` env fallback is test-only; a seam
- test asserts the key never appears in `MemoryConfig` `Debug` output or client error messages
- (401 path included).
-4. **Sync taint provenance (W-SYNC)** — every crate-side sync ingest must stamp
- `MemoryTaint::ExternalSync`; the mocked Composio pipeline test pins this.
diff --git a/docs/tinycortex-parity-checklist.md b/docs/tinycortex-parity-checklist.md
deleted file mode 100644
index 6fc0c30068..0000000000
--- a/docs/tinycortex-parity-checklist.md
+++ /dev/null
@@ -1,191 +0,0 @@
-# TinyCortex Data-Format Parity Checklist (Phase 0.3)
-
-**Status (2026-07-22):** The engine cutover and crate test port are complete.
-The proposed pre-migration golden-fixture generator and differential
-comparators 2–4 are deliberately **descoped**: there is no trustworthy
-pre-cutover binary/fixture left to generate them from after cutover. Retained
-gates are the security-critical `MemoryTaint` byte/serde pins, deterministic
-chunk IDs, vector encoding/signature, content paths, schema composition,
-idempotent reopen, and the host public-surface E2E suites.
-
-**Purpose.** Existing user workspaces must open **unchanged** after every cutover flip.
-This checklist enumerates every on-disk format shared between the host engine and TinyCortex,
-records the audit result, and specifies the **golden-workspace parity harness** that gates W3, W5, W6.
-
-**Hard rule (plan §0.3/§6):** any mismatch is fixed **upstream in tinycortex**, never papered over
-with a host shim.
-
-Anchors: historical audit host `7850cf363` · crate `d1a8c7be`; consolidation
-base host `5b8a9f269` · reviewed crate `daaaf6ba` · migration branch `7b4b115`.
-
-## Ownership tiers in the shared workspace (key finding)
-
-A user workspace's `chunks.db` (and content vault) holds **two tiers**:
-
-1. **Crate-owned substrate** — moves to TinyCortex, schema must match byte-for-byte:
- `vectors`, `kv_global`, `kv_namespace`, `store_meta`, `legacy_marker`, `mcp_writes`,
- `mem_tree_chunks`, `mem_tree_chunk_embeddings`, `mem_tree_chunk_reembed_skipped`,
- `mem_tree_summaries`, `mem_tree_summary_embeddings`, `mem_tree_summary_reembed_skipped`,
- `mem_tree_buffers`, `mem_tree_trees`, `mem_tree_score`, `mem_tree_entity_index`,
- `mem_tree_entity_edges`, `mem_tree_entity_hotness`, `mem_tree_ingested_sources`,
- `mem_tree_jobs` **(20 tables — exact name parity confirmed)**.
-
-2. **Host-retained `UnifiedMemory` namespace-document tier** — stays host (the "namespace
- document/graph store" plan §1 keeps host), coexisting in the **same** DB file:
- `memory_docs`, `graph_global`, `graph_namespace`, `episodic_log` (+ `episodic_fts` virtual +
- `episodic_ai/ad/au` triggers), `event_log` (+ `event_fts` + `event_embeddings` +
- `event_ai/ad/au` triggers), `conversation_segments`, `segment_embeddings`, `vector_chunks`,
- `user_profile` **(10 tables + FTS + triggers)**.
-
- These live in `src/openhuman/memory/store/namespace_store/{init,fts5,events,segments,profile}.rs`.
- **The host continues creating/reading these in the same DB the crate now manages** —
- the crate's `chunks::with_connection` opens the shared handle; host `UnifiedMemory` schema
- init runs alongside the crate's. Parity requirement: crate schema init and host namespace-store
- init must **compose without collision** on both fresh and existing DBs.
-
-## Parity results by format dimension
-
-| # | Format | Result | Evidence |
-| --- | --- | --- | --- |
-| P1 | **Deterministic chunk ID** | ✅ **IDENTICAL** | `chunk_id()` = SHA-256 over `source_kind.as_str()` `\0` `source_id` `\0` `seq_in_source.to_be_bytes()` `\0` `content`, first 32 hex chars. Host `memory_store/chunks/types.rs:269` vs crate `chunks/types.rs:282` — byte-for-byte identical. |
-| P2 | **Vector encoding (packed f32)** | ✅ **IDENTICAL** | `vec_to_bytes`: little-endian `f32::to_le_bytes`, 4 bytes/elem, no header. Host `vectors/store.rs:467` vs crate `store/vectors/store.rs:397` — identical. |
-| P3 | **`vectors` table schema** | ✅ **IDENTICAL** | `(id TEXT, namespace TEXT, text TEXT, embedding BLOB, metadata TEXT DEFAULT '{}', created_at REAL, updated_at REAL, PRIMARY KEY(namespace,id))` + `idx_vectors_ns`. Identical. |
-| P4 | **`mem_tree_jobs` (queue) columns** | ✅ **MATCH** | Both persist `(id, kind, payload_json, dedupe_key, status, attempts, max_attempts, available_at_ms, locked_until_ms, last_error, created_at_ms, started_at_ms, completed_at_ms)` (identical INSERT column list). Job **payload_json** shapes must also match — verify per `JobKind` in harness (P9). |
-| P5 | **`mem_tree_chunks` base columns** | ✅ **MATCH (base)** ⚠️ **new-DB divergence** | Base 15 columns identical (`id…chunk_id`). **Divergence:** crate's `CREATE` inlines 3 legacy embedding columns (`model_signature TEXT, vector BLOB, dim INTEGER`) that the host **dropped** after migrating inline embeddings to the `mem_tree_chunk_embeddings` sidecar (host `chunks/store.rs:110` comment, #1574). **Existing DBs: compatible** — both run `CREATE TABLE IF NOT EXISTS` (no-op on existing) + `migrate_legacy_embeddings_to_sidecar` (crate `chunks/migrations.rs:23`). **Fresh DBs: crate adds 3 unused columns.** Risk: positional `INSERT`/`SELECT *`. **Action: harness asserts fresh-DB schema equality; if the 3 cols matter, drop them upstream.** |
-| P6 | **Content vault paths** | ✅ **IDENTICAL sig** ⚠️ verify `sanitize_filename` | `chunk_rel_path(source_kind, source_id, chunk_id)` and `summary_rel_path(tree_kind, scope_slug, level, summary_id)` — identical signatures, same per-`source_kind` branching (`email` special-case). Host sanitizes chunk-id colons → `-` (`content/paths.rs:284`); crate uses `sanitize_filename` (`paths.rs:179`). **Action: harness asserts identical relative paths for a corpus of colon/unicode/long chunk-ids** (Windows-illegal chars are the risk). |
-| P7 | **YAML frontmatter** | ✅ **MATCH** (verify key order) | Summary markdown frontmatter delimited by `---\n … ---\n` (crate `content/compose/summary.rs:76,127`; `split_front_matter` on `rposition(line=="---")`). **Action: harness asserts identical frontmatter key set + order + serialization** for chunk & summary markdown (byte-compare composed files). |
-| P8 | **Entity markdown** | ⏳ harness | `entities/` registry markdown. Host `memory_entities` (0 external refs) ↔ crate `entities/`. Low risk (full port, no drift). Harness byte-compares entity files. |
-| P9 | **Git diff-ledger layout** | ✅ git-backed both | Host migrated to git-backed ledger 06-25 (`040e6e20d`), captured in port (crate `diff/ledger.rs`, `diff.rs:98`). Verify `.git` repo layout + snapshot markdown + read-marker storage identical. Harness opens an existing diff repo with both. |
-| P10 | **`store_meta` / embedding signature** | ✅ format | `format_embedding_signature` = `"provider={name};model={model};dims={dims}"` (crate `store/vectors/embedding.rs`). Host must produce the identical signature string from `Config` (W1 `embeddings.rs` seam) or re-embed churn triggers. **Action: seam test asserts signature string equality.** |
-| P11 | **Remaining `mem_tree_*` column parity** | ⏳ harness | `mem_tree_summaries`, `mem_tree_buffers`, `mem_tree_trees`, `mem_tree_score`, `mem_tree_entity_index`, `mem_tree_entity_edges`, `mem_tree_entity_hotness`, `mem_tree_ingested_sources`, `mem_tree_chunk_embeddings`, reembed-skipped tables, `kv_*`, `mcp_writes`, `legacy_marker`. Spot-checks clean; full column+index+PK diff is automated in the harness. |
-| P12 | **Host-retained tier coexistence** | ⏳ W3 gate | Crate schema init + host `unified` init must both run on the shared DB without `CREATE`/index collisions. Harness opens a real workspace, runs crate init then host init (and vice-versa), asserts full `sqlite_master` superset is preserved and no data dropped. |
-
-Legend: ✅ audited-identical · ⚠️ divergence flagged · ⏳ deferred to harness (automated per-flip).
-
----
-
-## The golden-workspace parity harness (design)
-
-The built-in parity harness is the read-side comparator that gates each risky flip. It exists at
-two layers.
-
-### Layer 1 — schema/format asserters (host-side unit tests, cheap, run every PR)
-
-Pure-function comparators (no disk), implemented in **`src/openhuman/memory/tinycortex/parity.rs`**
-(`#[cfg(test)]`). Status ✅ = landed & green; ⏳ = pending.
-
-- ✅ **`chunk_id_matches_historical_golden` / `chunk_id_is_sensitive_to_every_field`** — golden +
- every-field sensitivity for the deterministic `chunk_id` (covers P1). *(After W3 both resolve to the
- crate; the golden vector stays as a regression pin.)*
-- ✅ **`vector_encoding_is_le_packed_f32`** — `vec_to_bytes`/`bytes_to_vec` LE-packed-f32 round-trip
- + golden bytes (P2).
-- ✅ **`chunk_rel_path_host_crate_byte_parity` / `summary_rel_path_host_crate_byte_parity`** —
- adversarial id corpus (colons, all Windows-illegal chars, unicode, >255 chars, gmail participant
- slugs, malformed email; every summary-id shape × 3 tree kinds × levels) → assert host
- `chunk_rel_path`/`summary_rel_path` **byte-equal** the crate's (P6). *(Landed; verified identical.)*
-- ✅ **`embedding_signature_host_crate_byte_parity`** — assert host
- `embeddings::format_embedding_signature` == crate `store::vectors::format_embedding_signature` and
- both == the golden `provider={name};model={model};dims={dims}` over a provider corpus (P10). The
- seam's own `signature()` pass-through is separately pinned in `tinycortex/embeddings.rs`.
-- ⏳ **`frontmatter_parity`** — compose a fixed chunk+summary → byte-compare markdown incl.
- frontmatter key order (P7). *(Not yet landed — needs the host/crate compose types aligned.)*
-
-### Layer 2 — golden-workspace differential harness (the flip gate)
-
-The core mechanism from plan §0.3: **one on-disk workspace, opened by both engines, outputs compared.**
-
-> **Status (2026-07-10).** First cut landed as **`tests/memory_golden_parity_e2e.rs`** —
-> comparator **1** (schema composition) and comparator **5** (idempotent re-open) are green:
-> a real workspace is stood up through the host production surface (`memory::ops`), the crate
-> substrate init is forced deterministically, and **all `*.db` files under the workspace are scanned
-> path-agnostically** (union of tables). It asserts the crate chunk-DB substrate (15 `chunks/schema.rs`
-> tables) and the host `UnifiedMemory` tier (10 tables) **coexist without collision** (P3/P5/P11/P12),
-> and that re-running the flow adds/drops no tables (comparator 5). Still TODO: `vectors`/`store_meta`/
-> `kv_*` (created by the chunk/embed pipeline, need a widened ingest flow), the seeded golden fixture +
-> Comparators **2** (recall/retrieval snapshot), **3** (tree read), and **4**
-> (byte-compare vault) were never landed before cutover and are now descoped by
-> the decision above. Comparator 1 (schema composition) and comparator 5
-> (idempotent reopen) remain active.
-
-**Fixture decision.** Do not synthesize a fixture and label it “pre-migration”
-after the fact. Compatibility is guarded by the retained format pins, schema
-composition/idempotency test, and real host E2E fixtures. A future format
-migration may add a versioned fixture captured before that migration starts.
-
-**Comparators (read-only, both engines open the SAME copied workspace):**
-
-1. **Schema snapshot** — dump `sqlite_master` (tables, indexes, triggers, `sql` text normalized) from
- the DB after each engine's `open`/init; assert the crate-owned 20-table set is identical and the
- host-retained 10-table tier is untouched (P3–P5, P11, P12).
-2. **Recall/retrieval snapshot** — run a fixed query battery through the stable public surface
- (`openhuman::memory::` recall + `read_rpc` retrieval primitives) on pre- and post-migration builds;
- assert identical ordered hit ids + scores (within f64 epsilon) + `supporting_relations` (guards G2)
- + taint (guards the security seam).
-3. **Tree read snapshot** — `read_tree` / `drill_down` / `cover_window` over the sealed tree; assert
- identical node structure + summary content.
-4. **Byte-compare vault** — after a read-only open, assert **no content files changed** (a flip must
- not rewrite the vault) and, for a controlled re-ingest of one source, assert composed markdown is
- byte-identical.
-5. **Idempotent re-open** — open → close → open with the post-migration build; assert no migration
- churn (no re-embed storm, no schema rewrite) on an already-current DB.
-
-**Wiring.** Runs under `pnpm test:rust` (host-side, counts toward coverage) and as a dedicated
-`tests/memory_golden_parity_e2e.rs`. The existing crate-level integration tests
-(`tests/memory_roundtrip_e2e.rs`,
-`tests/raw_coverage/memory_tree_sync_deep_raw_coverage_e2e.rs`) act as the
-"public-surface still green" guard (plan §5.1); this harness adds the **differential** guard that a
-flip preserves *existing* data, not just that the API still functions.
-
-**Gate mapping:** Layer-1 asserters run every PR. Layer-2 golden harness is **green-before-merge** on
-**W3** (store+chunks), **W5** (tree+retrieval+score), **W6** (ingest). W4 (queue) additionally asserts
-job payload_json parity (P4/P9). Any red = upstream fix in tinycortex, re-bump submodule, re-run.
-
-**W-SYNC gates (amendment 2026-07-09, plan §8):**
-- **P13 sync-status parity** — `memory_sync_status_list` output (per-`source_kind` freshness rows)
- byte-equal pre/post flip on a golden workspace; asserter added to
- `src/openhuman/memory/tinycortex/parity.rs`.
-- **P14 Composio sync test pair** — the crate's mocked-HTTP provider suite
- (`vendor/tinycortex/tests/composio_sync_mock.rs`, wiremock, always-on) covers Gmail, Slack,
- GitHub, Notion, Linear, and ClickUp, including pagination/cursors, request budgets, retries,
- taint, idempotency, proxied envelopes, and secret redaction. The live `#[ignore]` test
- (`composio_sync_live.rs`, `COMPOSIO_API_KEY`) remains the manual direct-mode smoke gate.
-
-### W8 test-ownership audit (2026-07-13)
-
-Engine tests now run at their ownership boundary rather than through OpenHuman re-export shims:
-
-- TinyCortex owns memory value/chunk/tree/queue/scoring behavior and the Composio sync pipelines.
- Duplicate engine assertions were removed from the pure `chunks::types`, `trees::types`,
- queue-backfill flag, retrieval-weight, and score re-export shims.
-- OpenHuman retains tests that cross a product boundary: config and credential mapping,
- `SkillDocSink` persistence, event-bus subscribers, RPC envelopes, provider profile/task/catalog
- surfaces, agent-tool response post-processing, source registry side effects, and the
- security-critical `MemoryTaint` seam.
-- OpenHuman CI now runs `cargo test --manifest-path vendor/tinycortex/Cargo.toml --features
- git-diff,sync,persona` when the submodule pointer changes and in the reusable full Rust suite. This is
- required because Cargo does not run dependency test targets while testing `openhuman`.
-
-The focused local verification commands are:
-
-```bash
-cargo test --manifest-path vendor/tinycortex/Cargo.toml --features git-diff,sync,persona
-cargo test --test raw_coverage_all memory_sync -- --test-threads=1
-cargo test --test memory_sync_pipeline_e2e --test memory_artifacts_e2e \
- --test memory_golden_parity_e2e --test memory_roundtrip_e2e --test memory_sources_e2e
-cargo test --test json_rpc_e2e json_rpc_memory
-```
-
-**W-EMB gate:** the existing **P10 `embedding_signature_parity`** asserter is the regression pin —
-the tinyagents-backed provider stack must emit byte-identical
-`provider={name};model={model};dims={dims}` signatures, or existing vector spaces split.
-
-## Open divergences to resolve upstream before their flip
-
-| Item | Flip gated | Resolution |
-| --- | --- | --- |
-| P5 `mem_tree_chunks` 3 legacy inline columns (fresh-DB) | W3 | Confirm no positional `INSERT`/`SELECT *`; if the columns are dead, drop them in a tinycortex PR so fresh DBs match. |
-| P6 `sanitize_filename` vs host colon→`-` | W3 | Prove identical output on adversarial id corpus; align upstream if any diverge (Windows-illegal chars). |
-| P7 frontmatter key **order** | W5/W6 | Byte-compare composed markdown; align serializer order upstream if diff. |
-| G2 `supporting_relations` (graph_* host-retained vs crate derive-on-read) | W6/W7 | Recall snapshot (comparator 2) must match; else upstream relation persist. |
-
-All other dimensions (P1–P4, P8–P12) audited compatible or covered by the automated harness.
diff --git a/plan-5560.md b/plan-5560.md
deleted file mode 100644
index 6b003083cc..0000000000
--- a/plan-5560.md
+++ /dev/null
@@ -1,349 +0,0 @@
-# openhuman#5560 — remaining work, host side
-
-**Audience:** whoever finishes `#5560` in the **openhuman** repo.
-**Boundary:** the upstream half (tinycortex + tinymemory) is **written, tested and pushed** — see _Upstream, not yours_ below. What is left upstream is two merges and a release tag, none of which is code. Everything in "Your work" assumes those have happened.
-
-Every file:line in this document was verified against the trees on 2026-08-25. Where a claim was inherited from an earlier session and turned out to be wrong, it is corrected here and marked.
-
----
-
-## 1. Where the issue actually stands
-
-`#5560`'s own acceptance criteria, measured at `0410ce73a` + the two commits after it:
-
-| # | Criterion | Status |
-| --- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
-| 1 | `grep -r 'tinymemory_core::' src/` clean outside the seam | ❌ **236 non-comment refs across 113 files** |
-| 2 | Crate out of the build (`cargo tree -i tinymemory-core`) | ❌ still resolves at the product feature set |
-| 3 | Kernel floor ratcheted down | ❌ blocked on 2 |
-| 4 | cargo-machete `ignored` entries removed | ❌ `Cargo.toml:35` |
-| 5 | Behaviour unchanged + coverage on the bus path | ✅ for everything migrated so far |
-| 6 | `AGENTS.md` memory section updated | ❌ — and **currently wrong**: line 941 claims "~71 lines across 38 production files"; actual is 236/113 |
-
-**1 of 6.** Criteria 2–4 are one gate: they all fall together on the day the last reference goes, and not before. Progress before that day does not move the table, which is why the count dropping 285 → 236 shows up nowhere above.
-
-### What is already done (do not redo)
-
-Every call site whose fix was _"add a contract member and route the caller"_ is migrated, and this is now proven rather than asserted — all 86 distinct engine symbols were classified: **15 EXACT** (migrated), **9 SHAPE_DIFFERS**, **44 NO_MEMBER** (they hand out a handle, not data). The `SeamExpressible` bucket in the ratchet is empty.
-
-Shipped: the diagnostics seam, recency recall, reset/flush, the archivist's episodic pivot, preferences, the safety scrubbers, the CLI read paths, and the type/alias surface.
-
-### The remaining 236, by bucket
-
-| Bucket | Refs | Nature |
-| ------------------------------------------------------------------------------------------ | ---- | ---------------------------------------------------------- |
-| chunk-store (`store::chunks`, `content`, `fts5`, `segments`, `profile`, `namespace_store`) | 93 | the big one — needs the new members below |
-| engine-handle (`global::*`, `MemoryClient`, `UnifiedMemory`, `factories`) | 27 | **structurally last** — they _construct_ the engine |
-| tree / ingest (`tree`, `ingest_pipeline`, `ingestion`) | 22 | partly covered by #99's `summary_forest` / `recent_leaves` |
-| chat-seam (`chat::`) | 19 | host-side provider construction; mostly `#[cfg(test)]` |
-| sync-pipeline (`sync::`, `tinycortex::`) | 12 | composio sync + sources registry |
-| queue (`queue::start`, `drain_until_idle`) | 5 | see H3 — cannot go until the module owns a pool |
-
-Top production files: `memory/host_impls.rs` (15 — the host→engine seam, **never leaves**), `memory/sources/rpc.rs` (10), `memory/store_golden.rs` (7, allowlisted fixture), `agent/experience/ops.rs` (5), `memory/tree/retrieval/rpc.rs` (4, all `#[cfg(test)]`), `memory/ops/sync.rs` (4).
-
----
-
-## 2. Upstream, not yours
-
-In flight, being finished separately. **Do not start Phase E until Phase D is done.**
-
-**All upstream code is written, verified and pushed as of 2026-08-25.** Nothing below is left to implement. Three non-code steps remain, and the first one needs a permission the author of this branch does not have.
-
-| Repo | PR / artifact | State |
-| ------------------------ | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
-| tinycortex (`neocortex`) | **#157** `feat/5560-filtered-chunk-count` @ `ef09f09` | open, **all checks green**, review threads answered and resolved, ⛔ **needs a maintainer merge** |
-| tinymemory | **#99** `feat/5560-close-every-gap` @ `38e03fb` | open, CI green, gitlink points at #157 @ `ef09f09` |
-| tinymemory | v1.4.0 (`346fe4e`) | released |
-| tinymemory | **v1.5.0** (`1a4cba8f48` pins `d722d36e9fc3`) | ✅ pinned by this PR |
-
-> ⛔ **The one hard blocker.** `gh pr merge 157 -R tinyhumansai/tinycortex` is refused —
-> the branch author's permissions on that repo are `{"admin":false,"maintain":false,"pull":true,"push":false}`.
-> Someone with merge rights has to press the button. Everything downstream — #99's gitlink
-> re-point, #99's merge, the v1.5.0 tag, and this entire plan's Phase D — is queued behind
-> that single click. Nothing else is blocking.
-
-**#99 already adds** (do not re-request): `MemoryChunks::count_chunks`, `MemoryEntities::{top_entities, chunk_entities, entity_chunk_ids}`, `MemoryTree::{summary_forest, recent_leaves}`, and `CONTRACT_VERSION` (2,2) → (3,0).
-
-**Everything below is LANDED** on the two branches above. It is listed so you can code against the real names without reading the diffs.
-
-_Group 1 — unblocks Phase E._ ✅ landed in #99 + #157. Reduced from an original ~14 asks down to **4 new bus methods + 1 amendment + 6 additive `ChunkQuery` fields**:
-
-- `MemoryChunks::list_chunk_details(query, scope) -> Vec<ChunkListRow>` — one SELECT; explicitly _not_ `chunk_detail` in a loop (that is 5 engine reads per chunk → a 1000-row page would be 5000 queries)
-- `MemoryChunks::source_totals(limit, scope) -> Vec<SourceTotal>`
-- `MemorySourceSink::forget_matching(&ForgetSelector) -> ForgetOutcome` — one door, four selectors (Chunk / Source / SourcePrefix / Owner)
-- `MemoryMaintenance::purge_all() -> PurgeOutcome`
-- **amend** `MemoryEntities::chunk_entities` to take `chunk_ids: &[String]` + `kinds` (legitimate only because #99 is unreleased; the `METHODS` sequence is untouched)
-- `ChunkQuery` gains `ids`, `source_kinds`, `source_ids`, `entity_ids`, `entity_kinds`, `content_contains` — all six land in one place (`append_filters`), so page / total / detail-list inherit them and cannot drift
-
-_Group 2 — unblocks Phase F._ ✅ landed in #99. Without these, deleting the host's second engine would be **data-loss-adjacent**, not merely incomplete (see H3):
-
-- **the module starts its own queue worker pool.** _(Done — `tinymemory-module/src/lib.rs`, `start_queue_pool`.)_ `services.rs:256` in the host was the only caller of `queue::worker::start` in any tree; the module owns one now. It also carries `claim_queue_pool`, because `queue::start`'s `Once` is process-global while a pool is bound to one workspace — a second workspace in one process is not a second pool, it is a store with nothing draining its queue, and that now logs as an error instead of being invisible.
- - Known degradation, stated rather than hidden: the pool consults the scheduler gate and registers a shutdown hook, and the module serves neither seam. So in module mode it runs **unthrottled** (ignores battery/CPU pressure) and its graceful lock-release hook is dropped — locks are recovered by lease expiry at startup instead, which `worker.rs` already documents as the hard-kill path. If throttling matters to the product, that needs a real `SchedulerGate` bus interface, which is a separate piece of work.
-- **`tinycortex/contacts` enabled in the module** _(Done — it replaces `people`, since upstream declares `contacts = ["people", ...]`.)_ Otherwise Phase F silently loses macOS address-book seeding (H4b). Verified live: the locked release build links `objc2-contacts`.
-- **the two silently-degrading seams made loud** — `scheduler_gate` and `shutdown` now report once per process through the already-installed `ErrorReporter` instead of quietly doing nothing. _(Done.)_
-
-### 2a. The as-landed contract — code against these exact names
-
-Copied from the merged source, not paraphrased. All four new trait members are **defaulted to `Unsupported`**, so nothing that exists today stops compiling.
-
-```rust
-// tinymemory_api::provider::chunks
-pub trait MemoryChunks {
- async fn list_chunk_details(&self, query: &ChunkQuery, scope: Option<&SourceScope>)
- -> Result<Vec<ChunkListRow>, MemoryError>;
- async fn source_totals(&self, limit: usize, scope: Option<&SourceScope>)
- -> Result<Vec<SourceTotal>, MemoryError>;
-}
-
-pub struct ChunkListRow { // ChunkDetail MINUS `body`, deliberately
- pub chunk: Chunk,
- pub content_path: Option<String>,
- pub lifecycle_status: Option<String>,
- pub has_embedding: bool,
-}
-
-pub struct SourceTotal {
- pub source_kind: SourceKind, // decoded enum, not a raw String
- pub source_id: String,
- pub chunk_count: u64,
- pub most_recent_ms: i64, // rows are ordered by this, DESC
-}
-
-// the six additive ChunkQuery fields — every one #[serde(default, skip_serializing_if = ...)]
-pub struct ChunkQuery {
- /* ...existing... */
- pub ids: Vec<String>,
- pub source_kinds: Vec<SourceKind>,
- pub source_ids: Vec<String>,
- pub entity_ids: Vec<String>,
- pub entity_kinds: Vec<String>,
- pub content_contains: Option<String>,
-}
-
-// tinymemory_api::provider::records / mod
-async fn forget_matching(&self, selector: &ForgetSelector) -> Result<ForgetOutcome, MemoryError>;
-async fn purge_all(&self) -> Result<PurgeOutcome, MemoryError>;
-
-// tinymemory_api::provider::knowledge — AMENDED, not added
-async fn chunk_entities(&self, chunk_ids: &[String], kinds: Option<&[String]>)
- -> Result<Vec<ChunkEntityOccurrence>, MemoryError>; // was: (chunk_id, ) -> [EntityOccurrence]
-```
-
-Five things about this surface that will save you a debugging session:
-
-- **An empty `Vec` predicate means UNFILTERED, not match-nothing.** Forced by `Default` + `#[serde(default)]`. The footgun is real: a caller that _computed_ a candidate set and got nothing must short-circuit and skip the query, because the query will happily return everything.
-- **`entity_ids` and `entity_kinds` are two independent `EXISTS` clauses.** Setting both asks for a chunk with some listed entity _and_ some entity of a listed kind — not for one index row satisfying both.
-- **`ChunkListRow` has no body, on purpose.** `ChunkDetail::body`'s docs promise `None` means the vault read _failed_; a listing can only honour that by reading every file or by lying. If you need bodies, that is `chunk_detail`, per row, knowingly.
-- **`content_contains` folds case for ASCII only** and scans the text the driver holds _inline_ — for a chunk whose body went to the content vault that is the stored preview, not the whole document. It narrows a browse; it does not replace `MemoryRecall`.
-- **`chunk_entities` rows each name their own chunk.** Group by `row.chunk_id`; never index the result by position against the ids you sent.
-
-**`PurgeOutcome::rows_deleted` is a cross-table sum, matching what `wipe_all_rpc` already reports.** This was a real disagreement between the engine and the contract during implementation and it was settled in favour of the host's existing wire shape: `WipeAllResponse.rows_deleted` has always been the sum over its nine tables, so returning only chunk rows would have shrunk a number the user already reads without anything having changed about what was forgotten. The engine's scoped deletes still return chunk counts — that asymmetry is deliberate and documented at `purge_all`.
-
-**Upstream verification actually run** (not "should pass"): both `cargo check --workspace --all-targets` trees; `cargo test --workspace` (1919 pass) and `--all-features` (1781 pass); the full CI feature matrix, all 13 rows; `cargo clippy --all-targets --all-features -D warnings` on the root and the module workspace; `cargo fmt --check` on both; `cargo doc --no-deps --all-features` with `-D warnings`; `cargo deny check` (advisories/bans/licenses/sources ok); `engine-containment.sh` and `dependency-budget.sh`; production-source coverage 81.89% and module coverage 86.81% lines, both over the 80% gate; the `--locked` release cdylib build; and the loader E2E, all 12 cases, one process per test, against that release artifact. `cargo hack --feature-powerset` is the one CI lane not run locally — `cargo-hack` is not installed on this machine.
-
-**Deliberately dropped, with reasons** (so nobody re-raises them): `chunk_score` / `DEFAULT_DROP_THRESHOLD` (engine-internal ranking the contract excludes by design); a per-chunk `delete_chunk` (folded into `forget_matching`); an Obsidian vault-registration member (host desktop policy — move the code like `redact`/`safety` did); a doctor chunk-count member (already covered by `store_stats().chunks`); a `delete_source` member (covered by existing `forget_source`).
-
----
-
-## 3. The ordering — this is the part that bites
-
-Nothing in the host refuses a contract-version mismatch, so the usual "bump and see" instinct is unsafe here.
-
-```
-PHASE A merge tinycortex #157 ← code done, green; needs a MAINTAINER click
-PHASE B re-point #99's vendor/tinycortex to A's merge SHA, merge #99
-PHASE C tag + release tinymemory v1.5.0 ← MUST precede any host change
-PHASE D ONE host commit, five pins move together ← YOUR FIRST TASK
-PHASE E route the new members, strike ALLOWED entries in the same commit
-PHASE F delete the second engine — LAST; the gate is open once v1.5.0 ships Group 2
-```
-
-Phases A–C are not development work. A is one click by someone with merge rights on
-tinycortex. B is a one-line gitlink bump (`git -C vendor/tinycortex checkout <A's merge SHA>`,
-commit, push to the fork branch backing #99) plus a second click. C is the repo's normal
-release flow. Only then does Phase D — your first task — become safe.
-
-#157 holds every engine-side query the new members forward to, not just
-`count_chunks_matching`: the six filter predicates, `list_chunk_details`, `source_totals`,
-the by-id delete arm, and `purge_all`. Merging #99 without it does not compile.
-
-**Phase F is where the issue actually closes.** Phases D and E clear roughly 13 of the 133 production references; the other ~120 — the engine handles, the queue boot, the sync and chat seams — only go in F. Anyone reading D+E as "done" will be surprised by the checkbox table.
-
-### Phase D — one commit, all five or none
-
-1. `vendor/tinycortex` `b7cf121` → merged tinycortex SHA — **without this the host does not compile** (see H4a)
-2. `vendor/tinymemory` `346fe4e` → merged #99 SHA
-3. `src/openhuman/modules/registry.rs:205-262` — version, `release_url`, all 11 archive names, all 11 sha256, **taken verbatim from the release's `checksum.toml`**, never recomputed locally
-4. `src/openhuman/modules/memory.rs:51` `ARTIFACT_CAPABILITIES_PIN` `"1.4.0"` → `"1.5.0"` — else `the_capability_list_matches_the_pinned_release` goes red
-5. All four CI download sites: `ci-full.yml:132`, `ci-lite.yml:749`, `e2e-reusable.yml:167` and `:365`
-
-> There is a re-pin helper that reads the release's own `checksum.toml` and rewrites `registry.rs`; it self-tests to byte-identical output when pointed at the already-pinned tag. Ask for it rather than hand-editing 11 digests.
-
-**The only safe half-state is "release cut, host untouched."** Never "gitlink bumped, registry still on the old version."
-
----
-
-## 4. Hazards — verified, with evidence
-
-### H1 — a version mismatch is not caught by anything _(mechanism corrected)_
-
-The earlier framing was "bind refused → silent empty." That is **wrong, and the truth is worse**: `is_compatible` (`tinymemory-bus/src/version.rs:86`) is major-equality as documented, but it has **zero call sites in the entire graph** — every hit is a re-export. The host's `PeerManifest` never declares the memory interface.
-
-The only cross-check is `ModuleMemoryProvider::verify` (`src/openhuman/modules/memory.rs:388-406`), which compares **capabilities only**, and capabilities are family-granular. #99's six new methods all land inside `Chunks` / `Entities` / `Tree` — families v1.4.0 already advertises. So `verify()` stays green, `as_chunks()` returns `Some`, the call goes out, and the module answers `UnknownMethod` → `MemoryError::Other`.
-
-CI would not catch it either: `modules/memory_tests.rs:237-254` compares a version **string**, `:45-81` asserts `capabilities_for(false) == Capabilities::all()` (no new family → green), and all four CI lanes download the **released** artifact rather than building `vendor/tinymemory`.
-
-**Consequence:** Phase C is not a formality. The release must exist before the host learns the new contract.
-
-### H2 — the host boots two engines _(confirmed verbatim)_
-
-`src/core/runtime/context.rs:608` calls `global::init(cfg.workspace_dir)`, and `:621` binds the module driver — same `if plan.memory` block, and both resolve to `<workspace>/memory/memory.db`. Two live `MemoryClient`s over one SQLite file.
-
-**Delete:** `context.rs:606-614` (the `global::init` arm) and its `:640` skip-log twin.
-**18 sites depend on it**, each its own migration to `CoreContext::memory_binding` / `MemoryProvider`:
-`store_golden.rs:145,:520` · `ops/documents.rs:381` · `ops/sync.rs:212,:253` · `ops/helpers.rs:391,:395` · `ops/test_support.rs:49` · `security/credentials/ops.rs:595,:835` · `desktop/app_state/ops.rs:526` · `agent/experience/ops.rs:78,:84,:116,:118` · `agent/learning/startup.rs:32` · `agent/harness/session/builder/factory.rs:266` · `integrations/composio/schemas.rs:937` · `core/memory_cli.rs:633`
-
-The deletion is already the tree's stated intent — `binding.rs:16-24` and `context.rs:310-319` both argue the workspace-keyed map supersedes the global slot. It was argued and never executed.
-
-### H3 — deleting the second engine breaks the queue _(this is the sequencing crux)_
-
-`flush_pending` is **not** a no-op today — the host starts the only worker pool that exists (`services.rs:256`, the sole caller of `queue::worker::start` in any tree).
-
-But **every enqueue in the released driver depends on that host-started pool**: `retry_failed`, `ensure_reembed_backfill`, and the ingest `extract_chunk` enqueue — that last one is how ingested content becomes retrievable at all. Delete H2's second engine and all of them become permanent no-ops.
-
-This cannot be fixed by any host change. **The module must start its own pool** — done, in #99 (`tinymemory-module/src/lib.rs`, `start_queue_pool`). Verify before you delete anything: the release you pin must contain the module-owned pool, not just the Group 1 members. Grep the tag, not the working tree.
-
-Accept the two degradations that come with it, or fix them first: in module mode the pool runs **unthrottled** and its shutdown hook is dropped. Both are stated at the function and in §2 — neither loses work, but the first is a real battery/CPU behaviour change on desktop.
-
-### H3b — the composio sync loop has no home once the engine goes _(found 2026-08-25; NOT in the original plan)_
-
-Same class as H3, found the same way, and it is on the critical path for criteria 1 and 2.
-
-The engine reaches its host through nine seam traits installed as process globals. In module
-mode the module installs **seven** (`error_reporter`, `event_sink`, `nlp_host`,
-`scheduler_gate`, `shutdown_host`, `chat_host`, `embedding_host`). The host installs **eight**
-(`memory/host_impls.rs`). The two the module does _not_ install are **`ComposioHost`** and
-**`ConfigLoader`**.
-
-That is not academic, because composio sync is **engine code running in the host process**:
-
-```
-core/runtime/services.rs:265 integrations::composio::start_periodic_sync()
-integrations/composio/mod.rs:66 → memory::sync::composio::periodic
-memory/sync/composio/mod.rs:8 → pub use tinymemory_core::sync::composio::*
-```
-
-So the host starts the _engine's_ periodic loop against the host's own engine handle. Delete
-that engine and the loop has no engine to run against; keep the loop and the engine crate can
-never leave the build — which is criterion 2.
-
-**It fails quietly, which is why it has to be designed against rather than discovered.**
-`composio_host::require_composio_host()` returns `Err` and `is_available()` returns `false`
-when unset. Nothing panics, nothing logs by default: composio sync would simply stop, and the
-first symptom is a user noticing their Slack or Gmail memory went stale.
-
-**Being fixed upstream now**, in the same PR (#99) and following the pattern that already
-works: `ChatHost` and `EmbeddingHost` are served _by the host_ over the bus
-(`modules/memory_host.rs`) and consumed by the module (`chat.rs`, `embedding.rs`).
-`ComposioHost` gets the same treatment — 4 methods, small trait. `ConfigLoader` is answered
-module-side from the `ModuleConfig` the module is already handed, because proxying it would
-mean asking the host to re-read a config the module already has, and the two could disagree.
-Ownership of the periodic loop moves to the module, following `start_queue_pool`'s precedent
-including its process-global guard.
-
-**Order this imposes on Phase F:** the host-side `pub use tinymemory_core::sync::composio::*`
-shim and the `services.rs:265` start come out **together with** the in-process engine, never
-before. Removing them earlier stops composio sync in a tree that still boots that engine.
-
-### H4a — a build break nobody has hit yet
-
-The host resolves tinycortex through `[patch.crates-io] tinycortex = { path = "vendor/tinycortex" }` (`Cargo.toml:1237`) — its **own** top-level submodule, currently `b7cf121`, _not_ the copy inside `vendor/tinymemory`. `Cargo.toml:223-225` says so explicitly.
-
-`git show b7cf121:src/memory/chunks/store_list.rs | grep -c count_chunks_matching` → **0**. So bumping only `vendor/tinymemory` fails to compile. Both gitlinks move in Phase D or neither does.
-
-### H4b — `contacts` was off in the module _(fixed upstream — keep reading, the reason still matters)_
-
-`crates/tinymemory-module/Cargo.toml:39` enabled `people` but not `contacts`. #99 now enables `contacts` there (it supersedes `people`, which upstream declares as a subset), and the locked release build was checked to link `objc2-contacts`. The reason is worth keeping in front of you anyway, because it is the shape of every remaining Phase F hazard: the shipping desktop build turns `contacts` **on** (`app/src-tauri/Cargo.toml:186` → `Cargo.toml:975` → `tinymemory-core/Cargo.toml:129`), and the whole people domain is a glob re-export of the in-process engine (`memory/people/mod.rs:8`). macOS address-book seeding works today _because_ the second engine exists. Phase F must not land before a **released** module carries `contacts` — the code is on #99, so this closes when v1.5.0 ships, not when #99 merges.
-
-### H4c — the tree's own tripwires fire during the cutover
-
-Defuse them **in the commit that causes them**, never after:
-
-1. `direct_engine_refs_tests.rs:730-742` `direct_reference_scanner_is_not_vacuous` asserts `found.len() > 20` and that `memory/mod.rs` is in the set — the final cutover drives both to zero **by design**. Rewrite it with the last removal.
-2. `:825-841` `the_blocked_set_matches_the_engine_still_being_linked` is the deliberate "day the engine leaves" tripwire, **and its failure message is the closing checklist**: drop the path deps (`Cargo.toml:241-260` + the dev-dep at `:657`), remove the machete `ignored` entry (`:35`), ratchet `scripts/kernel-floor.limits`, rewrite the module docs.
-3. `:804-816` `nothing_is_left_migratable` fails on **any** `Verdict::SeamExpressible`. `ALLOWED` is currently 22 `HostSide` + 56 `NeedsWiderSeam` + 0 `SeamExpressible`; the new members make some of those 56 seam-expressible. The test's own doc calls re-labelling-to-silence _"the one edit that would make the lint lie."_ **Strike each routed file from `ALLOWED` in the commit that routes it.**
-4. Same discipline on `bypass_allowlist_tests.rs:544-557` and `:567-578` — and `docs/specs/memory-guard-allowlist.md` moves in step. That allowlist's rule is _may shrink, never grow_; if you need a test-only fixture, put it under a `test_support/` directory, which the scanner skips by path.
-
----
-
-## 5. Your work — Phase E, site by site
-
-Each row is one migration. The RPC response fields are listed because **wire shape must not change** — these are read by `MemoryControls`, `OverviewPanel` and `MedullaDemoGraph`.
-
-| Site | Operation | Member to use |
-| -------------------------------------------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `read_rpc/chunks.rs:54` `list_chunks_blocking` | paged list + unpaged total | `list_chunk_details` + `count_chunks`, with the six new `ChunkQuery` fields |
-| `read_rpc/chunks.rs:208` `list_sources_blocking` | `GROUP BY source_kind, source_id` | `source_totals` (`display_name` stays host-side) |
-| `read_rpc/chunks.rs:268` `search_rpc` | content search | `list_chunk_details` with `content_contains` only |
-| `read_rpc/chunks.rs:354` `recall_rpc` hydrate | N ids → rows | `list_chunk_details` with `ids` — one call, re-map by id to preserve leaf order |
-| `read_rpc/entities.rs:30` `entity_index_for` | entities of a chunk | `chunk_entities(&[id], None)` — **already available from #99** |
-| `read_rpc/entities.rs:74` `chunks_for_entity` | chunk ids for an entity | `entity_chunk_ids` — **#99**. Note it _requires_ a limit; the SQL has none. Use `MAX_LIST_LIMIT` (`read_rpc/types.rs`) |
-| `read_rpc/entities.rs:110` `top_entities` | ranked entities | `top_entities` — **#99**. ⚠️ behaviour delta: the member returns `MemoryError::Invalid` for an unknown kind; the RPC currently returns an empty list |
-| `read_rpc/entities.rs:236` `delete_chunk_rpc` | delete + side rows | `forget_matching(ForgetSelector::Chunk)` |
-| `read_rpc/graph.rs:109,:250` `collect_tree_graph` | summary forest + leaves | `summary_forest` + `recent_leaves` — **#99**, field-for-field |
-| `read_rpc/graph.rs:352` `collect_contacts_graph` | person-kind chunks + edges | `ChunkQuery.entity_kinds` + amended `chunk_entities(ids, kinds)` — **one call, not 1500** |
-| `read_rpc/admin.rs:33` `wipe_all` | truncate 9 tables | `purge_all` (host keeps the content-dir removal and `dirs_removed`) |
-| `read_rpc/admin.rs:110` `clear_composio_sync_state` | raw `Connection::open` | `kv_list` + `kv_delete` — this is a **second unpoliced door** beside `with_connection` |
-| `read_rpc/admin.rs` `delete_source_rpc` | chunks + orphan tree | `forget_matching(Source)` — returns `trees_cleaned`, so `DeleteSourceResponse` keeps its shape |
-| `read_rpc/vault.rs:5` | Obsidian registration | **move the code host-side**; do not widen the contract |
-| `platform/doctor/core.rs:834` | `SELECT COUNT(*)` | `store_stats().chunks` — the file's own comment already says so; the blocker is that `run` is sync and `store_stats` is async, so hoist the probe into the caller |
-| `channels/controllers/ops/connect.rs:240` | clear channel memory | `forget_matching(Source + SourcePrefix, Chat)` |
-| `integrations/composio/ops/memory_cleanup.rs:21,:24,:31` | exact / prefix / owner deletes | `forget_matching`, all three arms |
-
-**Not gaps — do not touch:** `read_rpc/mod.rs:54` (the `with_connection` re-export is `#[cfg(test)]`-gated at `:53`), `tree/retrieval/rpc.rs:510-534` (all inside `#[cfg(test)]`), `store_golden.rs` (deliberately outside the contract; its module doc explains the escape hatches).
-
-**Stale comments to delete as you go:** `read_rpc/entities.rs:13-20` claims those three handlers have no member — #99 added all three. And the `ALLOWED` verdicts for all eleven target files say _"MemoryChunks is read-only … with no write or transaction door"_, which still holds for the write sites but not the reads.
-
----
-
-## 6. Verification
-
-Four scopes, because the default commands miss three of them:
-
-```bash
-export RUST_MIN_STACK=16777216
-export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=commit.gpgsign GIT_CONFIG_VALUE_0=false # macOS: temp-repo tests hang on pinentry otherwise
-F="$(bash scripts/ci/product-features.sh)"
-
-cargo check --all-targets --features "$F" # tests/ targets are NOT covered by --lib
-cargo clippy -p openhuman --features "$F" -- -D warnings
-cargo clippy -p openhuman -- -D warnings # CI lints the DEFAULT set too
-cargo test --lib --features "$F"
-cargo metadata --locked # and again for app/src-tauri — two Cargo worlds
-```
-
-Also: `crates/tinymemory-module` is its own workspace with its own lockfile; the root `cargo fmt --all` does not reach it.
-
-**One local-only caveat:** `cargo test --lib` hangs on `tree_e2e_tests::full_pipeline_ingest_to_retrieval`. It does not set `embeddings_provider = "none"` the way its sibling does, so it calls the live embedding service. Pre-existing, unrelated to this work, fine in CI.
-
-**Module-backed tests** need `TINYMEMORY_TEST_MODULE` pointing at a built cdylib, and must run **one process per test** — tinybus binds broker tasks to the creating runtime and never unloads, so a second module-loading test in one process _hangs rather than fails_.
-
----
-
-## 7. Definition of done
-
-The closing checklist is not this document's invention — it is the failure message of `the_blocked_set_matches_the_engine_still_being_linked`:
-
-- [ ] `grep -rn 'tinymemory_core::' src/` returns nothing outside `memory/host_impls.rs` and the binding
-- [ ] `Cargo.toml:241-260` path deps dropped, plus the dev-dependency at `:657`
-- [ ] cargo-machete `ignored` entry removed (`Cargo.toml:35`)
-- [ ] `scripts/assert-shed.sh` proves the crate gone from the product graph
-- [ ] `scripts/kernel-floor.limits` ratcheted — **measure on Linux**; macOS resolves +1/+1 from `core-foundation` / `security-framework`
-- [ ] `AGENTS.md` memory section rewritten (its current figure is 3× off)
-- [ ] both ratchets rewritten rather than silenced (H4c)
-
-**Honest estimate:** Phase D is an afternoon. Phase E is a few days. **Phase F is the long one** — 18 `global::` consumers plus the sync, chat and queue seams, each its own migration, and it is the phase that actually flips the checkboxes. Its upstream gate (module-owned pool + `contacts`) is being closed now, so it is no longer blocked, but it is not a day's work either. Anyone promising #5560 closes this week has not read §4.
-
-**Scope note:** every upstream dependency in §2 is **already written and pushed** — both groups. If you hit something that needs a _new_ contract member, that is a bug in this plan; say so rather than widening the contract yourself, because a member added host-side cannot ship (the host pins a released, digest-verified artifact, and §4 H1 explains why the mismatch would be silent rather than loud).
-
-**Housekeeping:** a stray copy of the tinymemory branch was pushed to `tinyhumansai/tinymemory` as `feat/5560-close-every-gap` before being pushed to the fork where PR #99 actually lives. It is byte-identical to the fork branch and harmless, but it should be deleted — `git push origin --delete feat/5560-close-every-gap` from a checkout whose `origin` is upstream.
diff --git a/plan.md b/plan.md
deleted file mode 100644
index e58059af5b..0000000000
--- a/plan.md
+++ /dev/null
@@ -1,518 +0,0 @@
-# Test Suite Audit & Improvement Plan
-
-Multi-agent audit of the OpenHuman test surface (2,367 files / ~25,900 test declarations per
-`docs/test-inventory/REPORT.md`). Ten parallel auditors each read their slice of the inventory
-**plus the actual test source**; every "drop this test" / "this is overfitted" recommendation was
-then adversarially reviewed by a second skeptic pass that tried to refute it by re-opening the
-cited files (40 verdicts: 32 confirmed, 8 refuted — the refuted ones are documented below so
-nobody deletes them later). A final completeness critic audited the audit itself.
-
-**Headline findings**
-
-1. The suite is **broadly healthy** — security/policy adversarial tests, tunnel crypto, composio
- client, core_process tests are genuinely behavioral and strong.
-2. The two **highest-risk untested surfaces in the codebase**:
- `src/openhuman/security/policy/command_checks.rs` + `path_checks.rs` (the documented
- autonomy-enforcement core: `classify_command`, `gate_decision`, `is_workspace_internal_path`)
- and `src/openhuman/security/encryption/core.rs` (Argon2id + AES-256-GCM primitives) have **zero unit
- tests**.
-3. A meaningful chunk of the suite **never runs in CI**: the mock server's own socket-auth tests,
- most of `scripts/__tests__/`, and the Pester Windows-install test are invoked by no workflow.
- A never-run test is worse than no test — it reads as coverage.
-4. The 80% changed-lines coverage gate has a **scope hole**: `scripts/**` (including the entire
- shared mock backend every other suite depends on) is outside all path filters.
-5. ~130 test declarations are **safe to delete** (verified duplicates, typeof-only boilerplate,
- empty compile-only tests, copy-paste connector templates) — see §2.
-
----
-
-## 1. Method
-
-- **Audit fan-out (Sonnet):** frontend unit (components/pages; services/store/hooks/lib),
- frontend E2E (WDIO + Playwright), Rust unit (agent/memory; channels/providers/platform;
- security/config/infra), Rust integration/E2E, Tauri shell, the mock/harness infrastructure
- itself, and a cross-cutting gap hunter comparing product domains ↔ inventory.
-- **Skeptic verify (Opus, high effort):** every drop/overfit finding re-verified against source;
- refuted items retained with the refutation recorded.
-- **Completeness critic (Opus):** audited the audit for missing dimensions (mutation testing,
- fuzzing, a11y, perf, flake data, CI orphans…).
-
-Legend: ✅ = skeptic-confirmed · ⚠️ = plausible, not independently re-verified · ❌ = refuted (do **not** act).
-
----
-
-## 2. Tests to DROP
-
-### 2.1 Confirmed safe to delete
-
-| # | File | What | Why |
-|---|------|------|-----|
-| ✅ | `app/src/components/settings/hooks/__tests__/useSettingsNavigation.test.tsx` | whole file | Asserts a retired, hardcoded-empty `breadcrumbs` field across 8 routes — tests a constant. Route resolution is fully covered by the sibling `useSettingsNavigation.coverage.test.tsx`. |
-| ✅ | `app/src/services/api/{graphCentralityApi,graphCohesionApi,memoryFreshnessApi,connectionPathApi,memoryTimelineApi,entityAssociationsApi,namespaceOverviewApi}.test.ts` | the copy-pasted `exposes the public surface` test in each (7 files) | typeof-only assertions on aggregate objects **no consumer imports** (tabs import the named exports directly); the functions are behaviorally tested above in each file. Do one grep-and-delete pass. |
-| ✅ | `src/openhuman/agent/harness/harness_gap_tests.rs` | `datetime_section_is_static_grounding_rule_not_a_volatile_timestamp` | Strict subset of `agent/prompts/mod_tests.rs::datetime_section_is_static_grounding_rule_without_volatile_timestamp`; the file's own header lists item 6 as covered elsewhere. |
-| ✅ | `app/src-tauri/src/lib_tests.rs` | `setup_tray_function_signature_compiles`, `tray_setup_logging_patterns_exist`, `app_runtime_type_exists`, `is_daemon_mode_detects_daemon_flag` | Empty bodies / comments-only / the one real assertion is commented out / result discarded with `let _`. Cannot fail; verify nothing. |
-| ✅ | `app/src-tauri/src/deep_link_ipc.rs` | `extract_deep_link_urls_filters_correctly` | Re-implements the prefix filter inline instead of calling the production `extract_deep_link_urls()` — passes even if the real filter regresses. Better fix: refactor to take an args slice like the Windows sibling (`collect_deep_link_urls_from_args`), then test the real function. |
-| ✅ | `src/openhuman/routing/factory.rs` | `factory_constructs_without_panic_when_runtime_enabled`, `factory_llamacpp_provider_constructs_without_panic`, `factory_custom_openai_provider_constructs_without_panic`, `factory_lm_studio_provider_constructs_without_panic` | Skeptic traced the whole construction path — provably infallible (pure struct init), so the tests cannot fail. One test's comment claims to verify probe-URL selection but the body asserts nothing; fields are private so strengthening is blocked. |
-| ⚠️ | `app/src/components/chat/ArtifactCard.test.tsx` | whole file (281 lines) | Duplicates `__tests__/ArtifactCard.test.tsx` test-for-test (in-progress label, download→done flow, error truncation + Show more, Retry). Keep the `__tests__/` version. |
-| ⚠️ | `app/src/components/settings/panels/RecoveryPhrasePanel.test.tsx` | whole file (1 test) | Subsumed by the 35-test `__tests__/RecoveryPhrasePanel.test.tsx`. |
-| ⚠️ | `src/openhuman/threads/ops_tests.rs` | `sanitize_generated_title_*`, `collapse_whitespace_*`, `title_log_fingerprint_*`, `title_from_user_message_*` | `threads/title.rs` inline tests already cover the same functions with equivalent cases. Keep the copies in `title.rs` (the owning module). |
-| ⚠️ | `src/openhuman/channels/providers/whatsapp_tests.rs` | 7 × `whatsapp_parse_<type>_message_skipped` | All hit the identical `type != "text" → continue` branch; collapse to one parameterized loop over the type strings. |
-| ⚠️ | `src/openhuman/routing/telemetry.rs` | `emit_does_not_panic` ×3 variants | Fire-and-forget calls with no assertion. |
-| ⚠️ | `app/src-tauri/src/deep_link_ipc.rs` | `no_primary_returns_appropriate_result` | Its own comment admits it can't reach the production branch; asserts stdlib `UnixStream::connect` errors on a bogus path. |
-| ⚠️ | `app/test/e2e/specs/smoke.spec.ts` | the permanently-`it.skip`ped auth-deep-link test | Skipped for a documented flake with no tracking issue/owner. File an issue and fix, or delete. |
-
-### 2.2 Consolidate, don't delete: the connector template family
-
-`connector-{airtable,asana,clickup,confluence,google-calendar,google-drive,google-sheets,notion,slack-composio,todoist,youtube}.spec.ts`
-— **11 WDIO files, ~99 test declarations, byte-identical** except for toolkit name/slug strings.
-Playwright already proves the fix: `connector-session-guard-matrix.spec.ts` parametrizes the same
-assertions over a `TOOLKITS` array in one file. Extract a `runConnectorContract(toolkit, opts)`
-helper, keep **`connector-jira.spec.ts`** (subdomain-field UI) and
-**`connector-gmail-composio.spec.ts`** (400-on-fetch-emails handling) as bespoke specs.
-Net: ~100 declarations → ~10 with identical per-toolkit coverage.
-
-### 2.3 ❌ Refuted — keep these (recorded so they don't get re-proposed)
-
-| File | What | Why it stays |
-|------|------|--------------|
-| `src/openhuman/memory/schema_tests.rs` | registry-sync + unknown-fn tests | **False duplicate.** `memory/schema/` (singular, `memory_tree` namespace) and `memory/schemas/` (plural, `memory` namespace) are two distinct live registries with disjoint function sets. These are the *only* parity/unknown-fn guards for the `memory_tree` controller surface. |
-| `src/openhuman/channels/providers/qq_tests.rs` | `test_name` | Sole coverage of `QQChannel::name()`, which keys routing (`routes.rs:345`) and the channel map (`runtime/startup.rs:701`). A rename would ship uncaught. |
-| `src/openhuman/provider_surfaces/schemas.rs` | `all_schemas_returns_two` etc. | Weak but the only guard that the registration lists are populated. **Improve** (see §3), don't delete. |
-| `src/core/jsonrpc_tests.rs` | wallet-message drift guard (L1421) | The literal pin is load-bearing: three Rust producers and six frontend components hardcode the same string; the pin is what forces a human to update the desynced sites on a wording change. |
-| `tests/x402_twit_sh_live.rs` | `#[ignore]`d live x402 test | Only coverage artifact for the money-moving `X402RequestTool` (compile-pins its API + manual E2E harness). Costs nothing in CI. |
-| `app/test/e2e/specs/gmail-flow.spec.ts` | blanket drop of 8 tests | Over-reach: 4 of the 8 carry a real "app still boots with revoked/expired-token mock state" guard nothing else reproduces. Only 9.1.2 and 9.3.3 are true no-ops. Fix the fixture instead (§3). |
-
----
-
-## 3. OVERFITTED tests to rewrite
-
-| # | File / test | Problem | Fix |
-|---|-------------|---------|-----|
-| ✅ | `src/openhuman/agent/prompts/mod_tests.rs::grounding_contract_requires_exact_numeric_evidence` | Pins 5 verbatim prose substrings of the grounding contract — breaks on any copywriting pass. | Behavioral guarantee ("contract appended on every build path") already covered by the marker-based test; convert this to a single explicitly-labeled wording-lock, or assert stable structural markers. |
-| ✅ | `src/openhuman/agent/prompts/mod_tests.rs::identity_section_creates_missing_workspace_files` | Also string-matches SOUL.md brand-voice prose (`"Don't validate FUD"`). | Split: (a) files created + seeded from the checked-in template (compare against template file content); (b) a narrow, labeled brand-voice lock if the phrase must stay pinned. |
-| ✅ | `app/src-tauri/src/core_process_tests.rs::startup_timeout_cleanup_aborts_task_and_clears_slot` | 5 substring checks against one human-readable diagnostic string. **Caveat:** it also asserts real behavior (task slot cleared, shutdown token cancelled) — preserve those two assertions. | Return a small struct (attempt, port, ready_signal, port_open, task_state) + display string; assert struct fields, one loose `contains` on the text. |
-| ✅ | `src/openhuman/hooks/../useDaemonLifecycle.test.ts` (`app/src/hooks/__tests__/`) | Pins exact `console.log` strings as an effect-rerun proxy. Listener-count assertions are legit — keep them. | Drop the log-text pinning; keep listener/startDaemon observable assertions. |
-| ✅ | `src/openhuman/provider_surfaces/schemas.rs::all_schemas_returns_two` / `all_controllers_returns_two` | Magic-number count breaks on any legitimate 3rd controller. | Replace with `schemas().len() == controllers().len()` parity + presence of a known op (`list_queue`). Standardize this as a shared `assert_schema_controller_parity()` helper — the `== N` pattern repeats across ~15 domains. |
-| ✅ | every `connector-*.spec.ts::composio_sync RPC routes to mock backend` | Name promises routing; body only asserts the session didn't crash (original assertion removed per inline comment). | Rename to what it checks, or move the real routing assertion to a native-provider connector where sync actually hits the mock. |
-| ✅ | `tests/composio_raw_coverage_e2e.rs::composio_controller_schema_catalog_covers_all_declared_functions` | Hardcoded `inputs.len() == N` per function breaks on additive optional params. | Assert on specific input *names*, keep the meaningful namespace/name/output checks. |
-| ⚠️ | `app/src/components/chat/__tests__/ApprovalRequestCard.test.tsx` opaque-surface test | Asserts exact Tailwind class names + a regex banning opacity utilities. | Assert computed style, or accept it as a labeled visual-regression lock. |
-| ⚠️ | `AppWalkthrough.test.tsx` | `querySelector('div.bg-gradient-to-r')` and hardcoded `returns 13 steps`. | `data-testid` for the progress bar; drop the step count (first/last-target tests carry the signal). |
-| ⚠️ | `app/test/e2e/specs/gmail-flow.spec.ts` | "if UI not found, log and pass" pattern — degrades to no-op instead of failing. | **Fix the fixture:** seed deterministic Gmail-skill discovery in the mock, then assert unconditionally with no branching. |
-
----
-
-## 4. MISSING coverage — prioritized backlog
-
-### P0 — security, crypto, data-loss, ingress (do these first)
-
-1. **`security/policy/command_checks.rs` + `path_checks.rs` — ZERO tests.** The enforcement core
- of the entire autonomy model. Build a parametrized gate-matrix suite:
- (tier `readonly/supervised/full`) × (`CommandClass` Read/Write/Network/Install/Destructive) ×
- path-root, asserting `gate_decision` Allow/Prompt/Block; `is_always_forbidden` blocks
- system/credential dirs even when tier+trusted_roots would allow; `is_workspace_internal_path`
- fail-closed regardless of tier; `classify_command` "unrecognized ⇒ Write" fail-safe against
- pipes/redirects/chained commands. (Note: `policy_tests.rs` — 2,606 lines — is excellent but
- covers the *higher-level* policy, not these modules.)
-2. **`encryption/core.rs` — ZERO tests** on the Argon2id/AES-256-GCM primitives. Round-trip;
- wrong password / tampered ciphertext / tampered nonce rejection; fresh salt+nonce per call;
- KDF determinism. Plus one RPC→crypto→RPC integration test (schema tests currently never touch
- real ciphertext).
-3. **`memory/read_rpc/admin.rs::delete_source_rpc` — ZERO tests** on a 427-line destructive
- cascade-delete (chunks, embeddings, entity-index, content files, orphan-tree). Cover: exact
- source_id scoping (prefix siblings untouched); shared path_scope/collection trees NOT torn down
- while referenced; orphan cascade when fully orphaned; idempotency; legacy partial-delete
- recovery.
-4. **Event bus panic isolation** (`src/core/event_bus/bus.rs`): production `catch_unwind` exists
- precisely so one handler can't kill the loop — no test exercises it. Two subscribers, one
- panics, assert both keep receiving subsequent events.
-5. **Webhook ingress flood** (`webhooks/router.rs`): externally-triggered, unauthenticated-by-default
- surface with no rate-limit/backpressure test. If no such logic exists, that's a **product** gap.
-6. **E2E: core-process crash/recovery.** Blocked on a missing debug-only `stop_core_process`
- Tauri command (documented in `connectivity-state-differentiation.spec.ts`'s own header). Add the
- command, then: kill core mid-chat-turn → recoverable error (not a hang) → offline state →
- `restart_core_process` restores a working session.
-7. **E2E: RPC bearer auth failure.** No spec covers `core_rpc_relay` with a missing/tampered/expired
- token; `tauri-commands.spec.ts` is happy-path only. Also add the in-memory token-handoff
- round-trip test (`core_rpc_token` → relay → Authorization header → 401 without it).
-8. **CI wiring (see §5):** un-run harness self-tests are a P0 process gap.
-
-### P1 — core workflows
-
-- **Approval gate × agent turn**: harness-level test that a Write/Destructive-class turn parks
- pending approval while background/cron turns bypass, plus the **concurrent double-decide race**
- on one request_id (exactly-one-terminal-outcome). Frontend twin: composer blocked while an
- approval card is pending on the thread (`composerInteractionBlocked` wiring is untested).
-- **`TransportManager.raceLanAndTunnel()`**: the LAN-vs-tunnel race is entirely untested despite
- the docstring claiming otherwise — LAN wins (tunnel closed), tunnel wins (LAN closed), both
- fail, win-then-fail → `reset()` re-race.
-- **Memory `path_scope` invariant**: two source_ids sharing a path_scope must summarize into one
- collection tree (the documented dedupe-key-vs-scope contract).
-- **Hostile webhook payloads** (whatsapp/lark/linq/dingtalk/mattermost): wrong JSON types on
- expected fields, deep nesting, oversized bodies — current "malformed" tests only cover missing
- fields.
-- **Socket reconnect/backoff state machine**: only yuanbao has explicit backoff-schedule tests;
- mirror them on the primary socket client (increase → cap → reset-on-success), plus
- socketService's reaction to mid-session auth expiry (teardown + fresh token on reconnect).
-- **web3 swap/bridge/dapp tool wiring** (money-moving, untested at tool layer): schema rejection,
- delegation to ops with stubbed quote, error propagation. Plus one cross-domain quote→execute
- JSON-RPC E2E against a stubbed wallet.
-- **`threadSlice.ts` (501 lines) and `accountsSlice.ts`**: no test files at all.
-- **`CoreProcessHandle::restart()`** and **`core_rpc.rs::apply_auth()`** error paths (Tauri side).
-- **E2E journey spec**: onboarding → connect channel → chat turn using it → approval gate →
- tool result renders → new thread → memory recall of the earlier interaction. Individual pieces
- exist; no single continuous-session spec does.
-- **Approval-gate Playwright mirror**: `agent-harness-behaviors.spec.ts` exists only in the slower
- WDIO lane.
-- **AgentAccessPanel tier cross-check**: which sub-controls are enabled/hidden per autonomy tier.
-- **Onboarding credential forms**: happy-path persistence + invalid-input-blocks-navigation for
- CustomInference/CustomSearch pages.
-- **Coverage-gate scope**: add `scripts/**` (and `packages/**`) to the path filters (§5).
-- **~20 RPC controller domains with zero E2E references** (`recall_calendar`,
- `devices`, `people`, `redirect_links`, …) — one RPC round-trip each; full list in Appendix A.3.
-
-### P2 — polish / lower blast radius
-
-- Unicode-homoglyph spoofing cases through `is_command_allowed` / path prefix checks (current
- multibyte tests are panic-safety only).
-- Tunnel `framing.ts` adversarial reassembly (out-of-order, duplicate seq, truncated final chunk).
-- Composio second-consecutive-auth-error must surface, not loop.
-- `socketSlice` / `channelConnectionsSlice` / `pttSlice` / `providerSurfaceSlice` reducer tests;
- `Invites.tsx` page test.
-- `redact_url_for_log` direct unit test (token-leak prevention).
-- Port native-free WDIO-only specs (memory-sync-schedule, skill-activation-persistence,
- chat-thread-todo-strip, chat-background-activity-panel) to Playwright; maintain a documented
- allowlist of intentionally native-only specs.
-- Symlink-chain (depth >1) cases for `is_workspace_internal_path` / `validate_path_within_root`.
-- `tauri-plugin-ptt` Rust command surface (iOS is non-shipping — lowest priority).
-
----
-
-## 5. Harness, mocks & CI — audit results
-
-**Good news:** the three mock entry points (`scripts/mock-api-core.mjs`, `scripts/mock-api-server.mjs`,
-`app/test/e2e/mock-server.ts`) are thin shims over **one** implementation in `scripts/mock-api/`,
-so drift risk is ~nil. Deterministic seeding (`fuzzyNumber`/`fuzzyPick` off `mockBehavior.seed`)
-already exists. `httpFaultRules` gives generic per-route status/body/latency injection.
-
-**Holes found (verified by exhaustive grep of package.json + workflows):**
-
-1. **Orphaned tests — never run in any CI job:** `scripts/mock-api/socket.auth.test.mjs`,
- `socket.transport.test.mjs`, most of `scripts/__tests__/*.test.mjs`, and the Pester
- Windows-install test (`OpenHumanWindowsInstall.Tests.ps1`). The mock server's socket-auth
- behavior — which every E2E suite depends on — is itself unverified in CI.
- → Add `pnpm test:scripts` (`node --test scripts/**/*.test.mjs`) + a CI step; wire the Pester lane.
-2. **Coverage-gate scope hole:** the diff-cover gate only arms on `frontend || rust-core || rust-tauri`
- path filters; `scripts/**` (mock backend, debug runners, coverage checkers) is outside all of
- them. A mock-backend rewrite ships with zero coverage pressure.
- → Add `scripts/mock-api/**` + `scripts/*.mjs` to the filters; optionally feed a c8 lcov into the
- same diff-cover invocation.
-3. **Fault-injection ceiling:** the mock can inject clean HTTP errors and latency, but **cannot**
- simulate connection reset mid-response, hung requests, truncated chunked bodies, or malformed
- (non-JSON 200) responses — all real outage shapes.
- → Add `mode: "reset"` and `mode: "malformed"` to `httpFaultRules`; document a small "chaos
- toolkit" (500 storm, slow drip, auth-expiry-mid-session) so authors stop adding bespoke
- one-off behavior flags (auth.mjs already has ~6 that `httpFaultRules` could express).
-4. **Order-dependent E2E flake source:** `wdio.conf.ts` runs all specs in ONE session with state
- deliberately carried spec-to-spec, over a mock with module-level mutable state that only resets
- when a spec remembers to call `/__admin/reset`. A spec failing before its reset poisons the next.
- → Unconditional `/__admin/reset` in a WDIO `afterTest`/per-spec hook.
-5. **Mock↔backend contract drift:** nothing validates mock route responses against the TS types the
- frontend api clients expect. → zod/JSON-schema contract test over a sample of mock responses;
- extend the existing `rpcMethods.test.ts` drift-guard pattern (frontend constants ↔ Rust schema
- source) to tool names and event names.
-
----
-
-## 5bis. Re-check under the two-lane CI (2026-07-03, after #4486)
-
-CI moved to a two-branch model: PRs → `main` run a fast lane (`pr-ci.yml`: quality checks +
-unit tests **only for changed files** — `vitest related` / domain-scoped `cargo llvm-cov`), and a
-standing main→release PR (auto-refreshed by `prepare-release-pr.yml` on every push to main) runs
-the full lane (`release-ci.yml`: full unit suites, Rust mock-backend E2E, Playwright, desktop E2E
-on 3 OSes, gated by "Release CI Gate"). Re-audit of every CI-related finding:
-
-### Improved by the change
-
-- **Full-suite cadence is now structural**: because the standing release PR synchronizes on every
- main push, the complete unit + Rust E2E + desktop matrix runs against every mainline state —
- cross-domain breakage can no longer reach a *release* unseen. (It can still land on `main`
- unseen; see below.)
-- Legacy `e2e.yml` / `e2e-playwright.yml` / `test.yml` are now `workflow_dispatch`-only — the
- fan-out lives behind the release gate instead of ad-hoc triggers.
-
-### Findings from §5 that are STILL open (re-verified by grep on the new workflows)
-
-| Plan item | Status |
-|---|---|
-| Orphaned harness self-tests (`scripts/mock-api/socket.{auth,transport}.test.mjs`, most of `scripts/__tests__/`, Pester `test:install-ps1`) | **Still orphaned.** No workflow references them in either lane (`pnpm docs:test` remains the only `scripts/__tests__` entry point; no `pwsh` anywhere). |
-| Coverage-gate scope hole for `scripts/**` | **Still open, and slightly worse.** The new `pr-ci.yml` path filters still exclude `scripts/mock-api/**` and `scripts/*.mjs` (only `ci-cancel-aware.sh`, `test-rust-e2e.sh`, `test-rust-with-mock.sh`, `scripts/ci/*.sh` appear). A mock-backend rewrite now triggers **zero tests of any kind on the PR lane** — the code it can break (Rust E2E, Playwright, desktop E2E) only runs at the release PR. |
-| Per-spec mock `/__admin/reset` WDIO hook | **Not landed** (`wdio.conf.ts` unchanged). Matters more now: the full WDIO matrix is the release gate, so its order-dependent flakes directly block releases. |
-| Test-file→CI orphan check | **Not implemented.** |
-| `check-domain-e2e-coverage.mjs` | Still not wired into any workflow (`check-coverage-matrix.mjs` runs in `pr-quality.yml`). |
-
-### §4/§A missing-test items: unchanged
-
-The restructure moved *where* suites run; it added no tests. Re-verified the P0s are still
-untested: `command_checks.rs`, `path_checks.rs`, `encryption/core.rs` have zero `#[test]`s and
-`delete_source_rpc` has none. Everything in §4 and Appendix A.3 stands.
-
-### NEW gaps introduced by the two-lane model
-
-1. **Playwright is decorative even at the release gate.** `playwright-e2e` has
- `continue-on-error: true` (TODO #3615), and a job with `continue-on-error` reports `success`
- to `needs`, so "Release CI Gate" can never fail on it. The whole web-E2E lane is currently a
- can-never-fail check — the same anti-pattern as the gmail-flow specs, one level up. Either fix
- the flaky specs and drop the flag, or exclude the job from the gate's `needs` and say so.
-2. **Cross-domain regressions land on `main` undetected.** The fast lane's own script comments
- state it: coverage/tests scoped to the changed domain only — a change in domain A that breaks
- domain B's tests, or breaks `tests/*.rs` integration behavior, merges green and only fails on
- the release PR, where failures from many merged PRs arrive **batched** and need bisection.
- Mitigations: treat a red release PR as build-cop priority with a revert-first policy; and/or a
- scheduled full unit run on `main` (cheaper than per-PR, catches breakage within hours with
- per-commit granularity via `git bisect` against a known-good tag).
-3. **Rust integration tests (`tests/*.rs`) never run on the PR lane for `src/**` changes** —
- `rust-coverage-changed.sh` maps `src/<a>/<b>` to unit-test filters and only runs a `--test`
- target when the *test file itself* changed. An RPC-behavior regression in a domain with thin
- unit tests but good E2E coverage sails through the fast lane. Consider mapping changed domains
- to their obvious integration targets too (e.g. `src/core/**` → `--test json_rpc_e2e`).
-4. **`vitest related` is import-graph-based**: tests coupled to a changed file through non-import
- seams (mock fixtures, runtime registration, `?raw` prompt assets) won't be selected. The
- 0%-lcov backstop protects *changed lines lacking any test*, not *existing tests that would now
- fail*. Low frequency, but worth knowing when a release-PR failure looks "impossible".
-
-### Phase 0 (updated) — ✅ landed
-
-Done in `ci/phase0-test-substrate`: wired orphaned tests (`test:scripts` + `scripts-tests` job,
-`pester-install` job), added `scripts/mock-api/**` + `scripts/*.mjs` to PR-lane filters (mock
-changes now trigger the scripts self-test job), WDIO per-spec-file `/__admin/reset` hook,
-orphan-check + controller-domain check (`generate-test-inventory.mjs` → `test-inventory` job),
-and resolved the Playwright `continue-on-error` gate bypass (#3615, excluded from the gate).
-**Still open (process, not code):** adopt a red-release-PR policy (build-cop + revert-first).
-
----
-
-## 6. Strategy: how to get a lot of functional tests cheaply
-
-The audit shows the marginal value is in **behavioral/functional tests over shared harnesses**,
-not more per-file unit tests. Concrete leverage:
-
-1. **Table-driven contract suites.** The repo's biggest waste is copy-paste template families:
- 11 connector WDIO specs, 4 scanner-registry suites, ~4 allowlist tests × N channel providers,
- 6× registry-composition patterns in `tools/ops_tests.rs`, ~15 `all_schemas_returns_N` files.
- Build shared helpers/macros once (`runConnectorContract()`, `allowlist_contract_tests!`,
- `assert_schema_controller_parity()`, generic `ScannerRegistry<T>`) — each collapses dozens of
- declarations while *increasing* consistency (some copies have drifted, e.g. one provider's
- allowlist suite missing the case-sensitivity check others have).
-2. **The JSON-RPC E2E lane is the functional sweet spot.** Follow the repo's own ladder
- (Rust → RPC → UI): most new functional coverage should be `tests/*.rs` against the mock —
- cheap, deterministic, cross-domain. Priority suites: security-gate matrix over RPC, approval
- park/decide/TTL, encryption round-trip, memory ingest→recall→delete_source, wallet/web3
- quote→execute.
-3. **Property-based tests where inputs are adversarial** (proptest — currently absent):
- `classify_command` ("never Read for a command containing an unescaped shell operator; never
- panics"), path validation with symlink chains, encryption round-trip, tunnel framing
- reassembly, webhook parsers. One property replaces dozens of hand-enumerated cases.
-4. **Fuzzing the untrusted-input parsers** (cargo-fuzz — currently absent): webhook JSON decode,
- tunnel frame decode, deep-link URL parse. Subsumes most of the missing hostile-payload unit
- tests at far higher coverage-per-effort; run time-boxed in CI.
-5. **Mutation testing to find vacuous tests systematically.** Auditors hand-found "asserts
- nothing" tests one at a time; `cargo-mutants` scoped to the P0 zones (security/policy,
- encryption, approval, webhooks) turns that into a measured, ranked list. Consider Stryker on
- `app/src/services/` later.
-6. **One long journey spec per lane** (§4 P1) instead of many more element-visible smoke specs.
-7. **Fixture discipline over test branching:** the gmail-flow "if UI missing, pass" pattern is the
- anti-pattern to ban — deterministic mock seeding, then unconditional assertions. Consider a
- lint/review rule: no `console.log`-and-return early exits in specs.
-
----
-
-## 7. Systemic improvements (from the completeness critic)
-
-Dimensions the suite (and this audit) currently have **zero** coverage of:
-
-| Dimension | State | Action |
-|---|---|---|
-| Test→CI orphan detection | Pester + scripts tests confirmed orphaned; no systematic map | Extend `scripts/generate-test-inventory.mjs` to assert every discovered test file is invoked by ≥1 CI job; fail on orphans. **Highest-leverage systemic fix.** |
-| Mutation testing | None (no cargo-mutants/Stryker) | Scoped cargo-mutants run on P0 zones. |
-| Property-based testing | None (no proptest/quickcheck) | §6.3 targets. |
-| Fuzzing | None (no cargo-fuzz targets) | §6.4 targets. |
-| Accessibility | Zero a11y assertions in the whole frontend | jest-axe smoke lane over ~10 key screens (approval card, recovery phrase, onboarding, composer). |
-| Performance/load | No benchmarks anywhere (no criterion/k6) | Start with criterion micro-benches on memory ingest + embeddings; defer load tests. |
-| Flake quantification | WDIO: maxInstances 1, no retries, order-dependent state; flake rate unmeasured | Pull CI rerun/failure history, rank flaky specs; land the per-spec mock reset (§5.4). |
-| Test-speed budget | Unknown critical path; 30s vitest timeout can hide sleeps | Emit per-suite duration report from the inventory generator; slowest-N list + soft budget. |
-| Upgrade/migration fixtures | migrate_openclaw/hermes logic exists; no prior-version snapshot test | Check in a prior-version workspace/DB/config snapshot; assert forward migration with no data loss. |
-| Local↔CI parity | Different E2E drivers per OS; GGML_NATIVE=OFF only locally | Document which specs run where; fold into the lane-parity report (§4 P2). |
-| Concurrency as a category | Races found anecdotally only | Start with the approval double-decide + event-bus tests; consider loom for the event bus later. |
-
----
-
-## 8. Execution plan
-
-**Phase 0 — CI substrate (hours, do immediately)** — ✅ landed (PR: `ci/phase0-test-substrate`)
-- [x] Wire orphaned tests into CI (`test:scripts` runs `scripts/__tests__`, `scripts/mock-api`
- socket auth/transport + route tests; new `scripts-tests` PR-lane job) and a Pester lane
- (`pester-install` job → `test:install-ps1`).
-- [x] Add `scripts/mock-api/**` + `scripts/*.mjs` (+ `scripts/__tests__/**`) to the PR-lane path
- filters so mock-backend/script changes trigger the scripts self-tests.
-- [x] Unconditional mock `/__admin/reset` per spec file in WDIO (`beforeSuite`, file-path-guarded).
-- [x] Orphan-check in the inventory generator (`scripts/generate-test-inventory.mjs`, wired as the
- `test-inventory` PR-lane job via `test:inventory`): every script-level test file is invoked by
- ≥1 package.json script or workflow.
-- [x] Controller-domain coverage check: every domain in `src/core/all.rs` referenced by ≥1 file in
- `tests/` (Appendix A.4). 26 currently-uncovered domains seeded into a burn-down allowlist.
-- [x] Resolve the Release CI Gate Playwright `continue-on-error` bypass (§5bis item 1, #3615):
- `playwright-e2e` excluded from the gate's `needs`/results with an explanatory comment.
-
-**Phase 1 — P0 coverage** — ⏳ partial (PR: `test/phase1-p0-coverage`). Each item was
-**re-verified against current source first** (the §4 backlog was never skeptic-verified); three
-of the five "ZERO tests" claims turned out **already covered**, so only the genuine gaps were filled.
-- [x] **Encryption core round-trip + tamper suite** — GENUINE GAP (verified 0 prior tests in
- `encryption/core.rs`). Added 11 tests: bytes/string round-trip, KDF determinism (behavioural —
- key_bytes is private), wrong-password / different-salt rejection, tampered-ciphertext and
- tampered-nonce GCM auth failure, fresh-random-nonce-per-call, salt length+randomness,
- malformed-JSON and empty-plaintext edge cases.
-- [x] **Event-bus panic isolation** — GENUINE GAP (verified: `catch_unwind` in `bus.rs` had no
- test; only `publish_without_subscribers`). Added a two-subscriber test: one handler panics on its
- first event then recovers; asserts the panicked handler's own loop survives AND a peer keeps
- receiving every event.
-- [~] **Security gate-matrix (command_checks/path_checks)** — ALREADY COVERED. `policy_tests.rs`
- comprehensively tests `classify_command` (unknown⇒Write, redirect-lifts, highest-segment-wins,
- all classes), `gate_decision` (all tiers × classes + Install), `is_always_forbidden`, and
- `is_workspace_internal_path`. Plan's "ZERO tests" was inaccurate; no suite added (would duplicate).
-- [~] **`delete_source_rpc` cascade** — ALREADY COVERED. `memory_store/chunks/store_tests.rs` has
- `delete_source_rpc_purges_document_source_fully`, `_unknown_id_is_idempotent`,
- `_rejects_empty_source_id`, `_cleans_legacy_partial_delete`, plus the cascade (shared-tree
- preserved while referenced, orphan cascade, escape-path/symlink rejection, per-owner scoping).
-- [~] **Webhook flood** — PRODUCT GAP (verified: no rate-limit/backpressure/throttle anywhere in
- `webhooks/router.rs`; it is registration/routing/logging only). Filed as a product gap, not a test.
-- [ ] **core-process crash/recovery E2E** and **RPC bearer-auth-failure E2E** — deferred: both need
- the Tauri crate (blocked locally by missing system `glib-2.0`) and/or the WDIO desktop harness.
- `tests/json_rpc_e2e.rs` already covers RPC bearer auth/401s at the transport layer; the remaining
- gap is the frontend `core_rpc_relay` E2E. To be done in the CI-capable environment.
-
-**Phase 2 — deletions & rewrites (parallel with Phase 1, low risk)** — ✅ landed (PR: `test/phase2-drops-rewrites`)
-- [x] §2.1 deletions applied (⚠️ items re-verified against source before deleting):
- useSettingsNavigation.test.tsx, RecoveryPhrasePanel.test.tsx, the 7 graph-api
- "exposes the public surface" tests, the duplicate root ArtifactCard.test.tsx (unique
- kind-label assertion ported into `__tests__/`), the it.skip smoke test; Rust:
- harness_gap datetime test, 4 lib_tests no-ops, 4 factory construct-only tests,
- 3 telemetry emit-no-assert tests, 15 threads/ops_tests title dups (lowercase-hex
- assertion folded into title.rs), whatsapp 7→1 parameterized skip test; deep_link_ipc
- refactored to `collect_deep_link_urls_from_args` + real-fn test, vacuous no_primary test dropped.
-- [x] §2.2 connector consolidation: 11 specs → `connector-composio-contract.spec.ts` +
- `runConnectorContract()`; jira/gmail-composio kept bespoke; misleading `composio_sync`
- test renamed across the contract + remaining specs.
-- [x] §3 overfit rewrites (load-bearing assertions preserved): grounding wording-lock,
- identity split (template-compare + labeled brand-voice lock), provider_surfaces parity via
- new `assert_schema_controller_parity()`, composio catalog input-names, core_process
- loose-contains (keeps task-slot/shutdown-token asserts), useDaemonLifecycle (keeps
- listener asserts), ApprovalRequestCard (labeled visual lock), AppWalkthrough (data-testid).
-- [x] Shared helper `assert_schema_controller_parity()` added (`src/core/all.rs`) and the
- connector contract runner. (`allowlist_contract_tests!` / envelope-unwrap helper: follow-up.)
-- Deferred: §3 gmail-flow fixture fix (needs deterministic mock Gmail-skill seeding validated
- against a running desktop E2E app — not runnable in the authoring env; §2.3 flagged those
- tests as load-bearing boot guards, so they were left intact rather than risk an unvalidated
- E2E change).
-
-**Phase 3 — P1 backlog** — ⏳ partial (PR: `test/phase3-p1-gaps`). Verification-first pass: like §4
-P0, most P1 "untested" claims were **inaccurate against current `main`**. Verified state:
-- [x] **`TransportManager.raceLanAndTunnel`** — GENUINE GAP (the sibling test only covered profile
- *selection*, never the race). Added a dedicated `TransportManager.race.test.ts`: LAN-wins /
- tunnel-wins (loser closed), both-fail throws, `reset()` re-race, and winner-caching. Surfaced a
- real timing quirk: when the first `isHealthy()` to settle is `false`, the
- `Promise.race`→`Promise.any` fallback grabs that already-fulfilled `null` and throws instead of
- waiting for a later-healthy peer — worth a production follow-up.
-- [~] ALREADY COVERED (no gap): `composerInteractionBlocked` (ChatComposer + composerSendDecision
- tests), `threadSlice`/`accountsSlice` (multiple `__tests__`), CustomInference/CustomSearch
- onboarding pages, AgentAccessPanel (23 tests), and every P2 slice reducer
- (socket/channelConnections/ptt/providerSurface) + TeamInvites. web3 tool layer has `web3_tests.rs`.
-- [~] NOT A GAP: primary socket-client backoff is delegated to socket.io
- (`reconnectionAttempts: Infinity`), not custom logic — nothing bespoke to unit-test.
-- [ ] Genuine-but-deferred (need a full Rust build + deep store/parser fixtures, high iteration cost
- in the authoring env): memory two-source-one-tree `path_scope` invariant; broad hostile-webhook
- payload matrix (wrong types / deep nesting / oversized) beyond the current missing-field tests;
- the ~20 controller domains with no `tests/` reference (the Phase 0 inventory allowlist to burn
- down). Approval×turn integration, journey spec, and the Playwright approval mirror need WDIO/PW.
-
-**Phase 4 — new dimensions** — ⏳ partial (PR: `test/phase4-new-dimensions`). Unlike the §4 backlog,
-these are genuinely greenfield (the suite had zero of them), so they were built and validated:
-- [x] **proptest** (was absent): added as a dev-dep; property suite for the command classifier +
- path check (never-panic on arbitrary/unicode input; fail-closed redirect floor). NOTE: an
- encryption round-trip property was trialled but dropped — under coverage Argon2id is ~2.5s/case,
- so it held the lib-test binary ~60s and deterministically exposed a pre-existing env-var race in
- the unrelated `config::schema::load` env-overlay tests; the round-trip stays covered by the
- Phase 1 fixed-input tests.
-- [x] **Mock chaos modes** (§5.3): `httpFaultRules` gains `mode: "reset"` (connection reset) and
- `mode: "malformed"` (non-JSON 200) beyond clean statuses; `scripts/mock-api/chaos.test.mjs`
- drives the real server (auto-run by the Phase 0 `test:scripts` job).
-- [x] **jest-axe a11y smoke lane** (§7 — the frontend had zero a11y assertions): axe-core over
- ArtifactCard + ApprovalRequestCard asserting no violations.
-- [ ] Still open (larger tooling / own PRs): cargo-fuzz targets, scoped cargo-mutants on the P0
- zones, criterion micro-benches, migration snapshot fixture, per-suite duration report,
- mock↔backend contract test.
-
----
-
-## Appendix A — Rust integration/E2E slice
-
-*(Re-audited separately after the original workflow auditor returned an unusable result. These
-findings did not go through the skeptic-verify pass — treat as ⚠️ plausible; spot-check before
-deleting anything.)*
-
-**Summary.** The 129-file suite is dominated by `*_roundNN_raw_coverage_e2e.rs` files (coverage
-sprints, rounds 13–26) that re-exercise the same internal helpers (`app_state::snapshot`,
-`AuthProfilesStore`, `threads::ops`, `memory_sources::sync`) across 5–8 files under different
-names — **in-process calls, not RPC** — i.e. unit tests mislabeled `_e2e`. Real transport coverage
-(bearer auth, 401s, public-path bypass, SSE auth, `/schema`) in `json_rpc_e2e.rs` is genuinely good.
-
-### A.1 Consolidate / drop
-
-- **The same app_state quarantine invariant is asserted in ~5 files** (`near90_closure_…`,
- `config_auth_app_state_connectivity_e2e.rs` ×2, `…round26…`, `config_credentials_raw_coverage…`).
- Keep the `config_auth_app_state_connectivity_e2e.rs` pair; drop the rest.
-- **Four whole files are in-process unit tests wearing `_e2e` names**
- (`app_credentials_threads_round24_…`, `…sources_round26_…`, `…memory_sources_raw_coverage…`,
- `composio_credentials_state_raw_coverage_e2e.rs`): identical import quartet, no
- `build_core_http_router`, no `/rpc` call. Fold their unique branch cases into the owning domains'
- unit test modules; the RPC-level equivalents already exist in `json_rpc_e2e.rs`.
-- **`x402_twit_sh_live.rs` / `live_routing_e2e.rs`** (`#[ignore]`, need real wallet/backend):
- contribute zero CI coverage but the x402 one is the *only* coverage artifact for the money-moving
- `X402RequestTool` (skeptic-confirmed keep in §2.3). Reconciled action: **move to a `tests/manual/`
- dir or Cargo feature gate** so they stop inflating the E2E count, and add mock-backed variants of
- the same assertions so the code paths actually run in CI.
-
-### A.2 Overfitted
-
-- `config_auth_app_state_connectivity_e2e.rs::worker_a_controller_schemas_are_fully_exposed` —
- exact-match hardcoded lists of 40+ RPC method names across 5 namespaces; any additive method
- breaks it. Fix: must-exist superset assertion, or diff against the live registry; or `insta`
- snapshots so additions are a `cargo insta review`, not a hand-edit.
-- `composio_raw_coverage_e2e.rs::…covers_all_declared_functions` — (also §3) claims "all" but never
- checks `expected.len()` against the live catalog, so a new composio RPC silently gets zero
- coverage while the test stays green. Assert catalog-length parity so omissions fail loudly.
-
-### A.3 Missing (adds to §4)
-
-- **P1 — ~20 registered controller domains with zero references anywhere in `tests/`**, including
- real backend-facing surface: `recall_calendar`, `redirect_links`,
- `desktop_companion`, `devices`, `announcements`, `provider_surfaces`, `people`,
- `council_registry`, `audio_toolkit`, `agent_experience`, `http_host`, `skill_runtime`,
- `session_import`. Minimum: one RPC round-trip (primary read + write) per domain via
- `build_core_http_router`.
-- **P1 — SSE `/events` payload delivery**: auth is well tested; nothing asserts an actual
- `DomainEvent` published via `publish_global` arrives as a correctly-shaped SSE frame.
-- **P1 — embedded-core crash mid-RPC**: `ollama_lifecycle_e2e.rs` covers the Ollama sidecar and
- `port_conflict_recovery…` covers port collisions, but nothing kills the serving task mid-request.
- (Pairs with the §4 P0 frontend crash-recovery E2E.)
-- **P2 — concurrent RPC cross-talk**: fire 20+ parallel mixed-method `/rpc` requests, assert each
- response `id` matches its request.
-- **P2 — token rotation mid-session**: an open `/ws/dictation` or SSE stream outliving a bearer
- rotation should terminate, not silently continue.
-
-### A.4 Ideas
-
-- Reorganize `raw_coverage` sprint files into per-domain modules — the "round" layout is exactly
- why 20 uncovered domains went unnoticed.
-- **CI check: every controller domain registered in `src/core/all.rs` must have ≥1 reference in
- `tests/`** — small script in the spirit of `generate-test-inventory.mjs`; would have caught all
- of A.3 automatically. (Add to Phase 0 alongside the orphan-test check.)
diff --git a/scripts/deep-work/continue.sh b/scripts/deep-work/continue.sh
index cd0223ecff..1e4f55f7ab 100755
--- a/scripts/deep-work/continue.sh
+++ b/scripts/deep-work/continue.sh
@@ -176,7 +176,6 @@ else
echo "Next steps:"
echo "1) Push and create PR"
echo "2) Run additional quality checks first"
- echo "3) Update memory with learnings"
echo ""
while true; do
@@ -228,21 +227,8 @@ ${body}
fi
break
;;
- 3)
- echo "[deep-work] 🧠 calling memory-keeper..."
- repo=$(resolve_deep_work_repo)
- issue_json=$(gh issue view "$issue" -R "$repo" --json title)
- title=$(jq -r '.title' <<<"$issue_json")
-
- memory_prompt="Update project memory with learnings from issue #${issue}: \"${title}\".
-
-Review the recent commits and changes to extract useful insights for future development."
-
- claude "$memory_prompt" --task memory-keeper
- break
- ;;
*)
- echo "Please enter 1, 2, or 3"
+ echo "Please enter 1 or 2"
continue
;;
esac
diff --git a/scripts/deep-work/start.sh b/scripts/deep-work/start.sh
index 950d970283..0f50fc8a3c 100755
--- a/scripts/deep-work/start.sh
+++ b/scripts/deep-work/start.sh
@@ -4,18 +4,17 @@
# Full workflow automation for a GitHub issue:
# 0. Worktree setup (create worktree → new branch)
# 1. Issue fetching and validation
-# 1.5. Context gathering (CLAUDE.md, memory.md, recent commits)
+# 1.5. Context gathering (CLAUDE.md, recent commits)
# 2. Planning with architectobot agent
# 3. Implementation with codecrusher agent
# 4. Cross-checking (typecheck, lint, format, build)
# 5. Quality checks and test runs
-# 6. Memory updates with memory-keeper agent
-# 7. Commit with proper message
-# 8. Merge main and resolve conflicts
-# 9. Push and create draft PR
-# 10. Review cycle with pr-reviewer agent
-# 11. Mark ready for review (with user confirmation)
-# 12. Cleanup (with user confirmation)
+# 6. Commit with proper message
+# 7. Merge main and resolve conflicts
+# 8. Push and create draft PR
+# 9. Review cycle with pr-reviewer agent
+# 10. Mark ready for review (with user confirmation)
+# 11. Cleanup (with user confirmation)
set -euo pipefail
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
@@ -104,14 +103,6 @@ else
context_info+="⚠️ CLAUDE.md not found\n"
fi
-if [ -f ".claude/memory.md" ]; then
- echo "[deep-work] ✅ found .claude/memory.md"
- context_info+="✅ .claude/memory.md available\n"
-else
- echo "[deep-work] ⚠️ .claude/memory.md not found"
- context_info+="⚠️ .claude/memory.md not found\n"
-fi
-
echo "[deep-work] checking recent commits..."
recent_commits=$(git log --oneline -10 main)
context_info+="📝 Recent commits:\n$recent_commits\n"
@@ -197,31 +188,9 @@ if ! run_quality_checks "implementation"; then
exit 1
fi
-# Step 6: Memory updates
-echo ""
-echo "[deep-work] === Step 6: Memory updates ==="
-echo "[deep-work] 🧠 calling memory-keeper to update project knowledge..."
-
-memory_prompt="I've just completed implementation work on GitHub issue #${issue}: \"${title}\".
-
-Please update the project memory (.claude/memory.md) with any important learnings, patterns, gotchas, or insights from this work that would help future development on this project.
-
-Focus on:
-- New patterns or conventions established
-- Technical challenges overcome
-- Important gotchas or edge cases discovered
-- Useful debugging techniques
-- Architecture insights
-- Testing approaches that worked well
-
-Only add genuinely useful information that would help someone working on similar issues in the future."
-
-# Call memory-keeper agent directly via claude with task flag
-echo "$memory_prompt" | claude --task memory-keeper
-
-# Step 7: Commit
+# Step 6: Commit
echo ""
-echo "[deep-work] === Step 7: Commit ==="
+echo "[deep-work] === Step 6: Commit ==="
echo "[deep-work] staging changes for commit..."
git add .
@@ -243,9 +212,9 @@ EOF
echo "[deep-work] ✅ changes committed"
-# Step 8: Merge main and resolve conflicts
+# Step 7: Merge main and resolve conflicts
echo ""
-echo "[deep-work] === Step 8: Merge main & resolve conflicts ==="
+echo "[deep-work] === Step 7: Merge main & resolve conflicts ==="
echo "[deep-work] fetching latest main..."
# Fetch main from main worktree location
@@ -262,9 +231,9 @@ fi
echo "[deep-work] ✅ main merged successfully"
-# Step 9: Push and create draft PR
+# Step 8: Push and create draft PR
echo ""
-echo "[deep-work] === Step 9: Push & create draft PR ==="
+echo "[deep-work] === Step 8: Push & create draft PR ==="
branch=$(git branch --show-current)
echo "[deep-work] pushing branch $branch to origin..."
@@ -316,9 +285,9 @@ fi
echo "[deep-work] 📝 draft PR created: $pr_url"
-# Step 10: Review cycle
+# Step 9: Review cycle
echo ""
-echo "[deep-work] === Step 10: Review cycle ==="
+echo "[deep-work] === Step 9: Review cycle ==="
echo "[deep-work] 🔍 calling pr-reviewer for automated review..."
review_prompt="Please perform a thorough CodeRabbit-style review of this PR: $pr_url
@@ -337,9 +306,9 @@ After review, apply any approved suggestions, run quality checks, commit and pus
# Call pr-reviewer agent directly via claude with task flag
echo "$review_prompt" | claude --task pr-reviewer
-# Step 11: Mark ready for review (user confirmation)
+# Step 10: Mark ready for review (user confirmation)
echo ""
-echo "[deep-work] === Step 11: Ready for review ==="
+echo "[deep-work] === Step 10: Ready for review ==="
echo "[deep-work] 🎉 Workflow complete! The PR has been created and auto-reviewed."
echo ""
echo "PR URL: $pr_url"
@@ -357,9 +326,9 @@ else
echo " gh pr ready $pr_url"
fi
-# Step 12: Cleanup (user confirmation)
+# Step 11: Cleanup (user confirmation)
echo ""
-echo "[deep-work] === Step 12: Cleanup ==="
+echo "[deep-work] === Step 11: Cleanup ==="
echo ""
echo "The worktree for issue #$issue is at $worktree_dir (branch: $branch)."
echo ""
diff --git a/tiny_mascot.riv b/tiny_mascot.riv
deleted file mode 100644
index b38e89f260..0000000000
Binary files a/tiny_mascot.riv and /dev/null differ