mercury-agent 0.24.4-beta.1 → 0.24.4-beta.3

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 (74) hide show
  1. package/docs/configuration.md +10 -2
  2. package/docs/extensions.md +11 -0
  3. package/docs/goals/rehearsal-bench/roadmap.md +1 -1
  4. package/docs/goals/release-gate/decisions.md +81 -0
  5. package/docs/goals/release-gate/goal.md +2 -2
  6. package/docs/goals/release-gate/roadmap.md +6 -5
  7. package/docs/live-testing.md +75 -10
  8. package/docs/pending-verification.md +22 -5
  9. package/docs/permissions.md +12 -0
  10. package/docs/release-gate.md +7 -7
  11. package/docs/web-search.md +4 -4
  12. package/examples/extensions/web-search/capability.ts +5 -1
  13. package/examples/extensions/web-search/chain.ts +3 -2
  14. package/examples/extensions/web-search/index.ts +15 -0
  15. package/examples/extensions/web-search/providers/index.ts +7 -1
  16. package/examples/extensions/web-search/providers/linkup.ts +203 -0
  17. package/examples/extensions/web-search/providers/types.ts +7 -1
  18. package/examples/extensions/web-search/skill/SKILL.md +3 -3
  19. package/package.json +2 -2
  20. package/resources/skills/problem-report/SKILL.md +53 -0
  21. package/resources/skills/tasks/SKILL.md +11 -0
  22. package/src/agent/container-entry.ts +28 -9
  23. package/src/agent/container-error.ts +43 -0
  24. package/src/agent/container-runner.ts +6 -2
  25. package/src/agent/image-content.ts +278 -0
  26. package/src/agent/pi-failure-class.ts +19 -0
  27. package/src/agent/pi-jsonl-parser.ts +68 -0
  28. package/src/agent/provider-auth-rejection.ts +23 -3
  29. package/src/agent/user-error-messages.ts +63 -1
  30. package/src/audit/ledger-queries.ts +3 -0
  31. package/src/cli/mercury.ts +568 -84
  32. package/src/cli/mrctl-http.ts +20 -0
  33. package/src/cli/mrctl.ts +11 -0
  34. package/src/cli/run-capture.ts +51 -0
  35. package/src/cli/shadow-rehearse-cli.ts +252 -0
  36. package/src/cli/unit-working-directory.ts +138 -0
  37. package/src/cli/upgrade.ts +4 -21
  38. package/src/core/api.ts +2 -0
  39. package/src/core/commands.ts +30 -1
  40. package/src/core/direct-send.ts +17 -0
  41. package/src/core/handler.ts +43 -3
  42. package/src/core/operator-alerts.ts +265 -70
  43. package/src/core/problem-report.ts +757 -0
  44. package/src/core/profiles.ts +14 -1
  45. package/src/core/router.ts +74 -6
  46. package/src/core/routes/console.ts +17 -2
  47. package/src/core/routes/dashboard.ts +5 -1
  48. package/src/core/routes/index.ts +1 -0
  49. package/src/core/routes/problem.ts +120 -0
  50. package/src/core/routes/spaces.ts +10 -2
  51. package/src/core/runtime.ts +251 -12
  52. package/src/core/space-delete.ts +71 -6
  53. package/src/core/storage-cleanup.ts +14 -0
  54. package/src/core/system-messages.ts +75 -1
  55. package/src/core/task-output.ts +100 -3
  56. package/src/core/web-access-failures.ts +1 -1
  57. package/src/extensions/extension-name.ts +49 -0
  58. package/src/extensions/hooks.ts +10 -2
  59. package/src/extensions/installer.ts +48 -28
  60. package/src/extensions/loader.ts +15 -31
  61. package/src/extensions/reserved.ts +1 -0
  62. package/src/extensions/types.ts +27 -0
  63. package/src/main.ts +24 -5
  64. package/src/ops/shadow-rehearse-run.ts +596 -0
  65. package/src/ops/shadow-rehearse.ts +540 -0
  66. package/src/ops/shadow-service.ts +256 -25
  67. package/src/ops/shadow-src.ts +667 -0
  68. package/src/preflight/checks/image-content.ts +208 -0
  69. package/src/preflight/report.ts +3 -0
  70. package/src/preflight/run.ts +25 -0
  71. package/src/server.ts +1 -0
  72. package/src/storage/db.ts +251 -0
  73. package/src/storage/memory.ts +9 -2
  74. package/src/types.ts +6 -1
@@ -24,7 +24,7 @@ These must be supplied via environment variables only; they are **not** read fro
24
24
  - `MERCURY_DISCORD_GATEWAY_SECRET`
25
25
  - `MERCURY_HEARTBEAT_URL` (see [Heartbeat](#heartbeat-mercury_heartbeat_url-mercury_heartbeat_tasks))
26
26
 
27
- Platform tokens, provider API keys, and extension keys (e.g. `MERCURY_TELEGRAM_BOT_TOKEN`, `MERCURY_BRAVE_API_KEY`, `MERCURY_TAVILY_API_KEY`) are also **env-only** today—they are not part of the YAML schema.
27
+ Platform tokens, provider API keys, and extension keys (e.g. `MERCURY_TELEGRAM_BOT_TOKEN`, `MERCURY_BRAVE_API_KEY`, `MERCURY_TAVILY_API_KEY`, `MERCURY_LINKUP_API_KEY`) are also **env-only** today—they are not part of the YAML schema.
28
28
 
29
29
  ## YAML layout
30
30
 
@@ -298,6 +298,14 @@ Env equivalents: **`MERCURY_ALERTS_ENABLED`**, **`MERCURY_ALERTS_COOLDOWN_MS`**,
298
298
  is told once, through the space. With nothing reachable the alert has nowhere
299
299
  to go — Mercury logs that fact at ERROR and leaves the cooldown unclaimed, so
300
300
  the next failure tries again.
301
+ - **Client problem reports.** The same recipients receive the card for every
302
+ `/problem` (alias `/בעיה`) a client sends, with the client's own description
303
+ of the problem, the space name and the caller's role (never a phone number or
304
+ name). `alerts.enabled: false` does not stop these cards: a report is the
305
+ client's request to reach the team, not an operator alert. The reporting
306
+ space is never sent its own card. A recipient space that also holds people
307
+ who are not staff therefore sees every client's description too (open bug
308
+ `alert-recipient-space-receives-every-spaces-client-identifiers`).
301
309
  - **Startup check.** At boot Mercury logs `Operator alerts will reach no one: …`
302
310
  at ERROR when no configured admin or recipient resolves to a deliverable
303
311
  conversation, so the gap shows up before the first outage rather than during it.
@@ -570,7 +578,7 @@ agent:
570
578
  ```
571
579
 
572
580
  - **`claimed`** (default) — only variables an extension declared via `mercury.env()` are passed, and only when the triggering caller holds that extension's permission. Undeclared variables stay on the host.
573
- - **`all`** — every `MERCURY_*` var except a fixed blocklist is passed into the container with the prefix stripped (`MERCURY_BILLING_API_KEY` → `BILLING_API_KEY`). Convenient, but blunt: a secret added to `.env` for one purpose reaches **every space's container**, regardless of who triggered the turn or whether that space has anything to do with it. Vars an extension declares `hostOnly` are excluded even here — `MERCURY_BRAVE_API_KEY` and `MERCURY_TAVILY_API_KEY` stay on the host once `web-search` is installed, which brokers search queries through `mrctl capability web-search` (see `docs/web-search.md` for the provider chain and its `web-search.providers`, `monthly_budget` and `tavily_monthly_budget` keys).
581
+ - **`all`** — every `MERCURY_*` var except a fixed blocklist is passed into the container with the prefix stripped (`MERCURY_BILLING_API_KEY` → `BILLING_API_KEY`). Convenient, but blunt: a secret added to `.env` for one purpose reaches **every space's container**, regardless of who triggered the turn or whether that space has anything to do with it. Vars an extension declares `hostOnly` are excluded even here — `MERCURY_BRAVE_API_KEY`, `MERCURY_TAVILY_API_KEY` and `MERCURY_LINKUP_API_KEY` stay on the host once `web-search` is installed, which brokers search queries through `mrctl capability web-search` (see `docs/web-search.md` for the provider chain and its `web-search.providers`, `monthly_budget`, `tavily_monthly_budget` and `linkup_monthly_budget` keys).
574
582
 
575
583
  **Model-provider credentials are exempt** and pass in both modes (`MERCURY_ANTHROPIC_API_KEY`, `MERCURY_ANTHROPIC_OAUTH_TOKEN`, `MERCURY_GEMINI_API_KEY`, `MERCURY_GROQ_API_KEY`, and the rest of the provider list). pi reads them inside the container, and no extension declares them — without the exemption, `claimed` would leave the agent unable to reach any model. They remain subject to the blocklist.
576
584
 
@@ -167,6 +167,17 @@ mercury.on("workspace_init", async (event, ctx) => {
167
167
  | `before_container` | About to spawn container | Yes |
168
168
  | `after_container` | Container finished | Yes |
169
169
  | `delivery` | Reply stored, attachments final | No |
170
+ | `space_deleted` | A space's rows and workspace directory are gone | No |
171
+
172
+ `space_deleted` carries `spaceId`, `workspace` (the path it lived at),
173
+ `workspaceRemoved` (false when the directory could not be deleted), `source`
174
+ (`chat` | `api` | `console` | `cli`) and `callerId` (null for the console).
175
+ It is emitted once, from `deleteSpaceEverywhere`, after the delete — so it is
176
+ the place to undo what your extension created for the space *outside* its rows
177
+ and directory (a box-level timer, a remote copy). It is fire-and-forget: the
178
+ delete's reply does not wait for it, and a handler cannot undo or fail the
179
+ delete, so log what you did. The `mercury spaces delete` CLI loads no
180
+ extensions and therefore emits nothing; it prints a note saying so.
170
181
 
171
182
  Both `workspace_init` and `before_container` events include:
172
183
  - `workspace` — absolute host path (for file operations on the host)
@@ -89,7 +89,7 @@ F5 debug doc as the closing evidence.
89
89
 
90
90
  | ID | Story | Slug | Depends on | Status |
91
91
  |----|-------|------|------------|--------|
92
- | M3.1 | `shadow up --src ~/mercury-check/<slug>`: run the shadow from a check mirror; `/f-bug-fix` and `/f-feature-dev` gain a "Rehearse" step (after the check gate, before deploy) that records the `shadow say` transcript or `shadow diff` in the doc | shadow-from-worktree | M1.3 | backlog |
92
+ | M3.1 | `shadow up --src ~/mercury-check/<slug>`: run the shadow from a check mirror; `/f-bug-fix` and `/f-feature-dev` gain a "Rehearse" step (after the check gate, before deploy) that records the `shadow say` transcript or `shadow diff` in the doc | shadow-from-worktree | M1.3 | **landed 2026-10-19** as `1fe47951` (reconciled from `release-gate`'s continue session) — [spec](../../archive/2026-10-19-shadow-from-worktree.md); the Rehearse step inside `/f-*` went to the boilerplate idea `rehearse-step-in-fix-and-feature-dev`; six box checks are MANUAL-VERIFY lines |
93
93
  | M3.2 | `space-profile apply --rehearse`: snapshot → apply to shadow → diff → **run the space's smoke fixtures through the seam** (added 2026-09-03: a diff shows *what* changed, only a turn shows whether the bot can still do its job — the 08-23 instruction file was one visible line and a total refusal) → print, and refuse the live apply when the diff touches a row whose `updated_by` is a platform user unless `--i-know` names the key (the D3 fix of `space-profile-apply-silently-reverts-admin-config-edits` shares this seam). **The same `--rehearse` contract is exposed as a library call** so tagula's `deploy.sh` / space-sync — the path that actually deployed the 08-23 bug — can call it (`fleet-release-gate`) | profile-apply-rehearse | M1.4, release-gate R3 | backlog |
94
94
  | ~~M3.3~~ | ~~`~/sync-mercury.sh --rehearse`~~ — **moved 2026-09-03** to [`release-gate` R5](../release-gate/roadmap.md): it is a *caller* of the gate (preflight + smoke against a shadow from the mirror), the same shape as the fleet updater and cloud-init, and belongs with them | sync-rehearse | — | moved |
95
95
 
@@ -314,3 +314,84 @@
314
314
  story doc).
315
315
  - **Used by:** gate-regression-map (R3.3), every `/f-bug-fix` archive step
316
316
  from here on
317
+
318
+ ## G-012: The rehearsal is a Mercury command; `~/sync-mercury.sh` is a thin caller
319
+ - **Category:** architecture
320
+ - **Decided:** 2026-10-19, `/f-goal release-gate` continue session (R5.1
321
+ planning), owner approved the R5 plan.
322
+ - **What:** R5.1 ships `mercury shadow rehearse --src <tree> [--json]` in
323
+ `src/` — snapshot, `shadow up`, full `preflight` against the shadow, `down`,
324
+ `smoke` for every space with fixtures, `shadow diff`, one
325
+ `rehearsal.json` with a verdict and exit 0 / 1 / 2. `~/sync-mercury.sh`
326
+ only calls it, reads the report, and asks before the live restart.
327
+ - **Alternatives considered:** writing the sequence in bash inside
328
+ `~/sync-mercury.sh` (the row's wording) — that script is in no repository,
329
+ so the logic would be untested, outside both lint and typecheck (the
330
+ half-perimeter gotcha), and invisible to the fleet, which needs the same
331
+ "preflight then smoke in a shadow of the new version"
332
+ (`fleet-release-gate`); a `scripts/sync-rehearse.ts` — tested, but not a
333
+ command the fleet's callers can reach on an npm install.
334
+ - **Reasoning:** goal constraint "one implementation, many callers". The
335
+ orchestrator runs from the **deployed** mirror's code (the trusted version),
336
+ while each inner check runs the **candidate's** code from its staged copy —
337
+ a broken rehearse in the candidate cannot green-light itself.
338
+ - **Revisit if:** the fleet's updater needs a different step order; then the
339
+ steps become options, not a second orchestrator.
340
+ - **Used by:** sync-rehearse (R5.1), `fleet-release-gate`
341
+
342
+ ## G-013: Rehearse before the mirror moves, from a detached worktree of the target commit
343
+ - **Category:** architecture
344
+ - **Decided:** 2026-10-19 (R5.1 planning). **Corrects the R5.1 row**, which
345
+ said "after the mirror is reset and before the restart".
346
+ - **What:** `~/sync-mercury.sh` fetches, resolves `windows/<branch>` to one
347
+ sha, creates a detached worktree of `~/mercury-src` at that sha in a fixed
348
+ literal path, rehearses it, and only on a green report and a yes resets the
349
+ mirror and restarts. A red or refused rehearsal leaves the mirror untouched.
350
+ - **Alternatives considered:** reset the mirror first and rehearse
351
+ `~/mercury-src` (the row) — the live process keeps running against files
352
+ that changed under it (lazy imports, scripts it spawns, `container/Dockerfile`
353
+ read at the next derived build) and a refusal would need a second hard
354
+ reset back to the old sha; rehearse `~/projects/mercury` directly — it is
355
+ the shared checkout, usually dirty with other sessions' work, and its `HEAD`
356
+ is not necessarily the commit being deployed.
357
+ - **Reasoning:** a rehearsal that changes the live tree before it has passed
358
+ is not a gate — it is the 0.17.0 ordering again. A worktree of the mirror
359
+ keeps `~/projects/mercury`'s worktree list free of deploy plumbing.
360
+ - **Revisit if:** `shadow up --src` stops requiring a git tree.
361
+ - **Used by:** sync-rehearse (R5.1)
362
+
363
+ ## G-014: R5.2 is split — the workflow step is boilerplate code, the gate is a Mercury ratchet
364
+ - **Category:** scope
365
+ - **Decided:** 2026-10-19 (R5 planning), following the owner's 2026-10-19
366
+ decision recorded in `docs/archive/2026-10-19-shadow-from-worktree.md`
367
+ (Out of scope): the Rehearse step in `/f-bug-fix` / `/f-feature-dev` is
368
+ filed in `agentic-project-boilerplate`
369
+ (`pr-idea-rehearse-step-in-fix-and-feature-dev`), not here and not in
370
+ `~/projects/my-workflow`.
371
+ - **What:** R5.2 in this repo is `tests/release-gate-evidence.test.ts`: every
372
+ feature spec archived and every post-mortem dated on or after R5.2's landing
373
+ carries the `docs/release-gate.md` §4 evidence block with its `Classes` and
374
+ `Shadow (Gate 2)` lines filled — a `rehearsal.json` path, or the class
375
+ `docs-only`, or a named refusal from the closed list rehearse emits. The
376
+ class list is read **from §4's fence**, not retyped. The template line, the
377
+ workflow step, and the owner field on `pending-verification.md` entries go
378
+ into the boilerplate idea, because all three are workflow-owned formats that
379
+ a sync wave would overwrite here.
380
+ - **Amended 2026-10-20 (plan review, owner approved):** the evidence a doc
381
+ carries is a **branch** rehearsal (`shadow rehearse --src <worktree>` before
382
+ archiving), because the doc is archived and merged before the sync runs. The
383
+ sync's rehearsal of the merged sha is the gate and logs to the journal. So
384
+ every non-docs fix or feature now needs a box rehearsal before archiving,
385
+ and the owner accepted that cost. Only specs (`**Slug**` + Implementation
386
+ Checklist) and dated `docs/debug/<severity>/` post-mortems are checked;
387
+ summaries and notes under `docs/archive/` are not deploy docs.
388
+ - **Alternatives considered:** editing the vendored `docs/templates/` and
389
+ `.claude/commands/` here — shadowed for this user and overwritten by the
390
+ next sync wave; waiting for the boilerplate to ship before any Mercury gate
391
+ — the rule would stay a sentence (G-004) for as long as that takes.
392
+ - **Reasoning:** the gate must fail in this repo whoever writes the doc — a
393
+ session, the partner, or the owner by hand. The workflow step is what makes
394
+ passing it convenient, not what makes it a gate.
395
+ - **Revisit if:** the boilerplate ships the step with its own archive-time
396
+ check; then the Mercury test stays as the backstop, it is not removed.
397
+ - **Used by:** workflow-gate-step (R5.2), Gate 4 / Gate 12 in `docs/release-gate.md`
@@ -1,9 +1,9 @@
1
1
  # Release Gate — the checks a deploy must pass, and the rules that say every deploy path must call them
2
2
 
3
- **Status**: Active — created 2026-09-03 from the VPS cutover review. **8/16 stories done**: R0.1/R0.2 landed 2026-09-06; R0.3 proven end to end by the v0.20.0 release 2026-09-07; R0.4 shipped 2026-09-06 as its two post-mortems and was reconciled on the roadmap 2026-09-09, with its unbuilt *pin* branch split out as the new R0.6; R1.1 `preflight` is on the box, and R1.2, R2.1 and R2.2 are the R2 half. Next unblocked: **R0.5, R0.6, R3.1, R4.1** (R2 is complete; R3.2 still waits on rehearsal-bench M2.2) · **2026-09-13 (B3): R3.1, R3.2, R3.3 built and gate-green on `worktree-feature-smoke-fixture-format`, landed on `dev` 2026-09-13 by C-B together with B4's R4.1/R0.6/R0.5 — 14/16; the R3 thread is complete (G-010 drops the live leg, G-011 makes the regression map a gate).
3
+ **Status**: Active — created 2026-09-03 from the VPS cutover review. **14/16 stories done** (R0–R4 complete; R3 landed on `dev` 2026-09-13). Remaining: **R5.1 `sync-rehearse`**, unblocked 2026-10-19 by bench M3.1, and **R5.2 `workflow-gate-step`**, after R5.1. Both are planned in `docs/backlog/` (G-012–G-014). Open owner checkpoints: R4 (read `docs/release-gate.md` and strike), and box evidence for R1–R3.
4
4
  **Slug**: release-gate
5
5
  **Created**: 2026-09-03
6
- **Last updated**: 2026-09-09 (R0.4 reconciled and R0.6 split out; R2.2 `env diff` landed, closing R2)
6
+ **Last updated**: 2026-10-19 (continue session: status reconciled, R5 planned)
7
7
 
8
8
  ---
9
9
 
@@ -1,7 +1,7 @@
1
1
  # Roadmap: Release Gate
2
2
 
3
3
  **Goal**: [release-gate](goal.md)
4
- **Last updated**: 2026-09-09 (R0.4 reconciled — done since 2026-09-06, its pin branch split out as R0.6; R2.2 `env diff` landed)
4
+ **Last updated**: 2026-10-20 (**push deferred by the owner, 2026-10-20**: the R5 planning commits `6e97bc4d` and `53056629` are on local `dev` only, and local `dev` is behind `origin/dev`. Push them, from a fresh worktree on `origin/dev`, only when the owner says so. R5 plan **approved by the owner** after a review that folded in five fixes: branch rehearsal as the doc's evidence and the deploy-doc filter (G-014 amended), a pre-restart gap check in the sync, `live-cron-due` / `credential-stale` passthrough and the shared-OAuth-token risk). Earlier, 2026-10-19 (continue session: R3.1 row reconciled — landed 2026-09-13; R5.1 unblocked by bench M3.1 `shadow up --src` (`1fe47951`) and planned as `mercury shadow rehearse` called by `~/sync-mercury.sh` before the mirror moves (G-012, G-013); R5.2 split into a Mercury evidence ratchet plus the boilerplate's workflow step (G-014). Both R5 specs in `docs/backlog/` with architecture. Earlier: 2026-09-09 R0.4 reconciled, R0.6 split out, R2.2 `env diff` landed)
5
5
 
6
6
  > Order is by leverage against the live risk, not by size: R1 protects the
7
7
  > customer box within a session or two and depends on nothing; R2 is the
@@ -97,7 +97,7 @@ evidence, after a grep proves no secret value is in them.
97
97
 
98
98
  | ID | Story | Slug | Depends on | Status |
99
99
  |----|-------|------|------------|--------|
100
- | R3.1 | **Fixture format**: one file per space (`smoke.yaml` under the space's profile or workspace), each fixture = sender role (`member` / `admin` / `owner`), message (text, optional quoted message, optional file), timeout, and assertions on *shape* only: replied-within, not-a-refusal (a small refusal lexicon per language, absence denies), produced-file (kind + non-empty), lint passes (`reporter-lint` where the space has a standard), optional regex on structure. Documented with three worked examples (a DM answer, a group mention, a proposal PDF) | smoke-fixture-format | — | **planned 2026-09-09**, not started — Goal and Architecture in [`docs/backlog/smoke-fixture-format.md`](../../backlog/smoke-fixture-format.md), written by the round's S2 session after R2.2 landed. Four decisions past the row: D-11 YAML validated by a `.strict()` zod schema, so a misspelled assertion key is a **refusal** rather than a fixture that asserts nothing; D-12 resolution is a fixed order (`--fixtures` → the space's workspace → its profile) and the parse result names the file that won, which is what keeps customer fixtures out of this repo (G-006); D-13 the refusal lexicon is per language and **absence denies** — an unknown language fails `not-a-refusal` instead of passing it, and `isRefusal` returns a third case so a caller cannot ignore it; D-14 `lint` delegates to `reporter-lint`'s existing `evaluateReplyCase` shape rather than re-implementing a comparison. Two open questions are the owner's: the lexicon's contents (a false positive there fails a healthy deploy) and whether `produced-file` may name a filename pattern. **Built 2026-09-12 (B3, bench-and-gate round), gate-green on its branch, unlanded at the time of writing** — `src/smoke/fixture.ts` (strict zod, an unknown key names its file and line), `src/smoke/refusal.ts` (`isRefusal` with a third `unknownLanguage` case), three worked examples as real files under `examples/smoke/`, `docs/smoke-fixtures.md`; three deviations the code forced are recorded there (`mentionBot`, `lint.standard` as a space-relative path, examples outside the football profile). Spec: [`docs/archive/2026-09-13-smoke-fixture-format.md`](../../archive/rehearsal/2026-09-13-smoke-fixture-format.md) |
100
+ | R3.1 | **Fixture format**: one file per space (`smoke.yaml` under the space's profile or workspace), each fixture = sender role (`member` / `admin` / `owner`), message (text, optional quoted message, optional file), timeout, and assertions on *shape* only: replied-within, not-a-refusal (a small refusal lexicon per language, absence denies), produced-file (kind + non-empty), lint passes (`reporter-lint` where the space has a standard), optional regex on structure. Documented with three worked examples (a DM answer, a group mention, a proposal PDF) | smoke-fixture-format | — | **landed 2026-09-13** (C-B, with R3.2/R3.3; reconciled 2026-10-19 — the cell below was written before the merge). Was: **planned 2026-09-09** — Goal and Architecture in [`docs/backlog/smoke-fixture-format.md`](../../backlog/smoke-fixture-format.md), written by the round's S2 session after R2.2 landed. Four decisions past the row: D-11 YAML validated by a `.strict()` zod schema, so a misspelled assertion key is a **refusal** rather than a fixture that asserts nothing; D-12 resolution is a fixed order (`--fixtures` → the space's workspace → its profile) and the parse result names the file that won, which is what keeps customer fixtures out of this repo (G-006); D-13 the refusal lexicon is per language and **absence denies** — an unknown language fails `not-a-refusal` instead of passing it, and `isRefusal` returns a third case so a caller cannot ignore it; D-14 `lint` delegates to `reporter-lint`'s existing `evaluateReplyCase` shape rather than re-implementing a comparison. Two open questions are the owner's: the lexicon's contents (a false positive there fails a healthy deploy) and whether `produced-file` may name a filename pattern. **Built 2026-09-12 (B3, bench-and-gate round), gate-green on its branch, unlanded at the time of writing** — `src/smoke/fixture.ts` (strict zod, an unknown key names its file and line), `src/smoke/refusal.ts` (`isRefusal` with a third `unknownLanguage` case), three worked examples as real files under `examples/smoke/`, `docs/smoke-fixtures.md`; three deviations the code forced are recorded there (`mentionBot`, `lint.standard` as a space-relative path, examples outside the football profile). Spec: [`docs/archive/2026-09-13-smoke-fixture-format.md`](../../archive/rehearsal/2026-09-13-smoke-fixture-format.md) |
101
101
  | R3.2 | `mercury smoke --space <id> [--fixtures <file>] [--json]`: runs each fixture through `simulateIngress` (bench M2.2, function half) in the current process — a shadow, or a designated test space on live when the caller says so — as the fixture's role, records `sent[]`, evaluates the assertions, writes a report with per-fixture verdict, transcript, elapsed and cost from `token_usage`. Refuses on live unless the target space is named in config as a test space (absence denies) | smoke-runner | R3.1, rehearsal-bench M2.2 | **built 2026-09-12/13 (B3), gate-green on its branch, unlanded at the time of writing** — `mercury smoke --space <id> [--fixtures] [--profile] [--json] [--report]`, its own process booting a headless shadow (`src/smoke/boot.ts`, a documented twin of `main.ts` — idea `shared-runtime-boot`), one pure evaluation (`src/smoke/evaluate.ts`), the report beside preflight's with cost since the run started, exit 0/1/2. **The live leg and the test-space key are dropped: G-010.** The role is a chosen sender and the run's own read-back is the verdict (owner = first configured admin; absent denies). Live check is shadow-side, deploy 3. Spec: [`docs/archive/2026-09-13-smoke-runner.md`](../../archive/rehearsal/2026-09-13-smoke-runner.md) |
102
102
  | R3.3 | Regression map: `tests/release-gate-map.test.ts` asserts every post-mortem under `docs/debug/**` since 2026-09-01 names a check in `preflight`, `smoke` or `env diff` (by a `Gate check:` line) — the football regression-map pattern applied to the gate | gate-regression-map | R1.1, R3.2 | **built 2026-09-13 (B3), gate-green on its branch** — `tests/release-gate-map.test.ts` + `tests/fixtures/release-gate/regression-map.json` (97 allowlist entries on day one, 14 of them `gate-candidate` naming the check that should own the failure); an allowlisted file that gains a line is refused; G-011. Every post-mortem archived from here on must carry a `Gate check:` line or an entry. Spec: [`docs/archive/release-gate/2026-09-13-gate-regression-map.md`](../../archive/release-gate/2026-09-13-gate-regression-map.md) |
103
103
 
@@ -123,8 +123,8 @@ command or strikes the rule; no rule survives without a command.
123
123
 
124
124
  | ID | Story | Slug | Depends on | Status |
125
125
  |----|-------|------|------------|--------|
126
- | R5.1 | `~/sync-mercury.sh --rehearse` (ex rehearsal-bench M3.3): after the mirror is reset and before the restart, `shadow up --src <mirror>`, `preflight`, `smoke` for the spaces that have fixtures, print cost and `shadow diff`, ask before restarting live; `--rehearse` becomes the default and `--no-rehearse` must name a reason that lands in the journal | sync-rehearse | R1.1, R3.2, rehearsal-bench M1.3 + M3.1 | backlog |
127
- | R5.2 | Workflow wiring: `/f-bug-fix` and `/f-feature-dev` gain a **Gate** step between the check gate and deploy that runs preflight + smoke in the shadow and attaches both reports to the doc; the post-mortem template gains a required `Gate check:` line; `pending-verification.md` entries must carry an owner and a date | workflow-gate-step | R4.1, R5.1 | backlog |
126
+ | R5.1 | `~/sync-mercury.sh --rehearse` (ex rehearsal-bench M3.3): after the mirror is reset and before the restart, `shadow up --src <mirror>`, `preflight`, `smoke` for the spaces that have fixtures, print cost and `shadow diff`, ask before restarting live; `--rehearse` becomes the default and `--no-rehearse` must name a reason that lands in the journal | sync-rehearse | R1.1, R3.2, rehearsal-bench M1.3 + M3.1 | **landed 2026-10-20 (code + docs); box checks wait for the bootstrap deploy.** `mercury shadow rehearse`, the `~/sync-mercury.sh` patch, and fixtures for `main`. Spec: [`docs/archive/2026-10-20-sync-rehearse.md`](../../archive/2026-10-20-sync-rehearse.md). The first box run refused `boot-report-missing`: the deployed `8407fdb6` predates M3.1, so nothing is rehearsable until the bootstrap deploy. Earlier: **backlog, unblocked 2026-10-19** (M3.1 landed as `1fe47951`; its six box checks are still open). Planned in [`docs/backlog/sync-rehearse.md`](../../backlog/sync-rehearse.md), with two corrections to this row: the sequence is a Mercury command, `mercury shadow rehearse --src <tree>` (G-012), and `~/sync-mercury.sh` rehearses a detached worktree of the target sha **before** the mirror moves, not after (G-013). `smoke` refuses while a shadow is up (`src/smoke/boot.ts`), so it runs after `down` from a second staging of the same tree hash. No live space has a `smoke.yaml` yet, so the owner's first fixtures are part of the story (absence denies → `no-fixtures`). Image-baked and dependency changes cannot be rehearsed yet → idea `rehearse-what-the-shadow-refuses` |
127
+ | R5.2 | Workflow wiring: `/f-bug-fix` and `/f-feature-dev` gain a **Gate** step between the check gate and deploy that runs preflight + smoke in the shadow and attaches both reports to the doc; the post-mortem template gains a required `Gate check:` line; `pending-verification.md` entries must carry an owner and a date | workflow-gate-step | R4.1, R5.1 | **backlog — split 2026-10-19 (G-014).** Mercury half planned in [`docs/backlog/workflow-gate-step.md`](../../backlog/workflow-gate-step.md): `tests/release-gate-evidence.test.ts` fails any spec or post-mortem archived after the cutoff without the `release-gate.md` §4 block (class list read from §4, refusal ids from R5.1's `RehearseRefusal`). The `Gate check:` line is already enforced by R3.3. The Gate step, the template block and the owner field are workflow formats and go to the boilerplate idea `rehearse-step-in-fix-and-feature-dev` (local `555f5ad`, unpushed) |
128
128
 
129
129
  **Checkpoint:** one real fix ships through the full path — check gate,
130
130
  shadow, preflight report, smoke report, deploy — and the corresponding
@@ -153,7 +153,8 @@ R1.1 ─┬─ R1.2
153
153
  ├─ R4.1 ─ R5.2
154
154
  └─ R3.3
155
155
  R3.1 ─ R3.2 ─┬─ R3.3
156
- └─ R5.1 ◄─ rehearsal-bench M1.3, M3.1
156
+ └─ R5.1 ◄─ rehearsal-bench M1.3, M3.1 (both done 2026-10-19)
157
+ R5.1 ─ R5.2 (Mercury ratchet) ◄─ boilerplate idea rehearse-step-in-fix-and-feature-dev (workflow half)
157
158
  rehearsal-bench M2.2 (function half) ─► R3.2
158
159
  ```
159
160
 
@@ -65,7 +65,7 @@ What belongs where:
65
65
  | Does the run produce the right reply, files, page? | fixtures (lint) | ✔ real container, page written to a file | ✔ |
66
66
  | Does a scheduled task post the right thing? | ✔ scheduler tests | ✔ trigger in the shadow DB, read the outbox journal | ✔ |
67
67
  | What will `space-profile apply` change? | ✔ `--dry-run` | ✔ apply to the shadow, `shadow diff` | — (rehearse in R2 first, always) |
68
- | Does a fix branch work end-to-end before deploy? | partly | ✔ `shadow up --src ~/mercury-check/<slug>` | — |
68
+ | Does a fix branch work end-to-end before deploy? | partly | ✔ `shadow up --src <worktree>` (§7 "Rehearse a branch") | — |
69
69
  | Does an ops script do what it says? | — | ✔ run it against the shadow tree first | — |
70
70
  | LID↔phone aliasing, the client's own mention JIDs, media from the socket, the offline queue on reconnect, edit/delete round-trips | — | — | ✔ only here |
71
71
  | How does the model actually write for this group? | fixtures | ✔ | ✔ |
@@ -333,22 +333,86 @@ line above every destructive command (archived spec:
333
333
  or when the live bot's containers predate the `mercury.instance` label. It
334
334
  prints **every** refusal, not the first. `--dry-run` runs every check and
335
335
  prints the unit command without starting anything — run it first, always.
336
- `--src` defaults to `~/mercury-src` and also takes a check mirror
337
- (`~/mercury-check/<slug>/`) or the literal `mercury-agent` for a box where
338
- Mercury is an installed package. The unit's `PATH` is the live `mercury`
336
+ `--src` defaults to `~/mercury-src` and takes any git working tree — a
337
+ worktree included — or the literal `mercury-agent` for a box where Mercury
338
+ is an installed package. A tree is never run in place: `up` copies its
339
+ git-visible files (tracked plus untracked-not-ignored, so never `.env*` or
340
+ `node_modules/`) into `~/mercury-shadow/src/<stamp>/` and the unit runs that
341
+ copy, so a later edit, a check run or a `~/sync-mercury.sh` reset cannot
342
+ change the running code. A check mirror (`~/mercury-check/<slug>/`) has no
343
+ `.git` and is refused (`src-not-git`): pass the worktree it mirrors. The
344
+ copy borrows `~/mercury-src/node_modules`, so a branch whose `package.json`
345
+ dependency fields, `bun.lock` or `patches/` differ from `~/mercury-src`'s is
346
+ refused (`src-deps-differ`, naming each). The unit's `PATH` is the live `mercury`
339
347
  unit's own (a Linux base when no unit is running), or `--path <PATH>` —
340
348
  never the shell that typed `up`, which on a WSL box driven from Windows
341
349
  carries the Windows `bun` ahead of the Linux one; the interpreter itself is
342
350
  always the absolute `bun` the CLI is running on.
343
351
  - **A shadow never fetches an image.** It neither pulls the base image nor
344
352
  builds the derived one; a miss is fatal at boot, naming the tag. A rehearsal
345
- runs the image the live bot runs, or it does not run.
353
+ runs the image the live bot runs, or it does not run. And it runs only code
354
+ that image carries: the shadow's boot preflight writes
355
+ `<snapshot>/.mercury/preflight/boot-latest.json`, `up` waits for it after
356
+ `/health`, and when `image.contract` (version, contract paths) or
357
+ `image.content` (every `COPY`'d file, byte for byte, against the staged
358
+ tree) is not `pass` it refuses with `image-drift`, naming each differing
359
+ file — unit stopped, staged copy removed, no run file. A branch that
360
+ changes a baked file cannot be rehearsed here; it is rebuilt and deployed.
346
361
  - **`mercury shadow down`** stops it and prints what the rehearsal cost, from
347
362
  the shadow's own `token_usage` since it started — including zero.
348
363
  **`mercury shadow status`** says whether one is running, from which snapshot
349
- and source commit, and what it has spent so far (exit 3 when stopped, so a
350
- script can branch). **`mercury shadow logs -f`** tails its journal.
351
- `shadow prune` never deletes a snapshot a running shadow claims.
364
+ and source — `src: <worktree> @ <commit8> (dirty|clean) tree <sha12>`, then
365
+ `tree: unchanged since up` or `CHANGED since up` from a re-hash of the staged
366
+ copy — and what it has spent so far (exit 3 when stopped, so a script can
367
+ branch). **`mercury shadow logs -f`** tails its journal. `down` also removes
368
+ the run's staged copy. `shadow prune` never deletes a snapshot a running
369
+ shadow claims, and sweeps staged copies no run file names once they are an
370
+ hour old (none at all while any run file is unreadable).
371
+
372
+ ### Rehearse a branch (M3.1, one command since R5.1)
373
+
374
+ One command, from the live project directory, on a **detached worktree** of
375
+ the candidate commit (a worktree can be edited mid-rehearsal; a detached one
376
+ that only rehearse uses cannot):
377
+
378
+ ```bash
379
+ git -C ~/mercury-src worktree add --detach /home/guysaha/mercury-rehearse <sha>
380
+ cd ~/whatsapp-bot && ~/.bun/bin/bun run ~/mercury-src/src/cli/mercury.ts \
381
+ shadow rehearse --src /home/guysaha/mercury-rehearse [--space <id>]… [--json]
382
+ git -C ~/mercury-src worktree remove /home/guysaha/mercury-rehearse
383
+ ```
384
+
385
+ It runs snapshot → `up --src` → full `preflight` from the staged copy while
386
+ the shadow is up → `down` → `smoke` for every space whose snapshot copy has a
387
+ `smoke.yaml` (or each `--space`), from a second staging hash-checked against
388
+ the first → `shadow diff`. It prints one line per step, the verdict, the cost
389
+ and the report path (`~/mercury-shadow/rehearsal/<timestamp>.json`, plus
390
+ `latest.json`; each child's report and log sit in the matching directory).
391
+ Exit 0 green, 1 red, 2 refused, and the verdict is read from the report.
392
+ `--no-smoke "<reason>"` skips smoke and records why; no fixtures and no reason
393
+ is `no-fixtures`. `--window` (default 30m) is passed to `up`. `~/sync-mercury.sh`
394
+ runs exactly this before it moves the mirror (`docs/release-gate.md` Gate 4).
395
+ Paste the report path into the item's doc as the §4 `Shadow (Gate 2)` line.
396
+
397
+ What it does, as the by-hand procedure (still valid, and what to fall back to
398
+ when one step needs a closer look):
399
+
400
+ 1. **Check gate** on the worktree: `~/check-mercury.sh check '<worktree>'`.
401
+ 2. **Snapshot** from the live project:
402
+ `cd ~/whatsapp-bot && ~/.bun/bin/bun run ~/mercury-src/src/cli/mercury.ts shadow snapshot`.
403
+ 3. **Dry run**: `… shadow up --src <worktree> --dry-run`. Read the `src:` line
404
+ (commit, dirty state, file count), the `extensions:` line (which installed
405
+ extensions the shadow's boot sync refreshes from the branch) and every
406
+ refusal. `src-deps-differ` means deploy the dependency change first.
407
+ 4. **Up**: `… shadow up --src <worktree>`. An `image-drift` refusal means the
408
+ branch changes a file baked into the agent image (or the version): it
409
+ cannot be rehearsed on the live image — stop here.
410
+ 5. **Exercise it**: `mercury smoke`, the simulate route
411
+ (`POST /api/shadow/simulate`), then `shadow diff` for what the rehearsal
412
+ changed.
413
+ 6. **Evidence**: `shadow status` (the `src:` and `tree:` lines), the smoke
414
+ report, the diff verdict — pasted into the item's doc.
415
+ 7. **Down**: `… shadow down` — prints the cost, removes the staged copy.
352
416
  - **Profile migrations:** `space-profile apply --dry-run`, read every line,
353
417
  then `backup`, then `apply`, then `check`. Any key whose live `updated_by`
354
418
  is a platform user is a decision, not a write (bug
@@ -415,7 +479,8 @@ with the shadow's own secret); `mercury shadow say` (M2.3) is the CLI over it.
415
479
  cannot replay yesterday's. Record/replay waits for the egress proxy
416
480
  (`container-egress-unrestricted`).
417
481
  - Image-baked files (`container/Dockerfile` `COPY` list) are not rehearsed
418
- by a `--src` change alone; a base image build under a shadow tag is not in
419
- this goal.
482
+ by a `--src` change alone, and since M3.1 `up` refuses such a branch
483
+ (`image-drift`) instead of passing it; a base image build under a shadow tag
484
+ is not in this goal.
420
485
  - The §2 socket list is R3-only until Baileys behaviour is worth stubbing,
421
486
  which it is not.
@@ -2438,6 +2438,11 @@ Image rebuild (`src/agent/container-entry.ts` is baked), then restart; the host
2438
2438
  - [ ] MANUAL-VERIFY(2026-10-10): On a console box (Tagula), in a space whose Anthropic grant was revoked: send one message. The user should get the "session expired / reconnect" reply, not "Something went wrong", and the operator should get one 🚨 DM naming `MERCURY_ANTHROPIC_OAUTH_TOKEN (console credential blob)`. A second message within the cooldown should send no second DM.
2439
2439
  - [ ] MANUAL-VERIFY(2026-10-10): After reconnecting in the console, the next message should get a normal answer, and a later revoke should alert again without waiting for the cooldown.
2440
2440
 
2441
+ ## Plan tagula-client-1008 / S4 — a run that fails after its tools finish keeps the result (added 2026-10-20, deploy-gated: image rebuild + restart)
2442
+
2443
+ - [ ] MANUAL-VERIFY(2026-10-20): After the rebuild, wait for the derived image's `Built derived agent image` line, then `docker run --rm --entrypoint grep <derived image> -c completedToolResults /app/src/agent/pi-jsonl-parser.ts /app/src/agent/container-entry.ts`. Both files should count at least 1.
2444
+ - [ ] MANUAL-VERIFY(2026-10-20): The next time a DM run fails after a tool finished (journal: `Run failed after its tools had finished`), the user's error message should end with "the last step it completed (…) returned:" and that step's output, and the operator should get one ⚠️ "failed … after its tools had already finished" DM, with no tool output in it. In a group, the message should say the output is not shown.
2445
+
2441
2446
  ## Plan monitoring-1005 / S12
2442
2447
 
2443
2448
  - [ ] MANUAL-VERIFY(2026-10-11): Before re-rendering the unit, copy `~/.config/systemd/user/mercury.service` aside. Re-run `service install` from a script file with the old unit's `PATH` exported. `diff` old and new should show exactly two added lines, `NotifyAccess=all` and `WatchdogSec=120`, and the `PATH` line should be unchanged.
@@ -2524,11 +2529,23 @@ zap extractor reads one-store cards labelled `למפרט טכני` (restart-depl
2524
2529
 
2525
2530
  ## Issue #143 / F19 — dashboard sessions and the failed-secret throttle (added 2026-10-19, deploy-gated: new release + restart)
2526
2531
 
2527
- - [ ] MANUAL-VERIFY(2026-10-19): Open `https://<box>/dashboard/login` in a private window. A password form should appear, not the dashboard. Enter the secret: the dashboard opens, the URL has no `token=`, and the browser's cookie list for the site shows `mercury_token` marked Secure, with a value that is not the secret.
2528
- - [ ] MANUAL-VERIFY(2026-10-19): Click **Sign out** at the top right. You should land on the login form, and reloading `/dashboard` should bring you back to it.
2529
- - [ ] MANUAL-VERIFY(2026-10-19): From a laptop, run `for i in $(seq 11); do curl -s -o /dev/null -w "%{http_code} " -H "Authorization: Bearer wrong" https://<box>/api/spaces; done`. You should see ten `401` then `429`. The journal should show `Secret check refused` lines with your real IP as `clientAddress` (not 127.0.0.1) and one `Failed-secret throttle engaged`. Wait 10 minutes before using the secret from that IP again.
2530
- - [ ] MANUAL-VERIFY(2026-10-19): In the Tagula console, open this box's embedded dashboard. It should load and update live, with no "Assistant login did not return a session" error (the console's `init` login still uses `?token=` and looks for a `mercury_token` cookie).
2532
+ *Verified 2026-10-20 on tagula-assistant (46.225.180.66), installed package `0.24.4-beta.2` (F19 throttle, `space-delete.ts` and `reapHostChildren` grepped in `/usr/lib/node_modules/mercury-agent/src`).*
2533
+
2534
+ - [x] MANUAL-VERIFY(2026-10-19): Open `https://<box>/dashboard/login` in a private window. A password form should appear, not the dashboard. Enter the secret: the dashboard opens, the URL has no `token=`, and the browser's cookie list for the site shows `mercury_token` marked Secure, with a value that is not the secret.
2535
+ *Verified 2026-10-20 by the owner.*
2536
+ - [x] MANUAL-VERIFY(2026-10-19): Click **Sign out** at the top right. You should land on the login form, and reloading `/dashboard` should bring you back to it.
2537
+ *Verified 2026-10-20 by the owner.*
2538
+ - [x] MANUAL-VERIFY(2026-10-19): From a laptop, run `for i in $(seq 11); do curl -s -o /dev/null -w "%{http_code} " -H "Authorization: Bearer wrong" https://<box>/api/spaces; done`. You should see ten `401` then `429`. The journal should show `Secret check refused` lines with your real IP as `clientAddress` (not 127.0.0.1) and one `Failed-secret throttle engaged`. Wait 10 minutes before using the secret from that IP again.
2539
+ *Verified 2026-10-20 23:38 IDT, run from the box through its public hostname (Caddy): ten `401` then `429`; journal `Secret check refused clientAddress=46.225.180.66` and one `Failed-secret throttle engaged ... retryAfterSeconds=600`. Side note: requests made on the box directly to `localhost:8787` carry no X-Forwarded-For and all share the `::1` bucket — local tools only, Caddy traffic is per client.*
2540
+ - [x] MANUAL-VERIFY(2026-10-19): In the Tagula console, open this box's embedded dashboard. It should load and update live, with no "Assistant login did not return a session" error (the console's `init` login still uses `?token=` and looks for a `mercury_token` cookie).
2541
+ *Verified 2026-10-20 by the owner: the embedded dashboard opens. Another console link answered 401; the box journal showed no refused console request at that time, so it is being checked on the tagula-agents side.*
2531
2542
 
2532
2543
  ## Issue #143 / F14 — deleting a space removes all of it (added 2026-10-19, deploy-gated: new release + restart)
2533
2544
 
2534
- - [ ] MANUAL-VERIFY(2026-10-19): Create a throwaway space, link a test group to it, send a message, then delete it from chat with `/spaces delete <id>` and answer `yes`. The reply should say it removed its files. On the box, `ls ~/whatsapp-bot/.mercury/spaces/<id>` should say "No such file", and `sqlite3 ~/whatsapp-bot/.mercury/state.db "SELECT COUNT(*) FROM conversations WHERE observed_title LIKE '%<group name>%'"` should print 0. Adjust the paths if the project lives elsewhere.
2545
+ - [x] MANUAL-VERIFY(2026-10-19): Create a throwaway space, link a test group to it, send a message, then delete it from chat with `/spaces delete <id>` and answer `yes`. The reply should say it removed its files. On the box, `ls ~/whatsapp-bot/.mercury/spaces/<id>` should say "No such file", and `sqlite3 ~/whatsapp-bot/.mercury/state.db "SELECT COUNT(*) FROM conversations WHERE observed_title LIKE '%<group name>%'"` should print 0. Adjust the paths if the project lives elsewhere.
2546
+ *Verified 2026-10-20 on `0.24.4-beta.2` with the stale customer space `meirav-magnezi` (owner-approved delete, not a throwaway): `ls /opt/tagula/assistants/tagula-assistant/.mercury/spaces/meirav-magnezi` → "No such file or directory"; a read-only scan of all 27 `state.db` tables found 0 rows with that `space_id`. Its `mercury-space-backup@` timer and its Drive copy (`rclone copy` never deletes) are outside F14 and still exist.*
2547
+
2548
+ ## Plan tagula-client-1008 / S8 — the "Third-party apps" 400 falls to the next leg and alerts (added 2026-10-20, deploy-gated: image rebuild + restart)
2549
+
2550
+ - [ ] MANUAL-VERIFY(2026-10-20): After the rebuild, `docker run --rm --entrypoint grep mercury-agent:<version> -c isThirdPartyAppRejection /app/src/agent/pi-failure-class.ts` should print a number above 0. Check this in the image itself, never the repo.
2551
+ - [ ] MANUAL-VERIFY(2026-10-20): On a shadow only (never the live bot), set `MERCURY_OVERRIDE_PI_SYSTEM_PROMPT=false` in the shadow's `.env` with an Anthropic OAuth leg first in the chain, and send one message. The Anthropic leg should be tried **once**, then the next leg should answer (or, with a single-leg chain, the reply should be "Something went wrong on my end. This has been logged for the operator.", never "try again"). The operator should get one 🚨 DM that says "third-party app (HTTP 400)" and names `agent.override_pi_system_prompt`, not `claude setup-token`.
@@ -63,6 +63,18 @@ Custom roles can be created by assigning permissions to any role name.
63
63
  | `media.receive` | Incoming attachments are saved to `inbox/` and shown to the agent |
64
64
  | `media.send` | Outbox files produced on this caller's turn are delivered back to the chat |
65
65
 
66
+ `/problem` (alias `/בעיה`) needs no permission: every role may send it, in a
67
+ DM or a group, while the space is paused, and while the caller is muted. It
68
+ sends a report card to the operator recipients (`alerts.recipients`, see
69
+ `docs/configuration.md`) and starts no agent run. A paused space accepts only
70
+ the one-message form, `/problem <what does not work>`.
71
+
72
+ `mrctl problem report "<summary>"` (`POST /api/problem`) also needs no
73
+ permission: the agent files the same report for the person it is talking to,
74
+ from any role's run. Identity is the caller token's (caller, space,
75
+ conversation); the body carries only the summary. A scheduled run, the
76
+ operator credential, and the `system` / `preflight` callers are refused.
77
+
66
78
  ### Media permissions
67
79
 
68
80
  `media.receive` and `media.send` gate the media pipeline per caller role, per space. Both are granted to `member` by default, so behavior is unchanged unless an operator revokes them (e.g. `mrctl permissions set member prompt,prefs.get` — omitting the media names revokes them in that space).
@@ -91,17 +91,17 @@ or the pending-verification line it ticks.
91
91
  | | |
92
92
  |---|---|
93
93
  | **Rule** | The candidate runs as a shadow on the box being upgraded, on a fresh copy of the live data, and passes `preflight` and `smoke` there before the live process is touched. |
94
- | **Command that fails** | From the project directory on the box: `mercury shadow snapshot --dry-run` then `mercury shadow snapshot`; `mercury shadow up --dry-run --src <mirror>` then without `--dry-run` — `up` exits 1 printing **every** `ShadowUpRefusalId` it found (`snapshot-stale`, `port-8787-foreign`, `low-mem`, `low-disk`, `live-container-running`, `live-cron-due`, `src-not-mercury`, …) and a refusal is a wait, never an override; then, in the shadow's project directory (`~/mercury-shadow/current`), `mercury preflight --json` — exit 1 on any `blocked` check; then `mercury smoke --fixtures <file> --space <id> --json` — a `fail` verdict on any fixture (*lands with R3.2*); then `mercury shadow down`. *Same commit*: `mercury shadow status` prints the source commit — it must equal `<candidate>`. *Same image*: the shadow never pulls or builds (`EnsureAgentImageDeps.refusePull`), so its image **is** the live image — which is why an image-class change takes the §1 path instead. |
95
- | **Evidence** | The shadow's `<dataDir>/preflight/latest.json`; the smoke report (R3.2); the `shadow status` line (snapshot, source commit); the `shadow down` cost line. |
94
+ | **Command that fails** | From the project directory on the box, one command: `mercury shadow rehearse --src <detached worktree of the candidate> [--space <id>]… [--json]` (R5.1). It runs the steps below in order, stops at the first that is not a pass, always runs `shadow down` after a successful `up`, and writes `~/mercury-shadow/rehearsal/<timestamp>.json` (+ `latest.json`). Exit 0 green, 1 red (a check ran and failed), 2 refused (could not rehearse: every `ShadowUpRefusalId` by name, plus `snapshot-failed`, `up-failed`, `no-fixtures`, `tree-changed-between-stages`, `step-timeout`, `report-missing`). The verdict is the report's `verdict`, never the exit code alone. The steps it runs, which is also the by-hand procedure: `mercury shadow snapshot --dry-run` then `mercury shadow snapshot`; `mercury shadow up --dry-run --src <mirror>` then without `--dry-run` — `up` exits 1 printing **every** `ShadowUpRefusalId` it found (`snapshot-stale`, `port-8787-foreign`, `low-mem`, `low-disk`, `live-container-running`, `live-cron-due`, `src-not-mercury`, …) and a refusal is a wait, never an override; then, in the shadow's project directory (`~/mercury-shadow/current`), `mercury preflight --json` — exit 1 on any `blocked` check; then `mercury smoke --fixtures <file> --space <id> --json` — a `fail` verdict on any fixture (*lands with R3.2*); then `mercury shadow down`. *Same commit*: `mercury shadow status` prints the source commit — it must equal `<candidate>`. *Same image*: the shadow never pulls or builds (`EnsureAgentImageDeps.refusePull`), so its image **is** the live image — which is why an image-class change takes the §1 path instead. |
95
+ | **Evidence** | The rehearsal report `~/mercury-shadow/rehearsal/<timestamp>.json`, which names the preflight report, each smoke report, the diff JSON and the cost. By hand: the shadow's `<dataDir>/preflight/latest.json`, the smoke report (R3.2), the `shadow status` line (snapshot, source commit), the `shadow down` cost line. |
96
96
  | **Where it goes** | The deploy doc's verification block, as file paths plus the one-line summary of each. |
97
- | **Status** | **in force** for `snapshot`, `up`, `preflight`, `status`, `down`; the `smoke` step **lands with R3.2** |
97
+ | **Status** | **in force**; one command since R5.1 (`shadow rehearse`). An image-class or dependency change cannot be rehearsed (`image-drift`, `src-deps-differ`) and takes the §1 path (`docs/ideas/rehearse-what-the-shadow-refuses.md`). |
98
98
 
99
99
  ### Gate 3 — Verify inside the artifact
100
100
 
101
101
  | | |
102
102
  |---|---|
103
103
  | **Rule** | A deploy is proven by what the running artifact contains — the image, the process, the installed extension copy, the row — never by the repo, the diff, `package.json`, a merge-base or an exit code alone. |
104
- | **Command that fails** | After the restart, from the project directory: `mercury preflight --json` — `image.contract` is `blocked` when the image's recorded version is not the host's or a `COPY`'d file is missing, and the run exits 1; `docker image inspect -f '{{index .Config.Labels "com.mercury.version"}}' <effective image>` must print `mercury --version`; `journalctl --user -u mercury --since '-10m'` must carry `Agent image resolved … imageId=…` naming the expected image, and for a derived-image change `Built derived agent image` (until that line, spawns run on the base image — correct, and still the new code); for an extension change, `grep -c '<marker from the change>' <project>/.mercury/extensions/<name>/<file>` ≥ 1 on the **installed copy**; for a data change, the `SELECT` after. A grep count of 0, a label that is not the host version, or exit 1 fails the gate. |
104
+ | **Command that fails** | After the restart, from the project directory: `mercury preflight --json` — `image.contract` is `blocked` when the image's recorded version is not the host's or a `COPY`'d file is missing, and the run exits 1; `image.content` is `warn` when any `COPY`'d file's bytes differ from this tree's (a restart that deployed nothing baked — `blocked` in a shadow, where `shadow up` refuses on it); `docker image inspect -f '{{index .Config.Labels "com.mercury.version"}}' <effective image>` must print `mercury --version`; `journalctl --user -u mercury --since '-10m'` must carry `Agent image resolved … imageId=…` naming the expected image, and for a derived-image change `Built derived agent image` (until that line, spawns run on the base image — correct, and still the new code); for an extension change, `grep -c '<marker from the change>' <project>/.mercury/extensions/<name>/<file>` ≥ 1 on the **installed copy**; for a data change, the `SELECT` after. A grep count of 0, a label that is not the host version, exit 1, or `image.content` anything but `pass` fails the gate — its `warn` keeps the fleet updater's exit code unchanged, it does not pass this gate. |
105
105
  | **Evidence** | `<dataDir>/preflight/latest.json`; the `Agent image resolved` line; the grep line with its count. |
106
106
  | **Where it goes** | The pending-verification line it ticks, or the deploy doc's verification block. |
107
107
  | **Status** | **in force** |
@@ -111,10 +111,10 @@ or the pending-verification line it ticks.
111
111
  | | |
112
112
  |---|---|
113
113
  | **Rule** | The owner's sync script, `mercury upgrade`, the agent workflows and every fleet path call the same `preflight` / `smoke` binaries (G-001); a path that cannot call them may not restart a live bot. |
114
- | **Command that fails** | `~/sync-mercury.sh --rehearse` refusing to restart without a green shadow run, with `--rehearse` the default and `--no-rehearse <reason>` landing the reason in the journal (**lands with R5.1**); the **Gate** step of `/f-bug-fix` and `/f-feature-dev` refusing to archive without the two reports attached (**lands with R5.2**); `mercury upgrade` pulling the matching image before touching the host and refusing when the tag does not exist (R0.5 — the image half of this gate for a package install; it prints `mercury preflight` as the next step and does not run it, because it runs outside any project directory); the fleet's `tagula-box-upgrade` and cloud-init calling `mercury preflight --json` before declaring success (`fleet-release-gate`). |
114
+ | **Command that fails** | `~/sync-mercury.sh` running `mercury shadow rehearse` on a detached worktree of the target commit **before** the mirror moves, and refusing to reset or restart unless the report's verdict is `green`. Rehearsing is the default; `--no-rehearse "<reason>"` refuses an empty reason and writes `no-rehearse <sha>: <reason>` to the journal (`journalctl --user -t mercury-sync`). Every rehearsal writes `rehearsal <sha>: <verdict> <report path>` there. No TTY and no `--yes` stops after the rehearsal. Right before the reset it refuses `live-not-quiet` on a running agent container, a `pi` process, or a live task due within 5 minutes, and `--no-rehearse` does not skip that check (Gate 9) (**R5.1, landed**); the **Gate** step of `/f-bug-fix` and `/f-feature-dev` refusing to archive without the two reports attached (**lands with R5.2**); `mercury upgrade` pulling the matching image before touching the host and refusing when the tag does not exist (R0.5 — the image half of this gate for a package install; it prints `mercury preflight` as the next step and does not run it, because it runs outside any project directory); the fleet's `tagula-box-upgrade` and cloud-init calling `mercury preflight --json` before declaring success (`fleet-release-gate`). |
115
115
  | **Evidence** | The journal line the refusing path writes; the reports the Gate step attaches. |
116
116
  | **Where it goes** | The deploy doc; for the fleet, the box's `<dataDir>/preflight/latest.json`. |
117
- | **Status** | **lands with R5.1 / R5.2** (Mercury side); **policy hook** (fleet side). **Not in force today**: until R5.1/R5.2 land, Gates 2, 3 and 5 are run by hand and their evidence attached, and a deploy doc without that evidence is the failure a reviewer reads. |
117
+ | **Status** | **R5.1 in force** for the owner's sync script (the script lives outside the repo, and its patch is recorded in `docs/archive/*-sync-rehearse.md`); **R5.2 pending** (the workflow Gate step); **policy hook** (fleet side). Until R5.2 lands, the agent workflows attach Gates 2, 3 and 5 evidence by hand, and a deploy doc without it is the failure a reviewer reads. |
118
118
 
119
119
  ### Gate 5 — Health is not done
120
120
 
@@ -229,7 +229,7 @@ line per file. An empty cell is a gate not passed.
229
229
  ```
230
230
  Classes (Gate 1): <image | code | environment | config | profile | data | docs-only> — discriminator lines pasted below
231
231
  Deploy needs: <restart-only | image rebuild (<which baked file / version bump>) | extension snapshot refresh | none>
232
- Shadow (Gate 2): snapshot <dir>, source commit <sha>, preflight <path> exit <n>, smoke <path> (R3.2), down: $<cost> over <n> run(s)
232
+ Shadow (Gate 2): rehearsal <path> verdict <green|red|refused> (source commit <sha>, cost $<n>) — or by hand: snapshot <dir>, source commit <sha>, preflight <path> exit <n>, smoke <path>, down: $<cost> over <n> run(s)
233
233
  Rollback rehearsed (5): shadow on <previous sha>, preflight <path> exit <n>
234
234
  Gap (Gate 9): shadow up --dry-run: <no refusals | refusals>, docker ps: empty, pgrep: empty, at <time>
235
235
  Restart: <time>, journal: WhatsApp connection open / Agent image resolved imageId=<id>
@@ -12,16 +12,16 @@ Or install from the dashboard's **Features** page (one click).
12
12
 
13
13
  No API key is required for the browser. The extension uses [pinchtab](https://www.npmjs.com/package/pinchtab) to control a local headless Chromium and opens pages the same way a human would. It states no search policy: it does not tell the agent to search through a search engine's own site, because a scraped `search.brave.com` is unmetered and ends in a "Verifying you're not a bot" page after a few queries.
14
14
 
15
- The separate `web-search` extension (`mercury add web-search`) adds structured site search (flights, hotels, cars, apartments) on top of pinchtab and, for fast keyword and news lookups, exposes a search **API** as a host-side capability: the agent runs `mrctl capability web-search news '{"q":"..."}'` (or `web`) and the host answers from a chain of providers, Brave first, then Tavily. Set a provider's key in `.env` to enable it: `MERCURY_BRAVE_API_KEY`, `MERCURY_TAVILY_API_KEY` (Tavily's free plan: 1,000 searches a month, no card). The order is `web-search.providers` in the `@global` scope (default `brave,tavily`); a provider runs only when it is named there **and** its key is set, so a provider that must not run on a box has no key there. An unknown or repeated name narrows the chain to the names it gets right, warns on every call and alerts the operators once a month; it never widens to the default. Every reply names the `provider` that answered, and so does the journal's `web-search: query` line.
15
+ The separate `web-search` extension (`mercury add web-search`) adds structured site search (flights, hotels, cars, apartments) on top of pinchtab and, for fast keyword and news lookups, exposes a search **API** as a host-side capability: the agent runs `mrctl capability web-search news '{"q":"..."}'` (or `web`) and the host answers from a chain of providers, Brave first, then Tavily, then Linkup. Set a provider's key in `.env` to enable it: `MERCURY_BRAVE_API_KEY`, `MERCURY_TAVILY_API_KEY` (Tavily's free plan: 1,000 searches a month, no card), `MERCURY_LINKUP_API_KEY` (Linkup: $20/month free top-up for organizations signed up with a professional email, about 4,000 searches). The order is `web-search.providers` in the `@global` scope (default `brave,tavily,linkup`); a provider runs only when it is named there **and** its key is set, so a provider that must not run on a box has no key there. An unknown or repeated name narrows the chain to the names it gets right, warns on every call and alerts the operators once a month; it never widens to the default. Every reply names the `provider` that answered, and so does the journal's `web-search: query` line.
16
16
 
17
17
  A search moves to the next provider only when the provider fails: out of credit, a rejected key, a rate limit, a 5xx or network error, a timeout (10 s per attempt, 20 s per search), or a request it will not take. The caps below on the caller never fail over. While `web-search` is loaded **and some provider has a key**, every run's system prompt says keyword search goes only through that capability, never through a search engine's site in the browser, and its run-cap, hourly-cap and broken-key refusals say the same instead of pointing at the browser. Once **every** provider's credit is gone for the month (its budget below is spent, or it said so), that rule is replaced: the prompt and the refusal tell the agent to search in the browser, because a box with keys and no credit would otherwise have no keyword search at all. Without any key the capability answers every call with a 503, so that rule is not emitted: a keyless host states no search policy, like a host without `web-search`. Every key is declared `hostOnly`, so none enters a container; the host makes the call, applies a per-space hourly cap (`brave_hourly_cap`, default 60, counting searches whichever provider answers), and returns trimmed results.
18
18
 
19
19
  More brakes sit behind it:
20
20
  - **Per run:** `run_cap`, default 20 searches. The same query (same `q`, `count` and `freshness`) asked twice in one run is answered once, including two copies sent at the same time and a repeat after the run was refused. A cap set to a number too large to be exact (past 2^53 - 1) is rejected and falls back to the default.
21
- - **Per provider per host per calendar month (UTC):** `monthly_budget` (Brave's; default 1000, about its free grant) and `tavily_monthly_budget` (default 950, Tavily's 1,000 free credits less a margin). Read from the `@global` scope only, so a space cannot change them. They count attempts, so calls that time out or fail upstream count too. A provider whose budget is spent is skipped until the next month and the next one answers.
21
+ - **Per provider per host per calendar month (UTC):** `monthly_budget` (Brave's; default 1000, about its free grant) `tavily_monthly_budget` (default 950, Tavily's 1,000 free credits less a margin) and `linkup_monthly_budget` (default 3600, Linkup's $20 top-up at $0.005 a search, about 4,000, less a 10% margin because the top-up day is not stated). Read from the `@global` scope only, so a space cannot change them. They count attempts, so calls that time out or fail upstream count too. A provider whose budget is spent is skipped until the next month and the next one answers.
22
22
  - **Monthly warnings:** the host's operators (`admins`) get one message per provider at 80%, one at 95%, and one at 100%, when that provider is skipped; one more when every provider is spent and the bot moves to the browser (only with more than one provider enabled).
23
- - **A provider's own "out of credit":** credit can run out before this host's count does (another bot on the key, or usage from before the count existed). Brave's 402 marks Brave's month spent at the current `monthly_budget` and sends its 100% message; raising `monthly_budget` after topping up brings Brave back the same month. Tavily's 432/433 skips Tavily for 24 hours (its reset day is not stated), then it is tried once again; the first one each month alerts the operators.
24
- - **Skips that clear:** a rejected key skips that provider for 24 hours or until the key changes (one alert per key); a rate limit skips it for its `Retry-After` (60 s default, at most 10 min); a 5xx, network error or unreadable answer for 60 s. A timeout or a refused request skips nothing. A request a provider refuses alerts once a month, because a request shape every query trips is a bug.
23
+ - **A provider's own "out of credit":** credit can run out before this host's count does (another bot on the key, or usage from before the count existed). Brave's 402 marks Brave's month spent at the current `monthly_budget` and sends its 100% message; raising `monthly_budget` after topping up brings Brave back the same month. Tavily's 432/433 and Linkup's 429 with `INSUFFICIENT_FUNDS_CREDITS` or `EXCEED_BUDGET_LIMIT` (or any 429 whose body mentions credit) skip that provider for 24 hours (neither states its reset day), then it is tried once again; the first one each month alerts the operators. Linkup's other 429s are a rate limit, and its 402 (x402 pay-per-request, sent when no usable key reached it) counts as a rejected key.
24
+ - **Skips that clear:** a rejected key skips that provider for 24 hours or until the key changes (one alert per key); a rate limit skips it for its `Retry-After` (60 s default, at most 10 min); a 5xx, network error or unreadable answer for 60 s. A timeout or a refused request skips nothing. A request a provider refuses alerts once a month, because a request shape every query trips is a bug. Linkup answers a search that matched nothing with a 400 (`SEARCH_QUERY_NO_RESULT`); today that is a refused request too, so it moves on and can trigger that alert (`docs/bugs/linkup-no-result-400-is-read-as-a-refused-request.md`).
25
25
 
26
26
  The skips are rows in the extension's store and survive a restart. Read and clear them from a script file on the box:
27
27
 
@@ -50,6 +50,7 @@ import {
50
50
  } from "./providers/types.js";
51
51
 
52
52
  export { BRAVE_ENV } from "./providers/brave.js";
53
+ export { LINKUP_ENV } from "./providers/linkup.js";
53
54
  export { TAVILY_ENV } from "./providers/tavily.js";
54
55
  export { SEARCH_ACTIONS, type SearchAction } from "./providers/types.js";
55
56
 
@@ -62,7 +63,10 @@ export const BRAVE_PROVIDER = braveProvider.id;
62
63
  */
63
64
  export const braveApiKey = providerApiKey;
64
65
 
65
- /** Every provider's ceiling for `count` (Brave's and Tavily's are both 20). */
66
+ /**
67
+ * Every provider's ceiling for `count` (Brave's and Tavily's are both 20;
68
+ * Linkup's `maxResults` states no ceiling).
69
+ */
66
70
  export const MAX_COUNT = 20;
67
71
  export const DEFAULT_COUNT = 5;
68
72
 
@@ -400,8 +400,9 @@ async function attempt(
400
400
  query: SearchQuery,
401
401
  fetchImpl: FetchLike,
402
402
  boundMs: number,
403
+ nowMs: number,
403
404
  ): Promise<Raw | "timeout"> {
404
- const req = cp.provider.buildRequest(action, query, cp.apiKey);
405
+ const req = cp.provider.buildRequest(action, query, cp.apiKey, nowMs);
405
406
  const controller = new AbortController();
406
407
  const work = (async (): Promise<Raw> => {
407
408
  try {
@@ -531,7 +532,7 @@ export async function runChain(
531
532
  continue;
532
533
  }
533
534
 
534
- const raw = await attempt(cp, action, query, fetchImpl, boundMs);
535
+ const raw = await attempt(cp, action, query, fetchImpl, boundMs, startMs);
535
536
  const at = now();
536
537
 
537
538
  if (raw === "timeout") {
@@ -158,6 +158,10 @@ function readChainDeps(ctx: ConfigReader): Pick<
158
158
  apiKey: process.env[PROVIDERS.tavily.envKey],
159
159
  monthlyBudget: readMonthlyBudget(ctx, "tavily"),
160
160
  },
161
+ linkup: {
162
+ apiKey: process.env[PROVIDERS.linkup.envKey],
163
+ monthlyBudget: readMonthlyBudget(ctx, "linkup"),
164
+ },
161
165
  },
162
166
  order: orderParse.order,
163
167
  orderParse,
@@ -205,6 +209,13 @@ export default function (mercury: MercuryExtensionAPI) {
205
209
  validate: isValidCap,
206
210
  });
207
211
 
212
+ mercury.config(PROVIDERS.linkup.budgetConfigKey, {
213
+ description:
214
+ "Max billed Linkup searches this host makes per calendar month (UTC), across all spaces. Read from the global scope only. Linkup tops eligible accounts back up to $20 a month, about 4,000 searches at $0.005; the default leaves a margin. Warns at 80% and 95%; at 100% Linkup is skipped until next month. 0 skips Linkup.",
215
+ default: String(PROVIDERS.linkup.defaultMonthlyBudget),
216
+ validate: isValidCap,
217
+ });
218
+
208
219
  mercury.config(PROVIDERS_CONFIG_KEY, {
209
220
  description: `Search providers to try, in order, comma-separated (${Object.keys(PROVIDERS).join(", ")}). Read from the global scope only. A provider is used only when its API key is set on the host. An unknown or repeated name narrows the chain to the names it gets right, never widens it.`,
210
221
  default: DEFAULT_ORDER.join(","),
@@ -280,6 +291,10 @@ export default function (mercury: MercuryExtensionAPI) {
280
291
  apiKey: process.env[PROVIDERS.tavily.envKey],
281
292
  monthlyBudget: PROVIDERS.tavily.defaultMonthlyBudget,
282
293
  },
294
+ linkup: {
295
+ apiKey: process.env[PROVIDERS.linkup.envKey],
296
+ monthlyBudget: PROVIDERS.linkup.defaultMonthlyBudget,
297
+ },
283
298
  },
284
299
  }).length > 0;
285
300
  ctx.log?.warn("web-search: ledger read failed; assuming credit left", {