mercury-agent 0.24.4-beta.1 → 0.24.4-beta.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 (44) hide show
  1. package/docs/configuration.md +8 -0
  2. package/docs/goals/rehearsal-bench/roadmap.md +1 -1
  3. package/docs/goals/release-gate/decisions.md +81 -0
  4. package/docs/goals/release-gate/goal.md +2 -2
  5. package/docs/goals/release-gate/roadmap.md +6 -5
  6. package/docs/live-testing.md +75 -10
  7. package/docs/pending-verification.md +10 -0
  8. package/docs/permissions.md +6 -0
  9. package/docs/release-gate.md +7 -7
  10. package/package.json +1 -1
  11. package/src/agent/container-entry.ts +28 -9
  12. package/src/agent/container-error.ts +43 -0
  13. package/src/agent/container-runner.ts +6 -2
  14. package/src/agent/image-content.ts +278 -0
  15. package/src/agent/pi-failure-class.ts +19 -0
  16. package/src/agent/pi-jsonl-parser.ts +68 -0
  17. package/src/agent/provider-auth-rejection.ts +23 -3
  18. package/src/agent/user-error-messages.ts +63 -1
  19. package/src/cli/mercury.ts +554 -82
  20. package/src/cli/run-capture.ts +51 -0
  21. package/src/cli/shadow-rehearse-cli.ts +252 -0
  22. package/src/cli/unit-working-directory.ts +138 -0
  23. package/src/cli/upgrade.ts +4 -21
  24. package/src/core/commands.ts +30 -1
  25. package/src/core/handler.ts +43 -3
  26. package/src/core/operator-alerts.ts +265 -70
  27. package/src/core/problem-report.ts +623 -0
  28. package/src/core/profiles.ts +14 -1
  29. package/src/core/router.ts +74 -6
  30. package/src/core/runtime.ts +113 -9
  31. package/src/core/storage-cleanup.ts +14 -0
  32. package/src/core/system-messages.ts +70 -1
  33. package/src/extensions/extension-name.ts +49 -0
  34. package/src/extensions/installer.ts +48 -28
  35. package/src/extensions/loader.ts +15 -31
  36. package/src/main.ts +24 -5
  37. package/src/ops/shadow-rehearse-run.ts +596 -0
  38. package/src/ops/shadow-rehearse.ts +540 -0
  39. package/src/ops/shadow-service.ts +256 -25
  40. package/src/ops/shadow-src.ts +667 -0
  41. package/src/preflight/checks/image-content.ts +208 -0
  42. package/src/preflight/report.ts +3 -0
  43. package/src/preflight/run.ts +25 -0
  44. package/src/storage/db.ts +251 -0
@@ -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.
@@ -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.
@@ -2532,3 +2537,8 @@ zap extractor reads one-store cards labelled `למפרט טכני` (restart-depl
2532
2537
  ## Issue #143 / F14 — deleting a space removes all of it (added 2026-10-19, deploy-gated: new release + restart)
2533
2538
 
2534
2539
  - [ ] 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.
2540
+
2541
+ ## 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)
2542
+
2543
+ - [ ] 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.
2544
+ - [ ] 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,12 @@ 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
+
66
72
  ### Media permissions
67
73
 
68
74
  `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>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mercury-agent",
3
- "version": "0.24.4-beta.1",
3
+ "version": "0.24.4-beta.2",
4
4
  "description": "Personal AI assistant for chat platforms (WhatsApp, Slack, Discord, Telegram)",
5
5
  "license": "MIT",
6
6
  "author": "Avishai Tsabari",
@@ -27,6 +27,8 @@ import {
27
27
  type PiFailureClass,
28
28
  } from "./pi-failure-class.js";
29
29
  import {
30
+ type CompletedToolResult,
31
+ completedToolResults,
30
32
  mergeTokenUsage,
31
33
  type PiFailureKind,
32
34
  type PiJsonlParseResult,
@@ -1815,13 +1817,13 @@ function invokePiOnce(
1815
1817
  });
1816
1818
  }
1817
1819
  if (parsed.piFailureMessage) {
1818
- reject(
1819
- new PiRunFailure(
1820
- parsed.piFailureMessage,
1821
- parsed.usage,
1822
- parsed.piFailureKind ?? "provider",
1823
- ),
1820
+ const failure = new PiRunFailure(
1821
+ parsed.piFailureMessage,
1822
+ parsed.usage,
1823
+ parsed.piFailureKind ?? "provider",
1824
1824
  );
1825
+ failure.completed = completedToolResults(stdout);
1826
+ reject(failure);
1825
1827
  return;
1826
1828
  }
1827
1829
  resolve({
@@ -1852,17 +1854,20 @@ export function chainFailure(
1852
1854
  ? err.kind
1853
1855
  : undefined,
1854
1856
  refused: readonly RefusedLeg[] = [],
1857
+ completed: readonly CompletedToolResult[] = [],
1855
1858
  ): Error {
1856
1859
  if (refused.length > 0) {
1857
1860
  const tagged = new LegAuthRejectedError(err.message, spent, kind, refused);
1858
1861
  tagged.stack = err.stack;
1862
+ if (completed.length > 0) tagged.completed = completed;
1859
1863
  return tagged;
1860
1864
  }
1861
- if (!spent && !kind) return err;
1865
+ if (!spent && !kind && completed.length === 0) return err;
1862
1866
  // The kind survives the re-wrap: the host decides whether a task may be
1863
1867
  // re-run on it (`failureResult`'s `failureKind`).
1864
1868
  const failure = new PiRunFailure(err.message, spent, kind);
1865
1869
  failure.stack = err.stack;
1870
+ if (completed.length > 0) failure.completed = completed;
1866
1871
  return failure;
1867
1872
  }
1868
1873
 
@@ -1898,11 +1903,13 @@ export function piExitFailure(
1898
1903
  // stdout is still pi's JSONL: what it says about the provider, and what the
1899
1904
  // attempt was billed, is read the way a zero exit's would be.
1900
1905
  const parsed = parsePiPrintJsonlOutput(stdout);
1901
- return new PiExitFailure(
1906
+ const failure = new PiExitFailure(
1902
1907
  `pi CLI failed (${code}): ${stderr || stdout}`,
1903
1908
  parsed.usage,
1904
1909
  stderr.trim() ? stderr : parsed.piFailureMessage,
1905
1910
  );
1911
+ failure.completed = completedToolResults(stdout);
1912
+ return failure;
1906
1913
  }
1907
1914
 
1908
1915
  /**
@@ -1988,6 +1995,7 @@ export function failureResult(error: unknown): {
1988
1995
  usage?: TokenUsage;
1989
1996
  authRejected?: RefusedLeg[];
1990
1997
  failureKind?: "max-tokens";
1998
+ completedTools?: CompletedToolResult[];
1991
1999
  } {
1992
2000
  // The usage goes with it: a failed run is still billed.
1993
2001
  const usage = error instanceof PiRunFailure ? error.usage : undefined;
@@ -2003,6 +2011,11 @@ export function failureResult(error: unknown): {
2003
2011
  ...(error instanceof LegAuthRejectedError
2004
2012
  ? { authRejected: [...error.refused] }
2005
2013
  : {}),
2014
+ // What the run had already finished: the host hands it to the user
2015
+ // instead of dropping it with the error.
2016
+ ...(error instanceof PiRunFailure && error.completed?.length
2017
+ ? { completedTools: [...error.completed] }
2018
+ : {}),
2006
2019
  };
2007
2020
  }
2008
2021
 
@@ -2053,10 +2066,14 @@ export async function runModelChain(
2053
2066
  spent,
2054
2067
  kind,
2055
2068
  refused,
2069
+ completed,
2056
2070
  );
2057
2071
  // Usage of the attempts that failed, so a run that fails — or fails and then
2058
2072
  // succeeds — reports everything it was billed for.
2059
2073
  let spent: TokenUsage | undefined;
2074
+ // The latest attempt that finished any tool call: a later attempt that
2075
+ // fails before its own tools run must not erase what an earlier one did.
2076
+ let completed: readonly CompletedToolResult[] = [];
2060
2077
 
2061
2078
  for (let li = 0; li < legs.length; li++) {
2062
2079
  const leg = legs[li];
@@ -2103,6 +2120,7 @@ export async function runModelChain(
2103
2120
  if (err instanceof PiRunFailure) {
2104
2121
  spent = mergeTokenUsage(spent, err.usage);
2105
2122
  if (err.kind === "max-tokens") kind = "max-tokens";
2123
+ if (err.completed?.length) completed = err.completed;
2106
2124
  }
2107
2125
  // A refused credential fails the same way on every retry of this leg,
2108
2126
  // so it is the next leg whatever the classifier would say.
@@ -2113,7 +2131,7 @@ export async function runModelChain(
2113
2131
  }
2114
2132
  const cls = classifyAttemptFailure(err);
2115
2133
  if (cls === "failFast")
2116
- throw chainFailure(err, spent, undefined, refused);
2134
+ throw chainFailure(err, spent, undefined, refused, completed);
2117
2135
  if (cls === "fallbackable") break;
2118
2136
  if (cls === "retryable" && attempt < maxRetries) continue;
2119
2137
  break;
@@ -2126,6 +2144,7 @@ export async function runModelChain(
2126
2144
  spent,
2127
2145
  kind ?? (lastErr instanceof PiRunFailure ? lastErr.kind : undefined),
2128
2146
  refused,
2147
+ completed,
2129
2148
  );
2130
2149
  }
2131
2150
 
@@ -1,4 +1,10 @@
1
1
  import type { TokenUsage } from "../types.js";
2
+ import {
3
+ COMPLETED_TOOL_EXCERPT_MAX,
4
+ COMPLETED_TOOLS_MAX,
5
+ type CompletedToolResult,
6
+ clipText,
7
+ } from "./pi-jsonl-parser.js";
2
8
 
3
9
  export type ContainerFailureReason =
4
10
  | "timeout"
@@ -29,6 +35,18 @@ export class ContainerError extends Error {
29
35
  * for every leg of the chain.
30
36
  */
31
37
  failureKind?: "max-tokens";
38
+ /**
39
+ * Tool calls the run had finished before it failed, as the container
40
+ * reported them — the deliverable a late failure would otherwise drop. Set
41
+ * only from `parseCompletedTools`, so every entry is bounded.
42
+ */
43
+ completedTools?: CompletedToolResult[];
44
+ /**
45
+ * The notice about `completedTools` the user is sent under the error, set
46
+ * by the runtime when it closes the failed turn — the stored stub carries
47
+ * the same text, so the reply and the history cannot disagree.
48
+ */
49
+ completedNotice?: { text: string; shownChars: number };
32
50
 
33
51
  constructor(
34
52
  reason: ContainerFailureReason,
@@ -160,3 +178,28 @@ export class ContainerError extends Error {
160
178
  );
161
179
  }
162
180
  }
181
+
182
+ /**
183
+ * The `completedTools` of a container's `result.json`, re-bounded here: the
184
+ * file is written inside the sandbox, so its shape and sizes are checked, not
185
+ * trusted. Anything malformed is dropped entry by entry; absence is `[]`.
186
+ */
187
+ export function parseCompletedTools(raw: unknown): CompletedToolResult[] {
188
+ if (!Array.isArray(raw)) return [];
189
+ const out: CompletedToolResult[] = [];
190
+ for (const entry of raw) {
191
+ if (!entry || typeof entry !== "object") continue;
192
+ const { tool, excerpt, chars } = entry as Record<string, unknown>;
193
+ if (typeof tool !== "string" || typeof excerpt !== "string") continue;
194
+ if (!excerpt.trim()) continue;
195
+ out.push({
196
+ tool: clipText(tool, 100),
197
+ excerpt: clipText(excerpt, COMPLETED_TOOL_EXCERPT_MAX),
198
+ chars:
199
+ typeof chars === "number" && Number.isFinite(chars) && chars >= 0
200
+ ? Math.floor(chars)
201
+ : excerpt.length,
202
+ });
203
+ }
204
+ return out.slice(-COMPLETED_TOOLS_MAX);
205
+ }