AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(ui): add the History tab and settings for Always in the loop (#344)
Rufus870ff2b146b8
diff --git a/packages/core/openexecutive/architecture/prebuilt/memory.json b/packages/core/openexecutive/architecture/prebuilt/memory.jsonindex 15bd17ba..c16a36d7 100644--- a/packages/core/openexecutive/architecture/prebuilt/memory.json+++ b/packages/core/openexecutive/architecture/prebuilt/memory.json@@ -1,7 +1,7 @@{"section_id": "memory","title": "Memory System",- "markdown": "The Executive's durable memory is an episodic SQLite store at `./episodic_memory.db`, managed by `openexecutive.memory.episodic`. It holds four tables:\n\n- `decisions` — choices made, with `domain`, `summary`, `rationale`, `outcome`, and `tags`. `outcome` is filled in when the principal says how a decision turned out — the `record_decision_outcome` chat tool (principal on a verified surface only) or the Memories page. The weekly review reads this table twice: the week's decisions (`decisions_since`) and up to three older than 30 days with no outcome yet (`decisions_awaiting_outcome`), which it asks about.\n- `initiatives` — tracked efforts with a `status` and `summary` (idempotent upserts).\n- `advice_given` — query/advice pairs per domain.\n- `scheduled_actions` — a dispatch queue, treated separately from recall memory. `cancel_scheduled_action` guards its UPDATE on `status = 'pending'`, so a cancel never overwrites a row the scheduler claimed a moment earlier.\n\n### What gets extracted, and when\n\n`episodic.extract_and_store` runs after a turn and asks a utility-fast model for decisions, initiatives and advice. Every candidate must carry a `user_commitment_quote` that appears verbatim in the principal's own message (`_is_valid_user_commitment`) — the turn's speaker text (`memory_text` when the entry point supplies one, else the prompt), so a quoted Executive email or a briefing card's body inside the prompt cannot satisfy it — the model has repeatedly tried to log the Executive's *recommendations* as the user's commitments, and that quote is the hard gate against it.\n\nA turn reaches the extractor if `should_extract(speaker_text, session=...)` is true, which means only that the principal said something on a surface that proved it was them — there is deliberately **no length floor**. There used to be one, on the combined user+assistant length, and on a live tenant it selected almost exactly the wrong turns: 9 of 16 exchanges were blocked, and the 9 held every instruction the principal gave, while the 7 admitted were long analytical exchanges with no commitment in them. The extractor ran 13 times and stored nothing.\n\nMoving that floor to the user's side would relocate the bug, not fix it. The canonical executive decision is a long analysis answered with \"Approve option B.\" (17 chars) or \"Do B.\" (5), and any floor high enough to skip \"Done\" (4) also skips those — \"Do B.\" and \"Done\" differ by one character and mean opposite things. Length cannot separate a decision from an acknowledgement; the verbatim-quote check can, so `_is_valid_user_commitment` is the gate that decides. The price is one utility-fast call on turns that propose nothing.\n\nThat quote check is only meaningful when `user_message` holds the **principal's** words, and on a chat channel it does not — `Executive.chat()` is reached from Slack, Discord, Telegram, Google Chat and the email poller. A teammate's line would be written to `decisions` with no speaker attached, indistinguishable from the principal's own; an inbound email body is text the sender chose, so a self-quote is free. Removing the length floor is what makes this bite — short channel traffic used to fall under it incidentally — so `should_extract` asks the untrusted-content policy (`orchestrator.content_trust.principal_speaking`) whether the principal is speaking. It names the principal's surfaces rather than inferring them: the web chat (signed in as the principal — or, on an install with no principal on the People page yet, a request that carried no sign-in; a signed-in email on nobody's entry, such as an archived teammate still allowed to sign in, is not the principal), the CLI (`Session.from_cli`), the principal's own Slack or Discord or a private Telegram chat with a valid webhook secret (`people_tools.is_principal_on_verified_surface`), and email from the principal's primary address that Gmail's own `Authentication-Results` marks `dmarc=pass` (`Session.email_authenticated`). Everything else fails closed: a teammate (on the web too), an unrostered sender, the principal's address on mail Gmail did not authenticate, Google Chat, the MCP server (its caller names themselves), unattended runs, and an unreadable roster. The rule used to be \"no `origin_channel` means the principal's own surface\", and the email poller left `origin_channel` empty, so every stranger's email ran through the extractor with its body — headers, quoted chain and all — as the principal's words, and whatever it stored rendered on every later turn. The poller now tags its sessions `origin_channel=\"email\"`, and the gate no longer reads an empty channel as trust.\n\nThe extractor also reads only the words **outside** every `<untrusted_content>` block (`schedule_extraction` runs `content_trust.strip_untrusted` first): an attached document's text is inlined in that block, so a sentence the principal did not type can never be quoted back as their commitment, and a turn that is nothing but an attachment is not extracted at all.\n\nEach pass writes a `memory_extraction` audit row — in a `finally`, so a pass that crashed is recorded too, with the exception type as its `failure` reason: how many items the model proposed, how many were stored, a `malformed` count so a pass where the model returned only garbage does not read as one that found nothing, and a `{kind, reason}` record per drop — `bad_quote` and `missing_field` for an item the model proposed, `not_a_list`, `item_not_a_dict` and `payload_not_a_dict` for a shape that was never a usable item. Every proposed item is either stored or dropped, so `proposed == stored + item drops` is the arithmetic that says whether anything was lost silently. The tool payload is not schema-checked anywhere, so a malformed shape is counted as a drop rather than raised — it used to abort the whole pass, discarding the other two kinds with it and suppressing the row, which read exactly like \"extraction never ran\". Without it, \"the model found nothing\" and \"the model found things and every one was rejected\" are indistinguishable from outside the database — which is why the failure above survived undetected and took a SQLite session on the tenant to find. A `proposed>0, stored=0` streak is the signal to watch.\n\nThe validator rejects a paraphrase, and the model paraphrases: on one install two of three real commitments were lost that way, the quote beginning \"SVN's engagement covers only …\" where the person had typed something else. So a `bad_quote` drop earns exactly one corrective call. The model is shown the rejected items and the quotes it gave, told to copy the span character-for-character (typos and casing included) or return empty arrays, and the tool is forced where the provider supports tool choice. Every retry item is validated first; a still-invalid one adds no second drop and is counted `still_invalid`. A valid item is then classified in order: its label matches a pending drop record → a recovery, stored and the record released; else its quote (terminal punctuation ignored) already supports a stored item of that kind → a re-send, ignored and counted `repeated`, so a model that re-sends everything cannot double-count `stored`; else a new proposal, stored and counted — a reworded label cannot be told from a different item, and crediting it would erase the very `bad_quote` census the row exists to show, so its original drop stands. Recovery is checked before re-send because two commitments can rest on one sentence. Malformed shapes at any level — a kind that is not a list, an item or payload that is not a dict, a response with no tool call — are counted `malformed`, so a retry that returned garbage does not read like one that obediently returned nothing. The row's `retry` block (`rejected`, `recovered`, `repeated`, `still_invalid`, `malformed`, `failure`) is always present, zeros when nothing was rejected; `rejected` is set from the complete drop list when the row is written, so neither a store failure before the retry nor a cancellation during it can zero it. The arithmetic above still holds after the retry. An exception on the retry is recorded as the retry's own `failure` and leaves the first pass's results untouched; the cost is one utility-model call, only on turns that dropped something. `memory_extraction` is a declared event type, so the audit page's filter can select it.\n\n### Standing facts (corrections that persist everywhere)\n\nA fifth table, `facts` (`openexecutive.memory.facts`, created on first write), holds facts and corrections the principal stated and asked to keep — \"Maple House is 48 units, not 52\". Before it, a chat correction's only durable home was Honcho peer memory: optional, best-effort (its prefetch times out or errors under load), re-injected only into that person's later chat turns, and never read by the briefs, the scheduled runs or the alert review. The episodic extractor cannot hold one either: it stores only decisions backed by a commitment quote, and a fact is not a commitment.\n\n- **Written from chat, by the principal or an attributed teammate.** `remember_fact` stores one (subject, statement, optional wrong value) and `forget_fact` retires one. The principal on a verified surface may do both. A teammate on the People list (a `team` row, not archived, not a contact) on a verified surface (the web app signed in, their own Slack or Discord; `fact_tools._teammate_speaker`) may call `remember_fact` only; email, Google Chat and unrostered senders are refused. Both tools are withheld from every unattended run and every turn private to the principal. Every call, `forget_fact` included (retiring a fact changes what later prompts treat as true just as writing one does), also needs `source_quote`: at least two words and eight characters, found in what the speaker typed this turn (`delegation.settings.own_words` over the pinned `TurnDelegation.speaker_text`). The `<outbound_reply_context>` backstory a Slack or Discord reply is hydrated with is stripped first, and a message with an attachment is refused outright. The quote alone only proves the principal asked, so everything `remember_fact` stores and renders (the statement, the subject shown as `[fact N] subject:`, and a previous value shown as `(corrects: …)`) is tied to their words too. An omitted previous value falls back to the replaced fact's own statement. Every figure must be a number they wrote, compared at its magnitude: `$180k` matches `180,000`, but `180m` never lets `$180k` through. Every name must also appear in what they typed: a capitalised word, or any word holding a non-ASCII letter, other than the statement's very first word (a statement is one fact, so splitting a document's names into one-word sentences exempts nothing). So must every month, weekday or quarter. A name the model writes in lower case is not caught: the gate narrows what a real quote can carry in; it does not prove a paraphrase. A real quote therefore cannot carry a document's figure, name or date in with it (\"Cedar Court's lease expires in March\" after \"remember what the lease doc says\"), while a paraphrase of what they said still passes. So the model cannot store its own inference, a document's figure or text quoted back at the principal as something they said. Every audit row the tools write, and the chat loop's `skill:` dispatch row for them (whose input quotes the principal verbatim), is private to the principal (`executive._private_tool_row`). Those rows tie a fact to the principal's session and turn, which `GET /memories/facts` hides from teammates, and a teammate can read any non-private audit row. The handlers run in a worker thread (`asyncio.to_thread`, which carries the turn's context), and the chat and committee paths, the alert review, the morning brief's synthesis and the end-of-day, weekly-review and reflection workflows read the block the same way, so SQLite, the profile file and its lock never block the event loop the SSE streams share. The principal's own email may ask too: the change is checked the same way, then held until they confirm it by replying to a one-time token sent to their own address (see Integrations → Standing facts by email).\n- **Provenance and attribution.** Each row keeps the quote, the channel (`web` or the adapter), `session_id`, `turn_id`, the recording person and the time, plus `recorded_by_role` (`principal` or `teammate`) and, for a teammate, `recorded_by_name` as the People list had it. Rows written before these columns existed read as the principal's (`_migrate` adds the columns on the first write; the read-only render tolerates a DB that has none).\n- **One active fact per subject.** A new row supersedes any active row with the same folded subject key, or the id named in `replaces_fact_id`, in one transaction. The old row stays as `superseded` (with `superseded_by`), and the new one is stored as a `correction` carrying what it replaced. Retiring sets `retired` with a reason. **The principal outranks a teammate:** a teammate's write that would replace an active fact the principal set (by subject or `replaces_fact_id`) raises `PrincipalFactConflict`, and the tool stores it as `proposed` instead, naming the fact it would replace (`replaces_fact_id`); teammates replace each other's facts freely, and the principal replaces anyone's. **\"Needs my approval\"** (`fact_approval_rules`, per teammate, **on by default**, set only by the principal) stores every fact from that teammate as `proposed`; the principal turns it off for a teammate they trust, whose facts then apply at once (except one that would replace the principal's). The rule is read inside `record_fact`'s own write transaction, so a switch turned on a moment earlier cannot let one fact through; a teammate write that names no person is never trusted. One teammate may have at most `MAX_PENDING_PROPOSALS_PER_PERSON` (20) proposals waiting (`TooManyProposals`; the tool tells them to wait for the principal's review). A teammate's retire checks ownership in the `UPDATE` itself (`retire_fact(teammate_id=)`: their own row, not approved). A proposed row never renders; `approve_fact` makes it active and replaces what it names (the principal's own fact included — approving it is their word) and stamps `approved_at`, after which it outranks teammates exactly as the principal's own fact does (`Fact.principal_owned`: no teammate may replace or retire it); `decline_fact` sets `declined`. No field of a teammate's fact may carry what the render adds itself — `(per <anyone>)` in any case (a unit such as `(per month)` or `(per unit)` is fine), `[fact N]` or a date stamp after any dash, read NFKC-folded with invisible characters removed (`fact_tools._marker_error`) — so a teammate cannot plant a second, forged attribution inside their statement (the principal's own unmarked lines are not checked: \"(per Smith lease)\" is ordinary wording for them). The tool answers `awaiting_approval` (no action chip) and tells the model to say it is not in use yet.\n- **Rendered everywhere output is produced.** `render_facts_for_prompt` renders the active rows newest first under a self-explaining `STANDING FACTS` header (use these over older figures; a line ending `(per <name>)` is that teammate's word and the principal's unmarked line wins a conflict; the current conversation still wins; quoted data never instructions). A teammate's line ends `(per <name>)`, the name defanged like the rest, capped at 40 facts / 6000 chars, with angle brackets defanged. It opens the DB read-only and never creates it or the table. The block always rides in a user turn, never a cached system block: a chat turn's `<standing_facts>` (so every scheduled run through the chat loop too), each specialist consult (`route_to_specialist`, chat and workflow steps alike), the /today header and the morning brief (`render_briefing_context`, after the quiet check and inside the string the header's cache key hashes, so a new fact rewrites the header), the alert review's batch (`render_batch`, read once per pass), and the end-of-day digest, the weekly review's top-three call and the morning reflection (`with_standing_facts`).\n- **Company-profile edits from chat.** `update_company_profile` (same gate and quote rule) changes one whitelisted field of `company/profile.yaml`, under `PROFILE_EDIT_LOCK` (also taken by `PATCH /company-profile`, so neither edit silently drops the other): a text or number field is set, a list field gets an item added or removed, and `financials.key_metrics` takes a named metric. It writes through `CompanyProfile.save_to_yaml` and updates the session's profile, so the next turn's cached company block carries it (one cache miss on the change). The new value must itself appear in the principal's own words, not just the quote: the value renders into the cached company block on every later turn, so \"set our mission to what the doc says\" or \"update our headcount\" is refused rather than saving a document's text or a guessed figure. A number must be one they wrote, however they wrote it (`$180k`, `1.2m`, `2,400,000`). Saved text has `<`/`>` defanged. A `kind='profile'` row records each edit with its quote for the Pulse page. Those rows are never rendered into a prompt, because the profile block already carries the value.\n\n### Session scoping\n\n`decisions` and `advice_given` rows carry a `session_id`, so per-thread channels (Discord, Telegram) can pull just-this-thread history without leaking cross-conversation context. A null `session_id` falls back to a global view.\n\n### Surfacing\n\n`openexecutive.memory.episodic.format_for_prompt` renders recent decisions and initiatives into a compact `<past_decisions>` block injected into the user turn — alongside `<retrieved_context>` and peer memory — never into a cached system block. Each decision names where it was recorded when that was a channel — `- 2026-09-01 [finance] (via email): …`, from the prefix of its `session_id` (`email:`, `slack:`, `discord:`, `telegram:`, `google_chat:`); a web or CLI decision has no tag. Rows extracted from mail before the untrusted-content policy, when any sender's body could be stored, therefore read as mail rather than as the principal's own word.\n\nThe chat route also injects a `<briefing>` block into the same user turn: a compact digest of the current open (unread) alerts, built by `openexecutive.briefing.context.format_open_alerts_for_prompt` (company-wide, `status=\"unread\"`, mirroring `/today`). This is what lets the Executive discuss a briefing item the principal clicked or named on `/today` (e.g. \"Gulf Coast Port Cyberattack\"). It is resolved in parallel with the other context fetches, omitted when there are no open alerts, and never placed in a cached system block.\n\nOn the Pulse page the Memory section shows the three lists as Decisions, Initiatives and Advice tabs, then a **Corrections** tab (`GET /memories/facts`: active standing facts and profile edits with their quote, channel and — for a teammate's — their name; proposals first under \"Waiting for your approval\" with **Approve** / **Decline** for the principal; the replaced, retired and declined history folded away; **Retire** on any fact for the principal and on their own not-yet-approved one for a teammate; and, for the principal, a per-teammate \"needs my approval\" switch), and a **People** tab for peer memory (what Honcho has derived about each person, read-only, see the peer memory section). The header's Memories tile counts the three lists plus the peer notes, and says how many of the number are peer notes in its hint, since the People tab's badge counts people rather than notes.\n\nThe same user turn carries a `<drive_memory>` block when the conversation has touched Google Drive (`openexecutive.memory.drive_reads`). Drive is reached only as live Google Workspace calls inside a turn and history keeps only prose, so without it a file found one turn was gone the next. `MCPGateway.call_tool` hands each `search_drive_files` and `get_drive_file_content` result to `record_drive_result`, which keeps, per session, every file found or opened (file id, name, type, link, and for an opened file its first 600 characters) and every search that matched nothing, with its query. `format_drive_memory` lists the 20 most recent files, so \"the file you found earlier\" resolves to a file id the Executive reopens rather than searching again, and the queries that found nothing (dropped once the same query later finds something). Rows are keyed on the session *and* the speaker, and shown only to that speaker in that session, because one session can span several people (an email thread, a Slack or Discord thread). Nothing is recorded or shown without a bound `current_session` and a rostered speaker, on a turn private to the principal, or on one that touched the speaker's own mailbox (Act as me). workspace-mcp writes file names into its output unescaped, so a name containing a newline can forge a result line. Only a Drive-shaped file id, type and `docs`/`drive.google.com` link are therefore kept; any other line is dropped, and the name is always quoted as the file's own content, not instructions. Each speaker keeps at most 100 files and 100 searches per session, older rows are pruned on write, and `session_store.delete_session` drops them all.\n\nA conversation can also become its owner's alone. When Act as me first reads the speaker's own mailbox in it, `session_store.mark_mail_private` sets `sessions.mail_private` (creating the row with its owner when a channel adapter hasn't written it yet), and from then on only the session's owner may open, continue or delete it — the principal included, when it is a team member's (`chat._session_access`). It is never cleared. A search that matched nothing also gains a note in its tool result: say the exact query and that it found nothing, never that the file does not exist. This is a first step: Drive is still not indexed into the company collection.\n\n### System of record\n\nSQL is the system of record; the peer-memory service is a recall layer mirrored from it, not a replacement. When `store_decision` / `store_initiative` / `store_advice` insert a row whose `department` is non-empty and not `\"general\"`, the row is mirrored as a kind-tagged note into that department's peer via `append_department_note`. The mirror fires only after a successful INSERT, is fire-and-forget, and never rolls back the SQL row on peer-memory failure. `scheduled_actions` is never mirrored — it is a queue, not memory.\n\nThe episodic extractor still learns only from the principal's own words. Commitments and asks from everyone else on the roster are tracked as **open loops** (see Attunement) — `scheduled_actions` rows with `kind='open_loop'`, opened and closed by a separate quote-gated pass after each attributed turn. That pass depends on `chat_messages.sender_person_id`, which records who actually wrote each persisted user message. An open loop counts toward `list_awaiting_replies_by_person` only once it is due, and `list_scheduled_actions(exclude_internal=True)` filters `__internal__` rows in SQL so readers that want real sends are not starved by them. `mark_outbound_context_consumed` also resolves the Attunement outcome row for that DM as `replied` — a matched reply is the clearest sign proactive outreach landed — and a real change to an existing initiative (`store_initiative` / `update_initiative`, new status or summary) marks the updater's own check-in nudges `acted` — an update with no known updater, such as `PATCH /memories/initiatives/{id}`, credits nobody.\n\n### Workspace settings\n\nThe same database holds one row of settings that are not memory: `workspace_settings` (`openexecutive.memory.workspace_settings`) — the install's mode (`team` by default, or `solo` for one person using Open Executive just for themselves), the user's IANA time zone, the principal's role (`PrincipalRole`: `role_kind`, `role_title`, `reports_to`, `remit`, `measured_on`, all nullable; only solo mode reads it), and the company's own email domains (`company_domains`, a JSON list, or NULL to derive them from the principal's primary address — `people.identity` matches a teammate by local part on them; `validate_company_domains` lowercases, dedupes and sorts, allows at most 10 plain DNS names and refuses a free-mail provider's, and a stored value that no longer validates reads as NULL). It is a table of its own rather than a company-profile field because onboarding rebuilds the profile from scratch. Every read is fresh and read-only (a missing file or table reads as the defaults; a table from before the role or `company_domains` columns reads them as unset and is migrated additively by the next init or write). A read error (a locked database, say) also reads as the defaults, so `get_workspace` then says team; `read_stored_mode` is the strict read of the mode alone — None when the row cannot be read or holds no valid mode — for the scheduler's weekly-review check, which must not take a failed read for team. A session may carry an explicit `workspace_mode` override; otherwise the mode is read fresh at the start of each turn and pinned on the session for that turn only (`Session.turn_workspace_mode`, via `pin_turn_workspace_mode`), so every tool handler in the turn sees the mode its persona and tools were built in. `effective_workspace_mode` reads override, then the pin, then the setting; `effective_principal_role` reads a session's `principal_role` override, then the role pinned for the turn (`Session.turn_principal_role`, via `pin_turn_principal_role`), then the stored role. See Org for what solo changes and Scheduler for the time zone.\n\n### Act as me\n\n`initialize_db` also creates Act as me's per-person tables (`delegation.schema.ensure_schema`): `delegation_settings`, `delegation_voice` and `delegation_voice_history`. They hold a setting and a writing profile rather than memory, and nothing in them is mirrored to peer memory. A turn that touched the speaker's own mailbox teaches no memory: the episodic, open-loop and working-style passes are skipped along with the Honcho peer and department syncs, since its reply quotes a draft built from other people's mail. See **Act as Me (Delegation)**.\n\n### Always in the loop (notes from replies you sent)\n\nA person can keep private, dated notes of what they told people by email: what they promised, agreed, declined, answered, asked for or shared. The switch is per person (\"Keep track of what happens\", `history_person_settings.reply_notes`, off by default) and needs Act as me (`delegation.settings.can_delegate`), since the only source today is a reply they approved and sent through it.\n\n- **Where notes come from.** After `delegation.reply_send` sends a reply, it starts `memory.history_notes.note_sent_reply` in the background. The note-taker reads only the words the person sent (`email_poller.sender_new_text` strips quoted mail) and the recipients' names, cut to four words of name characters (`history_notes.short_name`): never the mail being answered, nor the subject, which others in the thread write too, so nothing another person wrote can become a note. One forced `record_notes` call with a constant prompt and no other tools returns at most three notes. Code then drops any note that says more than they did: the `quote` must appear word for word in what they sent, every figure in the summary must be in the quote, every name or date word must be in what they sent or the recipients' names, at least half its other content words must be theirs, the summary carries no link or address, and a `due_date` is kept only for something promised or agreed. Notes record events, never instructions, and carry `trust = high` because they rest on the person's own words.\n- **Whose they are.** Every note is private to its person (`visibility = private`). Nobody else reads it, the principal included; there is no shared note.\n- **How long they last.** The company default is 90 days (`history_settings.retention_days`, the principal's choice of 30, 90, 365 or until forgotten). A person may only choose a shorter time; shortening the company time clamps everyone's choice and re-dates live notes. A pinned note never expires; unpinning restarts its clock, and a later retention change counts from there. Reads skip expired notes and the scheduler's alert sweep deletes them (`history.sweep_expired`).\n- **What a person controls.** In `/memories/history` they read, search, pin, correct and forget their own notes. \"Don't remember this\" forgets every note from that conversation and adds it to `history_excluded`, so it is never noted again.\n- **Recall.** `recall_history` (`orchestrator.history_tools`) is offered only on a turn where the speaker may read their notes: verified, in a conversation private to them, interactive, not private to the principal, with their switch on. Before any note is read the turn is set `touched_mail`, for the principal too, so its rows are private to the speaker, it teaches no memory and the mail lockdown holds from that round on. The conversation is also marked theirs alone (`session_store.mark_mail_private`), so every later turn in it starts the same way and, for a team member, the principal can't open it; recall refuses if that can't be stored. Notes come back in a `<history_notes>` block as history to cite: the date, the person's own words first, then how they were noted.\n- **Not peer memory.** Notes never reach Honcho, episodic extraction, standing facts or another person's turn. The tables (`history_notes`, `history_settings`, `history_person_settings`, `history_excluded`, created by `history_schema.ensure_schema` from `initialize_db`) swap with a client slot and are cleared by a factory reset.",+ "markdown": "The Executive's durable memory is an episodic SQLite store at `./episodic_memory.db`, managed by `openexecutive.memory.episodic`. It holds four tables:\n\n- `decisions` — choices made, with `domain`, `summary`, `rationale`, `outcome`, and `tags`. `outcome` is filled in when the principal says how a decision turned out — the `record_decision_outcome` chat tool (principal on a verified surface only) or the Memories page. The weekly review reads this table twice: the week's decisions (`decisions_since`) and up to three older than 30 days with no outcome yet (`decisions_awaiting_outcome`), which it asks about.\n- `initiatives` — tracked efforts with a `status` and `summary` (idempotent upserts).\n- `advice_given` — query/advice pairs per domain.\n- `scheduled_actions` — a dispatch queue, treated separately from recall memory. `cancel_scheduled_action` guards its UPDATE on `status = 'pending'`, so a cancel never overwrites a row the scheduler claimed a moment earlier.\n\n### What gets extracted, and when\n\n`episodic.extract_and_store` runs after a turn and asks a utility-fast model for decisions, initiatives and advice. Every candidate must carry a `user_commitment_quote` that appears verbatim in the principal's own message (`_is_valid_user_commitment`) — the turn's speaker text (`memory_text` when the entry point supplies one, else the prompt), so a quoted Executive email or a briefing card's body inside the prompt cannot satisfy it — the model has repeatedly tried to log the Executive's *recommendations* as the user's commitments, and that quote is the hard gate against it.\n\nA turn reaches the extractor if `should_extract(speaker_text, session=...)` is true, which means only that the principal said something on a surface that proved it was them — there is deliberately **no length floor**. There used to be one, on the combined user+assistant length, and on a live tenant it selected almost exactly the wrong turns: 9 of 16 exchanges were blocked, and the 9 held every instruction the principal gave, while the 7 admitted were long analytical exchanges with no commitment in them. The extractor ran 13 times and stored nothing.\n\nMoving that floor to the user's side would relocate the bug, not fix it. The canonical executive decision is a long analysis answered with \"Approve option B.\" (17 chars) or \"Do B.\" (5), and any floor high enough to skip \"Done\" (4) also skips those — \"Do B.\" and \"Done\" differ by one character and mean opposite things. Length cannot separate a decision from an acknowledgement; the verbatim-quote check can, so `_is_valid_user_commitment` is the gate that decides. The price is one utility-fast call on turns that propose nothing.\n\nThat quote check is only meaningful when `user_message` holds the **principal's** words, and on a chat channel it does not — `Executive.chat()` is reached from Slack, Discord, Telegram, Google Chat and the email poller. A teammate's line would be written to `decisions` with no speaker attached, indistinguishable from the principal's own; an inbound email body is text the sender chose, so a self-quote is free. Removing the length floor is what makes this bite — short channel traffic used to fall under it incidentally — so `should_extract` asks the untrusted-content policy (`orchestrator.content_trust.principal_speaking`) whether the principal is speaking. It names the principal's surfaces rather than inferring them: the web chat (signed in as the principal — or, on an install with no principal on the People page yet, a request that carried no sign-in; a signed-in email on nobody's entry, such as an archived teammate still allowed to sign in, is not the principal), the CLI (`Session.from_cli`), the principal's own Slack or Discord or a private Telegram chat with a valid webhook secret (`people_tools.is_principal_on_verified_surface`), and email from the principal's primary address that Gmail's own `Authentication-Results` marks `dmarc=pass` (`Session.email_authenticated`). Everything else fails closed: a teammate (on the web too), an unrostered sender, the principal's address on mail Gmail did not authenticate, Google Chat, the MCP server (its caller names themselves), unattended runs, and an unreadable roster. The rule used to be \"no `origin_channel` means the principal's own surface\", and the email poller left `origin_channel` empty, so every stranger's email ran through the extractor with its body — headers, quoted chain and all — as the principal's words, and whatever it stored rendered on every later turn. The poller now tags its sessions `origin_channel=\"email\"`, and the gate no longer reads an empty channel as trust.\n\nThe extractor also reads only the words **outside** every `<untrusted_content>` block (`schedule_extraction` runs `content_trust.strip_untrusted` first): an attached document's text is inlined in that block, so a sentence the principal did not type can never be quoted back as their commitment, and a turn that is nothing but an attachment is not extracted at all.\n\nEach pass writes a `memory_extraction` audit row — in a `finally`, so a pass that crashed is recorded too, with the exception type as its `failure` reason: how many items the model proposed, how many were stored, a `malformed` count so a pass where the model returned only garbage does not read as one that found nothing, and a `{kind, reason}` record per drop — `bad_quote` and `missing_field` for an item the model proposed, `not_a_list`, `item_not_a_dict` and `payload_not_a_dict` for a shape that was never a usable item. Every proposed item is either stored or dropped, so `proposed == stored + item drops` is the arithmetic that says whether anything was lost silently. The tool payload is not schema-checked anywhere, so a malformed shape is counted as a drop rather than raised — it used to abort the whole pass, discarding the other two kinds with it and suppressing the row, which read exactly like \"extraction never ran\". Without it, \"the model found nothing\" and \"the model found things and every one was rejected\" are indistinguishable from outside the database — which is why the failure above survived undetected and took a SQLite session on the tenant to find. A `proposed>0, stored=0` streak is the signal to watch.\n\nThe validator rejects a paraphrase, and the model paraphrases: on one install two of three real commitments were lost that way, the quote beginning \"SVN's engagement covers only …\" where the person had typed something else. So a `bad_quote` drop earns exactly one corrective call. The model is shown the rejected items and the quotes it gave, told to copy the span character-for-character (typos and casing included) or return empty arrays, and the tool is forced where the provider supports tool choice. Every retry item is validated first; a still-invalid one adds no second drop and is counted `still_invalid`. A valid item is then classified in order: its label matches a pending drop record → a recovery, stored and the record released; else its quote (terminal punctuation ignored) already supports a stored item of that kind → a re-send, ignored and counted `repeated`, so a model that re-sends everything cannot double-count `stored`; else a new proposal, stored and counted — a reworded label cannot be told from a different item, and crediting it would erase the very `bad_quote` census the row exists to show, so its original drop stands. Recovery is checked before re-send because two commitments can rest on one sentence. Malformed shapes at any level — a kind that is not a list, an item or payload that is not a dict, a response with no tool call — are counted `malformed`, so a retry that returned garbage does not read like one that obediently returned nothing. The row's `retry` block (`rejected`, `recovered`, `repeated`, `still_invalid`, `malformed`, `failure`) is always present, zeros when nothing was rejected; `rejected` is set from the complete drop list when the row is written, so neither a store failure before the retry nor a cancellation during it can zero it. The arithmetic above still holds after the retry. An exception on the retry is recorded as the retry's own `failure` and leaves the first pass's results untouched; the cost is one utility-model call, only on turns that dropped something. `memory_extraction` is a declared event type, so the audit page's filter can select it.\n\n### Standing facts (corrections that persist everywhere)\n\nA fifth table, `facts` (`openexecutive.memory.facts`, created on first write), holds facts and corrections the principal stated and asked to keep — \"Maple House is 48 units, not 52\". Before it, a chat correction's only durable home was Honcho peer memory: optional, best-effort (its prefetch times out or errors under load), re-injected only into that person's later chat turns, and never read by the briefs, the scheduled runs or the alert review. The episodic extractor cannot hold one either: it stores only decisions backed by a commitment quote, and a fact is not a commitment.\n\n- **Written from chat, by the principal or an attributed teammate.** `remember_fact` stores one (subject, statement, optional wrong value) and `forget_fact` retires one. The principal on a verified surface may do both. A teammate on the People list (a `team` row, not archived, not a contact) on a verified surface (the web app signed in, their own Slack or Discord; `fact_tools._teammate_speaker`) may call `remember_fact` only; email, Google Chat and unrostered senders are refused. Both tools are withheld from every unattended run and every turn private to the principal. Every call, `forget_fact` included (retiring a fact changes what later prompts treat as true just as writing one does), also needs `source_quote`: at least two words and eight characters, found in what the speaker typed this turn (`delegation.settings.own_words` over the pinned `TurnDelegation.speaker_text`). The `<outbound_reply_context>` backstory a Slack or Discord reply is hydrated with is stripped first, and a message with an attachment is refused outright. The quote alone only proves the principal asked, so everything `remember_fact` stores and renders (the statement, the subject shown as `[fact N] subject:`, and a previous value shown as `(corrects: …)`) is tied to their words too. An omitted previous value falls back to the replaced fact's own statement. Every figure must be a number they wrote, compared at its magnitude: `$180k` matches `180,000`, but `180m` never lets `$180k` through. Every name must also appear in what they typed: a capitalised word, or any word holding a non-ASCII letter, other than the statement's very first word (a statement is one fact, so splitting a document's names into one-word sentences exempts nothing). So must every month, weekday or quarter. A name the model writes in lower case is not caught: the gate narrows what a real quote can carry in; it does not prove a paraphrase. A real quote therefore cannot carry a document's figure, name or date in with it (\"Cedar Court's lease expires in March\" after \"remember what the lease doc says\"), while a paraphrase of what they said still passes. So the model cannot store its own inference, a document's figure or text quoted back at the principal as something they said. Every audit row the tools write, and the chat loop's `skill:` dispatch row for them (whose input quotes the principal verbatim), is private to the principal (`executive._private_tool_row`). Those rows tie a fact to the principal's session and turn, which `GET /memories/facts` hides from teammates, and a teammate can read any non-private audit row. The handlers run in a worker thread (`asyncio.to_thread`, which carries the turn's context), and the chat and committee paths, the alert review, the morning brief's synthesis and the end-of-day, weekly-review and reflection workflows read the block the same way, so SQLite, the profile file and its lock never block the event loop the SSE streams share. The principal's own email may ask too: the change is checked the same way, then held until they confirm it by replying to a one-time token sent to their own address (see Integrations → Standing facts by email).\n- **Provenance and attribution.** Each row keeps the quote, the channel (`web` or the adapter), `session_id`, `turn_id`, the recording person and the time, plus `recorded_by_role` (`principal` or `teammate`) and, for a teammate, `recorded_by_name` as the People list had it. Rows written before these columns existed read as the principal's (`_migrate` adds the columns on the first write; the read-only render tolerates a DB that has none).\n- **One active fact per subject.** A new row supersedes any active row with the same folded subject key, or the id named in `replaces_fact_id`, in one transaction. The old row stays as `superseded` (with `superseded_by`), and the new one is stored as a `correction` carrying what it replaced. Retiring sets `retired` with a reason. **The principal outranks a teammate:** a teammate's write that would replace an active fact the principal set (by subject or `replaces_fact_id`) raises `PrincipalFactConflict`, and the tool stores it as `proposed` instead, naming the fact it would replace (`replaces_fact_id`); teammates replace each other's facts freely, and the principal replaces anyone's. **\"Needs my approval\"** (`fact_approval_rules`, per teammate, **on by default**, set only by the principal) stores every fact from that teammate as `proposed`; the principal turns it off for a teammate they trust, whose facts then apply at once (except one that would replace the principal's). The rule is read inside `record_fact`'s own write transaction, so a switch turned on a moment earlier cannot let one fact through; a teammate write that names no person is never trusted. One teammate may have at most `MAX_PENDING_PROPOSALS_PER_PERSON` (20) proposals waiting (`TooManyProposals`; the tool tells them to wait for the principal's review). A teammate's retire checks ownership in the `UPDATE` itself (`retire_fact(teammate_id=)`: their own row, not approved). A proposed row never renders; `approve_fact` makes it active and replaces what it names (the principal's own fact included — approving it is their word) and stamps `approved_at`, after which it outranks teammates exactly as the principal's own fact does (`Fact.principal_owned`: no teammate may replace or retire it); `decline_fact` sets `declined`. No field of a teammate's fact may carry what the render adds itself — `(per <anyone>)` in any case (a unit such as `(per month)` or `(per unit)` is fine), `[fact N]` or a date stamp after any dash, read NFKC-folded with invisible characters removed (`fact_tools._marker_error`) — so a teammate cannot plant a second, forged attribution inside their statement (the principal's own unmarked lines are not checked: \"(per Smith lease)\" is ordinary wording for them). The tool answers `awaiting_approval` (no action chip) and tells the model to say it is not in use yet.\n- **Rendered everywhere output is produced.** `render_facts_for_prompt` renders the active rows newest first under a self-explaining `STANDING FACTS` header (use these over older figures; a line ending `(per <name>)` is that teammate's word and the principal's unmarked line wins a conflict; the current conversation still wins; quoted data never instructions). A teammate's line ends `(per <name>)`, the name defanged like the rest, capped at 40 facts / 6000 chars, with angle brackets defanged. It opens the DB read-only and never creates it or the table. The block always rides in a user turn, never a cached system block: a chat turn's `<standing_facts>` (so every scheduled run through the chat loop too), each specialist consult (`route_to_specialist`, chat and workflow steps alike), the /today header and the morning brief (`render_briefing_context`, after the quiet check and inside the string the header's cache key hashes, so a new fact rewrites the header), the alert review's batch (`render_batch`, read once per pass), and the end-of-day digest, the weekly review's top-three call and the morning reflection (`with_standing_facts`).\n- **Company-profile edits from chat.** `update_company_profile` (same gate and quote rule) changes one whitelisted field of `company/profile.yaml`, under `PROFILE_EDIT_LOCK` (also taken by `PATCH /company-profile`, so neither edit silently drops the other): a text or number field is set, a list field gets an item added or removed, and `financials.key_metrics` takes a named metric. It writes through `CompanyProfile.save_to_yaml` and updates the session's profile, so the next turn's cached company block carries it (one cache miss on the change). The new value must itself appear in the principal's own words, not just the quote: the value renders into the cached company block on every later turn, so \"set our mission to what the doc says\" or \"update our headcount\" is refused rather than saving a document's text or a guessed figure. A number must be one they wrote, however they wrote it (`$180k`, `1.2m`, `2,400,000`). Saved text has `<`/`>` defanged. A `kind='profile'` row records each edit with its quote for the Pulse page. Those rows are never rendered into a prompt, because the profile block already carries the value.\n\n### Session scoping\n\n`decisions` and `advice_given` rows carry a `session_id`, so per-thread channels (Discord, Telegram) can pull just-this-thread history without leaking cross-conversation context. A null `session_id` falls back to a global view.\n\n### Surfacing\n\n`openexecutive.memory.episodic.format_for_prompt` renders recent decisions and initiatives into a compact `<past_decisions>` block injected into the user turn — alongside `<retrieved_context>` and peer memory — never into a cached system block. Each decision names where it was recorded when that was a channel — `- 2026-09-01 [finance] (via email): …`, from the prefix of its `session_id` (`email:`, `slack:`, `discord:`, `telegram:`, `google_chat:`); a web or CLI decision has no tag. Rows extracted from mail before the untrusted-content policy, when any sender's body could be stored, therefore read as mail rather than as the principal's own word.\n\nThe chat route also injects a `<briefing>` block into the same user turn: a compact digest of the current open (unread) alerts, built by `openexecutive.briefing.context.format_open_alerts_for_prompt` (company-wide, `status=\"unread\"`, mirroring `/today`). This is what lets the Executive discuss a briefing item the principal clicked or named on `/today` (e.g. \"Gulf Coast Port Cyberattack\"). It is resolved in parallel with the other context fetches, omitted when there are no open alerts, and never placed in a cached system block.\n\nOn the Pulse page the Memory section shows the three lists as Decisions, Initiatives and Advice tabs, then a **Corrections** tab (`GET /memories/facts`: active standing facts and profile edits with their quote, channel and — for a teammate's — their name; proposals first under \"Waiting for your approval\" with **Approve** / **Decline** for the principal; the replaced, retired and declined history folded away; **Retire** on any fact for the principal and on their own not-yet-approved one for a teammate; and, for the principal, a per-teammate \"needs my approval\" switch), a **People** tab for peer memory (what Honcho has derived about each person, read-only, see the peer memory section), and a **History** tab for the person's own Always in the loop notes (see below). The header's Memories tile counts the three lists plus the peer notes, and says how many of the number are peer notes in its hint, since the People tab's badge counts people rather than notes.\n\nThe same user turn carries a `<drive_memory>` block when the conversation has touched Google Drive (`openexecutive.memory.drive_reads`). Drive is reached only as live Google Workspace calls inside a turn and history keeps only prose, so without it a file found one turn was gone the next. `MCPGateway.call_tool` hands each `search_drive_files` and `get_drive_file_content` result to `record_drive_result`, which keeps, per session, every file found or opened (file id, name, type, link, and for an opened file its first 600 characters) and every search that matched nothing, with its query. `format_drive_memory` lists the 20 most recent files, so \"the file you found earlier\" resolves to a file id the Executive reopens rather than searching again, and the queries that found nothing (dropped once the same query later finds something). Rows are keyed on the session *and* the speaker, and shown only to that speaker in that session, because one session can span several people (an email thread, a Slack or Discord thread). Nothing is recorded or shown without a bound `current_session` and a rostered speaker, on a turn private to the principal, or on one that touched the speaker's own mailbox (Act as me). workspace-mcp writes file names into its output unescaped, so a name containing a newline can forge a result line. Only a Drive-shaped file id, type and `docs`/`drive.google.com` link are therefore kept; any other line is dropped, and the name is always quoted as the file's own content, not instructions. Each speaker keeps at most 100 files and 100 searches per session, older rows are pruned on write, and `session_store.delete_session` drops them all.\n\nA conversation can also become its owner's alone. When Act as me first reads the speaker's own mailbox in it, `session_store.mark_mail_private` sets `sessions.mail_private` (creating the row with its owner when a channel adapter hasn't written it yet), and from then on only the session's owner may open, continue or delete it — the principal included, when it is a team member's (`chat._session_access`). It is never cleared. A search that matched nothing also gains a note in its tool result: say the exact query and that it found nothing, never that the file does not exist. This is a first step: Drive is still not indexed into the company collection.\n\n### System of record\n\nSQL is the system of record; the peer-memory service is a recall layer mirrored from it, not a replacement. When `store_decision` / `store_initiative` / `store_advice` insert a row whose `department` is non-empty and not `\"general\"`, the row is mirrored as a kind-tagged note into that department's peer via `append_department_note`. The mirror fires only after a successful INSERT, is fire-and-forget, and never rolls back the SQL row on peer-memory failure. `scheduled_actions` is never mirrored — it is a queue, not memory.\n\nThe episodic extractor still learns only from the principal's own words. Commitments and asks from everyone else on the roster are tracked as **open loops** (see Attunement) — `scheduled_actions` rows with `kind='open_loop'`, opened and closed by a separate quote-gated pass after each attributed turn. That pass depends on `chat_messages.sender_person_id`, which records who actually wrote each persisted user message. An open loop counts toward `list_awaiting_replies_by_person` only once it is due, and `list_scheduled_actions(exclude_internal=True)` filters `__internal__` rows in SQL so readers that want real sends are not starved by them. `mark_outbound_context_consumed` also resolves the Attunement outcome row for that DM as `replied` — a matched reply is the clearest sign proactive outreach landed — and a real change to an existing initiative (`store_initiative` / `update_initiative`, new status or summary) marks the updater's own check-in nudges `acted` — an update with no known updater, such as `PATCH /memories/initiatives/{id}`, credits nobody.\n\n### Workspace settings\n\nThe same database holds one row of settings that are not memory: `workspace_settings` (`openexecutive.memory.workspace_settings`) — the install's mode (`team` by default, or `solo` for one person using Open Executive just for themselves), the user's IANA time zone, the principal's role (`PrincipalRole`: `role_kind`, `role_title`, `reports_to`, `remit`, `measured_on`, all nullable; only solo mode reads it), and the company's own email domains (`company_domains`, a JSON list, or NULL to derive them from the principal's primary address — `people.identity` matches a teammate by local part on them; `validate_company_domains` lowercases, dedupes and sorts, allows at most 10 plain DNS names and refuses a free-mail provider's, and a stored value that no longer validates reads as NULL). It is a table of its own rather than a company-profile field because onboarding rebuilds the profile from scratch. Every read is fresh and read-only (a missing file or table reads as the defaults; a table from before the role or `company_domains` columns reads them as unset and is migrated additively by the next init or write). A read error (a locked database, say) also reads as the defaults, so `get_workspace` then says team; `read_stored_mode` is the strict read of the mode alone — None when the row cannot be read or holds no valid mode — for the scheduler's weekly-review check, which must not take a failed read for team. A session may carry an explicit `workspace_mode` override; otherwise the mode is read fresh at the start of each turn and pinned on the session for that turn only (`Session.turn_workspace_mode`, via `pin_turn_workspace_mode`), so every tool handler in the turn sees the mode its persona and tools were built in. `effective_workspace_mode` reads override, then the pin, then the setting; `effective_principal_role` reads a session's `principal_role` override, then the role pinned for the turn (`Session.turn_principal_role`, via `pin_turn_principal_role`), then the stored role. See Org for what solo changes and Scheduler for the time zone.\n\n### Act as me\n\n`initialize_db` also creates Act as me's per-person tables (`delegation.schema.ensure_schema`): `delegation_settings`, `delegation_voice` and `delegation_voice_history`. They hold a setting and a writing profile rather than memory, and nothing in them is mirrored to peer memory. A turn that touched the speaker's own mailbox teaches no memory: the episodic, open-loop and working-style passes are skipped along with the Honcho peer and department syncs, since its reply quotes a draft built from other people's mail. See **Act as Me (Delegation)**.\n\n### Always in the loop (notes from replies you sent)\n\nA person can keep private, dated notes of what they told people by email: what they promised, agreed, declined, answered, asked for or shared. The switch is per person (\"Keep track of what happens\", `history_person_settings.reply_notes`, off by default) and needs Act as me (`delegation.settings.can_delegate`), since the only source today is a reply they approved and sent through it.\n\n- **Where notes come from.** After `delegation.reply_send` sends a reply, it starts `memory.history_notes.note_sent_reply` in the background. The note-taker reads only the words the person sent (`email_poller.sender_new_text` strips quoted mail) and the recipients' names, cut to four words of name characters (`history_notes.short_name`): never the mail being answered, nor the subject, which others in the thread write too, so nothing another person wrote can become a note. One forced `record_notes` call with a constant prompt and no other tools returns at most three notes. Code then drops any note that says more than they did: the `quote` must appear word for word in what they sent, every figure in the summary must be in the quote, every name or date word must be in what they sent or the recipients' names, at least half its other content words must be theirs, the summary carries no link or address, and a `due_date` is kept only for something promised or agreed. Notes record events, never instructions, and carry `trust = high` because they rest on the person's own words.\n- **Whose they are.** Every note is private to its person (`visibility = private`). Nobody else reads it, the principal included; there is no shared note.\n- **How long they last.** The company default is 90 days (`history_settings.retention_days`, the principal's choice of 30, 90, 365 or until forgotten). A person may only choose a shorter time; shortening the company time clamps everyone's choice and re-dates live notes. A pinned note never expires; unpinning restarts its clock, and a later retention change counts from there. Reads skip expired notes and the scheduler's alert sweep deletes them (`history.sweep_expired`).\n- **What a person controls.** Through `/memories/history` they read, search, pin, correct and forget their own notes. On the Pulse page this is the **History** tab, last in the Memory section and shown only to someone with notes to see (signed in and on the People list): each note shows its kind, who it was with, the date, the person's own words, any due date and when it will be forgotten, and its menu holds **Correct** (a side panel; \"Use the original\" clears a correction), **Pin**, **Don't remember this** and **Forget**. \"Don't remember this\" forgets every note from that conversation and adds it to `history_excluded`, so it is never noted again. The switch and a shorter time for their own notes sit on Settings → Act as me (\"Keep track of what happens\"); the company time is on Settings → **Memory**, which the principal changes and everyone else reads.\n- **Recall.** `recall_history` (`orchestrator.history_tools`) is offered only on a turn where the speaker may read their notes: verified, in a conversation private to them, interactive, not private to the principal, with their switch on. Before any note is read the turn is set `touched_mail`, for the principal too, so its rows are private to the speaker, it teaches no memory and the mail lockdown holds from that round on. The conversation is also marked theirs alone (`session_store.mark_mail_private`), so every later turn in it starts the same way and, for a team member, the principal can't open it; recall refuses if that can't be stored. Notes come back in a `<history_notes>` block as history to cite: the date, the person's own words first, then how they were noted.\n- **Not peer memory.** Notes never reach Honcho, episodic extraction, standing facts or another person's turn. The tables (`history_notes`, `history_settings`, `history_person_settings`, `history_excluded`, created by `history_schema.ensure_schema` from `initialize_db`) swap with a client slot and are cleared by a factory reset.","mermaid": "flowchart TD\n Store[\"store_decision / store_initiative / store_advice\"]\n DB[\"episodic_memory.db<br/>decisions / initiatives<br/>advice_given / scheduled_actions\"]\n Fmt[\"format_for_prompt\"]\n Turn[\"User turn<br/>past_decisions block\"]\n Mirror[\"append_department_note\"]\n Peer[\"Department peer<br/>(Honcho)\"]\n Store --> DB\n DB --> Fmt\n Fmt --> Turn\n Store -->|\"dept set & not general\"| Mirror\n Mirror -->|\"fire-and-forget\"| Peer\n Tool[\"remember_fact / update_company_profile<br/>(principal, verified, quoted)\"]\n Facts[\"facts table<br/>active / superseded / retired\"]\n Every[\"STANDING FACTS block<br/>chat, specialists, briefs,<br/>alert review, workflows\"]\n Tool --> Facts\n Facts -->|\"render_facts_for_prompt\"| Every\n class Store entry\n class DB storage\n class Fmt compute\n class Turn hot\n class Peer external\n\n class Tool entry\n class Facts storage\n class Every hot",- "generated_at": "2026-10-03T12:00:00Z"+ "generated_at": "2026-10-03T13:50:00Z"}diff --git a/packages/ui/scripts/history.test.mjs b/packages/ui/scripts/history.test.mjsnew file mode 100644index 00000000..f6c0b9af--- /dev/null+++ b/packages/ui/scripts/history.test.mjs@@ -0,0 +1,52 @@+import assert from "node:assert/strict";+import test from "node:test";+import {+ counterpartName,+ kindLabel,+ noteExpiry,+ noteText,+ noteWhere,+ personRetentionChoices,+ retentionLabel,+} from "../src/lib/history.ts";++const CHOICES = [30, 90, 365, null];++test("retention reads as people say it", () => {+ assert.equal(retentionLabel(30), "30 days");+ assert.equal(retentionLabel(365), "1 year");+ assert.equal(retentionLabel(null), "until forgotten");+});++test("a person may only pick the company default or something shorter", () => {+ assert.deepEqual(personRetentionChoices(CHOICES, 90), [null, 30]);+ assert.deepEqual(personRetentionChoices(CHOICES, 30), [null]);+ assert.deepEqual(personRetentionChoices(CHOICES, 365), [null, 30, 90]);+ // Kept until forgotten for the company: every length is shorter.+ assert.deepEqual(personRetentionChoices(CHOICES, null), [null, 30, 90, 365]);+ // Their own choice stays on offer, even once the company's caught up with it.+ assert.deepEqual(personRetentionChoices(CHOICES, 30, 30), [null, 30]);+ assert.deepEqual(personRetentionChoices(CHOICES, 90, 30), [null, 30]);+});++test("a note names who it was with, never the bare address when there's a name", () => {+ assert.equal(counterpartName("Dana Lee <[email protected]>"), "Dana Lee");+ assert.equal(counterpartName('"Lee, Dana" <[email protected]>'), "Lee, Dana");+ assert.equal(counterpartName("[email protected]"), "[email protected]");+ assert.equal(counterpartName("<[email protected]>"), "[email protected]");+ assert.equal(noteWhere({ channel: "email", counterpart: "Dana Lee <[email protected]>" }), "Email with Dana Lee");+ assert.equal(noteWhere({ channel: "email", counterpart: "" }), "Email");+});++test("their correction replaces the note's words", () => {+ assert.equal(noteText({ summary: "Promised Friday.", correction: null }), "Promised Friday.");+ assert.equal(noteText({ summary: "Promised Friday.", correction: "Promised Monday." }), "Promised Monday.");+ assert.equal(noteText({ summary: "Promised Friday.", correction: " " }), "Promised Friday.");+});++test("each note says when it goes", () => {+ assert.equal(noteExpiry({ pinned: true, expires_at: null }), "Pinned: kept until you forget it");+ assert.equal(noteExpiry({ pinned: false, expires_at: null }), "Kept until you forget it");+ assert.equal(noteExpiry({ pinned: false, expires_at: "2026-12-30T09:00:00+00:00" }), "Forgotten on 2026-12-30");+ assert.equal(kindLabel("promised"), "Promised");+});diff --git a/packages/ui/scripts/navConfig.test.mjs b/packages/ui/scripts/navConfig.test.mjsindex d2cc8102..1d4ee1cd 100644--- a/packages/ui/scripts/navConfig.test.mjs+++ b/packages/ui/scripts/navConfig.test.mjs@@ -183,6 +183,7 @@ test("the Settings hub: one tile per page, each with its own route", () => {["Your Executive → /settings/executive","Act as me → /settings/act-as-me",+ "Memory → /settings/memory","Workspace → /settings/workspace","Advanced → /settings/advanced","About → /settings/about",@@ -202,6 +203,7 @@ test("old /settings#anchors land on the matching page", () => {assert.equal(to("#executive"), "/settings/executive");assert.equal(to("#workspace"), "/settings/workspace");assert.equal(to("act-as-me"), "/settings/act-as-me");+ assert.equal(to("#memory"), "/settings/memory");assert.equal(to("#tools"), "/settings/advanced");for (const g of ADVANCED_GROUPS) assert.equal(to(`#tools-${g.key}`), "/settings/advanced");assert.equal(to("#about"), "/settings/about");diff --git a/packages/ui/src/app/settings/act-as-me/page.tsx b/packages/ui/src/app/settings/act-as-me/page.tsxindex d0e93b3e..9b18dbee 100644--- a/packages/ui/src/app/settings/act-as-me/page.tsx+++ b/packages/ui/src/app/settings/act-as-me/page.tsx@@ -3,7 +3,8 @@import ActAsMeCard, { ACT_AS_ME_INTRO } from "@/components/settings/ActAsMeCard";import SettingsSubpage from "@/components/settings/SettingsSubpage";-// Settings → Act as me: drafts written as you, in your own mailbox.+// Settings → Act as me: drafts written as you, in your own mailbox, and+// whether the Executive keeps notes of the replies you send.export default function ActAsMeSettingsPage() {return (<SettingsSubpage title="Act as me" description={ACT_AS_ME_INTRO}>diff --git a/packages/ui/src/app/settings/memory/page.tsx b/packages/ui/src/app/settings/memory/page.tsxnew file mode 100644index 00000000..78f86805--- /dev/null+++ b/packages/ui/src/app/settings/memory/page.tsx@@ -0,0 +1,16 @@+"use client";++import { CompanyRetentionCard } from "@/components/settings/HistorySettings";+import SettingsSubpage from "@/components/settings/SettingsSubpage";++// Settings → Memory: how long the private notes Always in the loop keeps last.+export default function MemorySettingsPage() {+ return (+ <SettingsSubpage+ title="Memory"+ description="The Executive keeps private notes of what people said in replies they approved and sent, so it can remind them later. Each person sees only their own."+ >+ <CompanyRetentionCard />+ </SettingsSubpage>+ );+}diff --git a/packages/ui/src/app/settings/page.tsx b/packages/ui/src/app/settings/page.tsxindex c8307c29..50b37a35 100644--- a/packages/ui/src/app/settings/page.tsx+++ b/packages/ui/src/app/settings/page.tsx@@ -15,11 +15,20 @@ import {type SettingsPageId,} from "@/components/shell/navConfig";import { useWorkspace } from "@/components/workspace/WorkspaceContext";-import { getAgentDetail, getDelegation, getVersion, listPersonas, type DelegationSettings } from "@/lib/api";+import {+ getAgentDetail,+ getDelegation,+ getHistory,+ getVersion,+ listPersonas,+ type DelegationSettings,+ type HistoryState,+} from "@/lib/api";+import { retentionLabel } from "@/lib/history";import { versionNotice } from "@/lib/versionNotice";// Settings — a hub of tiles, one per page (SETTINGS_PAGES): Your Executive,-// Act as me, Workspace, Advanced and About. Each tile says what's on its page+// Act as me, Memory, Workspace, Advanced and About. Each tile says what's on its page// and, where it's cheap to know, how things stand right now. The one-page// Settings this replaces used anchors (`/settings#workspace`); a link that// still carries one is sent on to the matching page.@@ -54,7 +63,12 @@ export default function SettingsPage() {const statuses = useTileStatuses();// Act as me has a tile only for someone who can have it (GET /delegation// answers null for everyone else).- const pages = SETTINGS_PAGES.filter((p) => p.id !== "act-as-me" || statuses.actAsMeOffered);+ // Memory, only for someone with notes to keep (GET /memories/history+ // answers null for anyone not signed in or not on the People list).+ const pages = SETTINGS_PAGES.filter(+ (p) =>+ (p.id !== "act-as-me" || statuses.actAsMeOffered) && (p.id !== "memory" || statuses.memoryOffered),+ );if (hash === null || target) return <main className="flex-1" />;@@ -122,12 +136,14 @@ function SettingsTile({ page, status }: { page: SettingsPageDef; status?: TileStfunction useTileStatuses(): {byPage: Partial<Record<SettingsPageId, TileStatus>>;actAsMeOffered: boolean;+ memoryOffered: boolean;} {const { status: run, unknown } = useExecutiveStatus();const { mode, effectiveTimezone, loading: workspaceLoading } = useWorkspace();const [voice, setVoice] = useState<string | null>(null);const [delegation, setDelegation] = useState<DelegationSettings | null | "error">(null);const [version, setVersion] = useState<TileStatus | null>(null);+ const [history, setHistory] = useState<HistoryState | null | "error">(null);useEffect(() => {const ctrl = new AbortController();@@ -143,6 +159,11 @@ function useTileStatuses(): {.catch((err) => {if ((err as Error)?.name !== "AbortError") setDelegation("error");});+ getHistory(undefined, ctrl.signal)+ .then((h) => setHistory(h))+ .catch((err) => {+ if ((err as Error)?.name !== "AbortError") setHistory("error");+ });getVersion(ctrl.signal).then((v) => {const notice = versionNotice(v);@@ -179,6 +200,14 @@ function useTileStatuses(): {: { text: "Mailbox not connected", tone: "warn" };}+ if (history && history !== "error") {+ const days = history.company_retention_days;+ byPage.memory = {+ text: days === null ? "Notes kept until forgotten" : `Notes last ${retentionLabel(days)}`,+ tone: "none",+ };+ }+if (!workspaceLoading) {byPage.workspace = {text: [MODE_LABEL[mode], effectiveTimezone].filter(Boolean).join(" · "),@@ -189,5 +218,5 @@ function useTileStatuses(): {byPage.advanced = { text: `${ADVANCED_ITEMS.length} tools for power users`, tone: "none" };if (version) byPage.about = version;- return { byPage, actAsMeOffered: delegation !== null };+ return { byPage, actAsMeOffered: delegation !== null, memoryOffered: history !== null };}diff --git a/packages/ui/src/components/memories/HistoryTab.tsx b/packages/ui/src/components/memories/HistoryTab.tsxnew file mode 100644index 00000000..fd6ace73--- /dev/null+++ b/packages/ui/src/components/memories/HistoryTab.tsx@@ -0,0 +1,335 @@+"use client";++import Link from "next/link";+import { useCallback, useEffect, useRef, useState } from "react";++import Button from "@/components/ui/Button";+import OverflowMenu from "@/components/ui/OverflowMenu";+import SidePanel from "@/components/ui/SidePanel";+import {+ forgetHistoryConversation,+ forgetHistoryNote,+ getHistory,+ updateHistoryNote,+ type HistoryNote,+ type HistoryState,+} from "@/lib/api";+import { kindLabel, noteExpiry, noteText, noteWhere } from "@/lib/history";+import { EmptyState, formatDate } from "./shared";++// History — Always in the loop. The signed-in person's own private notes of+// what they said in replies they approved and sent. Only they see them (the+// owner included); here they correct, pin and forget them, or ask the+// Executive not to remember a conversation at all.++const SEARCH_DELAY_MS = 300;++export default function HistoryTab({+ onCount,+ onAvailable,+}: {+ onCount: (n: number | null) => void;+ /** false when this viewer has no notes to see; the tab then goes away. */+ onAvailable: (available: boolean) => void;+}) {+ const [state, setState] = useState<HistoryState | null>(null);+ const [loading, setLoading] = useState(true);+ const [failed, setFailed] = useState(false);+ const [query, setQuery] = useState("");+ const [correcting, setCorrecting] = useState<HistoryNote | null>(null);+ // Only the newest read may land: an older one (a reload after a pin, a+ // search the person has since typed past) must not overwrite it.+ const latest = useRef(0);++ const refresh = useCallback(+ async (q: string, signal?: AbortSignal) => {+ const mine = ++latest.current;+ setFailed(false);+ try {+ const next = await getHistory(q, signal);+ if (mine !== latest.current) return;+ onAvailable(next !== null);+ setState(next);+ // The badge counts every note, not just the ones a search found.+ if (!q.trim()) onCount(next ? next.notes.length : null);+ } catch (err) {+ if ((err as Error)?.name === "AbortError" || mine !== latest.current) return;+ setFailed(true);+ onCount(null);+ } finally {+ // An aborted or superseded read leaves the newer one to finish loading.+ if (mine === latest.current) setLoading(false);+ }+ },+ [onCount, onAvailable],+ );++ useEffect(() => {+ const ctrl = new AbortController();+ const timer = setTimeout(() => void refresh(query, ctrl.signal), query ? SEARCH_DELAY_MS : 0);+ return () => {+ clearTimeout(timer);+ ctrl.abort();+ };+ }, [query, refresh]);++ const reload = useCallback(() => refresh(query), [refresh, query]);++ const act = useCallback(+ async (run: () => Promise<unknown>, failure: string) => {+ try {+ await run();+ } catch (err) {+ window.alert(err instanceof Error ? err.message : failure);+ return;+ }+ void reload();+ },+ [reload],+ );++ if (loading) return <div className="text-fg-muted text-[15px] py-4">Loading…</div>;+ const failure = (+ <div className="text-fg-muted text-sm py-3">+ Couldn't load your notes.{" "}+ <button onClick={() => void reload()} className="font-medium text-accent hover:underline">+ Try again+ </button>+ </div>+ );+ // A failed first read has nothing to show; a later one keeps the search box+ // and the notes already on screen.+ if (!state) return failed ? failure : null;++ const empty = state.notes.length === 0 && !query.trim();+ return (+ <div className="py-3">+ {empty ? (+ <HistoryEmpty state={state} />+ ) : (+ <>+ <input+ type="search"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Search your notes"+ aria-label="Search your notes"+ className="w-full bg-surface border border-line rounded-xl px-3 py-2.5 text-[15px] text-fg focus:outline-none focus:ring-2 focus:ring-accent/40"+ />+ {failed && failure}+ {state.notes.length === 0 ? (+ <EmptyState message="No notes match." />+ ) : (+ <div className="mt-1 divide-y divide-line">+ {state.notes.map((note) => (+ <NoteRow+ key={note.id}+ note={note}+ onCorrect={() => setCorrecting(note)}+ onPin={() =>+ void act(() => updateHistoryNote(note.id, { pinned: !note.pinned }), "Couldn't change the note.")+ }+ onForget={() => {+ if (!window.confirm("Forget this note? This cannot be undone.")) return;+ void act(() => forgetHistoryNote(note.id), "Couldn't forget the note.");+ }}+ onDontRemember={() => {+ if (+ !window.confirm(+ "Forget every note from this conversation, and never note it again? This cannot be undone.",+ )+ )+ return;+ void act(() => forgetHistoryConversation(note.id), "Couldn't forget the conversation.");+ }}+ />+ ))}+ </div>+ )}+ <p className="mt-3 text-xs text-fg-subtle">+ Only you see these. New notes are kept {retentionPhrase(state.effective_retention_days)}.+ </p>+ </>+ )}+ {/* Keyed by note, so the box starts from the note it opened on. */}+ <CorrectPanel+ key={correcting?.id ?? "closed"}+ note={correcting}+ onClose={() => setCorrecting(null)}+ onSave={async (correction) => {+ const note = correcting;+ if (!note) return;+ try {+ await updateHistoryNote(note.id, { correction });+ } catch (err) {+ window.alert(err instanceof Error ? err.message : "Couldn't change the note.");+ return;+ }+ setCorrecting(null);+ void reload();+ }}+ />+ </div>+ );+}++function retentionPhrase(days: number | null): string {+ return days === null ? "until you forget them" : days === 365 ? "for a year" : `for ${days} days`;+}++function HistoryEmpty({ state }: { state: HistoryState }) {+ if (state.reply_notes) {+ return (+ <EmptyState message="No notes yet. They're added after you send a reply the Executive drafted for you." />+ );+ }+ return (+ <div className="text-center py-14 px-4 text-fg-muted text-[15px] leading-relaxed">+ <p>+ Keep track of what happens is off. When it's on, the Executive keeps private notes of what+ you said in replies you approve and send, so it can remind you later.+ </p>+ {state.can_note_replies && (+ <Link href="/settings/act-as-me" className="mt-3 inline-block font-medium text-accent hover:underline">+ Turn it on in Act as me+ </Link>+ )}+ </div>+ );+}++function NoteRow({+ note,+ onCorrect,+ onPin,+ onForget,+ onDontRemember,+}: {+ note: HistoryNote;+ onCorrect: () => void;+ onPin: () => void;+ onForget: () => void;+ onDontRemember: () => void;+}) {+ const corrected = Boolean(note.correction?.trim());+ return (+ <div className="py-3.5">+ <div className="flex items-center justify-between gap-3 mb-1">+ <div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-sm text-fg-muted">+ <span className="px-2 py-0.5 rounded-lg bg-surface-overlay text-fg font-medium">{kindLabel(note.kind)}</span>+ {/* The name is theirs to choose; the address says who it really was. */}+ <span className="truncate" title={note.counterpart}>+ {noteWhere(note)}+ </span>+ <span>{formatDate(note.occurred_at)}</span>+ {note.pinned && <span className="text-xs font-medium text-accent">Pinned</span>}+ </div>+ <OverflowMenu+ size="sm"+ label="Note actions"+ items={[+ { label: "Correct", onSelect: onCorrect },+ { label: note.pinned ? "Unpin" : "Pin", onSelect: onPin },+ { label: "Don't remember this", onSelect: onDontRemember },+ { label: "Forget", danger: true, onSelect: onForget },+ ]}+ />+ </div>+ <div className="space-y-1">+ <div className="text-[15px] text-fg">+ {noteText(note)}+ {corrected && <span className="ml-1 text-xs text-fg-subtle">(as you corrected it)</span>}+ </div>+ {note.quote && (+ <div className="text-sm text-fg-muted line-clamp-3" title={note.quote}>+ Your words: “{note.quote}”+ </div>+ )}+ <div className="text-xs text-fg-subtle">+ {note.due_date ? `Due ${note.due_date} · ` : ""}+ {noteExpiry(note)}+ </div>+ </div>+ </div>+ );+}++function CorrectPanel({+ note,+ onClose,+ onSave,+}: {+ note: HistoryNote | null;+ onClose: () => void;+ onSave: (correction: string) => Promise<void>;+}) {+ const [text, setText] = useState(() => (note ? noteText(note) : ""));+ const [busy, setBusy] = useState(false);++ const save = async (correction: string) => {+ setBusy(true);+ try {+ await onSave(correction);+ } finally {+ setBusy(false);+ }+ };++ const corrected = Boolean(note?.correction?.trim());+ return (+ <SidePanel+ open={note !== null}+ onClose={onClose}+ title="Correct this note"+ subtitle={note ? `${noteWhere(note)} · ${formatDate(note.occurred_at)}` : undefined}+ footer={+ <div className="flex flex-wrap justify-end gap-2">+ {corrected && (+ <Button variant="ghost" onClick={() => void save("")} disabled={busy}>+ Use the original+ </Button>+ )}+ <Button variant="ghost" onClick={onClose} disabled={busy}>+ Cancel+ </Button>+ <Button variant="primary" onClick={() => void save(text.trim())} disabled={busy || !text.trim()}>+ Save+ </Button>+ </div>+ }+ >+ {note && (+ <div className="space-y-4">+ <textarea+ value={text}+ onChange={(e) => setText(e.target.value)}+ rows={4}+ maxLength={400}+ aria-label="What the note should say"+ className="w-full bg-surface border border-line rounded-xl px-3 py-2.5 text-[15px] text-fg focus:outline-none focus:ring-2 focus:ring-accent/40"+ />+ <div className="text-sm text-fg-muted space-y-1">+ {note.counterpart && (+ <div className="break-all">+ <span className="text-fg-subtle">With: </span>+ {note.counterpart}+ </div>+ )}+ <div>+ <span className="text-fg-subtle">Noted as: </span>+ {note.summary}+ </div>+ {note.quote && (+ <div>+ <span className="text-fg-subtle">Your words: </span>“{note.quote}”+ </div>+ )}+ </div>+ <p className="text-xs text-fg-subtle">+ The Executive uses your version from now on. Your words stay as you wrote them.+ </p>+ </div>+ )}+ </SidePanel>+ );+}diff --git a/packages/ui/src/components/memories/MemorySection.tsx b/packages/ui/src/components/memories/MemorySection.tsxindex 150f8af7..3090d929 100644--- a/packages/ui/src/components/memories/MemorySection.tsx+++ b/packages/ui/src/components/memories/MemorySection.tsx@@ -24,11 +24,19 @@ import Button from "@/components/ui/Button";import OverflowMenu from "@/components/ui/OverflowMenu";import SectionTabs from "@/components/ui/SectionTabs";import CorrectionsTab from "./CorrectionsTab";+import HistoryTab from "./HistoryTab";import { DOMAINS, STATUSES, EmptyState, formatDate } from "./shared";-type MemoryTab = "decisions" | "initiatives" | "advice" | "corrections" | "people";+type MemoryTab = "decisions" | "initiatives" | "advice" | "corrections" | "people" | "history";-export const MEMORY_TABS: readonly MemoryTab[] = ["decisions", "initiatives", "advice", "corrections", "people"];+export const MEMORY_TABS: readonly MemoryTab[] = [+ "decisions",+ "initiatives",+ "advice",+ "corrections",+ "people",+ "history",+];const MEMORY_EMPTY = "No memories yet — they're extracted automatically after chats.";const PEOPLE_EMPTY =@@ -51,11 +59,15 @@ export default function MemorySection() {advice: null,corrections: null,people: null,+ history: null,});// Peer memory is optional: until its status is known the People tab shows// (so the bar does not jump on installs that have it); once the backend says// "disabled" the tab goes away for good.const [peopleEnabled, setPeopleEnabled] = useState<boolean | null>(null);+ // History (Always in the loop) is the signed-in person's own notes: it goes+ // away for anyone with none to see (not signed in, not on the roster).+ const [historyEnabled, setHistoryEnabled] = useState<boolean | null>(null);// Stable per-tab callbacks — these are passed to the (always-mounted) tabs as// `onCount`, which lives in each tab's `refresh` useCallback deps. They MUST// keep a constant identity across renders, or the tab's refresh→useEffect@@ -72,6 +84,11 @@ export default function MemorySection() {(n: number | null) => setCounts((c) => ({ ...c, people: n })),[],);+ const onCountHistory = useCallback(+ (n: number | null) => setCounts((c) => ({ ...c, history: n })),+ [],+ );+ const onHistoryAvailable = useCallback((available: boolean) => setHistoryEnabled(available), []);const onPeopleStatus = useCallback((s: PeopleMemory["status"]) => setPeopleEnabled(s !== "disabled"),[],@@ -79,7 +96,8 @@ export default function MemorySection() {useEffect(() => {if (peopleEnabled === false && tab === "people") setTab("decisions");- }, [peopleEnabled, tab]);+ if (historyEnabled === false && tab === "history") setTab("decisions");+ }, [peopleEnabled, historyEnabled, tab]);// `/memories?tab=corrections` (the chat chip after remember_fact) opens// that tab. Read once on mount from the URL, so the page needs no Suspense@@ -89,10 +107,9 @@ export default function MemorySection() {if (wanted && (MEMORY_TABS as readonly string[]).includes(wanted)) setTab(wanted as MemoryTab);}, []);- const tabs: MemoryTab[] =- peopleEnabled === false- ? MEMORY_TABS.filter((t) => t !== "people")- : [...MEMORY_TABS];+ const tabs: MemoryTab[] = MEMORY_TABS.filter(+ (t) => !(t === "people" && peopleEnabled === false) && !(t === "history" && historyEnabled === false),+ );return (<div>@@ -125,6 +142,9 @@ export default function MemorySection() {<div className={tab === "people" ? "" : "hidden"}><PeopleTab onCount={onCountPeople} onStatus={onPeopleStatus} /></div>+ <div className={tab === "history" ? "" : "hidden"}>+ <HistoryTab onCount={onCountHistory} onAvailable={onHistoryAvailable} />+ </div></div></div>);diff --git a/packages/ui/src/components/settings/ActAsMeCard.tsx b/packages/ui/src/components/settings/ActAsMeCard.tsxindex 51b5b658..dfb8ddaa 100644--- a/packages/ui/src/components/settings/ActAsMeCard.tsx+++ b/packages/ui/src/components/settings/ActAsMeCard.tsx@@ -4,6 +4,7 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "reactimport Icon from "@/components/Icon";import AdvancedFold from "@/components/settings/AdvancedFold";+import { KeepTrackCard } from "@/components/settings/HistorySettings";import SettingsCard from "@/components/settings/SettingsCard";import Switch from "@/components/Switch";import Button from "@/components/ui/Button";@@ -243,6 +244,8 @@ export default function ActAsMeCard() {/>)}+ <KeepTrackCard />+<AdvancedFoldid="act-as-me-advanced"summary={settings.team ? "How I write · Let team members use it" : "How I write"}diff --git a/packages/ui/src/components/settings/HistorySettings.tsx b/packages/ui/src/components/settings/HistorySettings.tsxnew file mode 100644index 00000000..db638939--- /dev/null+++ b/packages/ui/src/components/settings/HistorySettings.tsx@@ -0,0 +1,172 @@+"use client";++import Link from "next/link";+import { useEffect, useState } from "react";++import SettingsCard from "@/components/settings/SettingsCard";+import Switch from "@/components/Switch";+import { getHistory, updateHistorySettings, type HistoryState } from "@/lib/api";+import { personRetentionChoices, retentionLabel } from "@/lib/history";++// Always in the loop's settings (PUT /memories/history/settings): each+// person's own "Keep track of what happens" switch and how long their notes+// last, on Act as me; the company-wide retention, the owner's, on Memory.++const SELECT =+ "w-full sm:w-auto bg-surface border border-line rounded-xl px-3 py-2.5 text-[15px] text-fg focus:outline-none focus:ring-2 focus:ring-accent/40 disabled:opacity-50";++function useHistoryState(): {+ state: HistoryState | null | "loading" | "error";+ save: (patch: Parameters<typeof updateHistorySettings>[0]) => Promise<void>;+ busy: boolean;+ error: string | null;+} {+ const [state, setState] = useState<HistoryState | null | "loading" | "error">("loading");+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ const ctrl = new AbortController();+ getHistory(undefined, ctrl.signal)+ .then(setState)+ .catch((err) => {+ if ((err as Error)?.name !== "AbortError") setState("error");+ });+ return () => ctrl.abort();+ }, []);++ const save = async (patch: Parameters<typeof updateHistorySettings>[0]) => {+ setBusy(true);+ setError(null);+ try {+ setState(await updateHistorySettings(patch));+ } catch (err) {+ setError(err instanceof Error ? err.message : "Couldn't save the setting.");+ } finally {+ setBusy(false);+ }+ };++ return { state, save, busy, error };+}++const asValue = (days: number | null) => (days === null ? "" : String(days));+const fromValue = (value: string) => (value === "" ? null : Number(value));++/** Act as me → "Keep track of what happens": the person's own switch, and a+ * shorter time for their own notes. Nothing for someone who can't have it. */+export function KeepTrackCard() {+ const { state, save, busy, error } = useHistoryState();+ if (state === "loading" || state === null) return null;+ if (state === "error") {+ return (+ <SettingsCard title="Keep track of what happens">+ <p className="text-[15px] text-fg-muted">Couldn't load this setting.</p>+ </SettingsCard>+ );+ }+ // Someone who can't use Act as me can still turn it off.+ if (!state.can_note_replies && !state.reply_notes) return null;++ const on = state.reply_notes;+ const company = state.company_retention_days;+ return (+ <SettingsCard+ title="Keep track of what happens"+ titleId="keep-track-label"+ description={+ on+ ? "On: after you send a reply it drafted, it keeps private notes of what you said, so it can remind you later. Only you see them."+ : "Off: nothing from your replies is noted."+ }+ action={+ <Switch+ checked={on}+ onChange={() => void save({ reply_notes: !on })}+ disabled={busy || (!on && !state.can_note_replies)}+ labelledBy="keep-track-label"+ />+ }+ >+ {on && (+ <div className="space-y-3">+ <label className="flex flex-col gap-1.5 sm:flex-row sm:items-center sm:gap-3">+ <span className="text-sm text-fg-muted">Keep my notes for</span>+ <select+ className={SELECT}+ value={asValue(state.retention_days)}+ disabled={busy}+ onChange={(e) => void save({ retention_days: fromValue(e.target.value) })}+ >+ {personRetentionChoices(state.retention_choices, company, state.retention_days).map((days) => (+ <option key={asValue(days)} value={asValue(days)}>+ {days === null ? `The company default (${retentionLabel(company)})` : retentionLabel(days)}+ </option>+ ))}+ </select>+ </label>+ <Link href="/memories?tab=history" className="inline-block text-sm font-medium text-accent hover:underline">+ See your notes+ </Link>+ </div>+ )}+ {error && <p className="mt-2 text-sm text-red-500">{error}</p>}+ </SettingsCard>+ );+}++/** Memory → how long notes last for everyone: the owner picks, everyone else+ * reads it. */+export function CompanyRetentionCard() {+ const { state, save, busy, error } = useHistoryState();+ if (state === "loading") return <p className="text-[15px] text-fg-muted">Loading…</p>;+ if (state === "error" || state === null) {+ return (+ <SettingsCard>+ <p className="text-[15px] text-fg-muted">+ {state === null ? "Notes are kept for people on the People list, signed in as themselves." : "Couldn't load this setting."}+ </p>+ </SettingsCard>+ );+ }++ const company = state.company_retention_days;+ return (+ <SettingsCard+ title="How long notes last"+ description="Notes from replies people approve and send are forgotten after this, unless they pin them. Each person can choose a shorter time for their own notes in Act as me."+ >+ {state.can_set_company_retention ? (+ <label className="flex flex-col gap-1.5 sm:flex-row sm:items-center sm:gap-3">+ <span className="text-sm text-fg-muted">For everyone</span>+ <select+ className={SELECT}+ value={asValue(company)}+ disabled={busy}+ onChange={(e) => void save({ company_retention_days: fromValue(e.target.value) })}+ >+ {state.retention_choices.map((days) => (+ <option key={asValue(days)} value={asValue(days)}>+ {days === null ? "Until they're forgotten" : retentionLabel(days)}+ </option>+ ))}+ </select>+ </label>+ ) : (+ <p className="text-[15px] text-fg">+ {company === null ? "Notes are kept until they're forgotten." : `Notes last ${retentionLabel(company)}.`}{" "}+ <span className="text-fg-muted">The owner of this Open Executive sets this.</span>+ </p>+ )}+ <p className="mt-3 text-sm text-fg-muted">+ {state.effective_retention_days === company+ ? ""+ : `Your own notes last ${retentionLabel(state.effective_retention_days)}. `}+ <Link href="/memories?tab=history" className="font-medium text-accent hover:underline">+ See your notes+ </Link>+ </p>+ {error && <p className="mt-2 text-sm text-red-500">{error}</p>}+ </SettingsCard>+ );+}diff --git a/packages/ui/src/components/shell/AppShell.tsx b/packages/ui/src/components/shell/AppShell.tsxindex dd4da59e..d677a683 100644--- a/packages/ui/src/components/shell/AppShell.tsx+++ b/packages/ui/src/components/shell/AppShell.tsx@@ -57,6 +57,7 @@ const SEGMENT_LABELS: Record<string, string> = {status: "Setup status",executive: "Your Executive","act-as-me": "Act as me",+ memory: "Memory",workspace: "Workspace",advanced: "Advanced",about: "About",diff --git a/packages/ui/src/components/shell/navConfig.ts b/packages/ui/src/components/shell/navConfig.tsindex 9bffd41c..0d5904b3 100644--- a/packages/ui/src/components/shell/navConfig.ts+++ b/packages/ui/src/components/shell/navConfig.ts@@ -394,10 +394,11 @@ export function advancedItemsByGroup(): {// The Settings hub's tiles, in hub order. Each opens a short page of its// own at `href`. "act-as-me" shows only for someone who can have Act as me-// (the hub drops it when the card is hidden). `hashes` are the anchors the+// (the hub drops it when the card is hidden), "memory" only for someone with+// notes to keep (signed in and on the People list). `hashes` are the anchors the// old one-page Settings used (`/settings#workspace`): links that still// carry one land on the matching page (see settingsPageForHash).-export type SettingsPageId = "executive" | "act-as-me" | "workspace" | "advanced" | "about";+export type SettingsPageId = "executive" | "act-as-me" | "memory" | "workspace" | "advanced" | "about";export interface SettingsPageDef {id: SettingsPageId;@@ -426,6 +427,14 @@ export const SETTINGS_PAGES: SettingsPageDef[] = [description: "Your mailbox, drafts written as you, and how you write.",hashes: ["act-as-me"],},+ {+ id: "memory",+ label: "Memory",+ href: "/settings/memory",+ icon: "archive",+ description: "How long the private notes from replies people send last.",+ hashes: ["memory"],+ },{id: "workspace",label: "Workspace",diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.tsindex f01a2bf4..9dd1acd1 100644--- a/packages/ui/src/lib/api.ts+++ b/packages/ui/src/lib/api.ts@@ -1,4 +1,5 @@import type { AnswerSources } from "@/lib/answerSources";+import type { HistoryNote, HistoryState } from "@/lib/history";import type { SetupStatus } from "@/lib/setupStatus";const API_BASE = "/api/backend";@@ -1677,6 +1678,65 @@ export async function getDelegation(signal?: AbortSignal): Promise<DelegationSetreturn res.json();}+// ---------------------------------------------------------------------------+// Always in the loop: the caller's own notes (/memories/history). Each person+// sees and changes only their own; the company retention is the owner's.+// ---------------------------------------------------------------------------++export type { HistoryNote, HistoryState } from "@/lib/history";++// null when this viewer has no notes to see (403: not signed in or not on the+// People list) or the backend predates it (404).+export async function getHistory(query?: string, signal?: AbortSignal): Promise<HistoryState | null> {+ const q = query?.trim() ? `?q=${encodeURIComponent(query.trim())}` : "";+ const res = await fetch(`${API_BASE}/memories/history${q}`, { signal });+ if (res.status === 403 || res.status === 404) return null;+ if (!res.ok) throw await delegationError(res, "Couldn't load your notes.");+ return res.json();+}++export async function updateHistorySettings(patch: {+ reply_notes?: boolean;+ retention_days?: number | null;+ company_retention_days?: number | null;+}): Promise<HistoryState> {+ const res = await fetch(`${API_BASE}/memories/history/settings`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(patch),+ });+ if (!res.ok) throw await delegationError(res, "Couldn't save the setting.");+ return res.json();+}++/** Pin or unpin, or correct it ("" clears the correction). */+export async function updateHistoryNote(+ id: number,+ patch: { pinned?: boolean; correction?: string },+): Promise<HistoryNote> {+ const res = await fetch(`${API_BASE}/memories/history/${id}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(patch),+ });+ if (!res.ok) throw await delegationError(res, "Couldn't change the note.");+ return res.json();+}++export async function forgetHistoryNote(id: number): Promise<void> {+ const res = await fetch(`${API_BASE}/memories/history/${id}`, { method: "DELETE" });+ if (!res.ok) throw await delegationError(res, "Couldn't forget the note.");+}++/** "Don't remember this": forgets every note from that note's conversation,+ * and nothing from it is noted again. Answers how many were forgotten. */+export async function forgetHistoryConversation(id: number): Promise<number> {+ const res = await fetch(`${API_BASE}/memories/history/${id}/forget-conversation`, { method: "POST" });+ if (!res.ok) throw await delegationError(res, "Couldn't forget the conversation.");+ const body = (await res.json()) as { forgotten?: number };+ return body.forgotten ?? 0;+}+export async function setDelegationEnabled(enabled: boolean): Promise<DelegationSettings> {const res = await fetch(`${API_BASE}/delegation`, {method: "PUT",diff --git a/packages/ui/src/lib/history.ts b/packages/ui/src/lib/history.tsnew file mode 100644index 00000000..3570d8c6--- /dev/null+++ b/packages/ui/src/lib/history.ts@@ -0,0 +1,102 @@+// Always in the loop: how the History tab and the settings word a person's+// notes and how long they last, from GET /memories/history. Kept free of+// React so scripts/ can test it.++export interface HistoryNote {+ id: number;+ source: string;+ channel: string;+ conversation_key: string;+ counterpart: string;+ subject: string;+ kind: string;+ summary: string;+ quote: string;+ due_date: string | null;+ trust: string;+ occurred_at: string;+ created_at: string;+ expires_at: string | null;+ pinned: boolean;+ correction: string | null;+ corrected_at: string | null;+}++export interface HistoryState {+ notes: HistoryNote[];+ reply_notes: boolean;+ /** The person's own choice; null is the company default. */+ retention_days: number | null;+ /** What applies to their new notes; null is until they forget them. */+ effective_retention_days: number | null;+ /** null is until forgotten. */+ company_retention_days: number | null;+ retention_choices: (number | null)[];+ can_note_replies: boolean;+ can_set_company_retention: boolean;+}++/** "30 days", "1 year", or "until forgotten" for null. */+export function retentionLabel(days: number | null): string {+ if (days === null) return "until forgotten";+ if (days === 365) return "1 year";+ return `${days} ${days === 1 ? "day" : "days"}`;+}++/** The choices a person may pick for their own notes: the company default+ * (null), then each choice shorter than the company's. Their stored choice+ * is always among them, even one no longer shorter (the owner shortening the+ * company time clamps it to the company's), so the box never shows a value+ * they didn't pick. */+export function personRetentionChoices(+ choices: (number | null)[],+ company: number | null,+ current: number | null = null,+): (number | null)[] {+ const shorter = choices.filter(+ (d): d is number => d !== null && (company === null || d < company),+ );+ if (current !== null && !shorter.includes(current)) shorter.push(current);+ return [null, ...shorter.sort((a, b) => a - b)];+}++const KIND_LABELS: Record<string, string> = {+ promised: "Promised",+ agreed: "Agreed",+ declined: "Declined",+ answered: "Answered",+ asked: "Asked",+ shared: "Shared",+};++export function kindLabel(kind: string): string {+ return KIND_LABELS[kind] ?? kind.charAt(0).toUpperCase() + kind.slice(1);+}++/** "Dana Lee <[email protected]>" → "Dana Lee"; a bare address stays as it is. */+export function counterpartName(counterpart: string): string {+ const trimmed = counterpart.trim();+ const named = /^(.*?)\s*<[^>]*>$/.exec(trimmed);+ if (named && named[1].trim()) return named[1].trim().replace(/^"|"$/g, "");+ return trimmed.replace(/^<|>$/g, "");+}++/** "Email with Dana Lee", or "Email" when nobody is named. */+export function noteWhere(note: Pick<HistoryNote, "channel" | "counterpart">): string {+ const channel = note.channel === "email" ? "Email" : note.channel.charAt(0).toUpperCase() + note.channel.slice(1);+ const who = counterpartName(note.counterpart);+ return who ? `${channel} with ${who}` : channel;+}++/** What the note says now: their correction when they made one. */+export function noteText(note: Pick<HistoryNote, "summary" | "correction">): string {+ return note.correction?.trim() ? note.correction : note.summary;+}++/** When it goes, as the row says it: "Kept until you forget it" when pinned+ * or kept for good, else "Forgotten on 2026-12-30". */+export function noteExpiry(note: Pick<HistoryNote, "pinned" | "expires_at">): string {+ if (note.pinned) return "Pinned: kept until you forget it";+ if (!note.expires_at) return "Kept until you forget it";+ return `Forgotten on ${note.expires_at.slice(0, 10)}`;+}