From cd41c790a9962d931b1f624cd6ac4302dbbc70ca Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 12:29:08 +0000 Subject: [PATCH 1/3] CONTRACT: feat: undo a confirmed media effect from hygiene review, removing a kept copy's entry with it (#2781) Implements the 2026-11-03 maintainer ruling on #2781: review reaches Undo through a new review command, { operation: "undo-media", journalId }, under the same preflights as the CLI Undo. - POST /hygiene/review accepts undo-media (hygieneReviewRequestSchema; the lifecycle command schema is unchanged). The response carries the Undo's receipt as mediaUndo; a refusal is a 200 result with nothing written. - The resolved card keeps its status and gets the Undo's receipt through a narrow store mutation (hygiene_media_receipt); an undone effect leaves the review's fixed or kept counter, and the restored finding returns on a successor card instead of colliding with the terminal one. - brain hygiene unkeep --journal removes exactly the kept entry that journal recorded, or refuses not-kept with nothing written. Undo, compensation and recovery of Keep a permanent copy run it after the copy and config are restored, so the original is pending again rather than reopened as copy-missing. - cli.md and package-api.md document the new shapes; the CLI inventory records hygiene unkeep at the 0.45.0 media feature floor. Co-Authored-By: Claude Opus 5.5 --- .changeset/media-undo-review.md | 11 ++ api-report/ui-sdk.txt | 81 +++++++++++++ docs/decisions/hygiene-review.md | 20 +++- docs/decisions/mechanical-hygiene.md | 2 +- docs/integration-contract/cli.md | 1 + docs/integration-contract/package-api.md | 32 +++++- docs/integration-contract/wire.md | 6 +- packages/core/src/cli/commands/hygiene.ts | 33 +++++- packages/core/src/lib/hygiene.ts | 29 ++++- packages/core/tests/hygiene-media.test.ts | 37 ++++++ packages/ui-sdk/src/protocol.ts | 14 +++ packages/ui-sdk/src/schemas.ts | 8 +- packages/ui-sdk/tests/inbox-schemas.test.ts | 15 +++ packages/ui-server/src/brain/client.ts | 2 +- .../ui-server/src/inbox/hygiene-review.ts | 23 +++- .../ui-server/src/inbox/hygiene-writes.ts | 36 +++++- packages/ui-server/src/inbox/media-effects.ts | 26 ++++- packages/ui-server/src/inbox/store.ts | 15 +++ .../ui-server/src/routes/hygiene-review.ts | 7 +- .../ui-server/tests/cli-inventory.test.ts | 8 +- .../tests/hygiene-media-effects.test.ts | 108 ++++++++++++++++++ 21 files changed, 484 insertions(+), 30 deletions(-) create mode 100644 .changeset/media-undo-review.md diff --git a/.changeset/media-undo-review.md b/.changeset/media-undo-review.md new file mode 100644 index 0000000000..a553728515 --- /dev/null +++ b/.changeset/media-undo-review.md @@ -0,0 +1,11 @@ +--- +"@schlessera/brain": minor +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +--- + +A confirmed media effect can now be undone from hygiene review (#2781). `POST /api/hygiene/review` accepts `{ "operation": "undo-media", "journalId" }`, the journal ID on the resolved card's media receipt. It runs the same checks as Undo elsewhere, so it refuses without writing anything when the saved bytes were evicted or a file changed since. The response carries the Undo's receipt as `mediaUndo`. The card keeps its resolved status and gets the Undo's receipt. The review's `fixed` or `kept` counter drops, and the finding is pending again, on a new card. + +Undoing Keep a permanent copy now also removes its `kept` entry, after the copy and config are restored, so the original is pending again instead of reopening as `copy-missing`. The new `brain hygiene unkeep --journal ` removes exactly the kept entry that journal recorded, or refuses `not-kept` and writes nothing. + +The UI SDK adds `HygieneReviewMediaUndoCommand` and `HygieneReviewRequest` (either command), with `hygieneReviewMediaUndoCommandSchema` and `hygieneReviewRequestSchema`; `HygieneReviewCommand` and its schema are unchanged. `HygieneReviewRead` gains the optional `mediaUndo` receipt. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 89132f637f..5955336e68 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -174,7 +174,9 @@ export "." (./src/index.ts) type HygieneMediaRefusal type HygienePreviewRequest type HygieneReviewCommand + type HygieneReviewMediaUndoCommand type HygieneReviewRead + type HygieneReviewRequest type HygieneReviewState type HygieneWorktreeDetails type HygieneWorktreeDetailsRead @@ -637,7 +639,9 @@ export "./client" (./src/client/index.ts) type HygieneMediaRefusal type HygienePreviewRequest type HygieneReviewCommand + type HygieneReviewMediaUndoCommand type HygieneReviewRead + type HygieneReviewRequest type HygieneReviewState type HygieneWorktreeDetails type HygieneWorktreeDetailsRead @@ -1444,7 +1448,9 @@ export "./protocol" (./src/protocol.ts) type HygieneMediaRefusal type HygienePreviewRequest type HygieneReviewCommand + type HygieneReviewMediaUndoCommand type HygieneReviewRead + type HygieneReviewRequest type HygieneReviewState type HygieneWorktreeDetails type HygieneWorktreeDetailsRead @@ -1767,7 +1773,9 @@ export "./schemas" (./src/schemas.ts) hygieneOutcomeSchema hygienePreviewRequestSchema hygieneReviewCommandSchema + hygieneReviewMediaUndoCommandSchema hygieneReviewReadSchema + hygieneReviewRequestSchema hygieneReviewStateSchema hygieneWorktreeDetailsReadSchema inboxActionItemSchema @@ -2131,7 +2139,9 @@ export "./server" (./src/server/index.ts) type HygieneMediaRefusal type HygienePreviewRequest type HygieneReviewCommand + type HygieneReviewMediaUndoCommand type HygieneReviewRead + type HygieneReviewRequest type HygieneReviewState type HygieneWorktreeDetails type HygieneWorktreeDetailsRead @@ -6865,6 +6875,11 @@ signatures (every public export and the types it is made of) export interface HygieneReviewCommand { operation: "start" | "pause" | "resume" | "refresh"; } + HygieneReviewMediaUndoCommand (packages/ui-sdk/src/protocol.ts) + export interface HygieneReviewMediaUndoCommand { + operation: "undo-media"; + journalId: string; + } HygieneReviewRead (packages/ui-sdk/src/protocol.ts) export interface HygieneReviewRead { review: HygieneReviewState; @@ -6872,7 +6887,10 @@ signatures (every public export and the types it is made of) privateDetailAccess?: { itemId: string; }; + mediaUndo?: HygieneMediaReceipt; } + HygieneReviewRequest (packages/ui-sdk/src/protocol.ts) + export type HygieneReviewRequest = HygieneReviewCommand | HygieneReviewMediaUndoCommand; HygieneReviewState (packages/ui-sdk/src/protocol.ts) export interface HygieneReviewState { version: 1; @@ -12980,6 +12998,11 @@ signatures (every public export and the types it is made of) start: "start"; }>; }, z.core.$strict>; + hygieneReviewMediaUndoCommandSchema (packages/ui-sdk/src/schemas.ts) + const hygieneReviewMediaUndoCommandSchema: z.ZodObject<{ + journalId: z.ZodString; + operation: z.ZodLiteral<"undo-media">; + }, z.core.$strict>; hygieneReviewReadSchema (packages/ui-sdk/src/schemas.ts) const hygieneReviewReadSchema: z.ZodObject<{ action: z.ZodNullable; }, z.core.$loose>>; + mediaUndo: z.ZodOptional; + copySha256: z.ZodOptional; + files: z.ZodArray; + }, z.core.$strict>>; + journalId: z.ZodString; + outcome: z.ZodEnum<{ + applied: "applied"; + compensated: "compensated"; + kept: "kept"; + partial: "partial"; + pending: "pending"; + refused: "refused"; + stale: "stale"; + undone: "undone"; + }>; + reason: z.ZodOptional; + refusals: z.ZodOptional; + limit: z.ZodOptional; + line: z.ZodOptional; + observed: z.ZodOptional; + path: z.ZodOptional; + }, z.core.$strict>>>; + undo: z.ZodObject<{ + available: z.ZodBoolean; + path: z.ZodOptional; + reason: z.ZodOptional; + }, z.core.$strict>; + }, z.core.$strict>>; privateDetailAccess: z.ZodOptional>; @@ -13292,6 +13361,18 @@ signatures (every public export and the types it is made of) version: z.ZodLiteral<1>; }, z.core.$strict>; }, z.core.$strict>; + hygieneReviewRequestSchema (packages/ui-sdk/src/schemas.ts) + const hygieneReviewRequestSchema: z.ZodUnion; + }, z.core.$strict>, z.ZodObject<{ + journalId: z.ZodString; + operation: z.ZodLiteral<"undo-media">; + }, z.core.$strict>]>; hygieneReviewStateSchema (packages/ui-sdk/src/schemas.ts) const hygieneReviewStateSchema: z.ZodObject<{ blocker: z.ZodOptional>; diff --git a/docs/decisions/hygiene-review.md b/docs/decisions/hygiene-review.md index bb1c7fc31c..e5062feea9 100644 --- a/docs/decisions/hygiene-review.md +++ b/docs/decisions/hygiene-review.md @@ -47,7 +47,7 @@ already carries category, path and stable evidence (`HygieneCandidate`, (`hygieneId`, `packages/core/src/lib/hygiene.ts:181-184`). Those primitives do not by themselves supply validation-to-hygiene equivalence, priority selection or review dispositions. The CLI exposes reconciliation, listing and deterministic selection -(`hygieneCommand`, `packages/core/src/cli/commands/hygiene.ts:241-243`). +(`hygieneCommand`, `packages/core/src/cli/commands/hygiene.ts:250-252`). ## Selection: severity and known urgency, then age and identity @@ -190,7 +190,7 @@ identity), the new finding carries the receipt only when the pairing is unambiguous. In one run, exactly one disposition in force with that category and path stops being detected, and exactly one new finding with them appears (`if (prior.length === 1 && siblings.length === 1)`, -`packages/core/src/lib/hygiene.ts:1513`). Otherwise the new finding opens +`packages/core/src/lib/hygiene.ts:1538`). Otherwise the new finding opens without one. Either way the old disposition does not suppress it. Entries moved by hand carry no fingerprint, so they keep their earlier behaviour. @@ -213,7 +213,7 @@ receipt (`keptInvalidity`, `packages/core/src/lib/hygiene.ts:998-1008`). Sync's count and review use one read-only function that applies these predicates to the log as it stands rather than trusting the file an entry sits -in (K2 B; `mediaReviewCounts`, `packages/core/src/lib/hygiene.ts:1753-1768`). +in (K2 B; `mediaReviewCounts`, `packages/core/src/lib/hygiene.ts:1778-1793`). Leave pending is a per-pass deferral in review state, never a log state: it skips the finding while its fingerprint holds, and the finding still counts. @@ -243,6 +243,18 @@ what the effect wrote, so a later edit is never overwritten and the outcome is No all-file atomicity is claimed. The contract is in [media review effects](../integration-contract/package-api.md#media-review-effects-additive-2781). +**Undo from review (#2781, maintainer ruling 2026-11-03).** A confirmed media +effect resolves its card, and a resolved card takes no option. So review +reaches Undo through a review command, `{ operation: "undo-media", journalId }`, +instead of keeping the card open ("applied · Undo available") until the next +selection. That keeps the resolved lifecycle, and the Undo stays bound to the +receipt's journal. It runs the CLI Undo's preflights. The card keeps its +resolved status and gets the Undo's receipt, and the restored finding returns +on a new card, never the old one. Undoing Keep a permanent copy also removes +its `kept` entry after the copy and config are restored (rev 5 §5.7, +`brain hygiene unkeep`), so the original is pending again rather than +reopened as `copy-missing`. + ## A disposition is not a repair or an authority grant Dismiss and Snooze do not change the document, acknowledge a successful repair @@ -253,7 +265,7 @@ permission, premise revalidation and a real post-apply check before success. Do not implement dismissal by marking a still-detected finding resolved: existing reconciliation reopens such an entry (`const prev = field(entry, "resolved-by")`, -`packages/core/src/lib/hygiene.ts:1487-1490`). Keep review disposition distinct from +`packages/core/src/lib/hygiene.ts:1512-1515`). Keep review disposition distinct from actual check success and from notification acknowledgement. Markdown remains authoritative for findings, dispositions and confirmed content diff --git a/docs/decisions/mechanical-hygiene.md b/docs/decisions/mechanical-hygiene.md index 980bb9807d..8b0b83023d 100644 --- a/docs/decisions/mechanical-hygiene.md +++ b/docs/decisions/mechanical-hygiene.md @@ -134,7 +134,7 @@ one explicit providerless CLI planner/apply operation for this supported grammar, with `--json` and dry-run output, followed by the existing reconciliation. Re-read every consulted input and use the existing unchanged-source writer (`replaceIfUnchanged`, -`packages/core/src/lib/hygiene.ts:1236-1246`) before application. Keep registry +`packages/core/src/lib/hygiene.ts:1246-1256`) before application. Keep registry ownership, inbox/archive exclusions and all unhandled cases visible as log-only. The skill delegates these two mechanical operations; canonical judgment remains with it. That follow-up needs the additive contract documentation and normal diff --git a/docs/integration-contract/cli.md b/docs/integration-contract/cli.md index b77893c118..0629c7f756 100644 --- a/docs/integration-contract/cli.md +++ b/docs/integration-contract/cli.md @@ -429,6 +429,7 @@ resumption. The host must retain a successful complete export at least every | `brain hygiene dismiss --expect-fingerprint [--reason ] [--extra ] --json` | `{ "status": "dismissed", "id", "fingerprint", "until": null, "reason", "changedFiles" }`. Reconciles, then moves the finding to `context/hygiene/dismissed.md` with the date and the fingerprint it applies to; it stays out of review until its evidence fingerprint changes. Refused with exit `1` and nothing written when the finding is not detected now or its fingerprint is not ``: `{ "status": "refused", "reason": "not-detected"\|"stale-fingerprint", "id", "expectedFingerprint", "currentFingerprint" }`. A finding reported through `reconcile --extra` is detected only when the same `--extra` file is given. A malformed argument exits `1` as a usage error (additive in 0.41.0) | | `brain hygiene snooze --until --expect-fingerprint [--reason ] [--extra ] --json` | As `dismiss`, with `"status": "snoozed"` and `"until"` as given, into `context/hygiene/snoozed.md`. `--until` is an ISO date (due at the start of that UTC day) or a date-time with `Z` or an offset (due at that instant), and must be in the future. The finding returns when due, or before then as soon as its fingerprint changes (additive in 0.41.0) | | `brain hygiene keep-copy --expect-fingerprint --copy --copy-sha256 --journal [--reason ] --json` | Additive in 0.45.0 (#2780). As `dismiss`, with `"status": "kept"` and `"copy"`, `"copySha256"` and `"journal"` appended, into `context/hygiene/kept.md` (created by its first entry) with `kept-on:`, `copy:`, `copy-sha256:`, `journal:` and `disposition-fingerprint:`. Keep a permanent copy runs it after making and verifying the copy. Refused with exit `1` and nothing written, besides `dismiss`'s reasons, as `"not-media"` (not a `media` finding), `"copy-missing"` (not a contained regular file outside `.brain/` and `workspaces/`), `"copy-untracked"` (`media.track` does not keep it) or `"copy-changed"` (its bytes are not ``) | +| `brain hygiene unkeep --journal --json` | Additive in 0.45.0 (#2781). Reconcile, then remove the `kept` entry that `keep-copy` recorded for `` under that journal ID: Undo of Keep a permanent copy runs it after the copy and config are restored. The original returns to `open.md` without its disposition fields and without an `invalidated:` receipt (or to `resolved.md` as `original-pruned` when it is no longer detected). `{ "status": "unkept", "id", "journal", "changedFiles" }`. Refused with exit `1` and nothing written as `{ "status": "refused", "reason": "not-kept", "id", "journal" }` when no kept entry for `` carries that journal | | `brain hygiene media --expect-fingerprint [--to ] (--dry-run \| --expect-premise --journal ) --json` | Additive in 0.45.0 (#2781). A media finding's effect. `--dry-run` plans it and writes nothing: `{ "status": "preview", "id", "action", "fingerprint", "source": { "path", "sha256", "bytes", "kind": "content"\|"scratch"\|"share-staged" }, "destination", "links": { "state": "linked"\|"unlinked"\|"unknown", "conversations" }, "references": { "complete", "count" }, "rewrites": [{ "note", "line", "kind", "before", "after" }], "blockers": [{ "note", "line", "kind", "target" }], "configDiff": { "path", "track": { "before", "after" }, "ignore": { "before", "after" } }\|null, "captureBytes", "copy": { "bytes", "sha256", "diskFreeAdvisory" }\|null, "resultClass": "TRACK"\|"ARTIFACT"\|null, "files": [{ "path", "role": "source"\|"destination"\|"note"\|"config"\|"directory", "before", "after", "bytes" }], "premiseDigest", "refusals": [{ "code", "path"?, "line"?, "limit"?, "effective"?, "observed"? }] }`. `files` is every file the effect writes, in apply order, with its expected SHA-256 before and after (`null` absent, `"directory"` for a created folder); it is empty when anything refuses. `move` and `keep-copy` need `--to`. A named refusal is a result, never an error: `share-staged`, `not-final-location` (scratch for `persist`, or a destination under `.brain/`, `workspaces/`, `.git/` or `context/hygiene/`), `pinned-scratch`, `pins-unknown`, `not-linked-scratch`, `destination-required`, `not-contained`, `exists`, `name-collision` (a sibling equal under NFC and case folding), `secret-name`, `ref-unsupported` (a frontmatter or HTML reference a Move cannot rewrite), `not-expressible` (no exact `media.track` form: a root-level name or a `*`), `ignore-adjustment-required` (an ignore entry other than this exact path matches), `config-not-literal`, `config-invalid`, `inventory-too-large` (with `limit` `rewrittenNotes` or `preview`, or the scan's own) and `inventory-unscannable`. A finding not detected now exits `1` with `{ "status": "refused", "reason": "not-detected" }`, one whose fingerprint is not `` with `"status": "stale"`. Apply recomputes the plan and writes only when its `premiseDigest` equals ``, otherwise `"status": "stale"` with nothing written; it returns `{ "status": "applied"\|"stale"\|"refused"\|"interrupted", "id", "action", "journal", "reason"?, "refusals"?, "files": [{ ...file, "state": "created"\|"changed"\|"removed"\|"unchanged" }], "copySha256"? }`. The caller (`--journal`) must retain every listed pre-image first and compensates from it: this command never compensates, and `interrupted` names what it wrote before a step failed. Move is `link` then `unlink` and never overwrites; across file systems it refuses `exdev`. A copy streams into a private `.part` beside the destination and publishes it with `link`. `persist` and `keep-copy` splice the exact `media.track` entry (removing an exact `media.ignore` of the same path) into a literal `brain.config`, parsed as syntax and never evaluated, then verify the written lists and that the file classes `TRACK`. `keep-copy` does not record the kept entry; `brain hygiene keep-copy` does, after the caller verifies the copy. Linux only for apply (`platform-unsupported`) | | `brain travel validate --json` | `{ "validation": { "valid": boolean, "files": number, "issues": [{ "file", "level": "error", "message" }] } }` — read-only canonical format, reference and asset checks. `files` counts successfully parsed travel/trip/place documents. Exit `0` when valid, `1` on domain errors. File paths are root-relative; messages are prose | | `brain travel migrate [--dry-run] --json` | `{ "migration": { "path", "changed": boolean, "dry_run": boolean } }` — `path` is `brain.config.ts` or `brain.config.json`; `changed` reports the proposed edit even during dry run. Reapplication reports false without a write. Refusals exit `1` with actionable stderr and no success envelope | diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 3fd08326ff..e184e240d2 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -1636,6 +1636,14 @@ compensation, Undo and recovery, in the bounded change journal (Rollback A). `brain hygiene keep-copy` only after the copy verified (step 6b). A refused entry compensates: the copy is removed and the config restored. The original's bytes, path and pins are never touched. +- **Undo of Keep a permanent copy** removes its `kept` entry in the same + Undo, after the copy and config are restored, with + `brain hygiene unkeep --journal `. The original is pending + again, without an `invalidated: … copy-missing` receipt. An entry already + gone needs nothing; any other answer makes the Undo `partial` with reason + `kept-entry-unremoved` (or `kept-entry-unknown`). A compensated or + recovered copy removes an entry its lost step 6b receipt may have written + the same way. Additive shapes in `@schlessera/brain-ui-sdk`: @@ -1644,6 +1652,8 @@ Additive shapes in `@schlessera/brain-ui-sdk`: | `HygieneEffect.operation` | gains `media-delete`, `media-move`, `media-persist`, `media-keep-copy`; the effect may carry `destination` and `premiseDigest` | | `InboxOption.media` | `HygieneMediaPlan`: the CLI plan (`action`, `premiseDigest`, `destination`, `files`, `captureBytes`, `links`, `references`, `rewrites`, `blockers`, `configDiff`, `copy`, `resultClass`, `refusals`) | | `HygieneAction.outcome.status` | gains `kept`, a confirmed Keep a permanent copy | +| `HygieneReviewMediaUndoCommand`, `HygieneReviewRequest` | new (0.45.0): `{ operation: "undo-media", journalId }`, Undo of a confirmed media effect from review (below); `HygieneReviewRequest` is it or the unchanged `HygieneReviewCommand`, parsed by the new `hygieneReviewMediaUndoCommandSchema` and `hygieneReviewRequestSchema`; `hygieneReviewCommandSchema` is unchanged | +| `HygieneReviewRead.mediaUndo` | `HygieneMediaReceipt`, on the `undo-media` response only (0.45.0) | | `HygieneAction.outcome.media` | `HygieneMediaReceipt`: `{ journalId, action, outcome: "pending"\|"applied"\|"kept"\|"compensated"\|"partial"\|"refused"\|"stale"\|"undone", reason?, refusals?, files: [{ path, state: "created"\|"changed"\|"removed"\|"restored"\|"unchanged"\|"left-changed"\|"conflict" }], copySha256?, undo: { available, reason?, path? } }` | A media finding's card offers Persist here, Move to a final location…, Keep a @@ -1660,6 +1670,25 @@ confirms a kept copy only when the log's entry is `kept` with the same fingerprint and copy SHA-256; otherwise `receipt-unknown`. Routes and their error strings are unchanged. +**Undo from review** (additive in 0.45.0, maintainer ruling 2026-11-03). +`POST /api/hygiene/review` with strict +`{ "operation": "undo-media", "journalId": "" }` +undoes the confirmed effect of a resolved media card, for the principal that +applied it, under the same preflights as the CLI Undo: every retained +pre-image still held and no file changed since. The response is the review +read plus `mediaUndo`, the Undo's own receipt. A refusal is a 200 result, +`mediaUndo.outcome: "refused"` with `reason` (`changed-since` with `path`, +`rollback-evicted`, `already-undone`), and nothing is written. The resolved +card keeps its status and gets the Undo's receipt by inbox replication: +`outcome.status: "undone"` with `media` the Undo receipt; `check_failed` with +code `partial` when some file could not be put back; or, after a refusal, its +original outcome with `media.undo` re-read. An undone effect leaves the +review's `fixed` or `kept` counter. The finding is pending again and an +active review selects it in order, on a new card. Repeating the command +returns the same receipt and changes nothing. A `journalId` that names no +resolved media card of this principal is `review_failed` (500); malformed is +400, as for every command. + ## Module hygiene context (breaking, #699) @@ -3238,7 +3267,8 @@ transaction or server-level replay/authorization guarantee. ### Human-started hygiene review (additive, #1027) The authenticated host exposes `GET /api/hygiene/review` and -`POST /api/hygiene/review` with strict `{ "operation": "start" | "pause" | "resume" | "refresh" }`. +`POST /api/hygiene/review` with strict `{ "operation": "start" | "pause" | "resume" | "refresh" }` +(and, additive in 0.45.0, `undo-media`: see [media review effects](#media-review-effects-additive-2781)). Both return `{ "review": HygieneReviewState, "action": InboxActionItem | null }`. The read is operational state; start/resume select through the supported `brain hygiene next --json` boundary without inference. Owner and ambient diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index 4594575508..d960b39d4c 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -22,7 +22,7 @@ states that overlapping writable windows share observations. `observedAt` names the retained window observation, not a guessed receipt time. The type is defined by (`TurnJournalSummary`, `packages/ui-sdk/src/turn-journal.ts:2-29`); validation uses -(`turnJournalSummarySchema`, `packages/ui-sdk/src/schemas.ts:1077-1095`). +(`turnJournalSummarySchema`, `packages/ui-sdk/src/schemas.ts:1081-1099`). `actor` additionally accepts `user` for a server-recorded history operation. Optional `kind` is `turn` or `revert`; a revert may name its original `sourceTurnId`. These facts do not create an assistant message or an inference @@ -104,8 +104,8 @@ previous observation rather than adding it. The frame never opens a message, reopens run state or moves focus. Older clients may ignore it. The same optional `budget` is retained on `TurnJournalSummary` and replayed with the existing single below-turn disclosure. The additive types and validation are -(`ServerUsage`, `packages/ui-sdk/src/protocol.ts:3872-3878`) and -(`serverUsageSchema`, `packages/ui-sdk/src/schemas.ts:1916-1918`). +(`ServerUsage`, `packages/ui-sdk/src/protocol.ts:3886-3892`) and +(`serverUsageSchema`, `packages/ui-sdk/src/schemas.ts:1920-1922`). Budget list-price inference cost is separate from the journal's billing-aware `costUsd`. Unpriced totals remain null; known lower bounds, estimated rates, diff --git a/packages/core/src/cli/commands/hygiene.ts b/packages/core/src/cli/commands/hygiene.ts index 9ac316d751..0e388828cf 100644 --- a/packages/core/src/cli/commands/hygiene.ts +++ b/packages/core/src/cli/commands/hygiene.ts @@ -27,7 +27,7 @@ import { resolveEnv } from "../../config/env.js"; import type { CliContext, CoreCommand } from "../types.js"; import { emit, parseArgs, UsageError } from "../io.js"; -const HELP = `brain hygiene — the content-hygiene log under context/hygiene/ +const HELP = `brain hygiene — the content-hygiene log under context/hygiene/ reconcile [--extra ] [--fixed ] [--dry-run] Refresh the index, detect issues (brain audit, brain validate's corpus @@ -90,7 +90,16 @@ const HELP = `brain hygiene . --json envelope: as dismiss, with "status": "kept", "copy", "copySha256" and "journal" appended; refused reasons add "not-media", "copy-missing", - "copy-untracked" and "copy-changed".`; + "copy-untracked" and "copy-changed". + + unkeep --journal + Reconcile, then remove the kept entry that keep-copy recorded for + under that journal ID: Undo of Keep a permanent copy, after the copy and + its config are restored. The original is open again, without an + invalidation receipt. Refused, with nothing written, when no such kept + entry exists. + --json envelope: { "status": "unkept", "id", "journal", "changedFiles" }; + refused: { "status": "refused", "reason": "not-kept", "id", "journal" }`; const MEDIA_HELP = ` media --expect-fingerprint [--to ] @@ -353,6 +362,24 @@ export const hygieneCommand: CoreCommand = { return 0; } + if (sub === "unkeep") { + const id = pos[1], journal = flags.journal; + if (!id || pos.length !== 2) throw new UsageError("Usage: brain hygiene unkeep --journal "); + if (typeof journal !== "string" || !/^[A-Za-z0-9._-]{1,128}$/.test(journal)) throw new UsageError("--journal needs the Keep a permanent copy journal ID"); + try { + const { result } = await detectAndReconcile(cli, { now: new Date(), unkeep: { id, journal } }); + emit(cli.json, { status: "unkept", id, journal, changedFiles: result.changedFiles }, () => { + console.log(`unkept ${id}`); + for (const f of result.changedFiles) console.log(` wrote ${f}`); + }); + return 0; + } catch (e) { + if (!(e instanceof HygieneRefusal)) throw e; + emit(cli.json, { status: "refused", reason: e.reason, id, journal }, () => console.error(e.message)); + return 1; + } + } + if (sub === "dismiss" || sub === "snooze" || sub === "keep-copy") { const now = new Date(); const request = dispositionRequest(sub, pos, flags, now); @@ -389,7 +416,7 @@ export const hygieneCommand: CoreCommand = { } } - if (sub !== "reconcile") throw new UsageError("Usage: brain hygiene "); + if (sub !== "reconcile") throw new UsageError("Usage: brain hygiene "); if (flags.extra === true) throw new UsageError("--extra needs a file"); if (flags.fixed === true) throw new UsageError("--fixed needs a file"); const extra = typeof flags.extra === "string" ? readExtra(flags.extra) : []; diff --git a/packages/core/src/lib/hygiene.ts b/packages/core/src/lib/hygiene.ts index c0c97daaef..093aa7019a 100644 --- a/packages/core/src/lib/hygiene.ts +++ b/packages/core/src/lib/hygiene.ts @@ -1155,6 +1155,14 @@ export interface ReconcileOptions { failedChecks?: string[]; /** Dismissals and snoozes to record this run (`brain hygiene dismiss` / `snooze`). */ dispositions?: HygieneDispositionRequest[]; + /** + * Remove the `kept` entry for `id` that Keep a permanent copy recorded + * under journal `journal` (#2781, rev 5 §5.7): Undo of the copy, after the + * copy and config are restored. The original returns to open without an + * invalidation receipt, since nothing about it changed. No such entry + * refuses `not-kept` before anything is written. + */ + unkeep?: { id: string; journal: string }; /** * The brain's media policy, which decides whether a kept copy is still * tracked (`keptInvalidity`). Callers pass the loaded configuration's. @@ -1179,7 +1187,7 @@ export type HygieneDispositionRequest = | { kind: "kept"; id: string; expectFingerprint: string; copy: string; copySha256: string; journal: string; reason?: string }; /** Why a disposition was refused. The `copy-…` and `not-media` reasons are a `kept` request's. */ -export type HygieneRefusalReason = "not-detected" | "stale-fingerprint" | "not-media" | "copy-missing" | "copy-untracked" | "copy-changed"; +export type HygieneRefusalReason = "not-detected" | "stale-fingerprint" | "not-media" | "copy-missing" | "copy-untracked" | "copy-changed" | "not-kept"; /** * A disposition reconcile would not record: the finding is not detected now, @@ -1196,6 +1204,8 @@ export class HygieneRefusal extends Error { super( reason === "not-detected" ? `${id} is not detected now; nothing was written` + : reason === "not-kept" + ? `${id} has no kept entry recorded by journal ${expectedFingerprint}; nothing was written` : reason === "stale-fingerprint" ? `${id} has fingerprint ${currentFingerprint}, not ${expectedFingerprint}: its evidence changed; nothing was written` : reason === "not-media" @@ -1355,6 +1365,12 @@ export function reconcile( for (const state of ["snoozed", "dismissed", "kept", "resolved", "open"] as const) { for (const entry of parsed[state].entries) if (!known.has(entry.id)) known.set(entry.id, entry); } + // Unkeep removes exactly the kept entry its journal recorded, or nothing at all. + const unkeep = opts.unkeep; + if (unkeep) { + const entry = known.get(unkeep.id); + if (!entry || entry.state !== "kept" || field(entry, "journal") !== unkeep.journal) throw new HygieneRefusal("not-kept", unkeep.id, unkeep.journal, null); + } // While any check failed, "not detected" may only mean "not looked for": // an entry that was not detected again is left as it is. @@ -1472,7 +1488,16 @@ export function reconcile( } } } else if (state === "kept") { - if (finding) { + if (unkeep && unkeep.id === entry.id && field(entry, "journal") === unkeep.journal) { + // Undo of the copy: the original is pending again, as it was before Keep a permanent copy. + if (finding) { + next.open.push(openFrom(finding, entry.id, withoutFields(entry.lines, DISPOSITION_FIELDS), firstSeenOf(entry) ?? today)); + counts.reopened++; + } else { + next.resolved.push(resolve_(entry, "original-pruned")); + counts.resolved++; + } + } else if (finding) { const why = keptInvalidity(root, policy, keptRecord(entry), finding, recorded?.fingerprint?.fields ?? {}); if (why) invalidate(finding, recorded!, entry.lines, firstSeenOf(entry) ?? today, null, why); else next.kept.push(entry); diff --git a/packages/core/tests/hygiene-media.test.ts b/packages/core/tests/hygiene-media.test.ts index 70418dd8f8..5223619cc8 100644 --- a/packages/core/tests/hygiene-media.test.ts +++ b/packages/core/tests/hygiene-media.test.ts @@ -168,6 +168,43 @@ describe("recording kept", () => { }); }); +describe("unkeep (Undo of Keep a permanent copy, #2781)", () => { + const unkeep = (root: string, journal = "7c1e", id = findingAt(root, LOOM).id, policy = policyWithCopy) => + reconcile(root, candidatesOf(root, policy), new Map(), { now: NOW, media: policy, unkeep: { id, journal } }); + const refusal = (fn: () => unknown) => { try { fn(); } catch (e) { return (e as HygieneRefusal).reason; } return null; }; + const hygieneBytes = (root: string) => ["open.md", "kept.md", "resolved.md", "_index.md", "last-run.md"] + .map((name) => existsSync(join(root, "context/hygiene", name)) ? readFileSync(join(root, "context/hygiene", name), "utf8") : null); + + test("after the copy and its rule are gone, the entry its journal recorded leaves kept.md and the original is open, with no receipt", () => { + const root = brain(); + const loom = findingAt(root, LOOM); + writeKept(root, keptEntry(loom)); + run(root); + // Undo restored the copy away and the config without its track rule. + rmSync(join(root, COPY)); + const result = unkeep(root, "7c1e", loom.id, { ...DEFAULT_MEDIA_POLICY }); + expect(result, "UNKEEP_NO_INVALIDATION").toMatchObject({ kept: 0, invalidations: [], reopened: 1 }); + const kept = readFileSync(join(root, "context/hygiene/kept.md"), "utf8"); + expect(kept).toContain("## Kept as a permanent copy\n\n(empty)\n"); + const open = readFileSync(join(root, "context/hygiene/open.md"), "utf8"); + expect(open).toContain(`### ${loom.id}`); + for (const gone of ["kept-on:", "copy:", "copy-sha256:", "journal:", "disposition-fingerprint:", "invalidated:"]) expect(open).not.toContain(gone); + expect(readHygieneLog(root).find((e) => e.id === loom.id)).toMatchObject({ state: "open", invalidation: null, disposition: null }); + expect(counts(root, NOW, { ...DEFAULT_MEDIA_POLICY }).awaitingReview).toBe(1); + }); + + test("another journal's entry, or no kept entry at all, is refused with every hygiene file unchanged", () => { + const root = brain(); + const loom = findingAt(root, LOOM); + writeKept(root, keptEntry(loom)); + run(root); + const before = hygieneBytes(root); + expect(refusal(() => unkeep(root, "9d2f")), "UNKEEP_JOURNAL_BOUND").toBe("not-kept"); + expect(refusal(() => unkeep(root, "7c1e", findingAt(root, SHIELD)?.id ?? "media-photos-achilles-shield-0000"))).toBe("not-kept"); + expect(hygieneBytes(root)).toEqual(before); + }); +}); + describe("mediaReviewCounts", () => { /** Dismissed, snoozed and kept log files holding entries for the loom and the shield. */ function logged(root: string, files: { dismissed?: string[]; snoozed?: string[]; kept?: string[] }): void { diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index 0c8a356b37..8928c9099b 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -3647,6 +3647,14 @@ export interface HygieneReviewState { media?: { awaitingReview: number; setAside: number; kept: number }; } export interface HygieneReviewCommand { operation: "start" | "pause" | "resume" | "refresh" } +/** + * Undo from review (#2781): undoes a confirmed media effect from its + * resolved card, by the receipt's `journalId`, under the same preflights as + * the CLI Undo. Undoing Keep a permanent copy also removes its kept entry. + */ +export interface HygieneReviewMediaUndoCommand { operation: "undo-media"; journalId: string } +/** Every body `POST /hygiene/review` accepts. */ +export type HygieneReviewRequest = HygieneReviewCommand | HygieneReviewMediaUndoCommand; export interface HygienePreviewRequest { itemId: string; optionId: string; expectedVersion: number; input: HygieneInput } export interface HygieneReviewRead { review: HygieneReviewState; @@ -3657,6 +3665,12 @@ export interface HygieneReviewRead { * never part of the replicated Action. */ privateDetailAccess?: { itemId: string }; + /** + * The Undo's own receipt, on the response to an `undo-media` command only + * (#2781): `undone`, `partial`, or `refused` with the reason (for example + * `changed-since` or `rollback-evicted`) and nothing written. + */ + mediaUndo?: HygieneMediaReceipt; } /** * The recorded facts of a private managed-worktree finding, read by the owner diff --git a/packages/ui-sdk/src/schemas.ts b/packages/ui-sdk/src/schemas.ts index 230b576e6b..1195273602 100644 --- a/packages/ui-sdk/src/schemas.ts +++ b/packages/ui-sdk/src/schemas.ts @@ -1,5 +1,5 @@ import { POLICY_CHANGE_REVIEW_SCHEMA } from "./tool-contracts/policy.js"; -import type { HygieneAction, HygieneDiff, HygieneEffect, HygieneMediaPlan, HygieneMediaReceipt, HygieneMediaRefusal, HygieneReviewCommand, HygienePreviewRequest, HygieneReviewState, HygieneReviewRead, HygieneWorktreeDetailsRead } from "./protocol.js"; +import type { HygieneAction, HygieneDiff, HygieneEffect, HygieneMediaPlan, HygieneMediaReceipt, HygieneMediaRefusal, HygieneReviewCommand, HygieneReviewMediaUndoCommand, HygieneReviewRequest, HygienePreviewRequest, HygieneReviewState, HygieneReviewRead, HygieneWorktreeDetailsRead } from "./protocol.js"; import { sharedFileMetaSchema } from "./track-schemas.js"; export { sharedFileMetaSchema } from "./track-schemas.js"; // ============================================================ @@ -728,6 +728,10 @@ export const hygieneReviewStateSchema = z.strictObject({ version: z.literal(1), kept: inboxSeq.default(0), pass: inboxSeq.default(0), deferred: z.array(z.strictObject({ findingId: id, fingerprint: id })).max(10_000).default([]), media: z.strictObject({ awaitingReview: inboxSeq, setAside: inboxSeq, kept: inboxSeq }).optional() }) satisfies z.ZodType; export const hygieneReviewCommandSchema = z.strictObject({ operation: z.enum(["start", "pause", "resume", "refresh"]) }) satisfies z.ZodType; +/** Undo from review (#2781): the media receipt's journal ID, as `createMediaEffects` issues it. */ +export const hygieneReviewMediaUndoCommandSchema = z.strictObject({ operation: z.literal("undo-media"), journalId: z.string().regex(/^[A-Za-z0-9._-]{16,96}$/) }) satisfies z.ZodType; +/** Every body `POST /hygiene/review` accepts. */ +export const hygieneReviewRequestSchema = z.union([hygieneReviewCommandSchema, hygieneReviewMediaUndoCommandSchema]) satisfies z.ZodType; export const hygienePreviewRequestSchema = z.strictObject({ itemId: id, optionId: id, expectedVersion: z.number().int().min(1), input: hygieneInputSchema }) satisfies z.ZodType; const enqueueEffectSchema = z.strictObject({ kind: z.literal("enqueue"), payload: inboxWorkPayloadSchema }); const cancelBlockedEffectSchema = z.strictObject({ kind: z.literal("cancel_blocked") }); @@ -1636,7 +1640,7 @@ export const inboxActionItemSchema = inboxItemBaseSchema.extend({ queue: z.literal("actions"), type: z.enum(["approve", "choose", "fyi"]), status: inboxActionStatusSchema, payload: z.looseObject({ title: inboxText, detail: z.string().max(MAX_PROMPT_CHARS) }), options: z.array(wireOptionSchema), hygiene: hygieneActionSchema.optional(), }).refine((item) => item.type !== "fyi" || item.options.length === 0, "FYIs cannot offer resolution options") satisfies z.ZodType; -export const hygieneReviewReadSchema = z.strictObject({ review: hygieneReviewStateSchema, action: inboxActionItemSchema.nullable(), privateDetailAccess: z.strictObject({ itemId: id }).optional() }) satisfies z.ZodType; +export const hygieneReviewReadSchema = z.strictObject({ review: hygieneReviewStateSchema, action: inboxActionItemSchema.nullable(), privateDetailAccess: z.strictObject({ itemId: id }).optional(), mediaUndo: hygieneMediaReceiptSchema.optional() }) satisfies z.ZodType; const detailCount = z.number().int().min(0).nullable(); export const hygieneWorktreeDetailsReadSchema = z.discriminatedUnion("status", [ z.strictObject({ status: z.literal("details"), details: z.strictObject({ diff --git a/packages/ui-sdk/tests/inbox-schemas.test.ts b/packages/ui-sdk/tests/inbox-schemas.test.ts index d8a813d11a..ba6348b17d 100644 --- a/packages/ui-sdk/tests/inbox-schemas.test.ts +++ b/packages/ui-sdk/tests/inbox-schemas.test.ts @@ -221,3 +221,18 @@ test("human hygiene refresh and superseded receipts round-trip without accepting const read: import("../src/protocol.js").HygieneReviewRead = { review: { version: 1, status: "active", position: 1, fixed: 0, dismissed: 0, snoozed: 0, kept: 0, pass: 0, deferred: [] }, action: { ...actionItem, status: "dropped", hygiene: { findingId: "finding", fingerprint: "old", finding: { evidence: "Eumaeus hut" }, outcome: { version: 1, status: "superseded", supersededBy: "new-card" } } } }; expect(read).toEqual(hygieneReviewReadSchema.parse(read)); }); + +test("undo-media names a media receipt and nothing else; its response carries the Undo receipt (#2781)", async () => { + const { hygieneReviewCommandSchema, hygieneReviewRequestSchema, hygieneReviewReadSchema } = await import("../src/schemas.js"); + const journalId = `media-${"0123456789abcdef".repeat(2)}01234567`; + expect(hygieneReviewRequestSchema.parse({ operation: "undo-media", journalId })).toEqual({ operation: "undo-media", journalId }); + expect(hygieneReviewRequestSchema.parse({ operation: "refresh" })).toEqual({ operation: "refresh" }); + // The lifecycle command schema is unchanged and never accepts it. + expect(hygieneReviewCommandSchema.safeParse({ operation: "undo-media", journalId }).success).toBe(false); + for (const bad of [{ operation: "undo-media" }, { operation: "undo-media", journalId: "short" }, { operation: "undo-media", journalId: "../../etc/passwd-0000000000" }, + { operation: "undo-media", journalId, principalId: "owner" }, { operation: "refresh", journalId }]) + expect(hygieneReviewRequestSchema.safeParse(bad).success, JSON.stringify(bad)).toBe(false); + const read: import("../src/protocol.js").HygieneReviewRead = { review: { version: 1, status: "complete", position: 1, fixed: 0, dismissed: 0, snoozed: 0, kept: 0, pass: 1, deferred: [] }, action: null, + mediaUndo: { journalId: `undo-${journalId}`, action: "delete", outcome: "undone", files: [{ path: "photos/penelope-loom.png", state: "restored" }], undo: { available: false, reason: "already-undone" } } }; + expect(read).toEqual(hygieneReviewReadSchema.parse(read)); +}); diff --git a/packages/ui-server/src/brain/client.ts b/packages/ui-server/src/brain/client.ts index b9e2148ee2..3599b758a8 100644 --- a/packages/ui-server/src/brain/client.ts +++ b/packages/ui-server/src/brain/client.ts @@ -105,7 +105,7 @@ export const INDEX_DIRECTORY_CLI_VERSION = "0.44.0"; /** * First core release with media findings, `hygiene next --defer`, `keep-copy` - * (#2780) and `hygiene media` (#2781). Review sends them only for a media + * (#2780), `hygiene media` and `hygiene unkeep` (#2781). Review sends them only for a media * finding, and only a CLI at or past this release reports media findings, * so an older CLI is never asked for them. The release that ships it raises * {@link MIN_BRAIN_CLI_VERSION} to it; tests/cli-inventory.test.ts fails a diff --git a/packages/ui-server/src/inbox/hygiene-review.ts b/packages/ui-server/src/inbox/hygiene-review.ts index 0d959a4f1f..b95e173efc 100644 --- a/packages/ui-server/src/inbox/hygiene-review.ts +++ b/packages/ui-server/src/inbox/hygiene-review.ts @@ -209,6 +209,27 @@ export function createHygieneReview(db: Database, deps: { brain: BrainClient; no if (operation !== "pause" && !state().pendingActionId) await ensureNext(principalId, !!state().pauseReason); return read(); } + /** + * Undo a confirmed media effect from its resolved card (#2781, ruling + * 2026-11-03), under the same preflights as the CLI Undo: rollback data + * still retained and no file changed since. A refusal is a result, recorded + * on the card as its current Undo availability, never a write. + */ + async function undoMedia(principalId: string, journalId: string): Promise { + authority(principalId); + if (!media) throw new Error("Media effects are unavailable"); + const attempts = db.query("SELECT * FROM hygiene_effect_attempts WHERE status = 'finished' AND principal_id = ? ORDER BY rowid DESC").all(principalId) as Attempt[]; + const attempt = attempts.find(a => mediaOperationId(a.id) === journalId); + if (!attempt) throw new Error("Media receipt unavailable"); + const item = action(attempt.item_id), e = hygieneEffectSchema.parse(JSON.parse(attempt.effect_json)); + if (!isMediaOperation(e.operation) || item.status !== "resolved" || busy(item.id)) throw new Error("Not an undoable media card"); + const receipt = await media.undo({ id: `undo-${journalId}`, principalId, sourceId: journalId }); + authority(principalId); + await write("mediaUndo", now(), principalId, item.id, journalId, receipt, receipt.outcome === "refused" ? media.receipt(journalId, principalId) : null); + // The finding is pending again; an active review with no card selects it in order. + if (receipt.outcome === "undone" && state().status === "active" && !state().pendingActionId) await ensureNext(principalId); + return { ...read(), mediaUndo: receipt }; + } async function preview(principalId: string, request: { itemId: string; optionId: string; expectedVersion: number; input: HygieneInput }) { authority(principalId); hygieneInputSchema.parse(request.input); const item = action(request.itemId), { option, effect: selected } = resolver.inspect(principalId, { type: "inbox_resolve", itemId: item.id, optionId: request.optionId }); @@ -315,7 +336,7 @@ export function createHygieneReview(db: Database, deps: { brain: BrainClient; no } if (state().status === "active" && !state().pendingActionId) await ensureNext(); } - return { read, readFor, details, command, preview, resolver, recover, + return { read, readFor, details, command, undoMedia, preview, resolver, recover, /** The app attaches the journal-backed media effects once its journal is ready. */ attachMedia(effects: MediaEffects) { media = effects; } }; } diff --git a/packages/ui-server/src/inbox/hygiene-writes.ts b/packages/ui-server/src/inbox/hygiene-writes.ts index 3837e0ddf6..3e087c8551 100644 --- a/packages/ui-server/src/inbox/hygiene-writes.ts +++ b/packages/ui-server/src/inbox/hygiene-writes.ts @@ -3,7 +3,7 @@ * never reapplied. All Action projections use the shared store/change stream. */ import type { Database } from "bun:sqlite"; import { z } from "zod"; -import type { ClientInboxResolve, HygieneAction, HygieneEffect, HygieneInput, HygieneReviewRead, HygieneReviewState, InboxActionItem, InboxOption } from "@schlessera/brain-ui-sdk/protocol"; +import type { ClientInboxResolve, HygieneAction, HygieneEffect, HygieneInput, HygieneMediaReceipt, HygieneReviewRead, HygieneReviewState, InboxActionItem, InboxOption } from "@schlessera/brain-ui-sdk/protocol"; import { hygieneDiffSchema, hygieneEffectSchema, hygieneMediaReceiptSchema, hygieneOutcomeSchema, hygieneReviewStateSchema, inboxOptionSchema } from "@schlessera/brain-ui-sdk/schemas"; import { isUsablePrincipal, resolvePrincipal } from "../db/principals.js"; import { createInboxAction, insertInboxAction, inboxIdentity } from "./actions.js"; @@ -106,7 +106,14 @@ export function setup(db: Database, { timeZone }: { timeZone?: string }): WriteP // Every remaining finding left pending is a complete pass too: the counts stay truthful. if (!finding) { save({ ...review, status: "complete", pauseReason: undefined, counts: next.counts, media: mediaOf(next) }); return; } const readmitting = paused && action(paused.retiredActionId).hygiene!.findingId === finding.id && action(paused.retiredActionId).hygiene!.fingerprint === finding.fingerprint; - const itemId = readmitting ? inboxIdentity("hygiene-readmission", paused.retiredActionId) : inboxIdentity("hygiene", finding.id, finding.fingerprint); + let itemId = readmitting ? inboxIdentity("hygiene-readmission", paused.retiredActionId) : inboxIdentity("hygiene", finding.id, finding.fingerprint); + // A media effect undone from review (#2781) leaves its card resolved and the finding + // pending at the same fingerprint: the finding gets a successor card, never the old one back. + let afterUndo = false; + for (let prior = store.getItem(itemId); prior?.queue === "actions" && prior.status === "resolved" && prior.hygiene?.outcome?.status === "undone"; prior = store.getItem(itemId)) { + itemId = inboxIdentity("hygiene-after-undo", prior.id); + afterUndo = true; + } const existing = store.orderedItems().map(v => v.item).find(i => i.queue === "actions" && i.hygiene?.findingId === finding.id && i.hygiene.fingerprint === finding.fingerprint && ["pending", "snoozed"].includes(i.status)) ?? store.getItem(itemId); if (existing) { if (existing.queue === "actions" && ["pending", "snoozed"].includes(existing.status)) { @@ -116,7 +123,7 @@ export function setup(db: Database, { timeZone }: { timeZone?: string }): WriteP } throw new Error("Finding already has a terminal Action for this fingerprint"); } - const threadId = readmitting ? inboxIdentity("hygiene-readmission-thread", itemId) : inboxIdentity("hygiene-thread", finding.id, finding.fingerprint); + const threadId = readmitting ? inboxIdentity("hygiene-readmission-thread", itemId) : afterUndo ? inboxIdentity("hygiene-after-undo-thread", itemId) : inboxIdentity("hygiene-thread", finding.id, finding.fingerprint); store.openReviewThread(threadId); const item: InboxActionItem = { id: itemId, dedupKey: itemId, threadId, queue: "actions", type: "choose", status: "pending", version: 1, createdAt: now(), updatedAt: now(), expiresAt: Number.MAX_SAFE_INTEGER, payload: { title: finding.title, detail: finding.path }, options, hygiene: { findingId: finding.id, fingerprint: finding.fingerprint, finding } }; @@ -207,6 +214,29 @@ export function setup(db: Database, { timeZone }: { timeZone?: string }): WriteP db.query("UPDATE hygiene_effect_attempts SET status = 'finished', result_json = ? WHERE id = ?").run(JSON.stringify(result), attempt.id); }).immediate(); }, + /** + * Undo from review (#2781, ruling 2026-11-03): record the Undo's receipt on + * the resolved card that applied the effect. An undone effect no longer + * counts as fixed or kept; a refused Undo only refreshes the card's + * receipt, so its Undo availability is current. + */ + mediaUndo(time: number, principalId: string, itemId: string, journalId: string, receipt: HygieneMediaReceipt, source: HygieneMediaReceipt | null) { + at = time; + authority(principalId); + return db.transaction(() => { + const item = action(itemId), prior = item.hygiene!.outcome; + if (item.status !== "resolved" || prior?.media?.journalId !== journalId) return; + const next: NonNullable = receipt.outcome === "undone" ? { version: 1, status: "undone", media: receipt } + : receipt.outcome === "partial" ? { version: 1, status: "check_failed", code: "partial", ...(receipt.reason ? { reason: receipt.reason } : {}), media: receipt } + : source ? { ...prior, media: source } : prior; + if (next === prior) return; + store.commit([{ kind: "hygiene_media_receipt", itemId, expectedVersion: item.version, outcome: hygieneOutcomeSchema.parse(next) }]); + if (receipt.outcome === "undone") { + const review = state(); + save({ ...review, fixed: Math.max(0, review.fixed - (prior.status === "fixed" ? 1 : 0)), kept: Math.max(0, (review.kept ?? 0) - (prior.status === "kept" ? 1 : 0)) }); + } + }).immediate(); + }, admit(time: number, principalId: string, request: ClientInboxResolve) { at = time; return db.transaction(() => { diff --git a/packages/ui-server/src/inbox/media-effects.ts b/packages/ui-server/src/inbox/media-effects.ts index 68c106b507..ee7ee2bf5e 100644 --- a/packages/ui-server/src/inbox/media-effects.ts +++ b/packages/ui-server/src/inbox/media-effects.ts @@ -169,11 +169,28 @@ export function createMediaEffects(db: Database, options: { return () => failure; } + /** + * Undo of Keep a permanent copy also removes the kept entry step 6b wrote, + * after the copy and config are restored (rev 5 §5.7, ruling 2026-11-03), + * so the original is pending again rather than reopened as `copy-missing`. + * An entry already gone (invalidated, hand-moved) needs nothing; any other + * answer leaves the Undo `partial`. + */ + async function releaseKept(source: Row): Promise { + let answer: z.infer; + try { answer = keptSchema.parse(await options.cli(["unkeep", "--journal", source.id, "--", source.finding_id])); } + catch { return "kept-entry-unknown"; } + finally { await journal.observe(); } + return answer.status === "unkept" || answer.reason === "not-kept" ? null : "kept-entry-unremoved"; + } + async function compensate(row: Row, plan: HygieneMediaPlan, reason: string): Promise { const versions = JSON.parse(row.versions) as Record; const files = await restore(plan.files, versions, row.journal_turn_id); const clean = files.every(f => ["restored", "unchanged"].includes(f.state)); - return { journalId: row.id, action: plan.action, outcome: clean ? "compensated" : "partial", reason, files, undo: { available: false, reason: "no-confirmed-effect" } }; + // A copy whose step 6b receipt was lost may have its entry: a copy never leaves a record behind. + const kept = clean && plan.action === "keep-copy" ? await releaseKept(row) : null; + return { journalId: row.id, action: plan.action, outcome: clean && !kept ? "compensated" : "partial", reason: kept ?? reason, files, undo: { available: false, reason: "no-confirmed-effect" } }; } /** @@ -273,7 +290,8 @@ export function createMediaEffects(db: Database, options: { const files = await restore(plan.files, JSON.parse(source.versions), source.journal_turn_id); await journal.observe(); const clean = files.every(f => ["restored", "unchanged"].includes(f.state)); - return { journalId: row.id, action: plan.action, outcome: clean ? "undone" : "partial", files, undo: { available: false, reason: "already-undone" } }; + const kept = clean && plan.action === "keep-copy" ? await releaseKept(source) : null; + return { journalId: row.id, action: plan.action, outcome: clean && !kept ? "undone" : "partial", ...(kept ? { reason: kept } : {}), files, undo: { available: false, reason: "already-undone" } }; }); } catch { receipt = { journalId: row.id, action: plan.action, outcome: "partial", reason: "operation-unavailable", files: [], undo: { available: false } }; @@ -304,7 +322,9 @@ export function createMediaEffects(db: Database, options: { receipt = await exclusive(`media-recover:${row.id}`, async () => { const files = await restore(plan.files, JSON.parse((source ?? row).versions), (source ?? row).journal_turn_id); const clean = files.every(f => ["restored", "unchanged"].includes(f.state)); - return { journalId: row.id, action: plan.action, outcome: row.source_id ? (clean ? "undone" : "partial") : (clean ? "compensated" : "partial"), reason: "interrupted", files, undo: { available: false, reason: "no-confirmed-effect" } }; + // A copy's kept entry goes with it, whether an Undo or an apply was interrupted. + const kept = clean && plan.action === "keep-copy" ? await releaseKept(source ?? row) : null; + return { journalId: row.id, action: plan.action, outcome: clean && !kept ? (row.source_id ? "undone" : "compensated") : "partial", reason: kept ?? "interrupted", files, undo: { available: false, reason: "no-confirmed-effect" } }; }); if (source && ["undone", "partial"].includes(receipt.outcome)) await save(source, receipt.outcome === "undone" ? "undone" : "undo-partial", JSON.parse(source.receipt)); } diff --git a/packages/ui-server/src/inbox/store.ts b/packages/ui-server/src/inbox/store.ts index e9f56bf713..30cd7c83e1 100644 --- a/packages/ui-server/src/inbox/store.ts +++ b/packages/ui-server/src/inbox/store.ts @@ -73,6 +73,11 @@ export interface InboxReservation { } export type InboxMutation = | { kind: "hygiene_update"; itemId: string; expectedVersion: number; hygiene: HygieneAction; options: InboxOption[] } + /** + * A resolved media card's receipt after Undo from review (#2781): only its + * outcome changes, never its options or its terminal status. + */ + | { kind: "hygiene_media_receipt"; itemId: string; expectedVersion: number; outcome: NonNullable } | { kind: "item"; item: InboxItem } | { kind: "retain_block"; itemId: string; expectedVersion: number; expiresAt: number } | { @@ -647,6 +652,16 @@ export class InboxStore { this.change(next.threadId, { kind: "upsert_item", itemId: next.id, item: next }); return; } + case "hygiene_media_receipt": { + const row = this.itemRow(mutation.itemId), item = wireItem(row); + if (row.deleted_at !== null || item.queue !== "actions" || !item.hygiene?.outcome?.media || !mutation.outcome.media || item.version !== mutation.expectedVersion || item.status !== "resolved") + throw new Error("Inbox version conflict"); + const next: InboxActionItem = { ...item, hygiene: { ...item.hygiene, outcome: mutation.outcome }, version: item.version + 1, updatedAt: now }; + validateItem(next); + this.db.query("UPDATE inbox_items SET version = ?, data_json = ? WHERE id = ?").run(next.version, JSON.stringify(next), next.id); + this.change(next.threadId, { kind: "upsert_item", itemId: next.id, item: next }); + return; + } case "item": this.insertItem(mutation.item); return; diff --git a/packages/ui-server/src/routes/hygiene-review.ts b/packages/ui-server/src/routes/hygiene-review.ts index 029666df73..d530b0c822 100644 --- a/packages/ui-server/src/routes/hygiene-review.ts +++ b/packages/ui-server/src/routes/hygiene-review.ts @@ -1,5 +1,5 @@ import { Hono } from "hono"; -import { hygienePreviewRequestSchema, hygieneReviewCommandSchema } from "@schlessera/brain-ui-sdk/schemas"; +import { hygienePreviewRequestSchema, hygieneReviewRequestSchema } from "@schlessera/brain-ui-sdk/schemas"; import type { AppEnv } from "../app-env.js"; import { readJsonBody } from "../middleware/body-limit.js"; import { requireJson } from "../middleware/origin.js"; @@ -26,9 +26,10 @@ export function createHygieneReviewRoutes(review: HygieneReview) { let body: unknown; try { body = await readJsonBody(c); } catch { return c.json({ error: "invalid_request" }, 400); } if (body instanceof Response) return body; - const parsed = hygieneReviewCommandSchema.safeParse(body); + const parsed = hygieneReviewRequestSchema.safeParse(body); if (!parsed.success) return c.json({ error: "invalid_request" }, 400); - try { return c.json(review.readFor(principal.id, await review.command(principal.id, parsed.data.operation))); } + const command = parsed.data; + try { return c.json(review.readFor(principal.id, command.operation === "undo-media" ? await review.undoMedia(principal.id, command.journalId) : await review.command(principal.id, command.operation))); } catch (e) { return c.json({ error: e instanceof HygieneAuthorityError ? "Unauthorized" : "review_failed" }, e instanceof HygieneAuthorityError ? 403 : 500); } }); app.post("/hygiene/review/preview", requireJson(), async c => { diff --git a/packages/ui-server/tests/cli-inventory.test.ts b/packages/ui-server/tests/cli-inventory.test.ts index 08bb862cdb..506e721d61 100644 --- a/packages/ui-server/tests/cli-inventory.test.ts +++ b/packages/ui-server/tests/cli-inventory.test.ts @@ -25,6 +25,8 @@ const available: Record = { // 0.45.0 (.changeset/media-review-effects.md, media-awaiting-review.md). "hygiene media delete": "0.45.0", "hygiene media move": "0.45.0", "hygiene media persist": "0.45.0", "hygiene media keep-copy": "0.45.0", "hygiene keep-copy": "0.45.0", + // #2781: Undo of a kept copy removes its kept entry (rev 5 §5.7). Unreleased until 0.45.0 (.changeset/media-undo-review.md). + "hygiene unkeep": "0.45.0", }; // Dynamic branches may overapproximate a command's flags. Record availability // within its namespace; this inventory enforces versions, not valid usage. @@ -49,7 +51,7 @@ const commandFlags: Record> = { * its flags. Every media effect acts on a media finding, which only a CLI at * HYGIENE_MEDIA_CLI_VERSION reports, so an older CLI is never asked for one. */ -const mediaCommands = ["hygiene media delete", "hygiene media move", "hygiene media persist", "hygiene media keep-copy", "hygiene keep-copy"]; +const mediaCommands = ["hygiene media delete", "hygiene media move", "hygiene media persist", "hygiene media keep-copy", "hygiene keep-copy", "hygiene unkeep"]; const featureFloors: Record = { "hygiene next --defer": HYGIENE_MEDIA_CLI_VERSION, ...Object.fromEntries(mediaCommands.map(command => [command, HYGIENE_MEDIA_CLI_VERSION])) }; const globalFlags: Record = { "--": "0.33.0", "--json": "0.33.0", "--version": "0.33.0" }; @@ -232,8 +234,8 @@ function inventory() { expect(selections).toBe(6); expect(probes).toBe(1); expect([...sites].sort()).toEqual(["packages/ui-server/src/brain/client.ts", "packages/ui-server/src/inbox/hygiene-review.ts", "packages/ui-server/src/inbox/media-effects.ts"]); - // Apply (`hygiene media`) and step 6b (`hygiene keep-copy`), and one bound CLI feeding them. - expect(mediaSites).toBe(2); + // Apply (`hygiene media`), step 6b (`hygiene keep-copy`) and its Undo (`hygiene unkeep`), and one bound CLI feeding them. + expect(mediaSites).toBe(3); expect(boundHygiene).toBe(1); // hygiene's forwarding wrapper adds --json to every subcommand. for (const [command, flags] of found) if (command.startsWith("hygiene ")) flags.add("--json"); diff --git a/packages/ui-server/tests/hygiene-media-effects.test.ts b/packages/ui-server/tests/hygiene-media-effects.test.ts index 4e61cb2e71..1d960db70c 100644 --- a/packages/ui-server/tests/hygiene-media-effects.test.ts +++ b/packages/ui-server/tests/hygiene-media-effects.test.ts @@ -23,6 +23,9 @@ import { createHygieneReview } from "../src/inbox/hygiene-review.js"; import { createPrincipal } from "../src/db/principals.js"; import type { BrainClient } from "../src/brain/client.js"; import { createInboxStore } from "../src/inbox/store.js"; +import { Hono } from "hono"; +import type { AppEnv } from "../src/app-env.js"; +import { createHygieneReviewRoutes } from "../src/routes/hygiene-review.js"; const createInboxStoreRead = (db: Parameters[0], id: string) => { const item = createInboxStore(db).getItem(id); return item?.queue === "actions" ? item : null; }; import { createNativeJournalFixture } from "./helpers/native-journal-fixture.js"; @@ -128,6 +131,12 @@ test("Keep a permanent copy records the kept entry after the copy verifies; Undo expect(existsSync(join(f.root, "places/ithaca/harbour-dawn.jpg"))).toBe(false); expect(read(f.root, "brain.config.json")).toBe("{}\n"); expect(read(f.root, SCRATCH), "MEDIA_KEEP_UNDO_ORIGINAL").toBe("dawn bytes"); + // The kept entry goes in the same Undo (rev 5 §5.7): the original is pending again, never reopened as copy-missing. + expect(read(f.root, "context/hygiene/kept.md"), "MEDIA_KEEP_UNDO_UNKEPT").not.toContain("harbour-dawn"); + const entries = run(f.root, process.execPath, CORE_CLI, "hygiene", "--json", "list").stdout; + const original = (JSON.parse(entries) as { entries: Array<{ path: string; state: string; invalidation: unknown }> }).entries.find(e => e.path === SCRATCH); + expect(original, "MEDIA_KEEP_UNDO_OPEN").toMatchObject({ state: "open", invalidation: null }); + expect(read(f.root, "context/hygiene/open.md")).not.toContain("copy-missing"); }); test("a refused kept entry (step 6b) removes the copy and restores the config", async () => { @@ -231,3 +240,102 @@ test("review offers the media effects with their plans, applies one through the expect(resolved?.hygiene?.outcome, "MEDIA_REVIEW_RECEIPT").toMatchObject({ status: "fixed", media: { outcome: "applied", action: "move", undo: { available: true } } }); expect(done.review.fixed).toBe(1); }); + +/** Two media findings in review, with nothing else selectable first. */ +async function reviewWithTwo(f: Awaited>) { + rmSync(join(f.root, NOTE)); rmSync(join(f.root, "places/ithaca.md")); + put(f.root, "photos/achilles-shield.jpg", "shield bytes"); + return (await f.review.command(f.reviewer.id, "start")).action!; +} +const resolveWith = (f: Awaited>, itemId: string, optionId: string) => f.review.resolver.resolveAsync(f.reviewer.id, { type: "inbox_resolve", itemId, optionId }); + +test("undo-media from review undoes a resolved Delete, records the Undo on the card, and the finding returns on a successor card", async () => { + const f = await setup(); + const card = await reviewWithTwo(f); + const deleted = (card.hygiene!.finding as { path: string }).path; + const bytes = read(f.root, deleted); + await resolveWith(f, card.id, "media-delete"); + const resolved = createInboxStoreRead(f.db, card.id)!; + expect(resolved.hygiene?.outcome).toMatchObject({ status: "fixed", media: { outcome: "applied", undo: { available: true } } }); + expect(existsSync(join(f.root, deleted))).toBe(false); + expect(f.review.read().review.fixed).toBe(1); + const second = f.review.read().action!; + + const result = await f.review.undoMedia(f.reviewer.id, resolved.hygiene!.outcome!.media!.journalId); + expect(result.mediaUndo, "MEDIA_REVIEW_UNDO").toMatchObject({ outcome: "undone", files: [{ path: deleted, state: "restored" }] }); + expect(read(f.root, deleted), "MEDIA_REVIEW_UNDO_BYTES").toBe(bytes); + const after = createInboxStoreRead(f.db, card.id)!; + expect(after.status, "MEDIA_REVIEW_UNDO_CARD_TERMINAL").toBe("resolved"); + expect(after.hygiene?.outcome, "MEDIA_REVIEW_UNDO_CARD").toMatchObject({ status: "undone", media: { outcome: "undone", action: "delete" } }); + expect(result.review.fixed, "MEDIA_REVIEW_UNDO_COUNTER").toBe(0); + // The same command again changes nothing. + expect((await f.review.undoMedia(f.reviewer.id, resolved.hygiene!.outcome!.media!.journalId)).mediaUndo.outcome).toBe("undone"); + expect(createInboxStoreRead(f.db, card.id)!.version).toBe(after.version); + + // Leaving the other card pending selects the restored finding again, on a new card. + await resolveWith(f, second.id, "leave-pending"); + const again = f.review.read().action; + expect(again?.hygiene?.findingId, "MEDIA_REVIEW_UNDO_RESELECTED").toBe(card.hygiene!.findingId); + expect(again?.id).not.toBe(card.id); + expect(again?.status).toBe("pending"); +}); + +test("undo-media refuses before any write when a file changed since, and the card shows why", async () => { + const f = await setup(); + const card = await reviewWithTwo(f); + const deleted = (card.hygiene!.finding as { path: string }).path; + await resolveWith(f, card.id, "media-delete"); + const journalId = createInboxStoreRead(f.db, card.id)!.hygiene!.outcome!.media!.journalId; + put(f.root, deleted, "Penelope wove it again\n"); + const result = await f.review.undoMedia(f.reviewer.id, journalId); + expect(result.mediaUndo, "MEDIA_REVIEW_UNDO_REFUSED").toMatchObject({ outcome: "refused", reason: "changed-since" }); + expect(read(f.root, deleted), "MEDIA_REVIEW_UNDO_REFUSAL_NO_WRITE").toBe("Penelope wove it again\n"); + expect(createInboxStoreRead(f.db, card.id)!.hygiene?.outcome, "MEDIA_REVIEW_UNDO_REFUSAL_CARD").toMatchObject({ status: "fixed", media: { outcome: "applied", undo: { available: false, reason: "changed-since", path: deleted } } }); + expect(result.review.fixed).toBe(1); + // Another principal cannot reach this receipt. + const other = createPrincipal(f.db, { authMethod: "password", label: "Telemachus", ttlSeconds: 86400 }); + await expect(f.review.undoMedia(other.id, journalId), "MEDIA_REVIEW_UNDO_OWNER").rejects.toThrow(); +}); + +test("undo-media of a kept copy from review removes the copy, its rule and its kept entry, and the kept counter drops", async () => { + const f = await setup(); + rmSync(join(f.root, NOTE)); rmSync(join(f.root, "places/ithaca.md")); rmSync(join(f.root, LOOM)); + put(f.root, SCRATCH, "dawn bytes"); + put(f.root, ".brain/scratch-pins/pins.json", JSON.stringify({ version: 1, ready: true, sessions: { '["claude","ithaca"]': [SCRATCH] } })); + const card = (await f.review.command(f.reviewer.id, "start")).action!; + expect((card.hygiene!.finding as { path: string }).path).toBe(SCRATCH); + const previewed = await f.review.preview(f.reviewer.id, { itemId: card.id, optionId: "media-keep-copy", expectedVersion: card.version, input: "places/ithaca/harbour-dawn.jpg" }); + expect(previewed.options.find(o => o.id === "media-keep-copy")?.media?.refusals).toEqual([]); + await resolveWith(f, card.id, "media-keep-copy"); + expect(createInboxStoreRead(f.db, card.id)!.hygiene?.outcome?.status).toBe("kept"); + expect(f.review.read().review.kept).toBe(1); + const result = await f.review.undoMedia(f.reviewer.id, createInboxStoreRead(f.db, card.id)!.hygiene!.outcome!.media!.journalId); + expect(result.mediaUndo, "MEDIA_REVIEW_UNDO_KEPT").toMatchObject({ outcome: "undone", action: "keep-copy" }); + expect(existsSync(join(f.root, "places/ithaca/harbour-dawn.jpg"))).toBe(false); + expect(read(f.root, "brain.config.json")).toBe("{}\n"); + expect(read(f.root, "context/hygiene/kept.md"), "MEDIA_REVIEW_UNDO_UNKEPT").not.toContain("harbour-dawn"); + expect(read(f.root, SCRATCH)).toBe("dawn bytes"); + expect(result.review.kept, "MEDIA_REVIEW_UNDO_KEPT_COUNTER").toBe(0); +}); + +test("POST /hygiene/review routes undo-media: a refusal is a 200 result, a malformed body 400, an unknown receipt 500", async () => { + const f = await setup(); + const card = await reviewWithTwo(f); + const deleted = (card.hygiene!.finding as { path: string }).path; + await resolveWith(f, card.id, "media-delete"); + const journalId = createInboxStoreRead(f.db, card.id)!.hygiene!.outcome!.media!.journalId; + const app = new Hono(); + app.use("*", async (c, next) => { c.set("principal", { id: f.reviewer.id } as never); await next(); }); + app.route("/", createHygieneReviewRoutes(f.review)); + const post = async (body: unknown) => { const res = await app.request("/hygiene/review", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); return { status: res.status, body: await res.json() as Record }; }; + put(f.root, deleted, "Penelope wove it again\n"); + const refused = await post({ operation: "undo-media", journalId }); + expect(refused.status, "MEDIA_ROUTE_UNDO_REFUSED").toBe(200); + expect(refused.body.mediaUndo).toMatchObject({ outcome: "refused", reason: "changed-since" }); + expect((await post({ operation: "undo-media" })).status, "MEDIA_ROUTE_UNDO_MALFORMED").toBe(400); + expect((await post({ operation: "undo-media", journalId: `media-${"0".repeat(40)}` })).status, "MEDIA_ROUTE_UNDO_UNKNOWN").toBe(500); + rmSync(join(f.root, deleted)); + const undone = await post({ operation: "undo-media", journalId }); + expect(undone, "MEDIA_ROUTE_UNDO").toMatchObject({ status: 200, body: { mediaUndo: { outcome: "undone" } } }); + expect(existsSync(join(f.root, deleted))).toBe(true); +}); From 111c4cd459671cf14e326b0f4e2f827756d6ee89 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 12:35:16 +0000 Subject: [PATCH 2/3] test(core): prove Keep a permanent copy refuses a source changed mid-copy and publishes by link, never rename (#2781) A test-only copyHooks seam in MediaEffectContext runs inside the copy step, after each chunk reaches the private .part and just before it is published. Two tests use it: a source rewritten mid-copy refuses source-changed with no copy and no .part left; a destination that appears just before publishing refuses exists and keeps its own bytes. Co-Authored-By: Claude Opus 5.5 --- packages/core/src/lib/media-effects.ts | 12 ++++++++++-- packages/core/tests/media-effects.test.ts | 24 +++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/packages/core/src/lib/media-effects.ts b/packages/core/src/lib/media-effects.ts index 8b51160b7c..876c04abe3 100644 --- a/packages/core/src/lib/media-effects.ts +++ b/packages/core/src/lib/media-effects.ts @@ -131,6 +131,12 @@ export interface MediaEffectContext { limits?: MediaReferenceLimits; /** Tests inject the inventory; otherwise it is built afresh. */ inventory?: MediaInventory; + /** + * Tests only: run inside Keep a permanent copy's copy step, after each + * chunk is written to the private `.part` and just before it is published, + * to change the source or the destination at exactly that moment. + */ + copyHooks?: { afterChunk?: () => void; beforePublish?: () => void }; } const sha256 = (data: string | Uint8Array) => createHash("sha256").update(data).digest("hex"); @@ -480,7 +486,7 @@ function replaceExpected(root: string, path: string, expected: string, text: str } /** Stream `source` into an exclusive private `.part` beside `destination`, hashing as it goes; publish it with link(2), which never overwrites. */ -function copyExclusive(root: string, source: string, destination: string, expected: string, opId: string): void { +function copyExclusive(root: string, source: string, destination: string, expected: string, opId: string, hooks: MediaEffectContext["copyHooks"] = {}): void { const srcParent = openDir(root, posix.dirname(source) === "." ? "" : posix.dirname(source)); const dstParent = openDir(root, posix.dirname(destination) === "." ? "" : posix.dirname(destination)); const name = posix.basename(destination), part = `.${name}.${opId}.part`; @@ -498,11 +504,13 @@ function copyExclusive(root: string, source: string, destination: string, expect let written = 0; while (written < read) written += writeSync(output, buffer, written, read - written, position + written); position += read; + hooks.afterChunk?.(); } const endStat = fstatSync(input); fsyncSync(output); if (hash.digest("hex") !== expected || endStat.size !== startStat.size || endStat.mtimeMs !== startStat.mtimeMs) throw new StepFailed("source-changed"); closeSync(output); output = undefined; + hooks.beforePublish?.(); try { linkSync(at(dstParent, part), at(dstParent, name)); } catch (e) { throw new StepFailed((e as NodeJS.ErrnoException).code === "EEXIST" ? "exists" : "copy-failed"); } unlinkSync(at(dstParent, part)); partMade = false; @@ -589,7 +597,7 @@ export function applyMediaEffect(ctx: MediaEffectContext, request: MediaEffectRe } } if (request.action === "keep-copy") { - copyExclusive(root, source, plan.destination!, sha, request.journal); + copyExclusive(root, source, plan.destination!, sha, request.journal, ctx.copyHooks); mark(plan.destination!, "created"); } const config = plan.files.find((f) => f.role === "config"); diff --git a/packages/core/tests/media-effects.test.ts b/packages/core/tests/media-effects.test.ts index 045b6ed6d5..55b8f08e61 100644 --- a/packages/core/tests/media-effects.test.ts +++ b/packages/core/tests/media-effects.test.ts @@ -291,6 +291,30 @@ describe("Keep a permanent copy", () => { expect(read(root, "places/harbour-dawn.jpg")).toBe("Telemachus's own photo"); }); + test("a source changed while it is being copied refuses the copy before any write; no copy or private part is left", () => { + const root = brain(); + pin(root, SCRATCH); + const { request, preview } = plan(root, "keep-copy", SCRATCH, "places/harbour-dawn.jpg"); + let changed = false; + const result = apply(root, request, preview, { copyHooks: { afterChunk: () => { if (!changed) { changed = true; writeFileSync(join(root, SCRATCH), "dawn bytes, then dusk"); } } } }); + expect(changed).toBe(true); + expect(result, "KEEP_SOURCE_CHANGED_MID_COPY").toMatchObject({ status: "refused", reason: "source-changed" }); + expect(existsSync(join(root, "places/harbour-dawn.jpg")), "KEEP_MID_COPY_NO_COPY").toBe(false); + expect(readdirSync(join(root, "places")).filter((n) => n.endsWith(".part")), "KEEP_MID_COPY_NO_PART").toEqual([]); + expect(read(root, SCRATCH)).toBe("dawn bytes, then dusk"); + }); + + test("the copy is published with link, never rename: a destination that appears just before publishing is kept", () => { + const root = brain(); + pin(root, SCRATCH); + const { request, preview } = plan(root, "keep-copy", SCRATCH, "places/harbour-dawn.jpg"); + const result = apply(root, request, preview, { copyHooks: { beforePublish: () => put(root, "places/harbour-dawn.jpg", "Telemachus's own photo") } }); + expect(result, "KEEP_LINK_NOT_RENAME").toMatchObject({ status: "refused", reason: "exists" }); + expect(read(root, "places/harbour-dawn.jpg"), "KEEP_LINK_NO_OVERWRITE").toBe("Telemachus's own photo"); + expect(readdirSync(join(root, "places")).filter((n) => n.endsWith(".part"))).toEqual([]); + expect(read(root, SCRATCH)).toBe("dawn bytes"); + }); + test("content media is not offered a copy", () => { const root = brain(); expect(plan(root, "keep-copy", LOOM, "places/loom.png").preview.refusals.map((r) => r.code), "KEEP_NOT_SCRATCH").toEqual(["not-linked-scratch"]); From daa700494c4223aa28328c8a5be752c6e0d79162 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 12:35:41 +0000 Subject: [PATCH 3/3] test(ui-server): a later ordinary sync commits a kept copy and its rule, never the scratch original (#2781) Co-Authored-By: Claude Opus 5.5 --- .../ui-server/tests/hygiene-media-effects.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/ui-server/tests/hygiene-media-effects.test.ts b/packages/ui-server/tests/hygiene-media-effects.test.ts index 1d960db70c..4550a44de6 100644 --- a/packages/ui-server/tests/hygiene-media-effects.test.ts +++ b/packages/ui-server/tests/hygiene-media-effects.test.ts @@ -139,6 +139,20 @@ test("Keep a permanent copy records the kept entry after the copy verifies; Undo expect(read(f.root, "context/hygiene/open.md")).not.toContain("copy-missing"); }); +test("a later ordinary sync commits the kept copy and its rule, and never the scratch original", async () => { + const f = await setup(); + put(f.root, SCRATCH, "dawn bytes"); + put(f.root, ".brain/scratch-pins/pins.json", JSON.stringify({ version: 1, ready: true, sessions: { '["claude","ithaca"]': [SCRATCH] } })); + expect((await f.apply(SCRATCH, "keep-copy", "places/ithaca/harbour-dawn.jpg")).outcome).toBe("kept"); + run(f.root, "git", "config", "user.name", "Penelope"); run(f.root, "git", "config", "user.email", "penelope@example.test"); + const synced = run(f.root, process.execPath, CORE_CLI, "sync", "commit"); + expect(synced.code, `MEDIA_KEEP_SYNC_EXIT ${synced.stderr}`).toBe(0); + expect(run(f.root, "git", "show", "HEAD:places/ithaca/harbour-dawn.jpg").stdout, "MEDIA_KEEP_SYNC_COPY").toBe("dawn bytes"); + expect(run(f.root, "git", "show", "HEAD:brain.config.json").stdout, "MEDIA_KEEP_SYNC_CONFIG").toBe('{ "media": { "track": ["places/ithaca/harbour-dawn.jpg"] } }\n'); + expect(run(f.root, "git", "ls-files", "--", ".brain").stdout, "MEDIA_KEEP_SYNC_NO_SCRATCH").toBe(""); + expect(read(f.root, SCRATCH)).toBe("dawn bytes"); +}); + test("a refused kept entry (step 6b) removes the copy and restores the config", async () => { const f = await setup({ wrap: (args, real) => args[0] === "keep-copy" ? { status: "refused", reason: "copy-changed" } : real(args) }); put(f.root, SCRATCH, "dawn bytes");