Skip to content

AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).

fix(memory): quote extraction and open loops from the speaker's own words (#187)

Rufus100f7d9ba07d
diff --git a/packages/core/openexecutive/api/models.py b/packages/core/openexecutive/api/models.py
index 91dcbff0..09046aa1 100644
--- a/packages/core/openexecutive/api/models.py
+++ b/packages/core/openexecutive/api/models.py
@@ -65,9 +65,10 @@ class ChatRequest(BaseModel):
# would contradict `_clean_client_turn_id`, which drops it and carries on.
# The max_length is a size bound, not a format check.
client_turn_id: str | None = Field(None, max_length=64)
- # What peer memory records as the caller's words for this turn, when
- # `message` carries text the caller did not write — a briefing handoff
- # seeds the turn with the Executive's own card body. Absent → `message`.
+ # The caller's own words for this turn, when `message` carries text the
+ # caller did not write — a briefing handoff seeds the turn with the
+ # Executive's own card body. Peer memory records it, and episodic
+ # extraction and open loops quote commitments from it. Absent → `message`.
# Recorded under the caller's own peer and, like `message` would be, in
# the shared memory of each department consulted that turn; it is not in
# the transcript, so the chat_turn audit row keeps it next to `message`.
diff --git a/packages/core/openexecutive/api/routes/chat.py b/packages/core/openexecutive/api/routes/chat.py
index eb3bc384..9367cede 100644
--- a/packages/core/openexecutive/api/routes/chat.py
+++ b/packages/core/openexecutive/api/routes/chat.py
@@ -1278,7 +1278,9 @@ async def chat_upload(
client_turn_id=client_turn_id,
# The extracted document text is the document's words, not the
# caller's: recorded in peer memory it becomes facts about the caller.
- memory_text=f"{message}\n\n[Attached: {', '.join(filenames)}]",
+ # "(Attached files: …)", not the "[Attached: …]" label that marks
+ # inlined document text — the open-loop pass skips turns carrying that.
+ memory_text=f"{message}\n\n(Attached files: {', '.join(filenames)})",
)
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index b90ac1cd..7e223b43 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -974,6 +974,12 @@ memory:
against the user's own words — is the gate that can, and it is the one
that runs. The cost of admitting acknowledgements is one utility-fast
call per turn that proposes nothing.
+ The "user's own words" are the turn's speaker text
+ (`executive._speaker_text`: `memory_text` when the entry point passes
+ one, else the prompt). An inbound email's prompt carries the quoted
+ chain and a briefing handoff's carries the Executive's card body, either
+ of which let the Executive's own recommendation pass the quote check as
+ the principal's decision.
That quote check presumes `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, so a teammate's line
@@ -1167,7 +1173,13 @@ peer_memory:
colleague to …". So the email poller passes ``_email_memory_text`` (subject, the
sender's new text, attachment filenames), ``/chat/upload`` passes
the typed text plus filenames, and the briefing handoffs send a short
- ``memory_text`` line through ``POST /chat``. ``co_present_person_ids``
+ ``memory_text`` line through ``POST /chat``, phrased as the user
+ speaking and ended with "." before the headline on its own line
+ ("I approve this proposal." / "<headline>"): an "Asked to …" line
+ was derived as "<person> was asked to …", and a "?" in a headline
+ inside the sentence voided the extraction quote gate. An email's
+ subject is dropped when it is a reply's or forward's (Re:/Fwd:) —
+ the earlier message's subject, often the Executive's own. ``co_present_person_ids``
enumerates other humans in the conversation context (Discord
thread members, Slack thread participants, email To+Cc) so
Honcho can store them as session peers — the data shape that
@@ -1536,6 +1548,13 @@ attunement:
Owner resolution: exact full name, or a UNIQUE first name only when the
model gave a single token — never a first-name fallback from an unknown
full name.
+ The "speaker's own message" is the turn's speaker text
+ (``executive._speaker_text``: ``memory_text`` when the entry point
+ passes one, else the prompt) — never an inbound email's quoted chain
+ or a briefing card's body, which would let the Executive's own words
+ satisfy the quote gate. The email / upload filename note is
+ "(Attached files: …)", deliberately not the "[Attached: …]" label
+ below, so a turn with attachments is not skipped.
Enforced in code: verbatim quote from the speaker's own message
(commitments via `_is_valid_user_commitment`, asks/closures by
normalized substring); owner resolves to exactly one rostered,
diff --git a/packages/core/openexecutive/architecture/prebuilt/attunement.json b/packages/core/openexecutive/architecture/prebuilt/attunement.json
index 825852d7..5fd5aef6 100644
--- a/packages/core/openexecutive/architecture/prebuilt/attunement.json
+++ b/packages/core/openexecutive/architecture/prebuilt/attunement.json
@@ -1,7 +1,7 @@
{
"section_id": "attunement",
"title": "Attunement (Open Loops)",
- "markdown": "Attunement is the Executive adapting to each person it works with. Its first piece is **open loops**: the concrete things someone on the roster committed to, or was asked for, in conversation — tracked until they're done, and chased when they slip. It lives in `openexecutive.attunement`.\n\n### Why it exists\n\nBefore this, commitments were captured only from the principal's own words (`memory.episodic.should_extract` requires `is_principal`), because stored messages did not record who said them. A teammate's \"I'll send the vendor quote by Thursday\" vanished. And nothing in production ever set `scheduled_actions.awaiting_response_since`, so the nudge engine's commitment-chasing source had nothing to chase.\n\n### Sender attribution and feedback\n\nEvery persisted user message records `chat_messages.sender_person_id`: the **resolved** rostered sender, never the session owner. Discord and Telegram sessions from unrostered senders are owned by the principal so they still show in the sidebar; attribution keeps those outsiders' words from ever being read as the principal's. The web route passes its header-resolved caller (a header-less caller is the principal's own CLI / API surface; a signed-in email not on the roster resolves to nobody). Slack, Discord and Telegram pass the sender they resolved. For the turn itself, the Executive records the resolved speaker on `Session.caller_person_id`, which tool handlers read.\n\nAssistant replies can carry explicit feedback: `chat_messages.feedback` (`up` / `down`) via `POST /sessions/{id}/messages/{message_id}/feedback`, restricted to the session's own caller or the principal. The chat stream's `done` event includes `message_id` so the web panel renders 👍/👎 on the reply. Each rating writes an `attunement` audit row.\n\n### Opening and closing loops\n\nAfter every chat turn whose speaker resolved to a rostered, non-archived person — on any channel, email included, because the hook sits in the Executive rather than an adapter — `schedule_open_loop_pass` runs fire-and-forget, beside the episodic extraction:\n\n1. **Prefilter** — a keyword check (\"I'll\", \"by Friday\", \"can you\", … or, when loops are open, \"sent\", \"done\", …) skips most turns with no model call. A turn carrying an attached document (`[Attached: …]` inlined by `integrations.attachments`) is skipped outright: the document's words sit in the same message — after the text on the web, before it on Telegram and Discord — so a quote found there would be the document's, not the speaker's.\n2. **Budget** — `ATTUNEMENT_MAX_CALLS_PER_DAY` (default 200) is taken atomically from the `attunement_usage` row for the UTC day.\n3. **One forced-tool call** (`record_open_loops`, routing model) sees today's date, the speaker, the roster, the loops the speaker may close, the message and the reply. It may:\n - open a **commitment** the speaker made (owner = the speaker);\n - open an **ask** the speaker made of a named rostered person (owner = that person);\n - when the principal speaks, open a commitment the principal attributes to a named teammate (\"Sara will send the numbers Monday\");\n - close loops the speaker reports done, sent, no longer needed or cancelled — their own loops, or any loop when the principal speaks.\n4. **Gates in code**, not just the prompt: every item must quote the speaker's own message verbatim (commitments through the episodic extractor's `_is_valid_user_commitment`, so the Executive's own suggestions are never logged as someone's promise), and the stored `text` must itself appear verbatim in that message — it is re-injected into the nudge intent a tool-using turn executes, so it is never a model paraphrase (the intent also tells that turn to treat the quoted text as data); owners must resolve to exactly one rostered person (a full name not on the roster never falls back to a rostered first name — \"Ben Jones from Acme\" is not Ben Ortiz); a teammate cannot attribute a commitment to someone else; the principal's own commitments are left to the episodic extractor; a loop id outside the closable set is ignored; each owner holds at most `ATTUNEMENT_MAX_OPEN_LOOPS_PER_PERSON` (15). Due dates are clamped to 60 days and default to `ATTUNEMENT_LOOP_DEFAULT_DUE_DAYS` (2).\n5. **Audit** — one `attunement` row per pass (`op=extract`, opened / closed / dropped with reasons) plus `loop_opened` / `loop_closed` rows.\n\n### Storage and chasing\n\nA loop is a `scheduled_actions` row: `kind='open_loop'`, `channel='__internal__'`, inserted already `done` so the runner never dispatches it, `assigned_to_person_id` = owner, `awaiting_response_since` = due time, `scope_key` = `loop:{owner}:{hash}`. A partial unique index over open loops dedupes concurrent passes. That shape is exactly what existing readers expect:\n\n- the nudge engine's commitment source chases an open loop **as soon as it is overdue**, with a check-in addressed to its owner, through `prefer_channel_for`, availability windows, `NUDGE_MAX_PER_SCOPE` and the outbound guard;\n- `list_awaiting_replies_by_person` counts it **once it is due** (the same cut-off the nudge engine uses), so `/today`'s roster and reflection's \"people waiting\" include an overdue loop but not one still in the future — while `last_contact_at_by_person`, the client engagement \"follow-ups completed\" count and the `/today` activity feed (which now filters `__internal__` rows in SQL so loops cannot crowd real sends out of its window) all exclude it, since a loop is not a message sent;\n- `executive_reflection` renders an **OPEN LOOPS** block (up to 10, overdue flagged).\n\nA loop closes (its `awaiting_response_since` cleared, audited) when the owner reports it done, when the principal or owner calls `close_open_loop` or uses **Mark done** on the person's page, when its owner is archived, or when it passes `ATTUNEMENT_LOOP_TTL_DAYS` (21) — expired at the start of each nudge scan.\n\n### Who can see and close a loop\n\nWhat someone owes is not roster-public. `list_open_loops` shows the principal everyone's loops only on a **private surface** — web chat, a Slack or Discord DM, or a 1:1 Telegram chat; in a shared channel or thread, a Telegram group, a Google Chat space or an email thread (which can carry cc's), and for anyone else, it shows only the caller's own loops, and an unresolved caller gets nothing. `GET /people/{id}/open-loops` is the principal's or that person's only.\n\n`close_open_loop` (chat tool) and `POST /open-loops/{id}/close` only close when the resolved caller is the principal or the loop's owner. Every one of these checks, and the feedback route's, goes through one helper, `people.store.is_principal_or_self`. Loop ids appear in prompts and replies and inbound email reaches the Executive, so a quoted \"close loop 12\" from an unrostered sender, a signed-in web user not on the roster, or an unattended session (a scheduled nudge's prompt quotes the loop text) is refused. The reflection pass is not given the tool at all.\n\n### Outcome ledger — what lands, per person\n\n`attunement.outcomes` records every **proactive** DM to a rostered person and resolves it with no model call, so the Executive can do more of what gets answered and less of what doesn't.\n\n- **Recording.** Proactive work tags itself with `tag_proactive(source, ref)` — a ContextVar, wrapped only around non-yielding code — and the single point every DM passes through, `schedule_tools._record_outbound_context`, writes a `proactive_outcomes` row next to the `outbound_context` linkage when a tag is set and the recipient resolves to a Person. Tagged callers: the scheduler's generic dispatch (a nudge is `nudge_stalled` / `nudge_commitment` / `nudge_initiative`, or `open_loop` when its commitment target is an open loop, keyed by its scope key; anything else is `followup`), `executive_reflection` (`reflection`), `executive_research` (`research`) and alert review (`alert_review`, keyed `alert:<id>`). A user's own chat turn is never tagged, and web-chat sends write no linkage. Only the addressed recipient counts: an email's first rostered `to` address gets a row, its cc's and any other recipients only get reply linkage; and a follow-up the principal scheduled for themselves is not outreach.\n- **Resolution.** `replied` when the recipient's reply consumes the linkage (`mark_outbound_context_consumed`). `acted` when the thing it was about got done, however it was done: the open loop a chase was about is reported done **by its owner** (the principal tidying a loop away, or saying someone else's is done, credits nobody); the approval a stalled-run nudge chased is resolved (`resumer.apply_resolution`), credited to the person who resolved it; the initiative a check-in was about gets a real change (a new status or summary, not a re-mention), credited only to the person who made it — an edit through `PATCH /memories/initiatives/{id}`, which carries no caller identity, credits nobody; or the alert a review DM was about is acknowledged or resolved — credited only to the person it is routed to and the principal, never to someone DM'd about it on an earlier pass. `void` when that alert is dismissed, found stale or expires unread: the DM didn't matter, so it counts neither way — a dismissal, which anyone with API access can make, can never lower someone's rate. `ignored` when still open after `ATTUNEMENT_IGNORE_AFTER_HOURS` (72) — swept at the start of each nudge scan and whenever rates are read, so the rates stay honest with the scan disabled. A later `acted` or `void` overrides an earlier `ignored` — the thing can get done days after the sweep, and that verdict is the truer one; a late reply does not. Expired, cancelled or archived loops resolve nothing.\n- **Use.** `acceptance()` gives per-(person, source) counts over 30 days. The nudge engine demotes a candidate whose person left their **last** `ATTUNEMENT_MUTE_MIN_SENDS` (5) resolved sends (by send time) of that source all unanswered (`muted_pairs`): it ranks after every other candidate and its cooldown is multiplied by `ATTUNEMENT_MUTE_COOLDOWN_MULTIPLIER` (3). It is never dropped, and a single answer lifts it — judged on the most recent sends rather than a 30-day share, which would keep a demoted source (with fewer chances to be answered) demoted long after the person came back. Reflection gets a **WHAT LANDS** block (per person, per source with ≥3 resolved), and the prompt steers DMs toward the kinds that land. `GET /people/{id}/outreach` (principal or that person) backs a \"How they respond\" card on the person page.\n\n### Working style — how each person likes replies\n\n`attunement.style` keeps at most four short style rules per person (\"lead with the recommendation, then the numbers\") and pins them into **that person's own turns** as a `<working_style>` block in the user turn — right after `<current_speaker>`, never a cached system block, and only for a resolved, rostered, non-archived speaker. The block says the current request always wins and that the rules never authorize an action.\n\n- **Evidence.** A background pass (one forced `record_working_style` call) reads the person's last 40 attributed messages, each paired with the reply that answered it and the reaction **they** gave it: 👍/👎 they left themselves (`chat_messages.feedback_by_person_id`, so the principal rating someone's session is not that person's reaction), any note, and replies stopped mid-stream. Every rule must cite that evidence — basis `feedback` needs a cited reply carrying a reaction; basis `stated` needs the person's request quoted verbatim from a cited message. Honcho is not read or written, so this works the same with `HONCHO_ENABLED=false`.\n- **Style only.** Rules are validated in code before they are stored or shown: one line of Latin-script text (so look-alike letters cannot hide a denied word), 8–160 characters; a deny-list that rejects action words (send, approve, pay, schedule…), nudges to act without checking (confirm, check, verify, pause, proceed, go ahead, judgment, instinct, trust, decide…), talk about instructions or tools, URLs, handles, amounts, markup, snake_case identifiers and roster names; and an allowlist — the rule must name some aspect of how a reply reads (length, format, tone, detail, what to lead with…). Edits typed on the person page go through the same checks, and every stored rule is checked again each time the block is rendered and when the lock is toggled, so a rule saved under an older, weaker check never reaches a turn. The block is scrubbed with the shared `utils.prompt_blocks.scrub_block_line`, which also backs `<peer_memory>`.\n- **Pacing.** The Executive schedules the pass after each attributed turn; it runs once `ATTUNEMENT_STYLE_TRIGGER_TURNS` (10) new messages have arrived since the last pass, or right after the person leaves a 👎 on a reply to their own message (`POST /sessions/{sid}/messages/{mid}/feedback`; someone else's rating triggers nothing), with at least 5 messages of history. At most once per `ATTUNEMENT_STYLE_MIN_INTERVAL_HOURS` (2) and `ATTUNEMENT_STYLE_MAX_PER_DAY` (4) times a day per person, and from the shared `ATTUNEMENT_MAX_CALLS_PER_DAY` budget. The slot is claimed with one conditional UPDATE (never under a one-minute interval, and `MAX_PER_DAY=0` means no passes), so concurrent triggers run one pass. The model returns the learned rules in full: a deliberate empty list drops them (newer reactions contradict them), while a malformed call or a list whose every rule fails validation changes nothing.\n- **People stay in charge.** `GET/PUT/DELETE /people/{id}/attunement` (the principal or that person) back a \"How I work with them\" card with edit, lock and reset. Rules typed there are always kept — a pass only fills the remaining slots — and toggling the lock alone (`PUT` without `rules`) keeps the learned rules and their provenance. A locked profile is never rewritten by a pass, a pass never overwrites an edit made while it ran, and an archived person's routes return 404. Every change is kept in `attunement_profile_history`; archiving a person drops both.\n\n### Settings\n\n`ATTUNEMENT_ENABLED`, `ATTUNEMENT_OPEN_LOOPS_ENABLED`, `ATTUNEMENT_LOOP_DEFAULT_DUE_DAYS`, `ATTUNEMENT_LOOP_TTL_DAYS`, `ATTUNEMENT_MAX_OPEN_LOOPS_PER_PERSON`, `ATTUNEMENT_MAX_CALLS_PER_DAY`, `ATTUNEMENT_IGNORE_AFTER_HOURS`, `ATTUNEMENT_MUTE_MIN_SENDS`, `ATTUNEMENT_MUTE_COOLDOWN_MULTIPLIER`, `ATTUNEMENT_STYLE_ENABLED`, `ATTUNEMENT_STYLE_TRIGGER_TURNS`, `ATTUNEMENT_STYLE_MIN_INTERVAL_HOURS`, `ATTUNEMENT_STYLE_MAX_PER_DAY`. The open loops themselves live in `scheduled_actions` and the attribution columns in `chat_messages`, both wiped by company switches and resets; `attunement_usage`, `proactive_outcomes`, `attunement_profiles` and `attunement_profile_history` are wiped with them.\n\n### Known gaps\n\nEmail and Google Chat turns open and close loops (the hook is in the Executive) but do not persist `chat_messages`, so they carry no stored attribution or feedback. `POST /alerts/{id}/ack` has no per-caller authorization (pre-existing), which is why a dismissal voids rather than counts against anyone. Principal briefs and dynamic-workflow deliveries run without a chat session, so they write no outreach linkage and are not in the outcome ledger; broadcasts to a channel have no single recipient and are not counted either.",
+ "markdown": "Attunement is the Executive adapting to each person it works with. Its first piece is **open loops**: the concrete things someone on the roster committed to, or was asked for, in conversation — tracked until they're done, and chased when they slip. It lives in `openexecutive.attunement`.\n\n### Why it exists\n\nBefore this, commitments were captured only from the principal's own words (`memory.episodic.should_extract` requires `is_principal`), because stored messages did not record who said them. A teammate's \"I'll send the vendor quote by Thursday\" vanished. And nothing in production ever set `scheduled_actions.awaiting_response_since`, so the nudge engine's commitment-chasing source had nothing to chase.\n\n### Sender attribution and feedback\n\nEvery persisted user message records `chat_messages.sender_person_id`: the **resolved** rostered sender, never the session owner. Discord and Telegram sessions from unrostered senders are owned by the principal so they still show in the sidebar; attribution keeps those outsiders' words from ever being read as the principal's. The web route passes its header-resolved caller (a header-less caller is the principal's own CLI / API surface; a signed-in email not on the roster resolves to nobody). Slack, Discord and Telegram pass the sender they resolved. For the turn itself, the Executive records the resolved speaker on `Session.caller_person_id`, which tool handlers read.\n\nAssistant replies can carry explicit feedback: `chat_messages.feedback` (`up` / `down`) via `POST /sessions/{id}/messages/{message_id}/feedback`, restricted to the session's own caller or the principal. The chat stream's `done` event includes `message_id` so the web panel renders 👍/👎 on the reply. Each rating writes an `attunement` audit row.\n\n### Opening and closing loops\n\nAfter every chat turn whose speaker resolved to a rostered, non-archived person — on any channel, email included, because the hook sits in the Executive rather than an adapter — `schedule_open_loop_pass` runs fire-and-forget, beside the episodic extraction:\n\n1. **Prefilter** — a keyword check (\"I'll\", \"by Friday\", \"can you\", … or, when loops are open, \"sent\", \"done\", …) skips most turns with no model call. A turn carrying an attached document (`[Attached: …]` inlined by `integrations.attachments`) is skipped outright: the document's words sit in the same message — after the text on the web, before it on Telegram and Discord — so a quote found there would be the document's, not the speaker's. The short filename note an email or upload leaves in the speaker text is written `(Attached files: …)` precisely so it does not trip this skip — that turn carries no document text.\n2. **Budget** — `ATTUNEMENT_MAX_CALLS_PER_DAY` (default 200) is taken atomically from the `attunement_usage` row for the UTC day.\n3. **One forced-tool call** (`record_open_loops`, routing model) sees today's date, the speaker, the roster, the loops the speaker may close, the message and the reply. It may:\n - open a **commitment** the speaker made (owner = the speaker);\n - open an **ask** the speaker made of a named rostered person (owner = that person);\n - when the principal speaks, open a commitment the principal attributes to a named teammate (\"Sara will send the numbers Monday\");\n - close loops the speaker reports done, sent, no longer needed or cancelled — their own loops, or any loop when the principal speaks.\n4. **Gates in code**, not just the prompt: every item must quote the speaker's own message verbatim — the turn's speaker text (`memory_text` when given: an email's new text without its quoted chain, a briefing handoff's short line), never the framed prompt (commitments through the episodic extractor's `_is_valid_user_commitment`, so the Executive's own suggestions are never logged as someone's promise), and the stored `text` must itself appear verbatim in that message — it is re-injected into the nudge intent a tool-using turn executes, so it is never a model paraphrase (the intent also tells that turn to treat the quoted text as data); owners must resolve to exactly one rostered person (a full name not on the roster never falls back to a rostered first name — \"Ben Jones from Acme\" is not Ben Ortiz); a teammate cannot attribute a commitment to someone else; the principal's own commitments are left to the episodic extractor; a loop id outside the closable set is ignored; each owner holds at most `ATTUNEMENT_MAX_OPEN_LOOPS_PER_PERSON` (15). Due dates are clamped to 60 days and default to `ATTUNEMENT_LOOP_DEFAULT_DUE_DAYS` (2).\n5. **Audit** — one `attunement` row per pass (`op=extract`, opened / closed / dropped with reasons) plus `loop_opened` / `loop_closed` rows.\n\n### Storage and chasing\n\nA loop is a `scheduled_actions` row: `kind='open_loop'`, `channel='__internal__'`, inserted already `done` so the runner never dispatches it, `assigned_to_person_id` = owner, `awaiting_response_since` = due time, `scope_key` = `loop:{owner}:{hash}`. A partial unique index over open loops dedupes concurrent passes. That shape is exactly what existing readers expect:\n\n- the nudge engine's commitment source chases an open loop **as soon as it is overdue**, with a check-in addressed to its owner, through `prefer_channel_for`, availability windows, `NUDGE_MAX_PER_SCOPE` and the outbound guard;\n- `list_awaiting_replies_by_person` counts it **once it is due** (the same cut-off the nudge engine uses), so `/today`'s roster and reflection's \"people waiting\" include an overdue loop but not one still in the future — while `last_contact_at_by_person`, the client engagement \"follow-ups completed\" count and the `/today` activity feed (which now filters `__internal__` rows in SQL so loops cannot crowd real sends out of its window) all exclude it, since a loop is not a message sent;\n- `executive_reflection` renders an **OPEN LOOPS** block (up to 10, overdue flagged).\n\nA loop closes (its `awaiting_response_since` cleared, audited) when the owner reports it done, when the principal or owner calls `close_open_loop` or uses **Mark done** on the person's page, when its owner is archived, or when it passes `ATTUNEMENT_LOOP_TTL_DAYS` (21) — expired at the start of each nudge scan.\n\n### Who can see and close a loop\n\nWhat someone owes is not roster-public. `list_open_loops` shows the principal everyone's loops only on a **private surface** — web chat, a Slack or Discord DM, or a 1:1 Telegram chat; in a shared channel or thread, a Telegram group, a Google Chat space or an email thread (which can carry cc's), and for anyone else, it shows only the caller's own loops, and an unresolved caller gets nothing. `GET /people/{id}/open-loops` is the principal's or that person's only.\n\n`close_open_loop` (chat tool) and `POST /open-loops/{id}/close` only close when the resolved caller is the principal or the loop's owner. Every one of these checks, and the feedback route's, goes through one helper, `people.store.is_principal_or_self`. Loop ids appear in prompts and replies and inbound email reaches the Executive, so a quoted \"close loop 12\" from an unrostered sender, a signed-in web user not on the roster, or an unattended session (a scheduled nudge's prompt quotes the loop text) is refused. The reflection pass is not given the tool at all.\n\n### Outcome ledger — what lands, per person\n\n`attunement.outcomes` records every **proactive** DM to a rostered person and resolves it with no model call, so the Executive can do more of what gets answered and less of what doesn't.\n\n- **Recording.** Proactive work tags itself with `tag_proactive(source, ref)` — a ContextVar, wrapped only around non-yielding code — and the single point every DM passes through, `schedule_tools._record_outbound_context`, writes a `proactive_outcomes` row next to the `outbound_context` linkage when a tag is set and the recipient resolves to a Person. Tagged callers: the scheduler's generic dispatch (a nudge is `nudge_stalled` / `nudge_commitment` / `nudge_initiative`, or `open_loop` when its commitment target is an open loop, keyed by its scope key; anything else is `followup`), `executive_reflection` (`reflection`), `executive_research` (`research`) and alert review (`alert_review`, keyed `alert:<id>`). A user's own chat turn is never tagged, and web-chat sends write no linkage. Only the addressed recipient counts: an email's first rostered `to` address gets a row, its cc's and any other recipients only get reply linkage; and a follow-up the principal scheduled for themselves is not outreach.\n- **Resolution.** `replied` when the recipient's reply consumes the linkage (`mark_outbound_context_consumed`). `acted` when the thing it was about got done, however it was done: the open loop a chase was about is reported done **by its owner** (the principal tidying a loop away, or saying someone else's is done, credits nobody); the approval a stalled-run nudge chased is resolved (`resumer.apply_resolution`), credited to the person who resolved it; the initiative a check-in was about gets a real change (a new status or summary, not a re-mention), credited only to the person who made it — an edit through `PATCH /memories/initiatives/{id}`, which carries no caller identity, credits nobody; or the alert a review DM was about is acknowledged or resolved — credited only to the person it is routed to and the principal, never to someone DM'd about it on an earlier pass. `void` when that alert is dismissed, found stale or expires unread: the DM didn't matter, so it counts neither way — a dismissal, which anyone with API access can make, can never lower someone's rate. `ignored` when still open after `ATTUNEMENT_IGNORE_AFTER_HOURS` (72) — swept at the start of each nudge scan and whenever rates are read, so the rates stay honest with the scan disabled. A later `acted` or `void` overrides an earlier `ignored` — the thing can get done days after the sweep, and that verdict is the truer one; a late reply does not. Expired, cancelled or archived loops resolve nothing.\n- **Use.** `acceptance()` gives per-(person, source) counts over 30 days. The nudge engine demotes a candidate whose person left their **last** `ATTUNEMENT_MUTE_MIN_SENDS` (5) resolved sends (by send time) of that source all unanswered (`muted_pairs`): it ranks after every other candidate and its cooldown is multiplied by `ATTUNEMENT_MUTE_COOLDOWN_MULTIPLIER` (3). It is never dropped, and a single answer lifts it — judged on the most recent sends rather than a 30-day share, which would keep a demoted source (with fewer chances to be answered) demoted long after the person came back. Reflection gets a **WHAT LANDS** block (per person, per source with ≥3 resolved), and the prompt steers DMs toward the kinds that land. `GET /people/{id}/outreach` (principal or that person) backs a \"How they respond\" card on the person page.\n\n### Working style — how each person likes replies\n\n`attunement.style` keeps at most four short style rules per person (\"lead with the recommendation, then the numbers\") and pins them into **that person's own turns** as a `<working_style>` block in the user turn — right after `<current_speaker>`, never a cached system block, and only for a resolved, rostered, non-archived speaker. The block says the current request always wins and that the rules never authorize an action.\n\n- **Evidence.** A background pass (one forced `record_working_style` call) reads the person's last 40 attributed messages, each paired with the reply that answered it and the reaction **they** gave it: 👍/👎 they left themselves (`chat_messages.feedback_by_person_id`, so the principal rating someone's session is not that person's reaction), any note, and replies stopped mid-stream. Every rule must cite that evidence — basis `feedback` needs a cited reply carrying a reaction; basis `stated` needs the person's request quoted verbatim from a cited message. Honcho is not read or written, so this works the same with `HONCHO_ENABLED=false`.\n- **Style only.** Rules are validated in code before they are stored or shown: one line of Latin-script text (so look-alike letters cannot hide a denied word), 8–160 characters; a deny-list that rejects action words (send, approve, pay, schedule…), nudges to act without checking (confirm, check, verify, pause, proceed, go ahead, judgment, instinct, trust, decide…), talk about instructions or tools, URLs, handles, amounts, markup, snake_case identifiers and roster names; and an allowlist — the rule must name some aspect of how a reply reads (length, format, tone, detail, what to lead with…). Edits typed on the person page go through the same checks, and every stored rule is checked again each time the block is rendered and when the lock is toggled, so a rule saved under an older, weaker check never reaches a turn. The block is scrubbed with the shared `utils.prompt_blocks.scrub_block_line`, which also backs `<peer_memory>`.\n- **Pacing.** The Executive schedules the pass after each attributed turn; it runs once `ATTUNEMENT_STYLE_TRIGGER_TURNS` (10) new messages have arrived since the last pass, or right after the person leaves a 👎 on a reply to their own message (`POST /sessions/{sid}/messages/{mid}/feedback`; someone else's rating triggers nothing), with at least 5 messages of history. At most once per `ATTUNEMENT_STYLE_MIN_INTERVAL_HOURS` (2) and `ATTUNEMENT_STYLE_MAX_PER_DAY` (4) times a day per person, and from the shared `ATTUNEMENT_MAX_CALLS_PER_DAY` budget. The slot is claimed with one conditional UPDATE (never under a one-minute interval, and `MAX_PER_DAY=0` means no passes), so concurrent triggers run one pass. The model returns the learned rules in full: a deliberate empty list drops them (newer reactions contradict them), while a malformed call or a list whose every rule fails validation changes nothing.\n- **People stay in charge.** `GET/PUT/DELETE /people/{id}/attunement` (the principal or that person) back a \"How I work with them\" card with edit, lock and reset. Rules typed there are always kept — a pass only fills the remaining slots — and toggling the lock alone (`PUT` without `rules`) keeps the learned rules and their provenance. A locked profile is never rewritten by a pass, a pass never overwrites an edit made while it ran, and an archived person's routes return 404. Every change is kept in `attunement_profile_history`; archiving a person drops both.\n\n### Settings\n\n`ATTUNEMENT_ENABLED`, `ATTUNEMENT_OPEN_LOOPS_ENABLED`, `ATTUNEMENT_LOOP_DEFAULT_DUE_DAYS`, `ATTUNEMENT_LOOP_TTL_DAYS`, `ATTUNEMENT_MAX_OPEN_LOOPS_PER_PERSON`, `ATTUNEMENT_MAX_CALLS_PER_DAY`, `ATTUNEMENT_IGNORE_AFTER_HOURS`, `ATTUNEMENT_MUTE_MIN_SENDS`, `ATTUNEMENT_MUTE_COOLDOWN_MULTIPLIER`, `ATTUNEMENT_STYLE_ENABLED`, `ATTUNEMENT_STYLE_TRIGGER_TURNS`, `ATTUNEMENT_STYLE_MIN_INTERVAL_HOURS`, `ATTUNEMENT_STYLE_MAX_PER_DAY`. The open loops themselves live in `scheduled_actions` and the attribution columns in `chat_messages`, both wiped by company switches and resets; `attunement_usage`, `proactive_outcomes`, `attunement_profiles` and `attunement_profile_history` are wiped with them.\n\n### Known gaps\n\nEmail and Google Chat turns open and close loops (the hook is in the Executive) but do not persist `chat_messages`, so they carry no stored attribution or feedback. `POST /alerts/{id}/ack` has no per-caller authorization (pre-existing), which is why a dismissal voids rather than counts against anyone. Principal briefs and dynamic-workflow deliveries run without a chat session, so they write no outreach linkage and are not in the outcome ledger; broadcasts to a channel have no single recipient and are not counted either.",
"mermaid": "flowchart TD\n Turn[\"Chat turn<br/>(any channel)\"]\n Resolve[\"Resolved speaker<br/>(rostered, not archived)\"]\n Persist[(\"chat_messages<br/>sender_person_id · feedback\")]\n Pre[\"Prefilter + daily budget\"]\n LLM[\"record_open_loops<br/>(forced tool)\"]\n Gate[\"Code gates<br/>verbatim quote · owner · closable set\"]\n Loops[(\"scheduled_actions<br/>kind=open_loop\")]\n Nudge[\"nudge_engine<br/>commitment source\"]\n Guard[\"prefer_channel_for<br/>+ outbound guard\"]\n Owner[\"Owner's channel\"]\n Reflect[\"executive_reflection<br/>OPEN LOOPS block\"]\n Today[\"/today awaiting counts\"]\n Close[\"close_open_loop · Mark done<br/>archive · TTL expiry\"]\n Turn --> Resolve\n Resolve --> Persist\n Resolve --> Pre\n Pre --> LLM\n LLM --> Gate\n Gate -- \"open / close\" --> Loops\n Loops -- \"overdue\" --> Nudge\n Nudge --> Guard\n Guard --> Owner\n Loops --> Reflect\n Loops --> Today\n Close --> Loops\n class Turn entry\n class Resolve compute\n class Persist storage\n class Pre compute\n class LLM hot\n class Gate compute\n class Loops storage\n class Nudge compute\n class Guard compute\n class Owner external\n class Reflect compute\n class Today compute\n class Close compute",
- "generated_at": "2026-09-22T23:17:20.508677+00:00"
+ "generated_at": "2026-09-23T19:09:39Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/memory.json b/packages/core/openexecutive/architecture/prebuilt/memory.json
index 889a0373..ca9e4110 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`.\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.\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 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(user_message)` is true, which means only that the principal said something — 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` also takes the turn's `origin_channel` and `person_id`. No channel means the web app, the CLI or the API, all of them the principal's own authenticated surfaces, where `person_id` is legitimately null in a single-user install. A turn that names a channel must resolve to a person marked `is_principal`, and an unresolvable speaker fails closed.\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### 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.\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, with a fourth **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\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.",
+ "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`.\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.\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(user_message)` is true, which means only that the principal said something — 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` also takes the turn's `origin_channel` and `person_id`. No channel means the web app, the CLI or the API, all of them the principal's own authenticated surfaces, where `person_id` is legitimately null in a single-user install. A turn that names a channel must resolve to a person marked `is_principal`, and an unresolvable speaker fails closed.\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### 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.\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, with a fourth **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\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.",
"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 class Store entry\n class DB storage\n class Fmt compute\n class Turn hot\n class Peer external\n",
- "generated_at": "2026-09-22T23:17:20.508677+00:00"
+ "generated_at": "2026-09-23T18:53:18Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/peer_memory.json b/packages/core/openexecutive/architecture/prebuilt/peer_memory.json
index 952bdf2c..4798d566 100644
--- a/packages/core/openexecutive/architecture/prebuilt/peer_memory.json
+++ b/packages/core/openexecutive/architecture/prebuilt/peer_memory.json
@@ -1,7 +1,7 @@
{
"section_id": "peer_memory",
"title": "Peer Memory (Person + Department)",
- "markdown": "An external, peer-keyed memory layer gives the Executive durable cross-channel recall, sitting on top of Honcho via `openexecutive.memory.honcho_client`. The `HONCHO_ENABLED` env var gates it; when false every entry point short-circuits with `outcome=disabled` and behavior matches the pre-Honcho posture.\n\n### Two scopes\n\n- **Per-person**, keyed by `Person.id` — a user chatting from Discord, Telegram, email, or web is one peer card, so facts shared in any channel surface in the others. Each entry point resolves the caller to a `Person.id` (channel-ID lookups for adapters; `x-caller-email` for web).\n- **Per-department**, keyed by `department_<slug>` — each department accumulates an institutional voice from dept-scoped decisions, advice, committee outcomes, and dept-bound specialist turns.\n\n### Flow\n\n`prefetch` runs once per turn and injects a `<peer_memory>` block into the user turn (empty on timeout or error). `HONCHO_PREFETCH_MODE` picks how the block is produced. `representation` (the default) reads the person's peer card and the derived conclusions most relevant to the inbound message straight from Honcho (`peer.context(search_query=…)`, `HONCHO_PREFETCH_MAX_CONCLUSIONS` of them, default 20): a GET with no LLM behind it, about 100 ms self-hosted. The block keeps whole lines only, up to a size cap (a line that does not fit is dropped, never cut), strips control characters and defangs a literal closing tag, since conclusions derive from text anyone who can email the Executive wrote. A person Honcho knows nothing about yet yields no block and an `empty` audit outcome. `dialectic` asks Honcho's chat endpoint with the message as the question and injects the synthesized prose (an LLM call, seconds), where `reasoning_level` trades latency for depth. The mode applies to every per-person prefetch, committee turns included. Only `prefetch_department` (one dialectic question per consulted specialist that maps to a department, yielding `<department_memory>`) and the `ask_about_person` tool always use the chat endpoint: they are deliberate questions off the inline path, the split Honcho's own guidance draws between `context()` for per-turn grounding and `chat()` for reasoned answers. After the response, `sync_turn` and `sync_department_turn` persist the exchange as fire-and-forget background tasks that never block the user. The Executive's reply is written under an `executive` peer resolved with `observe_me=false`: the person's representation sees both sides of the exchange, but Honcho no longer derives a representation of the Executive itself, which nothing read and which is where a person's words were occasionally misattributed to the Executive. Both record the person's words only. Honcho derives facts about a person from everything posted under their peer, so a turn whose prompt carries text the person did not write passes `memory_text` to `Executive.chat` / `stream_chat` / `stream_chat_with_committee`, and that — not the prompt — is what both syncs post: an inbound email records its subject, the sender's new text and the attachment filenames (never the \"You have an inbound email\" framing, the headers with the Executive's own address in `To:`, the `[POLICY]` notice or the quoted chain, which held the Executive's own earlier email and taught Honcho that the sender *was* the Executive); a web upload records the typed text and filenames, not the extracted document text; a briefing handoff records a short line of what the user asked (\"Asked to discuss the flagged artifact …\"), not the Executive's card body it seeds. Without `memory_text` the prompt is recorded, as before. The `<outbound_reply_context>` block that inbound hydration prepends for the LLM turn is also stripped before the message is posted, and from the prefetch query, so the Executive's own DM is never learned as something the person said.\n\n### What it knows, on Pulse\n\nThe Pulse page's Memory section has a **People** tab beside Decisions, Initiatives and Advice, backed by `GET /memories/people` (`people_overview`). It is read-only and costs no LLM call: one listing of the workspace's peers, then, for each peer that matches a rostered person by id, one page of that person's self-conclusions (newest first, `?recent=` of them, plus the total) and one card read with the identity lines the roster already supplies stripped out. Peers are matched, never created — `peer(id)` is a get-or-create POST, and a page you merely open must not mint peers for people who have never talked — and the `executive` and `department_*` peers and archived people are skipped. The listing runs under one clock (the SDK walks every page, bounded only per request otherwise) and each person is then read under the unscaled prefetch budget, at most eight at a time because these reads share the client with the live chat prefetch; one person's failure or timeout marks only that entry (`error`) and the others still render. The header and the tab share one in-flight request per page load. The header's Memories tile adds the conclusion total to the three episodic counts (its hint says how many are peer notes) without waiting on the read, and the tab hides itself when peer memory is disabled. Peers are matched only by an id spelled exactly as OE writes it, once per person, so a stray or repeated peer skips rather than fails or double-counts; within the newest page the conclusions are ordered by instant here (not by the rendered timestamp, which is not chronological across offsets) rather than trusting the server's order. Card elements and conclusions are split on physical lines before the scrub, so an identity claim on the second line of one element is caught too. Every line passes the same control-character and closing-tag scrub as the `<peer_memory>` block, since the text was derived from what people wrote. One `peer_memory` audit row per call, `op=overview`.\n\n### Prefetch budget\n\nIn representation mode the prefetch is a single read with no LLM behind it: it runs on `HONCHO_PREFETCH_TIMEOUT_S` unscaled and `reasoning_level` is ignored. The rest of this section is the dialectic mode.\n\n`HONCHO_PREFETCH_TIMEOUT_S` is the knob for the **fast per-turn path** and is used unscaled there. The two per-turn callers pick different levels on purpose: `stream_chat` awaits the prefetch inline before the first streamed byte and defaults to `minimal`, the cheapest level, after `low` was measured hitting the ~5 s tail for peers with large representations; the chat route runs the prefetch inside the same gather as knowledge and episodic retrieval, so its `low` adds no dead air of its own and buys a fuller answer. Only the deliberate levels scale off it — `medium` 4x, `high` 5x, `max` 6x — capped by an absolute ceiling and never taken below the configured base. At the default 3s base that is 12s for `medium` with `high`/`max` at the 15s ceiling; at a 10s base every deliberate level *is* the ceiling. The multipliers only differentiate below it — the ceiling is the binding constraint at realistic bases, by design.\n\nHoncho's dialectic latency scales steeply with the level (roughly 2s at `low` against 8s at `medium`), so a single flat budget made the deeper levels unreachable: every `medium` call — the committee path — timed out and the turn silently ran with no peer memory at all, which is strictly worse than having asked for `low`. `medium` gets more headroom than its measurement alone implies because the budget spans `peer()` plus `chat()`, and a budget set at the mean still times out on half the calls.\n\nThe fast levels stay unscaled for two reasons: `prefetch` is awaited inline before the first streamed byte, so multiplying the base there would add dead air to every ordinary turn; and a multiplier above 1.0 flattens every level onto the ceiling once the base approaches it, which would make the operator's knob stop distinguishing the two paths. Each prefetch audit row records the `timeout_s` it ran under.\n\nThe SDK client's HTTP timeout is an **outer** bound, kept strictly greater than every *per-call* budget; the aggregate ceilings on whole passes are deliberately not folded in, since it applies per request and would otherwise hand every unbudgeted call a bound several times too long. Because it is no longer a tight bound, all three fire-and-forget bodies (person sync, department sync, department note) — whose individual calls are not separately budgeted — carry their own aggregate ceiling, as does the session listing in the workspace purge.\n\n### Peer identity\n\nPeers are keyed by `Person.id`, so the only identity signal Honcho gets from the key alone is a bare integer — and its dreaming agent concludes that the number *is* the person's name (observed in production as a card reading `IDENTITY: Name: 1`). Because cards are injected into the dialectic system prompt on every `chat()`, that error propagates into every later answer about that person. So both sync paths seed each person peer's card from the roster, for the sender, the department-turn originator, and co-present peers alike.\n\nThe card carries the **name only** — email and role would export roster PII to a third-party memory service, including for people who were merely cc'd, and neither is needed to fix the defect. `set_card` replaces the whole card, so only `IDENTITY:` lines are swapped and the deriver's own `ATTRIBUTE:` / `RELATIONSHIP:` lines survive; the existing card is split on physical lines first, since one list element may itself span lines and hide an identity claim on its second.\n\nRoster values are attacker-reachable — `upsert_person` is a chat tool an inbound email sender can reach — so a value is NFKC-normalised, stripped of control and format characters, whitespace-flattened, length-capped, and then held to an **allow-list** of letters, combining marks, digits and a small punctuation set, with the colon lookalikes the category allow-list would otherwise admit **stripped out** — taken from Unicode's confusables data (everything it maps to `:`), not from character names, since U+A4FD `ꓽ` is a Lisu *tone letter* whose name never says colon. They are stripped rather than grounds for refusing the value, because the visarga is the nominative ending in formal Devanagari and Gujarati names: refusing would leave those people never seeded, while stripping keeps the name as its stem form and still lets no colon shape reach the card. Modifier letters as a class stay allowed (々 in 佐々木, ー in ジョーンズ, ʻ in Hawaiʻi). A deny-list of structure tokens is not enough here: the consumer is an LLM system prompt rather than a parser, so `ATTRIBUTE :`, a fullwidth colon and a homoglyph all read the same to the model while defeating a literal match. The allow-list refuses every colon variant, which is what card structure depends on — checked by an exhaustive test over every Unicode codepoint whose name contains COLON plus an explicit test of the confusables the names miss. It does **not** stop a value that is merely persuasive prose — OE already embeds `full_name` in its own system prompt, so that exposure is pre-existing rather than introduced here.\n\nSeeding runs *after* the message write and *outside* the sync ceiling, and is audited as its own `seed_identity` row (`ok` only when no peer's attempt failed; `error` when any did, with the `failed` count on the row; `timeout` when the pass or the roster read hit its ceiling; `empty` when there was nobody to seed) — so the sync row is a pure record of the persist, emitted the instant the write lands, and a slow card round trip can neither delay nor replace it. It is bounded per peer *and* per pass, and is best-effort. It is memoized per `(workspace, person)` on the facts sent with a recheck interval — a rename re-seeds immediately, and because the deriver keeps re-deriving identity from the peer id, a one-shot memo would let `IDENTITY: Name: 1` come back unnoticed. A failed attempt is memoized separately and briefly — including every peer a pass-ceiling cut-off left in flight or unreached — so a degraded card endpoint is probed once per interval rather than once per peer per turn.\n\n### Cross-pollination & isolation\n\nWhen a person turn touches a department, the dept peer joins the person's session as a co-present peer — the hybrid peer graph that lets later queries synthesize across both timelines, with synthesis depth degrading at greater peer-graph distance. Demo fixtures run in a sacrificial `openexec-fixture-<name>` workspace so demo turns never pollute real peer cards. Every wrapper call emits a `peer_memory` audit row (`op` + `outcome`) into the per-turn flow at `/audit/session/{id}`.",
+ "markdown": "An external, peer-keyed memory layer gives the Executive durable cross-channel recall, sitting on top of Honcho via `openexecutive.memory.honcho_client`. The `HONCHO_ENABLED` env var gates it; when false every entry point short-circuits with `outcome=disabled` and behavior matches the pre-Honcho posture.\n\n### Two scopes\n\n- **Per-person**, keyed by `Person.id` — a user chatting from Discord, Telegram, email, or web is one peer card, so facts shared in any channel surface in the others. Each entry point resolves the caller to a `Person.id` (channel-ID lookups for adapters; `x-caller-email` for web).\n- **Per-department**, keyed by `department_<slug>` — each department accumulates an institutional voice from dept-scoped decisions, advice, committee outcomes, and dept-bound specialist turns.\n\n### Flow\n\n`prefetch` runs once per turn and injects a `<peer_memory>` block into the user turn (empty on timeout or error). `HONCHO_PREFETCH_MODE` picks how the block is produced. `representation` (the default) reads the person's peer card and the derived conclusions most relevant to the inbound message straight from Honcho (`peer.context(search_query=…)`, `HONCHO_PREFETCH_MAX_CONCLUSIONS` of them, default 20): a GET with no LLM behind it, about 100 ms self-hosted. The block keeps whole lines only, up to a size cap (a line that does not fit is dropped, never cut), strips control characters and defangs a literal closing tag, since conclusions derive from text anyone who can email the Executive wrote. A person Honcho knows nothing about yet yields no block and an `empty` audit outcome. `dialectic` asks Honcho's chat endpoint with the message as the question and injects the synthesized prose (an LLM call, seconds), where `reasoning_level` trades latency for depth. The mode applies to every per-person prefetch, committee turns included. Only `prefetch_department` (one dialectic question per consulted specialist that maps to a department, yielding `<department_memory>`) and the `ask_about_person` tool always use the chat endpoint: they are deliberate questions off the inline path, the split Honcho's own guidance draws between `context()` for per-turn grounding and `chat()` for reasoned answers. After the response, `sync_turn` and `sync_department_turn` persist the exchange as fire-and-forget background tasks that never block the user. The Executive's reply is written under an `executive` peer resolved with `observe_me=false`: the person's representation sees both sides of the exchange, but Honcho no longer derives a representation of the Executive itself, which nothing read and which is where a person's words were occasionally misattributed to the Executive. Both record the person's words only. Honcho derives facts about a person from everything posted under their peer, so a turn whose prompt carries text the person did not write passes `memory_text` to `Executive.chat` / `stream_chat` / `stream_chat_with_committee`, and that — not the prompt — is what both syncs post: an inbound email records the sender's new text, the attachment filenames and its subject unless that is a reply's or forward's (`Re:`, `Fwd:`, `AW:`, `SV:`, `Re[2]:`, `[EXT] Re:` … — the earlier message's subject, often the Executive's own) (never the \"You have an inbound email\" framing, the headers with the Executive's own address in `To:`, the `[POLICY]` notice or the quoted chain, which held the Executive's own earlier email and taught Honcho that the sender *was* the Executive); a web upload records the typed text and filenames, not the extracted document text; a briefing handoff records a short line of what the user asked, phrased as the user speaking and ended before the headline, which follows on its own line (\"Let's discuss this flagged artifact.\" / \"I approve this proposal.\" — an \"Asked to …\" line came back as \"<user> was asked to …\", and a \"?\" in a headline inside the sentence voided the extraction quote); approve-with-edits records the same short line without the edited text, which starts as the Executive's card body and is often sent unchanged, not the Executive's card body it seeds. Filenames are noted as \"(Attached files: …)\", never the \"[Attached: …]\" label that marks inlined document text. The same speaker text, not the prompt, is what episodic extraction and the open-loop pass quote commitments from (see Memory and Attunement). Without `memory_text` the prompt is used, as before. The `<outbound_reply_context>` block that inbound hydration prepends for the LLM turn is also stripped before the message is posted, and from the prefetch query, so the Executive's own DM is never learned as something the person said.\n\n### What it knows, on Pulse\n\nThe Pulse page's Memory section has a **People** tab beside Decisions, Initiatives and Advice, backed by `GET /memories/people` (`people_overview`). It is read-only and costs no LLM call: one listing of the workspace's peers, then, for each peer that matches a rostered person by id, one page of that person's self-conclusions (newest first, `?recent=` of them, plus the total) and one card read with the identity lines the roster already supplies stripped out. Peers are matched, never created — `peer(id)` is a get-or-create POST, and a page you merely open must not mint peers for people who have never talked — and the `executive` and `department_*` peers and archived people are skipped. The listing runs under one clock (the SDK walks every page, bounded only per request otherwise) and each person is then read under the unscaled prefetch budget, at most eight at a time because these reads share the client with the live chat prefetch; one person's failure or timeout marks only that entry (`error`) and the others still render. The header and the tab share one in-flight request per page load. The header's Memories tile adds the conclusion total to the three episodic counts (its hint says how many are peer notes) without waiting on the read, and the tab hides itself when peer memory is disabled. Peers are matched only by an id spelled exactly as OE writes it, once per person, so a stray or repeated peer skips rather than fails or double-counts; within the newest page the conclusions are ordered by instant here (not by the rendered timestamp, which is not chronological across offsets) rather than trusting the server's order. Card elements and conclusions are split on physical lines before the scrub, so an identity claim on the second line of one element is caught too. Every line passes the same control-character and closing-tag scrub as the `<peer_memory>` block, since the text was derived from what people wrote. One `peer_memory` audit row per call, `op=overview`.\n\n### Prefetch budget\n\nIn representation mode the prefetch is a single read with no LLM behind it: it runs on `HONCHO_PREFETCH_TIMEOUT_S` unscaled and `reasoning_level` is ignored. The rest of this section is the dialectic mode.\n\n`HONCHO_PREFETCH_TIMEOUT_S` is the knob for the **fast per-turn path** and is used unscaled there. The two per-turn callers pick different levels on purpose: `stream_chat` awaits the prefetch inline before the first streamed byte and defaults to `minimal`, the cheapest level, after `low` was measured hitting the ~5 s tail for peers with large representations; the chat route runs the prefetch inside the same gather as knowledge and episodic retrieval, so its `low` adds no dead air of its own and buys a fuller answer. Only the deliberate levels scale off it — `medium` 4x, `high` 5x, `max` 6x — capped by an absolute ceiling and never taken below the configured base. At the default 3s base that is 12s for `medium` with `high`/`max` at the 15s ceiling; at a 10s base every deliberate level *is* the ceiling. The multipliers only differentiate below it — the ceiling is the binding constraint at realistic bases, by design.\n\nHoncho's dialectic latency scales steeply with the level (roughly 2s at `low` against 8s at `medium`), so a single flat budget made the deeper levels unreachable: every `medium` call — the committee path — timed out and the turn silently ran with no peer memory at all, which is strictly worse than having asked for `low`. `medium` gets more headroom than its measurement alone implies because the budget spans `peer()` plus `chat()`, and a budget set at the mean still times out on half the calls.\n\nThe fast levels stay unscaled for two reasons: `prefetch` is awaited inline before the first streamed byte, so multiplying the base there would add dead air to every ordinary turn; and a multiplier above 1.0 flattens every level onto the ceiling once the base approaches it, which would make the operator's knob stop distinguishing the two paths. Each prefetch audit row records the `timeout_s` it ran under.\n\nThe SDK client's HTTP timeout is an **outer** bound, kept strictly greater than every *per-call* budget; the aggregate ceilings on whole passes are deliberately not folded in, since it applies per request and would otherwise hand every unbudgeted call a bound several times too long. Because it is no longer a tight bound, all three fire-and-forget bodies (person sync, department sync, department note) — whose individual calls are not separately budgeted — carry their own aggregate ceiling, as does the session listing in the workspace purge.\n\n### Peer identity\n\nPeers are keyed by `Person.id`, so the only identity signal Honcho gets from the key alone is a bare integer — and its dreaming agent concludes that the number *is* the person's name (observed in production as a card reading `IDENTITY: Name: 1`). Because cards are injected into the dialectic system prompt on every `chat()`, that error propagates into every later answer about that person. So both sync paths seed each person peer's card from the roster, for the sender, the department-turn originator, and co-present peers alike.\n\nThe card carries the **name only** — email and role would export roster PII to a third-party memory service, including for people who were merely cc'd, and neither is needed to fix the defect. `set_card` replaces the whole card, so only `IDENTITY:` lines are swapped and the deriver's own `ATTRIBUTE:` / `RELATIONSHIP:` lines survive; the existing card is split on physical lines first, since one list element may itself span lines and hide an identity claim on its second.\n\nRoster values are attacker-reachable — `upsert_person` is a chat tool an inbound email sender can reach — so a value is NFKC-normalised, stripped of control and format characters, whitespace-flattened, length-capped, and then held to an **allow-list** of letters, combining marks, digits and a small punctuation set, with the colon lookalikes the category allow-list would otherwise admit **stripped out** — taken from Unicode's confusables data (everything it maps to `:`), not from character names, since U+A4FD `ꓽ` is a Lisu *tone letter* whose name never says colon. They are stripped rather than grounds for refusing the value, because the visarga is the nominative ending in formal Devanagari and Gujarati names: refusing would leave those people never seeded, while stripping keeps the name as its stem form and still lets no colon shape reach the card. Modifier letters as a class stay allowed (々 in 佐々木, ー in ジョーンズ, ʻ in Hawaiʻi). A deny-list of structure tokens is not enough here: the consumer is an LLM system prompt rather than a parser, so `ATTRIBUTE :`, a fullwidth colon and a homoglyph all read the same to the model while defeating a literal match. The allow-list refuses every colon variant, which is what card structure depends on — checked by an exhaustive test over every Unicode codepoint whose name contains COLON plus an explicit test of the confusables the names miss. It does **not** stop a value that is merely persuasive prose — OE already embeds `full_name` in its own system prompt, so that exposure is pre-existing rather than introduced here.\n\nSeeding runs *after* the message write and *outside* the sync ceiling, and is audited as its own `seed_identity` row (`ok` only when no peer's attempt failed; `error` when any did, with the `failed` count on the row; `timeout` when the pass or the roster read hit its ceiling; `empty` when there was nobody to seed) — so the sync row is a pure record of the persist, emitted the instant the write lands, and a slow card round trip can neither delay nor replace it. It is bounded per peer *and* per pass, and is best-effort. It is memoized per `(workspace, person)` on the facts sent with a recheck interval — a rename re-seeds immediately, and because the deriver keeps re-deriving identity from the peer id, a one-shot memo would let `IDENTITY: Name: 1` come back unnoticed. A failed attempt is memoized separately and briefly — including every peer a pass-ceiling cut-off left in flight or unreached — so a degraded card endpoint is probed once per interval rather than once per peer per turn.\n\n### Cross-pollination & isolation\n\nWhen a person turn touches a department, the dept peer joins the person's session as a co-present peer — the hybrid peer graph that lets later queries synthesize across both timelines, with synthesis depth degrading at greater peer-graph distance. Demo fixtures run in a sacrificial `openexec-fixture-<name>` workspace so demo turns never pollute real peer cards. Every wrapper call emits a `peer_memory` audit row (`op` + `outcome`) into the per-turn flow at `/audit/session/{id}`.",
"mermaid": "flowchart TD\n Turn[\"Executive turn\"]\n Gate{\"HONCHO_ENABLED\"}\n Pre[\"prefetch: representation read (default)<br/>or dialectic query; prefetch_department: dialectic\"]\n Inj[\"peer_memory + department_memory<br/>injected into USER turn\"]\n Sync[\"sync_turn / sync_department_turn<br/>fire-and-forget\"]\n Honcho[\"Honcho peers<br/>person + department\"]\n Audit[\"peer_memory audit row\"]\n Turn --> Gate\n Gate -->|enabled| Pre\n Pre -->|context() / chat()| Honcho\n Honcho --> Inj\n Inj --> Turn\n Turn -->|after response| Sync\n Sync -->|\"co-present peers\"| Honcho\n Pulse[\"Pulse People tab<br/>GET /memories/people (read-only)\"]\n Pulse -->|\"conclusions + card\"| Honcho\n Pre --> Audit\n Sync --> Audit\n Pulse --> Audit\n class Turn entry\n class Gate compute\n class Pre compute\n class Sync compute\n class Honcho external\n class Pulse entry\n class Audit storage\n",
- "generated_at": "2026-09-23T15:58:35Z"
+ "generated_at": "2026-09-23T19:18:37Z"
}
diff --git a/packages/core/openexecutive/integrations/email_poller.py b/packages/core/openexecutive/integrations/email_poller.py
index 11afb083..4e714aa5 100644
--- a/packages/core/openexecutive/integrations/email_poller.py
+++ b/packages/core/openexecutive/integrations/email_poller.py
@@ -149,6 +149,16 @@ _ATTACHMENTS_MARKER = "--- ATTACHMENTS ---"
# sender's words.
_NO_BODY_PLACEHOLDER = "[No text/plain body found]"
_NO_SUBJECT_PLACEHOLDER = "(no subject)"
+# A reply or forward carries the earlier message's subject — often the
+# Executive's own ("Re: Approve the Acme renewal") — which would let its words
+# pass the extraction and open-loop quote gates as the sender's.
+# Covers the common client prefixes (English, German AW/WG, Scandinavian SV,
+# Dutch Antw, Italian R), a counter ("Re[2]:"), and tags an MTA prepends
+# ("[EXT] Re:"). Each tag is bounded and ends at "]", so this stays linear.
+_REPLY_SUBJECT_RE = re.compile(
+ r"^(\[[^\]]{0,40}\]\s*)*(re|fwd?|fw|aw|wg|sv|antw|r)(\[\d{1,3}\])?\s*:",
+ re.IGNORECASE,
+)
# An attachment line is `N. <filename> (<mime>, <size> KB)`, optionally
# followed by ` [in attached message]`. Parsed by splitting from the right
# rather than one regex: the filename is free text an email sender controls,
@@ -293,8 +303,9 @@ def _email_memory_text(raw: str) -> str:
holds the Executive's earlier email. Recorded under the sender's peer,
Honcho reads all of that as the sender speaking and concludes the sender
*is* the Executive ("received an email from <sender>", "is associated
- with <exec address>"). So memory gets only the subject, the sender's new
- text and the attachment filenames.
+ with <exec address>"). So memory gets only the sender's new text, the
+ attachment filenames and the subject — unless it is a reply's or
+ forward's, which is the earlier message's subject, not the sender's.
"""
header, body, attachments = _split_gmail_content(raw)
subject = next(
@@ -306,14 +317,16 @@ def _email_memory_text(raw: str) -> str:
names = [name for name in map(_attachment_name, attachments) if name]
parts: list[str] = []
- if subject and subject != _NO_SUBJECT_PLACEHOLDER:
+ if subject and subject != _NO_SUBJECT_PLACEHOLDER and not _REPLY_SUBJECT_RE.match(subject):
parts.append(f"Subject: {subject}")
if new_text:
parts.append(new_text)
if forwarded:
parts.append("[Forwarded an earlier message]")
if names:
- parts.append(f"[Attached: {', '.join(names)}]")
+ # Not "[Attached: …]": that line marks inlined document text, and the
+ # open-loop pass skips any turn carrying it (see open_loops).
+ parts.append(f"(Attached files: {', '.join(names)})")
return "\n\n".join(parts)
diff --git a/packages/core/openexecutive/orchestrator/executive.py b/packages/core/openexecutive/orchestrator/executive.py
index e6483ea9..22869aef 100644
--- a/packages/core/openexecutive/orchestrator/executive.py
+++ b/packages/core/openexecutive/orchestrator/executive.py
@@ -347,10 +347,11 @@ _ALL_SKILL_HANDLERS = {
}
-def _peer_memory_text(memory_text: str | None, user_message: str) -> str:
- """What the post-turn syncs record as the person's words: the caller's
- ``memory_text`` when given (``""`` included — it means "nothing the
- person wrote"), else the prompt itself."""
+def _speaker_text(memory_text: str | None, user_message: str) -> str:
+ """The speaker's own words for this turn, which every post-turn pass reads
+ instead of the prompt — episodic extraction, open loops and peer memory:
+ the caller's ``memory_text`` when given (``""`` included — it means
+ "nothing the person wrote"), else the prompt itself."""
return memory_text if memory_text is not None else user_message
@@ -672,12 +673,15 @@ class Executive:
peers as their representations grew. The committee path keeps
``"medium"`` since it already pays the deep-review latency cost.
- ``memory_text`` is what peer memory records as the person's words
- for this turn; ``None`` records ``user_message``. Pass it whenever
- ``user_message`` carries text the person did not write (an inbound
- email's headers and quoted chain, a briefing card's body, an
- attachment's extracted text): Honcho derives facts about the
- person from everything recorded under their peer.
+ ``memory_text`` is the person's own words for this turn — what peer
+ memory records, and what episodic extraction and the open-loop pass
+ must quote a commitment from; ``None`` uses ``user_message``. Pass it
+ whenever ``user_message`` carries text the person did not write (an
+ inbound email's headers and quoted chain, a briefing card's body, an
+ attachment's extracted text): Honcho derives facts about the person
+ from everything recorded under their peer, and a quote gate satisfied
+ by the Executive's own words stores its recommendation as the
+ person's decision or open loop.
"""
logger.info(
"chat turn: %s",
@@ -842,6 +846,14 @@ class Executive:
should_extract,
)
+ # Everything below reads the speaker's own words, not the prompt: the
+ # extraction and open-loop passes accept an item only with a verbatim
+ # quote from this text, and peer memory records it as what the person
+ # said. A quoted Executive email or a briefing card's body in the
+ # prompt would otherwise satisfy that quote gate with the Executive's
+ # own words.
+ speaker_text = _speaker_text(memory_text, user_message)
+
# Re-bind the audit ContextVars for the duration of these calls so
# the fire-and-forget tasks they schedule can snapshot the right
# session_id/turn_id (the main `with set_turn(...)` block above
@@ -855,12 +867,12 @@ class Executive:
# None) and the memory_extractor's model call would record
# unattributed however correct the snapshot itself was.
if should_extract(
- user_message,
+ speaker_text,
origin_channel=session.origin_channel,
person_id=person_id,
):
schedule_extraction(
- user_message, full_response, session_id=session.session_id
+ speaker_text, full_response, session_id=session.session_id
)
# Open loops from ANY rostered speaker (not just the principal):
@@ -870,7 +882,7 @@ class Executive:
from openexecutive.attunement.open_loops import schedule_open_loop_pass
schedule_open_loop_pass(
- user_message, full_response, person_id=person_id,
+ speaker_text, full_response, person_id=person_id,
session_id=session.session_id,
)
# Re-learn this speaker's working style once enough new
@@ -883,9 +895,8 @@ class Executive:
# extraction can update the peer card. Fire-and-forget; the
# wrapper no-ops when person_id is None or Honcho is disabled.
from openexecutive.memory.honcho_client import sync_turn as _honcho_sync
- peer_memory_text = _peer_memory_text(memory_text, user_message)
_honcho_sync(
- peer_memory_text,
+ speaker_text,
full_response,
person_id=person_id,
session_id=session.session_id,
@@ -896,7 +907,7 @@ class Executive:
# syncs are visible in the audit log as a related pair.
_sync_consulted_departments_to_honcho(
consulted,
- peer_memory_text,
+ speaker_text,
full_response,
person_id=person_id,
session_id=session.session_id,
@@ -1300,20 +1311,23 @@ class Executive:
schedule_extraction,
should_extract,
)
+ # The speaker's own words, for extraction, open loops and peer
+ # memory alike — see stream_chat.
+ speaker_text = _speaker_text(memory_text, user_message)
if should_extract(
- user_message,
+ speaker_text,
origin_channel=session.origin_channel,
person_id=person_id,
):
schedule_extraction(
- user_message, final_response, session_id=session.session_id
+ speaker_text, final_response, session_id=session.session_id
)
# Open loops — see stream_chat.
from openexecutive.attunement.open_loops import schedule_open_loop_pass
schedule_open_loop_pass(
- user_message, final_response, person_id=person_id,
+ speaker_text, final_response, person_id=person_id,
session_id=session.session_id,
)
from openexecutive.attunement.style import schedule_style_pass
@@ -1323,9 +1337,8 @@ class Executive:
# Mirror the completed exchange into Honcho (see stream_chat for
# rationale). Fire-and-forget; no-ops when person_id is None.
from openexecutive.memory.honcho_client import sync_turn as _honcho_sync
- peer_memory_text = _peer_memory_text(memory_text, user_message)
_honcho_sync(
- peer_memory_text,
+ speaker_text,
final_response,
person_id=person_id,
session_id=session.session_id,
@@ -1333,7 +1346,7 @@ class Executive:
)
_sync_consulted_departments_to_honcho(
consulted,
- peer_memory_text,
+ speaker_text,
final_response,
person_id=person_id,
session_id=session.session_id,
@@ -1877,8 +1890,8 @@ class Executive:
for details. ``peer_memory_reasoning_level=None`` (default)
keeps each underlying entry point's own default (``"minimal"``
for the streaming path, ``"medium"`` for the committee path).
- ``memory_text`` overrides what peer memory records as the person's
- words (see ``stream_chat``).
+ ``memory_text`` is the person's own words for the post-turn passes
+ (see ``stream_chat``).
"""
# Build the kwargs dict so we can conditionally include the
# reasoning_level only when caller specified one — otherwise
diff --git a/packages/core/tests/unit/test_chat_route_memory_text.py b/packages/core/tests/unit/test_chat_route_memory_text.py
index 8ad95fd0..eb02ba4b 100644
--- a/packages/core/tests/unit/test_chat_route_memory_text.py
+++ b/packages/core/tests/unit/test_chat_route_memory_text.py
@@ -77,7 +77,7 @@ def captured(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
SEED = "Let's discuss this artifact you flagged for my review:\n\n# Plan\n\nAssign Sam to sign."
-LINE = 'Asked to discuss the flagged artifact "Plan".'
+LINE = 'Let\'s discuss the flagged artifact "Plan".'
@pytest.mark.parametrize(
@@ -133,7 +133,7 @@ def test_upload_records_typed_text_and_filenames_not_document_text(
assert resp.status_code == 200
_ = resp.text
kwargs = captured["stream_chat"]
- assert kwargs["memory_text"] == "Summarise these\n\n[Attached: appraisal (1).pdf, notes.txt]"
+ assert kwargs["memory_text"] == "Summarise these\n\n(Attached files: appraisal (1).pdf, notes.txt)"
# The Executive still sees the extracted text.
assert "EXTRACTED DOCUMENT TEXT" in kwargs["user_message"]
diff --git a/packages/core/tests/unit/test_email_poller_memory_text.py b/packages/core/tests/unit/test_email_poller_memory_text.py
index 98f2bf85..b79b8d40 100644
--- a/packages/core/tests/unit/test_email_poller_memory_text.py
+++ b/packages/core/tests/unit/test_email_poller_memory_text.py
@@ -61,7 +61,7 @@ def test_reply_keeps_subject_new_text_and_attachment_only() -> None:
assert _email_memory_text(REPLY) == (
"Subject: Q3 appraisal\n\n"
"Here you go.\n\nSam\n\n"
- "[Attached: Harbor Point appraisal (1).pdf]"
+ "(Attached files: Harbor Point appraisal (1).pdf)"
)
@@ -113,7 +113,7 @@ def test_forwarded_message_is_replaced_by_a_note() -> None:
subject="Fwd: Rates",
)
assert _email_memory_text(raw) == (
- "Subject: Fwd: Rates\n\nFYI see below.\n\n[Forwarded an earlier message]"
+ "FYI see below.\n\n[Forwarded an earlier message]"
)
@@ -126,7 +126,7 @@ def test_multiple_attachments_are_listed_by_name() -> None:
" Attachment ID: y"
),
)
- assert _email_memory_text(raw).endswith("[Attached: a.pdf, b (final).xlsx]")
+ assert _email_memory_text(raw).endswith("(Attached files: a.pdf, b (final).xlsx)")
def test_attachment_only_email_records_subject_and_names() -> None:
@@ -136,7 +136,7 @@ def test_attachment_only_email_records_subject_and_names() -> None:
attachments="1. appraisal.pdf (application/pdf, 1.0 KB)",
)
# The MCP's placeholder is not the sender's words.
- assert _email_memory_text(raw) == "Subject: Appraisal\n\n[Attached: appraisal.pdf]"
+ assert _email_memory_text(raw) == "Subject: Appraisal\n\n(Attached files: appraisal.pdf)"
def test_no_subject_placeholder_is_not_recorded() -> None:
@@ -195,7 +195,7 @@ def test_attachments_marker_inside_the_body_is_body_text() -> None:
attachments="1. real.pdf (application/pdf, 2.0 KB)",
)
text = _email_memory_text(raw)
- assert text.endswith("[Attached: real.pdf]")
+ assert text.endswith("(Attached files: real.pdf)")
assert "Thanks" in text
@@ -222,7 +222,7 @@ def test_non_attachment_lines_in_the_list_are_ignored() -> None:
"2. no size (application/pdf)\n3. bad size (x, lots KB)"
),
)
- assert _email_memory_text(raw).endswith("[Attached: ok.pdf]")
+ assert _email_memory_text(raw).endswith("(Attached files: ok.pdf)")
def test_many_on_lines_parse_in_linear_time() -> None:
@@ -296,3 +296,44 @@ def test_run_executive_skips_the_parse_for_an_unrostered_sender() -> None:
captured = _run(lambda _addr: None)
assert captured["person_id"] is None
assert captured["memory_text"] is None
+
+
+def test_memory_text_does_not_trip_the_open_loop_document_skip() -> None:
+ """The open-loop pass reads this text and skips any turn carrying the
+ "[Attached: …]" label for inlined document text. A filename note using
+ that label would silently drop every email with an attachment."""
+ from openexecutive.attunement.open_loops import _ATTACHMENT_MARKER
+
+ assert "Harbor Point appraisal (1).pdf" in _email_memory_text(REPLY)
+ assert _ATTACHMENT_MARKER.search(_email_memory_text(REPLY)) is None
+
+
+def test_reply_subject_is_dropped_because_it_is_the_earlier_senders() -> None:
+ """A reply's subject is usually the Executive's own; kept, its words pass
+ the extraction quote gate as the sender's decision ("Approve the …")."""
+ for subject in (
+ "Re: Approve the Acme renewal", "RE:Approve it", "Fw: Approve it", "FWD: x",
+ "Re[2]: Approve it", "AW: Approve it", "SV: Approve it", "Antw: Approve it",
+ "[EXT] Re: Approve it", "[EXT] [ext] RE: Approve it",
+ ):
+ assert _email_memory_text(_email("Not yet.", subject=subject)) == "Not yet."
+
+
+def test_reply_subject_cannot_become_the_senders_decision() -> None:
+ from openexecutive.memory.episodic import _is_valid_user_commitment
+
+ text = _email_memory_text(_email("Not yet.", subject="Re: Approve the Acme renewal at 3%"))
+ assert not _is_valid_user_commitment("Approve the Acme renewal at 3%", text)
+
+
+def test_a_new_subject_the_sender_wrote_is_kept() -> None:
+ assert _email_memory_text(_email("See you then.", subject="Regarding Friday")) == (
+ "Subject: Regarding Friday\n\nSee you then."
+ )
+
+
+def test_reply_subject_prefix_check_is_linear() -> None:
+ raw = _email("Hi", subject="[" + "x" * 30 + "] " * 5000 + "no prefix")
+ started = time.monotonic()
+ _email_memory_text(raw)
+ assert time.monotonic() - started < 0.5
diff --git a/packages/core/tests/unit/test_episodic.py b/packages/core/tests/unit/test_episodic.py
index fdca148a..77ec7455 100644
--- a/packages/core/tests/unit/test_episodic.py
+++ b/packages/core/tests/unit/test_episodic.py
@@ -528,7 +528,12 @@ def test_executive_call_sites_use_the_shared_gate() -> None:
assert isinstance(test.func, ast.Name) and test.func.id == "should_extract", (
f"line {guard.lineno}: guard must call should_extract"
)
- assert [a.id for a in test.args if isinstance(a, ast.Name)] == ["user_message"]
+ # The speaker's own words (`memory_text` when given), not the prompt:
+ # a quoted Executive email or a briefing card's body in the prompt
+ # would satisfy the verbatim-quote gate with the Executive's words.
+ assert [a.id for a in test.args if isinstance(a, ast.Name)] == ["speaker_text"], (
+ f"line {guard.lineno}: guard must read speaker_text, not the prompt"
+ )
# The speaker check is not optional: a channel turn carries someone
# else's words, and the quote validator cannot tell whose they are.
assert {kw.arg for kw in test.keywords} == {"origin_channel", "person_id"}, (
diff --git a/packages/core/tests/unit/test_executive_memory_text.py b/packages/core/tests/unit/test_executive_memory_text.py
index e00f55ec..785879dc 100644
--- a/packages/core/tests/unit/test_executive_memory_text.py
+++ b/packages/core/tests/unit/test_executive_memory_text.py
@@ -4,9 +4,9 @@ A turn's ``user_message`` often carries text the person did not write: an
inbound email's framing, headers and quoted chain, or a briefing card's
body. Recorded under the person's peer, Honcho derives facts about the
person from it ("<person> is associated with <the Executive's address>").
-Every entry point must hand ``memory_text`` — not the prompt — to both the
-person sync and the per-department sync, and fall back to ``user_message``
-when it is not given.
+Every entry point must hand ``memory_text`` — not the prompt — to the person
+sync, the per-department sync, episodic extraction and the open-loop pass,
+and fall back to ``user_message`` when it is not given.
"""
from __future__ import annotations
@@ -71,20 +71,26 @@ def _provider() -> SimpleNamespace:
)
-def _drive(entry: str, **kwargs: Any) -> tuple[list[str], list[str]]:
- """Run one turn through ``entry`` and return (person-sync texts,
- department-sync texts)."""
+def _drive(entry: str, **kwargs: Any) -> dict[str, list[str]]:
+ """Run one turn through ``entry`` and return the text each post-turn pass
+ received: the person sync, the department sync, episodic extraction and
+ the open-loop pass."""
from openexecutive.orchestrator.executive import Executive
from openexecutive.orchestrator.session import Session
- person_texts: list[str] = []
- dept_texts: list[str] = []
+ seen: dict[str, list[str]] = {"person": [], "dept": [], "extract": [], "loops": []}
def _sync_turn(user_message: str, *_a: Any, **_k: Any) -> None:
- person_texts.append(user_message)
+ seen["person"].append(user_message)
def _dept_sync(_consulted: Any, user_message: str, *_a: Any, **_k: Any) -> None:
- dept_texts.append(user_message)
+ seen["dept"].append(user_message)
+
+ def _extract(user_message: str, *_a: Any, **_k: Any) -> None:
+ seen["extract"].append(user_message)
+
+ def _loops(user_message: str, *_a: Any, **_k: Any) -> None:
+ seen["loops"].append(user_message)
exec_ = Executive()
@@ -106,27 +112,47 @@ def _drive(entry: str, **kwargs: Any) -> tuple[list[str], list[str]]:
"openexecutive.orchestrator.executive._sync_consulted_departments_to_honcho",
new=_dept_sync,
),
+ patch("openexecutive.memory.episodic.schedule_extraction", new=_extract),
+ patch("openexecutive.attunement.open_loops.schedule_open_loop_pass", new=_loops),
):
asyncio.run(_run())
- return person_texts, dept_texts
+ return seen
@pytest.mark.parametrize("entry", ["stream_chat", "stream_chat_with_committee", "chat"])
-def test_memory_text_is_what_peer_memory_records(entry: str) -> None:
- person, dept = _drive(entry, memory_text=MEMORY)
- assert person == [MEMORY]
- assert dept == [MEMORY]
+def test_memory_text_is_what_every_post_turn_pass_reads(entry: str) -> None:
+ """Extraction and open loops only accept an item with a verbatim quote
+ from the text they get; the prompt would let a quoted Executive email
+ satisfy that quote."""
+ seen = _drive(entry, memory_text=MEMORY)
+ assert seen == {"person": [MEMORY], "dept": [MEMORY], "extract": [MEMORY], "loops": [MEMORY]}
@pytest.mark.parametrize("entry", ["stream_chat", "stream_chat_with_committee", "chat"])
def test_without_memory_text_the_message_is_recorded(entry: str) -> None:
- person, dept = _drive(entry)
- assert person == [PROMPT]
- assert dept == [PROMPT]
+ seen = _drive(entry)
+ assert seen == {"person": [PROMPT], "dept": [PROMPT], "extract": [PROMPT], "loops": [PROMPT]}
def test_empty_memory_text_is_honoured_not_replaced_by_the_prompt() -> None:
"""An email with no subject, body or attachment yields "" — that must
- record nothing for the person, not fall back to the framed prompt."""
- person, _ = _drive("stream_chat", memory_text="")
- assert person == [""]
+ record nothing for the person, not fall back to the framed prompt, and
+ gives extraction nothing to quote from (should_extract skips it)."""
+ seen = _drive("stream_chat", memory_text="")
+ assert seen["person"] == [""]
+ assert seen["extract"] == []
+ assert seen["loops"] == [""]
+
+
+def test_briefing_approve_line_passes_the_quote_gate_with_a_question_headline() -> None:
+ """The UI's line (packages/ui/src/lib/briefing-memory.ts) ends the action
+ sentence before the headline, so a "?" in the headline cannot void the
+ approval as the principal's decision."""
+ from openexecutive.memory.episodic import _is_valid_user_commitment
+
+ line = 'I approve this proposal.\n"Should we renew Acme at 3%?"'
+ assert _is_valid_user_commitment("I approve this proposal", line)
+ # The shape it replaced put the headline first inside the sentence.
+ assert not _is_valid_user_commitment(
+ "I approve the proposal", 'I approve the proposal "Should we renew Acme at 3%?".'
+ )
diff --git a/packages/ui/scripts/briefing-memory.test.mjs b/packages/ui/scripts/briefing-memory.test.mjs
index 2b2c8ca8..71a74b97 100644
--- a/packages/ui/scripts/briefing-memory.test.mjs
+++ b/packages/ui/scripts/briefing-memory.test.mjs
@@ -1,23 +1,35 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { MEMORY_LINE_MAX_CHARS, briefingMemoryLine } from "../src/lib/briefing-memory.ts";
+import {
+ MEMORY_ACTIONS,
+ MEMORY_LINE_MAX_CHARS,
+ briefingMemoryLine,
+ nudgeAction,
+} from "../src/lib/briefing-memory.ts";
-test("names the action and the item, not the card body", () => {
+test("names the action, then the item on its own line — not the card body", () => {
assert.equal(
- briefingMemoryLine("Asked to discuss the flagged artifact", "Harbor Point disposition plan"),
- 'Asked to discuss the flagged artifact "Harbor Point disposition plan".',
+ briefingMemoryLine(MEMORY_ACTIONS.artifact, "Harbor Point disposition plan"),
+ 'Let\'s discuss this flagged artifact.\n"Harbor Point disposition plan"',
);
});
+test("the action sentence ends before a question-shaped headline", () => {
+ // Extraction accepts a quote only when "." follows it before any "?"; a
+ // headline inside the sentence would void "I approve this proposal".
+ const line = briefingMemoryLine(MEMORY_ACTIONS.approve, "Should we renew Acme at 3%?");
+ assert.ok(line.startsWith("I approve this proposal.\n"));
+});
+
test("collapses whitespace so a multi-line headline stays one line", () => {
assert.equal(
- briefingMemoryLine("Approved the proposal", " Renew\n\n the lease "),
- 'Approved the proposal "Renew the lease".',
+ briefingMemoryLine(MEMORY_ACTIONS.approve, " Renew\n\n the lease "),
+ 'I approve this proposal.\n"Renew the lease"',
);
});
test("clips long subjects well under the backend's 2000-char bound", () => {
- const line = briefingMemoryLine("Asked to dig into the briefing item", "x".repeat(5000));
+ const line = briefingMemoryLine(MEMORY_ACTIONS.narrative, "x".repeat(5000));
const quoted = line.slice(line.indexOf('"') + 1, line.lastIndexOf('"'));
assert.equal(quoted.length, MEMORY_LINE_MAX_CHARS);
assert.ok(quoted.endsWith("…"));
@@ -25,5 +37,26 @@ test("clips long subjects well under the backend's 2000-char bound", () => {
});
test("an empty subject still yields a non-empty line", () => {
- assert.equal(briefingMemoryLine("Asked about the proposal", " "), "Asked about the proposal.");
+ assert.equal(briefingMemoryLine(MEMORY_ACTIONS.proposal, " "), "Tell me about this proposal.");
+});
+
+test("every action reads as the user speaking, never as a passive fact", () => {
+ // "Asked to …" came back from peer memory as "<user> was asked to …".
+ for (const action of [...Object.values(MEMORY_ACTIONS), nudgeAction("Sam")]) {
+ assert.doesNotMatch(action, /^(Asked|Approved|Requested|Flagged)\b/, action);
+ assert.match(action, /^(Let's|Help me|Tell me|I |Nudge )/, action);
+ }
+});
+
+test("the nudge line names who to nudge", () => {
+ assert.equal(
+ briefingMemoryLine(nudgeAction("Sam"), "Lease renewal"),
+ 'Nudge Sam about this item.\n"Lease renewal"',
+ );
+});
+
+test("clipping never splits an emoji into a lone surrogate", () => {
+ const line = briefingMemoryLine(MEMORY_ACTIONS.proposal, "a".repeat(298) + "😀😀😀");
+ assert.doesNotMatch(line, /[\uD800-\uDBFF](?![\uDC00-\uDFFF])/);
+ assert.ok(line.endsWith('…"'));
});
diff --git a/packages/ui/src/components/Briefing.tsx b/packages/ui/src/components/Briefing.tsx
index 8fc4788a..3e10293d 100644
--- a/packages/ui/src/components/Briefing.tsx
+++ b/packages/ui/src/components/Briefing.tsx
@@ -21,7 +21,7 @@ import {
type ProposalItem,
type Today,
} from "@/lib/api";
-import { briefingMemoryLine } from "@/lib/briefing-memory";
+import { MEMORY_ACTIONS, briefingMemoryLine, nudgeAction } from "@/lib/briefing-memory";
import { clientCountsSummary, renewalBadge } from "@/lib/practice";
import {
HANDLED_REOPENABLE,
@@ -591,7 +591,7 @@ const moveButton = (() => {
onClick={() => onContinue(
`Nudge ${who} about this item — it has gone quiet: ${proposal.headline}\n\n` +
`Send a short, friendly check-in via message_person and tell me what you sent.`,
- briefingMemoryLine(`Asked to nudge ${who} about`, proposal.headline),
+ briefingMemoryLine(nudgeAction(who), proposal.headline),
)}
disabled={busy}
className="text-xs font-medium text-indigo-300 hover:text-indigo-200 px-2 py-1 rounded border border-indigo-500/30 transition-colors disabled:opacity-50"
@@ -764,12 +764,12 @@ function ProposalCard({
})();
const handoffMemory = briefingMemoryLine(
isArtifact
- ? "Asked to discuss the flagged artifact"
+ ? MEMORY_ACTIONS.artifact
: isMonitoring
- ? "Asked about the monitored signal"
+ ? MEMORY_ACTIONS.monitoring
: isDecision
- ? "Asked to talk through the proposed meeting"
- : "Asked about the proposal",
+ ? MEMORY_ACTIONS.meeting
+ : MEMORY_ACTIONS.proposal,
proposal.headline,
);
// Suggested-action block: visually promoted so the user reads it as a
@@ -1200,7 +1200,7 @@ function MonitoringRow({
{onContinue ? (
<button
type="button"
- onClick={() => onContinue(seed, briefingMemoryLine("Asked about the monitored signal", proposal.headline))}
+ onClick={() => onContinue(seed, briefingMemoryLine(MEMORY_ACTIONS.monitoring, proposal.headline))}
className="block w-full text-left pr-8 cursor-pointer focus:outline-none focus:ring-1 focus:ring-indigo-500/40"
>
{inner}
@@ -1500,7 +1500,7 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:
`call schedule_followup so I get a fresh check at the right time. Do NOT just ` +
`summarize what you would do, file it for later, or assign it to someone — ` +
`the assignment IS to you.\n\nProposal:\n${text}${action}`,
- briefingMemoryLine("Approved the proposal", proposal.headline),
+ briefingMemoryLine(MEMORY_ACTIONS.approve, proposal.headline),
);
}
} catch (e) {
@@ -1607,7 +1607,7 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:
`call ack_alert. Use the text below VERBATIM when you deliver the message: do not ` +
`rephrase, summarize, or restructure it. Then go execute (send the DM/email, ` +
`schedule any follow-up via schedule_followup) and tell me what you did.\n\n${editedBody}`,
- briefingMemoryLine("Approved the proposal with edits", proposal.headline),
+ briefingMemoryLine(MEMORY_ACTIONS.approveWithEdits, proposal.headline),
);
}
} catch (e) {
@@ -1833,7 +1833,7 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:
<li className="list-none">
<button
type="button"
- onClick={() => onContinue(buildNarrativeSeed(text), briefingMemoryLine("Asked to dig into the briefing item", text))}
+ onClick={() => onContinue(buildNarrativeSeed(text), briefingMemoryLine(MEMORY_ACTIONS.narrative, text))}
aria-label={`Discuss: ${text}`}
className="group flex w-full items-start gap-2 text-left cursor-pointer rounded -mx-1.5 px-1.5 py-0.5 transition hover:bg-indigo-500/10 focus:outline-none focus:ring-1 focus:ring-indigo-500/40"
>
diff --git a/packages/ui/src/lib/briefing-memory.ts b/packages/ui/src/lib/briefing-memory.ts
index 02083a4b..a7aed9e1 100644
--- a/packages/ui/src/lib/briefing-memory.ts
+++ b/packages/ui/src/lib/briefing-memory.ts
@@ -3,14 +3,48 @@
// message as the user's own words, so recording the seed would credit the
// user with what the Executive wrote ("<user> assigned a colleague to …"). Those
// handoffs send this short line as the turn's memory text instead.
+//
+// Phrase `action` as the user talking to the Executive, in the first person
+// or the imperative ("Let's discuss …", "I approve …"). Honcho reads the line
+// as the user's own message, and a clipped past participle ("Asked to …")
+// comes back as a passive fact — "<user> was asked to …".
+//
+// The action is its own sentence, ended with "." before the subject on the
+// next line. Episodic extraction and open loops only accept a commitment
+// quoted from this text and followed by "." — a headline such as "Should we
+// renew?" placed inside the sentence would put a "?" first and void it.
// Well under the backend's 2000-char `ChatRequest.memory_text` bound, so a
// long narrative bullet can never 422 the whole turn.
export const MEMORY_LINE_MAX_CHARS = 300;
+// By code point, not UTF-16 unit: a cut through an emoji leaves a lone
+// surrogate, which the backend cannot store.
+function clip(text: string, max: number): string {
+ const chars = Array.from(text);
+ return chars.length > max ? `${chars.slice(0, max - 1).join("")}…` : text;
+}
+
export function briefingMemoryLine(action: string, subject: string): string {
- const s = subject.trim().replace(/\s+/g, " ");
- const clipped =
- s.length > MEMORY_LINE_MAX_CHARS ? `${s.slice(0, MEMORY_LINE_MAX_CHARS - 1)}…` : s;
- return clipped ? `${action} "${clipped}".` : `${action}.`;
+ const s = clip(subject.trim().replace(/\s+/g, " "), MEMORY_LINE_MAX_CHARS);
+ return s ? `${action}.\n"${s}"` : `${action}.`;
+}
+
+// The handoff actions, in the phrasing the comment above asks for. Kept here
+// rather than inline so the wording is tested.
+export const MEMORY_ACTIONS = {
+ artifact: "Let's discuss this flagged artifact",
+ monitoring: "Help me understand this monitored signal",
+ meeting: "Let's talk through this proposed meeting",
+ proposal: "Tell me about this proposal",
+ narrative: "Let's dig into this briefing item",
+ approve: "I approve this proposal",
+ // The edited text itself is left out: it starts as the Executive's card
+ // body and is often sent unchanged or lightly edited, so recording it would
+ // let the Executive's recommendation pass as the user's own decision.
+ approveWithEdits: "I approve this proposal with my edits",
+} as const;
+
+export function nudgeAction(who: string): string {
+ return `Nudge ${who} about this item`;
}