mercury-agent 0.16.0 → 0.16.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +6 -0
  2. package/container/Dockerfile +6 -1
  3. package/container/Dockerfile.base +6 -1
  4. package/docs/README.md +50 -0
  5. package/docs/authoring-profiles.md +8 -0
  6. package/docs/behavior-layers.md +193 -0
  7. package/docs/extensions.md +2 -0
  8. package/docs/goals/football-reporter-profile/decisions.md +479 -0
  9. package/docs/goals/football-reporter-profile/goal.md +91 -0
  10. package/docs/goals/football-reporter-profile/roadmap.md +196 -0
  11. package/docs/goals/whatsapp-bot-hardening/README.md +43 -0
  12. package/docs/goals/whatsapp-bot-hardening/archive/ambient-group-context.md +211 -0
  13. package/docs/goals/whatsapp-bot-hardening/archive/command-routing-consistency.md +210 -0
  14. package/docs/goals/whatsapp-bot-hardening/archive/destructive-command-guards.md +218 -0
  15. package/docs/goals/whatsapp-bot-hardening/archive/docs-extension.md +182 -0
  16. package/docs/goals/whatsapp-bot-hardening/archive/handoff-2026-08-09.md +588 -0
  17. package/docs/goals/whatsapp-bot-hardening/archive/media-size-and-silent-drop.md +178 -0
  18. package/docs/goals/whatsapp-bot-hardening/archive/member-memory.md +199 -0
  19. package/docs/goals/whatsapp-bot-hardening/archive/message-author-attribution.md +211 -0
  20. package/docs/goals/whatsapp-bot-hardening/archive/run-from-source-switchover.md +212 -0
  21. package/docs/goals/whatsapp-bot-hardening/archive/setup-plan-2026-08-06.md +1117 -0
  22. package/docs/goals/whatsapp-bot-hardening/decisions.md +200 -0
  23. package/docs/goals/whatsapp-bot-hardening/goal.md +75 -0
  24. package/docs/goals/whatsapp-bot-hardening/open-threads.md +396 -0
  25. package/docs/goals/whatsapp-bot-hardening/roadmap.md +245 -0
  26. package/docs/memory.md +30 -0
  27. package/docs/profile-guide.md +483 -0
  28. package/docs/refactor/.gitkeep +0 -0
  29. package/docs/refactor/archive/.gitkeep +0 -0
  30. package/docs/refactor/audits/.gitkeep +0 -0
  31. package/docs/refactor/backlog/.gitkeep +0 -0
  32. package/docs/skills-guide.md +154 -0
  33. package/examples/extensions/README.md +1 -0
  34. package/examples/extensions/feed-watch/config.ts +354 -0
  35. package/examples/extensions/feed-watch/digest.ts +344 -0
  36. package/examples/extensions/feed-watch/feeds.ts +341 -0
  37. package/examples/extensions/feed-watch/index.ts +302 -0
  38. package/examples/extensions/feed-watch/items.ts +171 -0
  39. package/examples/extensions/feed-watch/match.ts +107 -0
  40. package/examples/extensions/feed-watch/prompts/verify.md +35 -0
  41. package/examples/extensions/feed-watch/skill/SKILL.md +128 -0
  42. package/examples/extensions/feed-watch/watch.ts +548 -0
  43. package/examples/extensions/longview/hook.ts +179 -16
  44. package/examples/extensions/longview/index.ts +13 -2
  45. package/examples/extensions/longview/prompts/summarize.md +3 -2
  46. package/examples/extensions/longview/render/telegraph-nodes.ts +21 -1
  47. package/examples/extensions/longview/summarize.ts +57 -14
  48. package/examples/extensions/napkin/index.ts +334 -86
  49. package/examples/extensions/napkin/pi-spawn.ts +196 -0
  50. package/examples/extensions/pinchtab/index.ts +37 -4
  51. package/examples/extensions/pinchtab/lib/session-injector.ts +31 -9
  52. package/examples/extensions/pinchtab/skill/SKILL.md +29 -0
  53. package/examples/profiles/_template/AGENTS.md +138 -0
  54. package/examples/profiles/_template/README.md +65 -0
  55. package/examples/profiles/_template/config.yaml +57 -0
  56. package/examples/profiles/_template/tasks/daily.md +32 -0
  57. package/examples/profiles/football-reporter/AGENTS.md +219 -0
  58. package/examples/profiles/football-reporter/README.md +138 -0
  59. package/examples/profiles/football-reporter/config.yaml +174 -0
  60. package/examples/profiles/football-reporter/seed/MEMORY.md +42 -0
  61. package/examples/profiles/football-reporter/seed/episodes/barcelona-2026-27.md +25 -0
  62. package/examples/profiles/football-reporter/seed/episodes/beitar-jerusalem-2026-27.md +25 -0
  63. package/examples/profiles/football-reporter/seed/episodes/maccabi-haifa-2026-27.md +24 -0
  64. package/examples/profiles/football-reporter/seed/episodes/man-united-2026-27.md +26 -0
  65. package/examples/profiles/football-reporter/seed/episodes/real-madrid-2026-27.md +25 -0
  66. package/examples/profiles/football-reporter/seed/napkin-distill.md +55 -0
  67. package/examples/profiles/football-reporter/tasks/daily-article.md +142 -0
  68. package/package.json +8 -5
  69. package/src/adapters/whatsapp.ts +75 -13
  70. package/src/bridges/whatsapp.ts +6 -4
  71. package/src/cli/mrctl.ts +9 -1
  72. package/src/core/handler.ts +51 -6
  73. package/src/core/routes/dashboard.ts +106 -5
  74. package/src/core/routes/tasks.ts +28 -0
  75. package/src/core/runtime.ts +63 -2
  76. package/src/core/task-scheduler.ts +103 -12
  77. package/src/extensions/catalog.ts +9 -0
  78. package/src/profile/space-profile.ts +780 -0
  79. package/src/storage/db.ts +215 -0
  80. package/src/types.ts +56 -0
package/docs/memory.md CHANGED
@@ -116,6 +116,36 @@ The vault is plain markdown. You can:
116
116
  - Edit files directly from the host
117
117
  - Back it up like any other directory
118
118
 
119
+ ## What the runtime actually injects (verified 2026-08-21)
120
+
121
+ The vault above is extension territory. Independently of any extension,
122
+ `src/agent/container-entry.ts buildPrompt()` puts these into **every** run's
123
+ user prompt, in this order:
124
+
125
+ | Block | Source | Condition / budget |
126
+ |---|---|---|
127
+ | `<episodic_memory>` | `MEMORY.md` in the space dir, verbatim | exists and non-empty. The prompt asks for ~1500 tokens; nothing enforces it |
128
+ | `<active_episodes>` | `knowledge/episodes/*.md` | frontmatter `status: active` or `cooling`, `keywords: ["…"]` as a JSON array; scored by keyword overlap with the message × (active 1.0 / cooling 0.5) × log(mentions+1); ≤800 tokens; body = `summary:` + the `## Current State` section |
129
+ | `<history>` | SQLite sliding window | `context.mode=context`; `context.window_size` **user** turns (default 10); halved on a swipe-reply; hand-created spaces default to `clear` |
130
+ | `<members>` / `<member_notes>` | `space_roles` / `knowledge/members/<id>.md` | always / ≤6000 chars, `<id>` with `/`→`_` |
131
+ | `<preferences>` | `space_preferences` | always; ≤500 chars each, ≤50 per space |
132
+
133
+ Everything else in the workspace — `knowledge/people/**`, `projects/**`,
134
+ `references/**`, `daily/**`, any notebook you add — is **not** injected. The
135
+ agent reads it only when an instruction (`AGENTS.md`, a task prompt, a skill)
136
+ tells it to, or when it chooses to `napkin search`. `mrctl recall` is a
137
+ substring search over the stored message history for anything outside the
138
+ window.
139
+
140
+ Design consequence for a profile: `MEMORY.md` is the one always-on page —
141
+ seed it and give the agent a rule for updating it; facts the bot must not
142
+ contradict later go in a file it is told to read each turn; episodes work
143
+ only with keywords that will recur. The napkin distillation job writes
144
+ entity files on its own "lasting signal" bar and is not a substitute for a
145
+ domain notebook (on the live bot it has written none for the space that
146
+ needed them most). See [`profile-guide.md`](profile-guide.md) §6 and
147
+ [`behavior-layers.md`](behavior-layers.md) §5.
148
+
119
149
  ## Space preferences (built-in)
120
150
 
121
151
  Short, structured **per-space** hints (sources, habits, rules) can be stored in SQLite and managed from chat via `mrctl prefs` (see the built-in **preferences** skill). The host injects them into each run as a `<preferences>` block in the user prompt. See [prd-chat-memory.md](prd-chat-memory.md).
@@ -0,0 +1,483 @@
1
+ # Profile authoring guide — building a bot for a specific use-case
2
+
3
+ This is the how-to for turning Mercury into *a particular assistant*: a
4
+ barber's booking line, a copywriter's studio assistant, a football reporter in
5
+ a friends' group, a trial-tier business helper. It is written from the
6
+ profiles that exist — the four in `tagula-agents/tagula-agent-profiles`
7
+ (barber, lawyers, copywriter, trial) and the football reporter in this repo —
8
+ and from what went wrong while building them. Where it states how Mercury
9
+ behaves, that was verified against the code and the running agent image on
10
+ 2026-08-21; the pointers are there so you can re-verify.
11
+
12
+ Companion references:
13
+
14
+ - [`behavior-layers.md`](behavior-layers.md) — every layer the model receives,
15
+ in order, with owner and when a change lands. **Read it first.**
16
+ - [`skills-guide.md`](skills-guide.md) — how skills are discovered and how to
17
+ make the bot use them.
18
+ - [`authoring-profiles.md`](authoring-profiles.md) — the applicative-profile
19
+ contract (manifest, capability broker, permissions).
20
+ - [`memory.md`](memory.md) — memory surfaces; §"What the runtime injects" is the
21
+ verified part.
22
+ - [`examples/profiles/football-reporter/`](../examples/profiles/football-reporter/)
23
+ and [`examples/profiles/_template/`](../examples/profiles/_template/) — a
24
+ live space profile and the scaffold.
25
+
26
+ ---
27
+
28
+ ## 0. The one-paragraph version
29
+
30
+ A profile is **a bounded set of facts and rules, each living in exactly one
31
+ place, with the accuracy-critical parts done by code and the voice done by
32
+ prose**. Facts the bot must get right come from a tool (an engine, a fetch, a
33
+ file it reads every turn), never from the model's memory; the prompt tells it
34
+ *which* tool and *what to do when the tool has no answer*. Voice lives in the
35
+ space `AGENTS.md` and overrides, in words, the platform text it disagrees
36
+ with. Memory is a file you design, not a side effect you hope for. Everything
37
+ is verified against the running bot — a trace, a drift check, a grep of the
38
+ image — not against the diff.
39
+
40
+ ---
41
+
42
+ ## 1. Two kinds of profile — pick before you write anything
43
+
44
+ | | Applicative profile (`mercury-profile.yaml`) | Space profile (`config.yaml`) |
45
+ |---|---|---|
46
+ | Scope | the whole deployment: every space, every DM auto-space | one space |
47
+ | What it carries | global `AGENTS.md`, extensions (capabilities, CLIs, skills), **exhaustive `member_permissions`**, `profile_prompt`, required capabilities, env | the space `AGENTS.md`, task prompts by live id, extension config keys, preferences to delete, workspace files to remove |
48
+ | Applied with | `mercury profiles apply <dir>` (non-interactive) or `mercury setup --profile`; needs a restart, and an image rebuild if it adds CLIs | `bun scripts/space-profile.ts apply --project <dir> --profile <dir>`; no restart |
49
+ | Verified with | `mercury doctor`, a DM from a non-admin number, the startup warning about excluded member permissions | `space-profile check` (exit 1 + diff on drift); runs on every `~/sync-mercury.sh` |
50
+ | Loader | `src/core/profiles.ts` | `src/profile/space-profile.ts` |
51
+ | Use it for | a bot that *is* one product (barber, lawyers, trial) — one persona, many isolated DM spaces, credentials wrapped host-side | a space inside a general bot that needs its own editorial standard (football-friends), or a repo-owned record of a space's rules |
52
+ | Examples | `tagula-agent-profiles/profiles/{barber,lawyers,copywriter,trial}`, `resources/profiles/{general,coding,research}` | `examples/profiles/football-reporter` |
53
+
54
+ They compose: a deployment can run an applicative profile *and* carry space
55
+ profiles for particular spaces. They do not overlap in what they own — the
56
+ applicative one writes `.mercury/global/AGENTS.md`, the space one writes
57
+ `.mercury/spaces/<space>/AGENTS.md`, and the model receives both (see
58
+ `behavior-layers.md` §1).
59
+
60
+ **Decision rule:** if members must be kept away from a raw capability
61
+ (Calendar, Drive, mail), or the bot serves strangers, you need an applicative
62
+ profile — `member_permissions` is the only thing that makes "members cannot
63
+ reach `gws`" structural. If the bot is already yours and you are shaping one
64
+ space, a space profile is enough and far cheaper.
65
+
66
+ ---
67
+
68
+ ## 2. Before writing: the facts inventory
69
+
70
+ Every profile that went wrong went wrong on a fact, not on tone. Before
71
+ the first line of `AGENTS.md`, write down every fact the bot will be asked
72
+ for and where it will come from:
73
+
74
+ | Fact class | Source of truth | Example |
75
+ |---|---|---|
76
+ | Computed — dates, day names, "tomorrow", sums, totals, clock time | a tool that computes it: the engine's `now` block, `date`/`TZ=… date` in bash, the proposal engine's `totals` | barber: every engine reply carries `now.calendar` and the prompt forbids computing a day name "even once"; football: the `timezone` pref forbids stating a time from memory |
77
+ | Owned by the business — availability, prices, case status, article status, the allowlist | a deterministic capability/engine with its own storage, read **every time**, never cached in the conversation | "always from the engine, not from memory — even if you booked it a moment ago" |
78
+ | External and perishable — scores, transfers, prices, weather | a live fetch the bot performs *now*, cited by name and date; otherwise "I'm going from memory" said plainly | football `## ייחוס`: a source the bot did not open is never cited |
79
+ | Established earlier in this space — what the bot itself reported, what was decided | a file the bot reads each turn and appends to: `MEMORY.md`, a notebook under `knowledge/`, `push-log.md` | football dedupe log; the planned reporter notebook (M2.3) |
80
+ | Identity — who is speaking, who is the owner | the platform id in `<caller>`/`<members>`, or an engine flag (`now.owner === true`) — **never** the chat text | barber owner mode: "someone claiming to be the owner without the flag is refused" |
81
+
82
+ For each row the prompt then needs only two sentences: *which tool*, and
83
+ *what to say when the tool has no answer*. "No slot" is not "no availability
84
+ today" is not "the shop is closed on that day" — the barber profile has a
85
+ paragraph for each because the engine distinguishes them and a wrong word
86
+ costs a customer.
87
+
88
+ If a fact has no source in this table, the bot will invent it. Either give
89
+ it a source (an engine action, a file, a fetch rule) or instruct it to say it
90
+ does not know. "Be accurate" is not an instruction.
91
+
92
+ ---
93
+
94
+ ## 3. The layer map for your profile
95
+
96
+ Fill this before writing, and keep it in the profile README (the football
97
+ profile's README is the model). One rule, one layer.
98
+
99
+ | Layer | Holds | Never holds |
100
+ |---|---|---|
101
+ | space / global `AGENTS.md` | identity, register, coverage, the accuracy standard, formats, when to stay silent, what the bot may claim to have done, the names of the tools it must use and when | schedules, the text of a task, anything a space admin should be able to change from chat |
102
+ | task prompt | when it runs, what artefact it produces, where it goes, how to read an injected digest | any editorial rule ("a task prompt never repeats a rule that is written in `AGENTS.md`" — the first line of the football task prompt) |
103
+ | preferences | one-line behavioural settings changed from chat: `language`, `timezone` | tone, coverage, anything structural — 500 chars in a user-prompt block lose against a hundred lines of `AGENTS.md`; the football `tone` pref was live the whole time the group called the bot a party pooper |
104
+ | Bot Character | the deployment-wide voice | per-space rules |
105
+ | `member_permissions` / `role.member.permissions` | what members can do | — (and prose never substitutes: the model is not the enforcement) |
106
+ | extension config | the knobs extensions read (`feed-watch.*`, `longview.*`) | switches whose *setter* matters (`feed-watch.enabled` runs verify tasks as whoever set it — a profile stamps `space-profile`, a principal with no role) |
107
+ | capability / engine | every computation and every business fact | prompt-shaped logic ("if the slot is in a break, say…" belongs in the engine reply, which the prompt then relays) |
108
+ | `MEMORY.md` / notebook | what the bot established and must not contradict next week | the rules themselves |
109
+
110
+ When you move a rule between layers, delete the old copy. A space profile has
111
+ `remove_preferences:` precisely so the deletion is part of the deploy and is
112
+ checked for drift afterwards.
113
+
114
+ ---
115
+
116
+ ## 4. Writing `AGENTS.md`
117
+
118
+ ### 4.1 Shape
119
+
120
+ The mature profiles converge on the same skeleton. Keep the order; the model
121
+ reads top-down and the first sections frame the rest.
122
+
123
+ ```
124
+ # <who> — agent instructions one line: role, for whom, on what platform
125
+ ## Identity / role who it is, who it serves, what it covers, what it never does
126
+ ## Critical rules — date & time the no-clock rule (see 4.3) — verbatim from a shared source
127
+ ## Critical rules — facts which tool for which fact; what to say when it has none
128
+ ## Owner / admin mode how the engine flags it; privacy relaxes only then
129
+ ## Style / register register, length, emoji, language, what never to say
130
+ ## Conversation continuity what counts as a follow-up vs new research
131
+ ## Flows (one per use-case) the funnel, one section each, with a worked example
132
+ ## Commands / skills every invocation, verbatim, with argument notes
133
+ ## Errors one line per engine status: the exact customer-facing wording
134
+ ## Silence when to say nothing and how (NO_UPDATE, "אין חדש")
135
+ ## Integrity about what was done "I wrote it" only after a successful write; who can change what
136
+ ## Dedupe / memory routine which file to read before posting and append after
137
+ ## Overrides of platform text the explicit sentences (see 4.4)
138
+ ```
139
+
140
+ Write in the language the bot speaks. Keep every rule **testable from the
141
+ transcript** ("never more than 3 time slots in one message") rather than
142
+ aspirational ("be helpful").
143
+
144
+ ### 4.2 Rules are mechanisms, not pleas
145
+
146
+ Compare:
147
+
148
+ - ✗ "Try to be accurate about appointments."
149
+ - ✓ "When asked 'what appointments do I have?' — call `my-appointments` again,
150
+ every time, even if you booked it a moment ago. The barber may have moved
151
+ it in the calendar. This also applies when you *volunteer* an appointment
152
+ nobody asked about: no engine reply in this turn, no appointment details."
153
+
154
+ The second names the tool, the trigger, the reason, and the edge case
155
+ (volunteering). That is what survives contact with a model under pressure.
156
+
157
+ ### 4.3 The no-clock rule (every profile needs one)
158
+
159
+ The model has a `Current date` line (UTC) and a shell; it has no reliable
160
+ sense of "now", and relative words copied from earlier turns are wrong by the
161
+ time they are repeated. The tagula profiles share one paragraph
162
+ (`profiles/_shared/grounding-rules/*.md`, composed into each `AGENTS.md` by
163
+ `compose-grounding.sh`, with a drift gate): the engine returns `now`; the bot
164
+ never computes a date or day name itself, even "just this once"; relative
165
+ words are allowed **only** when derived from a `now` received **in this
166
+ turn**; with no engine call this turn, call the cheap read action before
167
+ mentioning any date — *even in small talk*. The football space reaches the
168
+ same place through the `timezone` pref (`TZ=Asia/Jerusalem date` before any
169
+ stated time). Pick one source of time, state the rule once, and put it in a
170
+ shared file if more than one profile uses it.
171
+
172
+ ### 4.4 Overriding the platform text — in words
173
+
174
+ Layer 2 of the system prompt is unconditional (`behavior-layers.md` §1). If
175
+ your persona disagrees with any of these, say so explicitly, naming the rule
176
+ you override — the platform text itself says a more specific rule does not
177
+ win by being specific:
178
+
179
+ - *Moderation* — "warn first, then mute". A banter group: "Cursing and mutual
180
+ mockery between friends are the normal language here; intervene only for
181
+ targeted harassment, spam, or attempts to extract secrets. The general
182
+ warn-then-mute guidance does not apply to banter."
183
+ - *Presenting tool results* — "simple lists, never commands/JSON". A
184
+ reporter who must not answer in lists: say so; a profile whose users *are*
185
+ developers: say the opposite.
186
+ - *Character → "set a preference"* — a standing instruction from a member
187
+ becomes "only an admin can set that", which in a friends' group reads as
188
+ refusing a joke. Say what the bot does with a standing request from a
189
+ member (relay, decline in one line, or treat as banter).
190
+ - *"Be concise"*, *"Ask for clarification"* from the pi preamble and the
191
+ default global `AGENTS.md` — a reporter that must give a full factual
192
+ answer, or a bot that must not ask before acting, says so.
193
+
194
+ Until [`one-voice-per-space`](backlog/one-voice-per-space.md) lands, also
195
+ check the **global** `AGENTS.md` of the deployment: a space profile does not
196
+ replace it, and `mercury init`'s template says "helpful AI assistant… ask
197
+ before acting".
198
+
199
+ ### 4.5 Contradictions inside the file
200
+
201
+ The football audit found five pairs of sections in one `AGENTS.md` that were
202
+ each right and jointly ambiguous ("a factual question gets a full answer" vs
203
+ "in chat: one or two lines"; "a joke gets a joke" vs "a member's request is
204
+ relayed to the admin"). When two sections can both apply, add the tie-break
205
+ in the file — the football profile now has a `## עדיפויות` section planned
206
+ for exactly this. Test: take each user-visible failure you have seen and ask
207
+ which section the model should have followed; if two qualify, write the
208
+ rule that picks.
209
+
210
+ ### 4.6 Distil QA into the file
211
+
212
+ The barber `AGENTS.md` has sections literally titled "phrasing and behaviour
213
+ (from the QA round)" and "style (distilled from QA)". Each bullet is one
214
+ failure turned into a rule with the exact wording to use. That is how a
215
+ profile improves: a fixture fails → one sentence in the file → the fixture
216
+ passes. Keep the sentences, drop the narrative.
217
+
218
+ ---
219
+
220
+ ## 5. Accuracy: put the computation in code
221
+
222
+ The pattern that makes the barber and copywriter profiles accurate is not a
223
+ better prompt; it is that **nothing with a number in it is computed by the
224
+ model**:
225
+
226
+ - The engine returns `now` (date, time, day name, calendar of the next days
227
+ with open/closed flags, business name, owner phone, services with prices);
228
+ the prompt relays fields verbatim.
229
+ - Slots, bookings, cancellations, ownership, rate limits, no-show blocks,
230
+ handoff messages — engine actions with explicit status codes; the prompt
231
+ maps each code to one customer sentence.
232
+ - Proposals: the document is a stored record, rendered by a template;
233
+ "every correction is a patch op, totals are computed in the engine and
234
+ never stored, never quote a price from memory — `get` it".
235
+ - Puzzles: "the engine builds the board, not you"; the model only writes
236
+ clues.
237
+
238
+ The rule of thumb: **if the model can get it wrong and a user can notice,
239
+ move it into a capability.** `docs/authoring-profiles.md` is the contract;
240
+ `tagula-agent-profiles/appointment-engine` is the reference implementation
241
+ (tested engine package + thin extension wrapper + `now` block on every
242
+ reply).
243
+
244
+ Where there is no engine (a news reporter), the equivalents are:
245
+
246
+ - a live fetch per fact, cited by name and date, from an allow-list of
247
+ sources, with a certainty scale that is set by the *source's* wording;
248
+ - a freshness window — items without a date, or outside the window, are
249
+ dropped, not hedged;
250
+ - a written record of what was already reported (`push-log.md`, the
251
+ notebook) read before posting, so the same item is not re-reported and the
252
+ bot's own earlier statements are available outside the history window;
253
+ - silence as a first-class output (`NO_UPDATE` for scheduled runs — a
254
+ positive instruction a model follows; "emit nothing" is not).
255
+
256
+ And the honest fallback, in the global character and every profile: *"If you
257
+ are not sure, say so instead of guessing. Never say you searched, read or
258
+ changed anything unless you just ran the tool that does it."*
259
+
260
+ ---
261
+
262
+ ## 6. Memory: design it, do not hope for it
263
+
264
+ What the runtime gives you for free (verified, `behavior-layers.md` §5):
265
+ `MEMORY.md` injected verbatim every run; `knowledge/episodes/*.md` injected
266
+ when their `keywords` overlap the message; `knowledge/members/<id>.md`
267
+ injected every run; preferences every run; `mrctl recall` for substring
268
+ search over the whole history. The napkin extension additionally runs a
269
+ daily distillation that writes `knowledge/{people,projects,references,daily}`
270
+ — **none of which is injected**; the agent reads them only when told to.
271
+
272
+ What that means for a profile:
273
+
274
+ 1. **Decide what the bot must remember**, by class: its own past statements
275
+ (what it reported, with source and date), standing facts about the domain
276
+ (the current squad, the client list), and per-person context (member
277
+ notes). Give each a file and a routine.
278
+ 2. **`MEMORY.md` is the always-on page.** Seed it from the profile (a space
279
+ profile's `workspace_seed`, M2.3) with the structure you want, keep it
280
+ short (~1500 tokens is the guidance; nothing enforces it), and give the
281
+ bot an explicit rule for when to update it. The three DM spaces on the
282
+ live bot that have one use it; the football space, which needed it most,
283
+ never had one.
284
+ 3. **Episodes need keywords that will recur.** An episode about "Abu Fani's
285
+ transfer" with `keywords: ["אבו פאני","hapoel","transfer"]` surfaces on
286
+ the next message containing one of those words; without keywords it never
287
+ surfaces. Prefer a notebook the bot reads by rule over relying on scoring.
288
+ 4. **Do not let distillation stand in for a notebook.** On the live bot
289
+ napkin distils every space daily and has written *zero* entity files for
290
+ the football space — group banter does not meet its "lasting signal"
291
+ bar. A reporter's facts need a reporter's routine: "before answering a
292
+ factual question, read `knowledge/notebook/<topic>.md`; after research,
293
+ write the current view with `(source, dd/mm)`; never contradict the
294
+ notebook without saying what changed."
295
+ 5. **Business state is not memory.** Bookings, article status, proposals live
296
+ in the engine. "The tracker is the source of truth — never answer 'what is
297
+ the status?' from memory."
298
+ 6. **Size the history window to the space.** `context.mode` defaults to
299
+ `clear` for a hand-created space; `context.window_size` counts user turns
300
+ and scheduled runs are user turns. A space with several scheduled runs a
301
+ day loses its own chat within hours — which is how the football bot
302
+ contradicted its own lineup. Until `chat-window-and-silence` (M2.5)
303
+ excludes scheduler rows, size the window for the scheduled volume, and
304
+ never rely on the window for anything older than the current exchange.
305
+
306
+ ---
307
+
308
+ ## 7. Skills
309
+
310
+ Discovery is two roots and a description; use is a rule in `AGENTS.md`. The
311
+ full treatment is [`skills-guide.md`](skills-guide.md); the profile-level
312
+ rules are:
313
+
314
+ - Every skill the profile depends on is **named in `AGENTS.md`** with the
315
+ situation and the first command; the full `SKILL.md` is pointed to by path
316
+ ("read it before the first proposal").
317
+ - A space-local skill lives under `.mercury/spaces/<space>/.pi/skills/<name>/`
318
+ — nowhere else is scanned. An extension skill ships with the extension.
319
+ - When the host can do the work, prefer a **marker the host expands**
320
+ (`[feed-watch:digest]`) over a skill the model must remember to run.
321
+ - Verify use with a trace (`agent.trace_runs`), not with a correct answer.
322
+
323
+ ---
324
+
325
+ ## 8. Scheduled tasks
326
+
327
+ - A task runs with the **same prompt stack as chat** (global + space
328
+ `AGENTS.md`, character, preferences, memory) plus its prompt as the user
329
+ message, **as the caller who created it** (`createdBy` → role and
330
+ permissions). Create production tasks from chat as a named admin; a task
331
+ created by a non-user principal (`dashboard`, `space-profile`) runs as a
332
+ phantom member (`docs/bugs/feed-watch-runas-non-user-principal.md`).
333
+ - Task prompt = procedure only (see §3). Put the schedule in the cron, the
334
+ artefact in the prompt, the rules in `AGENTS.md`.
335
+ - Quiet runs: ask for `NO_UPDATE` as the entire reply; the send path drops
336
+ it and a list of bare acknowledgements (`src/core/task-output.ts`). An
337
+ empty reply becomes `"Done."` — a placeholder the prompt cannot prevent,
338
+ so never ask for "nothing".
339
+ - Failures are announced to the space after retries, `silent` or not
340
+ (`scheduling.notify_on_failure`). A profile that opens many one-shots a
341
+ day multiplies that surface; decide the policy.
342
+ - A space profile owns task prompts **by live id** (`tasks: - id: 24`);
343
+ `apply` refuses an id that belongs to another space. Record the id and the
344
+ cron in the README; `check` reports a deleted row as drift.
345
+ - Restarting the service kills in-flight runs and loses the retry — check
346
+ the crons before a restart.
347
+
348
+ ---
349
+
350
+ ## 9. Permissions
351
+
352
+ - Default `member`: `prompt, prefs.get, media.receive, media.send,
353
+ model.list`. `admin`: everything. `system`: scheduler/internal only.
354
+ - An applicative profile's `member_permissions` **replaces** the member set
355
+ (exhaustive); add the profile's own capability name, never the raw one
356
+ (`gws`). `roles.grant` in that list makes a member an owner.
357
+ - In a space, `role.member.permissions` is the override. Audit it against
358
+ the room: members of a friends' group with `tasks.delete` are one
359
+ `mrctl tasks delete 24` from removing the daily article; without
360
+ `prefs.set` every "from now on…" from a member becomes "the admin must
361
+ approve".
362
+ - Capability name = permission name = the entry in `member_permissions`;
363
+ the broker route checks it, the bash guard checks the CLI, and
364
+ `mercury.env` only injects the credential for callers who hold it.
365
+ - Ownership is `req.callerId` (token-derived), never an id in the body.
366
+ - `resolveRole` upserts any unknown caller id as a member — do not let a
367
+ non-user string reach a caller column.
368
+
369
+ ---
370
+
371
+ ## 10. Packaging and deploy
372
+
373
+ **Space profile** (`examples/profiles/_template/`):
374
+
375
+ ```
376
+ examples/profiles/<name>/
377
+ config.yaml space, agents_md, tasks (by id), remove_preferences,
378
+ extension_config (quoted strings), workspace_remove
379
+ AGENTS.md
380
+ tasks/<task>.md
381
+ README.md the layer map, the task ids and crons, the ops order
382
+ ```
383
+
384
+ Ops order (football README): `dump` → `backup` (VACUUM INTO, refuses to
385
+ overwrite) → `apply --dry-run` → `apply` → `check` → watch the next
386
+ scheduled run. `apply` is idempotent and ends with `check`. Never edit the
387
+ live `AGENTS.md` or a task row by hand — `check` calls it drift and the next
388
+ `apply` overwrites it.
389
+
390
+ **Applicative profile** (`tagula` layout, `docs/authoring-profiles.md` §4):
391
+
392
+ ```
393
+ <profile>/
394
+ mercury-profile.yaml name, agents_md, capabilities, extensions, member_permissions, env, defaults
395
+ AGENTS.md
396
+ extensions/<cap>/index.ts thin wrapper: mercury.permission({defaultRoles: []}) + mercury.capability(...)
397
+ config.example.json the business config the env var points at
398
+ README.md install steps, the permission table, the runtime settings
399
+ deploy.sh packages + uploads + `mercury profiles apply`
400
+ tests/ runbook + fixtures
401
+ ```
402
+
403
+ Lessons from four deployments of this shape:
404
+
405
+ - **Typecheck the extension against the deployed layout, not the source
406
+ tree.** Mercury copies only the extension dir; a deep relative import into
407
+ a sibling engine compiles locally and fails on the box. tagula's
408
+ `check-extensions.sh` stages the deployed layout and runs `tsc` there, and
409
+ derives its profile list from disk so the gate cannot silently shrink.
410
+ - **Never put a non-extension package under `.mercury/extensions/`** —
411
+ everything there is auto-loaded and must export a setup function.
412
+ - Files destined for Linux are LF (`.gitattributes`); a CRLF shebang breaks
413
+ `scp`'d scripts.
414
+ - **Verify on the box, inside the artefact**: grep the installed extension
415
+ copy under `.mercury/extensions/<name>/`, the skill under
416
+ `.mercury/global/skills/<name>/`, the image for baked files — never the
417
+ repo or `package.json`.
418
+ - A 403 from the capability route used to be silent; if the bot says
419
+ "technical error" with no host log, make it report the raw error once.
420
+
421
+ ---
422
+
423
+ ## 11. Testing a profile
424
+
425
+ 1. **Fixtures before prose.** For every rule that matters, one message →
426
+ expected properties of the reply (≤ N lines, contains the source, does not
427
+ contain "Done", no list). The barber profile keeps `tests/` with a
428
+ runbook and `test-full.sh`; the football goal has
429
+ `football-reporter-fixture-harness` planned. Probe callers must be
430
+ dedicated — probes spend the same per-caller daily budget as the test.
431
+ 2. **Trace the runs you are tuning** (`agent.trace_runs: true`, image
432
+ rebuild, bounded window). A trace answers "which sources did it open, did
433
+ it read the skill, where did the time go"; a reply does not.
434
+ 3. **Drift-check after every deploy** (`space-profile check`,
435
+ `compose-grounding.sh check`, `check-extensions.sh`). A gate whose
436
+ coverage is a hand-maintained list will shrink; derive it from disk.
437
+ 4. **Read the rendered output the way the user does** — on a phone, in the
438
+ group, right-to-left. A mirrored RTL grid and a three-paragraph "short"
439
+ answer both pass every structural test.
440
+ 5. **Test against the production identity variant** (LID-keyed WhatsApp DMs,
441
+ not phone-keyed fixtures) and on a clean box (no prior state, fresh
442
+ restart).
443
+ 6. **Before calling it done**, the manual check is in
444
+ `docs/pending-verification.md` and the change has run on the live bot.
445
+
446
+ ---
447
+
448
+ ## 12. Anti-patterns (each one has happened)
449
+
450
+ | Anti-pattern | What it did | Do instead |
451
+ |---|---|---|
452
+ | The same rule in a preference and in `AGENTS.md` | the two disagreed about silence; the pref lost on tone | one layer; `remove_preferences` on move |
453
+ | Task prompt carrying editorial rules | rules drifted between the two task prompts and the file | procedure only; "never repeats a rule written in `AGENTS.md`" as line one |
454
+ | "Be accurate" / "compute carefully" | the model computed the day name and got it wrong | engine `now`; forbid computing "even once" |
455
+ | Trusting the history window for the bot's own earlier facts | lineup contradicted two hours later | notebook / push-log read by rule |
456
+ | Relying on distillation for domain memory | zero entity files after two weeks in the space that needed them | a seeded `MEMORY.md` and a notebook routine |
457
+ | Hoping a specific rule beats the platform paragraph | "set a preference" → "the admin must approve" in reply to a joke | override in words; name the paragraph |
458
+ | Asking the model to emit nothing | `"Done."` reached the group | `NO_UPDATE` sentinel; host drops it |
459
+ | Granting `tasks.delete`/`prefs.set` by copying a DM space's permission row | group members could delete the daily article | audit `role.member.permissions` per room |
460
+ | Enabling an extension switch from a surface that stamps a non-user principal | verify runs as a phantom member | enable from chat as a named admin (until the fix lands) |
461
+ | Letting an engine error say "try another seed" | a 20-minute retry loop in front of the customer | transient vs structural errors; retry budget in the skill |
462
+ | A self-check threshold taken from the median | the agent would regenerate every board | thresholds from the measured low end; report, don't gate |
463
+ | Blanket-`cp` of a skill over its deployed copy | `{SPACE}` placeholders reverted; commands broke silently | copy → substitute → diff |
464
+ | Verifying a deploy against the repo | fixes "deployed" that were never built into the image | grep the image / the installed copy |
465
+ | A restart to deploy `container-entry.ts` changes | tracing silently did nothing | image rebuild, then verify in the image |
466
+
467
+ ---
468
+
469
+ ## 13. Checklist
470
+
471
+ - [ ] Kind chosen (applicative vs space) and the layer map written in the README.
472
+ - [ ] Facts inventory done; every fact has a source of truth; every "no answer" has its sentence.
473
+ - [ ] No computation in prose — dates, totals, availability, identity come from a tool.
474
+ - [ ] `AGENTS.md` follows the skeleton; rules are testable; QA findings are distilled into it.
475
+ - [ ] Explicit overrides of the platform paragraphs the persona disagrees with; global `AGENTS.md` checked.
476
+ - [ ] Tie-breaks written for sections that can both apply.
477
+ - [ ] Memory designed: `MEMORY.md` seeded; notebook / log routine named; episodes with keywords if used; window sized.
478
+ - [ ] Every skill named in `AGENTS.md` with situation + first command; skills under a scanned root.
479
+ - [ ] Task prompts are procedure only; `NO_UPDATE` for quiet runs; created by a named admin; ids and crons in the README.
480
+ - [ ] Permissions audited against the room; `member_permissions` exhaustive and raw capabilities absent.
481
+ - [ ] Extension config owned by the profile where a hand edit would matter; the `enabled`-style switch deliberately not.
482
+ - [ ] Fixtures exist for the rules that matter; a traced run shows the tools/skills being used.
483
+ - [ ] Deployed and verified inside the artefact; `check` clean; the change has run on the live bot.
File without changes
File without changes
File without changes
File without changes