From 14d6986b556a85ee21a122e3b8c3f76d23edf17d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 10:40:31 +0100 Subject: [PATCH 1/2] CONTRACT: feat: governed Delete, Move, Persist here and Keep a permanent copy for media findings, with journal capture, compensation and Undo (#2781) (#3421) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * CONTRACT: feat(core): plan and apply media finding effects against a previewed premise (#2781) `brain hygiene media ` plans a media finding's effect read-only (--dry-run): every file it writes with its expected SHA-256 before and after, Move's reference rewrites in each reference's own style (code untouched), the frontmatter/HTML references that block a Move, the exact media.track change, the bytes the caller must retain, and named refusals (rev 4 §4.2 matrix, §5.2 destination guards, §7 config scope). Apply recomputes the plan and writes only while its premise digest matches; Move is link then unlink (never overwrites, EXDEV refuses), a copy streams into a private .part published by link. The config is a minimal splice of a literal brain.config, parsed as syntax and never evaluated, then read back and verified to class the file TRACK. Apply never compensates: the journal holder retains every listed pre-image first and restores per file (ui-server, next commit), and `interrupted` names what was written before a step failed. BRAIN_MEDIA_REFERENCE_LIMITS gains rewrittenNotes (200) and preview (1 MiB), the remaining two Q1 limits, each admitted at its bound and refused one past it. Co-Authored-By: Claude Opus 5.5 * CONTRACT: feat(ui-server): journal-captured media effects with per-file compensation, Undo and recovery (#2781) The host side of Delete, Move, Persist here and Keep a permanent copy (Rollback A). Under the exclusive writer gate a user journal turn covers every file the plan lists, and each pre-image is retained and verified by SHA-256 before the CLI writes; a capture the journal cannot hold refuses as capture-capacity with nothing written. Compensation, Undo and restart recovery share one rule: a file is put back only while it still holds what the effect wrote, so a later edit is a reported conflict (outcome partial), never overwritten. Undo preflights retained data and every post-image and refuses before any write (rollback-evicted, changed-since). Recovery compensates an interrupted effect from its durable row and never re-applies. Keep a permanent copy runs `brain hygiene keep-copy` (step 6b) only after the copy verified, and compensates when it is refused. Review offers the four effects on a media card with their plans; a plan with refusals cannot be confirmed. Applied resolves the card as fixed, a kept copy as kept (the review's kept counter); compensated/partial are check_failed. Recovery confirms a kept copy only when entry, fingerprint and copy SHA-256 match. SDK additions: media-* effect operations, InboxOption.media, outcome status kept and outcome.media receipts. Co-Authored-By: Claude Opus 5.5 * fix(ui-server): register the media hygiene commands at their 0.45.0 feature floor (#2781) Ready-candidate CI failed the server CLI inventory: `brain hygiene media` and the media-* dispositions were not registered at an enforced floor. - dispatch's generic disposition argv could carry a media operation by type (startsWith did not narrow), so the scanner read four phantom `hygiene media-*` commands. A type guard narrows it, and the media plan's action comes from a bounded operation map. - The inventory now scans media-effects.ts's injected hygiene CLI (apply and step 6b `keep-copy`), which it previously missed, expands `hygiene media `, and pins the app's one bound hygiene CLI to the media effects' `cli` option. - `hygiene media `, `hygiene keep-copy` and `--to`, `--expect-premise`, `--journal`, `--copy`, `--copy-sha256` are recorded at 0.45.0 under HYGIENE_MEDIA_CLI_VERSION; a command's feature floor bounds its flags. MIN_BRAIN_CLI_VERSION is unchanged; the existing release check still raises it when 0.45.0 ships. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .changeset/media-review-effects.md | 13 + api-report/ui-sdk.txt | 1484 ++++++++++++++++- docs/configuration.md | 2 +- docs/decisions/claude-code-runtime.md | 4 +- docs/decisions/http-api-boundary.md | 8 +- docs/decisions/hygiene-review.md | 16 +- docs/decisions/managed-worktrees.md | 2 +- docs/decisions/scheduled-tasks.md | 2 +- docs/decisions/session-principals.md | 6 +- docs/integration-contract/cli.md | 1 + docs/integration-contract/package-api.md | 57 +- docs/integration-contract/wire.md | 6 +- .../plans/async-collaboration-requirements.md | 2 +- docs/plans/async-collaboration.md | 2 +- docs/plans/chat-history-deletion.md | 2 +- docs/plans/navigation-recovery.md | 2 +- docs/plans/storage-accounting.md | 2 +- packages/core/README.md | 2 +- packages/core/src/cli/commands/hygiene.ts | 51 +- packages/core/src/cli/io.ts | 2 +- packages/core/src/config/env.ts | 2 +- packages/core/src/lib/media-config-edit.ts | 173 ++ packages/core/src/lib/media-effects.ts | 627 +++++++ packages/core/src/lib/media-references.ts | 8 +- packages/core/src/lib/media-review.ts | 2 +- packages/core/tests/media-effects.test.ts | 298 ++++ packages/ui-sdk/src/protocol.ts | 56 +- packages/ui-sdk/src/schemas.ts | 34 +- .../075_hygiene_media_operations.journal.sql | 13 + packages/ui-server/src/app.ts | 11 + packages/ui-server/src/brain/client.ts | 8 +- .../ui-server/src/inbox/hygiene-review.ts | 83 +- .../ui-server/src/inbox/hygiene-writes.ts | 27 +- packages/ui-server/src/inbox/media-effects.ts | 322 ++++ .../ui-server/tests/cli-inventory.test.ts | 56 +- .../tests/hygiene-media-effects.test.ts | 233 +++ 36 files changed, 3554 insertions(+), 65 deletions(-) create mode 100644 .changeset/media-review-effects.md create mode 100644 packages/core/src/lib/media-config-edit.ts create mode 100644 packages/core/src/lib/media-effects.ts create mode 100644 packages/core/tests/media-effects.test.ts create mode 100644 packages/ui-server/migrations/075_hygiene_media_operations.journal.sql create mode 100644 packages/ui-server/src/inbox/media-effects.ts create mode 100644 packages/ui-server/tests/hygiene-media-effects.test.ts diff --git a/.changeset/media-review-effects.md b/.changeset/media-review-effects.md new file mode 100644 index 0000000000..64f3f28323 --- /dev/null +++ b/.changeset/media-review-effects.md @@ -0,0 +1,13 @@ +--- +"@schlessera/brain": minor +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +--- + +Media findings can now be acted on from hygiene review (#2781): Delete, Move to a final location, Persist here, and Keep a permanent copy of a conversation-linked scratch file. + +`brain hygiene media --expect-fingerprint [--to ] --dry-run` plans an effect and writes nothing: every file it would write with its expected SHA-256 before and after, the note references a Move rewrites (each in its own style; code untouched), the frontmatter and HTML references that block a Move, the `media.track` change, the bytes Undo must retain, and named refusals such as `pinned-scratch`, `exists`, `name-collision`, `not-final-location`, `not-expressible` or `config-not-literal`. Applying with `--expect-premise --journal ` recomputes the plan and writes only if nothing changed; it never overwrites a file and never compensates by itself. `persist` and `keep-copy` add the exact `media.track` entry to a literal `brain.config`, parsed as syntax only. `BRAIN_MEDIA_REFERENCE_LIMITS` gains `rewrittenNotes` (200) and `preview` (1 MiB). + +The UI server captures every pre-image in the bounded change journal before the CLI writes, and refuses as `capture-capacity` when it cannot. A failed or interrupted effect is put back file by file, only where a file still holds what the effect wrote; anything edited since is left alone and reported, so the outcome is honestly `partial`. Undo checks the retained data and every file first, and refuses without writing when either changed. A restart compensates an interrupted effect and never re-applies it. Keep a permanent copy records its `kept` entry only after the copy is verified, and removes the copy if that record is refused; the original's bytes, path and pins are never touched. + +The UI SDK adds the `media-delete`, `media-move`, `media-persist` and `media-keep-copy` effect operations, `InboxOption.media` (the plan), the `kept` outcome status and `HygieneAction.outcome.media` (the receipt). A server and CLI ship together: an older server reading a `kept` result fails closed as `check_failed`. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 63c72a5208..89132f637f 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -167,6 +167,11 @@ export "." (./src/index.ts) type HygieneDiff type HygieneEffect type HygieneInput + type HygieneMediaAction + type HygieneMediaFileState + type HygieneMediaPlan + type HygieneMediaReceipt + type HygieneMediaRefusal type HygienePreviewRequest type HygieneReviewCommand type HygieneReviewRead @@ -625,6 +630,11 @@ export "./client" (./src/client/index.ts) type HygieneDiff type HygieneEffect type HygieneInput + type HygieneMediaAction + type HygieneMediaFileState + type HygieneMediaPlan + type HygieneMediaReceipt + type HygieneMediaRefusal type HygienePreviewRequest type HygieneReviewCommand type HygieneReviewRead @@ -1427,6 +1437,11 @@ export "./protocol" (./src/protocol.ts) type HygieneDiff type HygieneEffect type HygieneInput + type HygieneMediaAction + type HygieneMediaFileState + type HygieneMediaPlan + type HygieneMediaReceipt + type HygieneMediaRefusal type HygienePreviewRequest type HygieneReviewCommand type HygieneReviewRead @@ -1746,6 +1761,9 @@ export "./schemas" (./src/schemas.ts) hygieneDiffSchema hygieneEffectSchema hygieneInputSchema + hygieneMediaPlanSchema + hygieneMediaReceiptSchema + hygieneMediaRefusalSchema hygieneOutcomeSchema hygienePreviewRequestSchema hygieneReviewCommandSchema @@ -2106,6 +2124,11 @@ export "./server" (./src/server/index.ts) type HygieneDiff type HygieneEffect type HygieneInput + type HygieneMediaAction + type HygieneMediaFileState + type HygieneMediaPlan + type HygieneMediaReceipt + type HygieneMediaRefusal type HygienePreviewRequest type HygieneReviewCommand type HygieneReviewRead @@ -6709,7 +6732,7 @@ signatures (every public export and the types it is made of) finding: Record; outcome?: { version: 1; - status: "applying" | "fixed" | "stale" | "refused" | "check_failed" | "still_detected" | "not_detected" | "undone" | "dismissed" | "snoozed" | "superseded" | "deferred"; + status: "applying" | "fixed" | "stale" | "refused" | "check_failed" | "still_detected" | "not_detected" | "undone" | "dismissed" | "snoozed" | "superseded" | "deferred" | "kept"; supersededBy?: string; reason?: string; code?: string; @@ -6718,6 +6741,7 @@ signatures (every public export and the types it is made of) field: string; message: string; }; + media?: HygieneMediaReceipt; }; } HygieneDiff (packages/ui-sdk/src/protocol.ts) @@ -6734,16 +6758,102 @@ signatures (every public export and the types it is made of) HygieneEffect (packages/ui-sdk/src/protocol.ts) export interface HygieneEffect { kind: "hygiene"; - operation: "resolve" | "check" | "undo" | "dismiss" | "snooze" | "defer"; + operation: "resolve" | "check" | "undo" | "dismiss" | "snooze" | "defer" | "media-delete" | "media-move" | "media-persist" | "media-keep-copy"; findingId: string; fingerprint: string; handler?: string; input?: HygieneInput; previewToken?: string; undoToken?: string; + destination?: string; + premiseDigest?: string; } HygieneInput (packages/ui-sdk/src/protocol.ts) export type HygieneInput = string | string[] | null; + HygieneMediaAction (packages/ui-sdk/src/protocol.ts) + export type HygieneMediaAction = "delete" | "move" | "persist" | "keep-copy"; + HygieneMediaFileState (packages/ui-sdk/src/protocol.ts) + export type HygieneMediaFileState = "created" | "changed" | "removed" | "restored" | "unchanged" | "left-changed" | "conflict"; + HygieneMediaPlan (packages/ui-sdk/src/protocol.ts) + export interface HygieneMediaPlan { + action: HygieneMediaAction; + premiseDigest: string; + destination: string | null; + files: Array<{ + path: string; + role: "source" | "destination" | "note" | "config" | "directory"; + before: string | null; + after: string | null; + bytes: number; + }>; + captureBytes: number; + links: { + state: "linked" | "unlinked" | "unknown"; + conversations: number; + }; + references: { + complete: boolean; + count: number; + }; + rewrites: Array<{ + note: string; + line: number; + kind: string; + before: string; + after: string; + }>; + blockers: Array<{ + note: string; + line: number; + kind: string; + target: string; + }>; + configDiff: { + path: string; + track: { + before: string[]; + after: string[]; + }; + ignore: { + before: string[]; + after: string[]; + }; + } | null; + copy: { + bytes: number; + sha256: string; + diskFreeAdvisory: number | null; + } | null; + resultClass: "TRACK" | "ARTIFACT" | null; + refusals: HygieneMediaRefusal[]; + } + HygieneMediaReceipt (packages/ui-sdk/src/protocol.ts) + export interface HygieneMediaReceipt { + journalId: string; + action: HygieneMediaAction; + outcome: "pending" | "applied" | "kept" | "compensated" | "partial" | "refused" | "stale" | "undone"; + reason?: string; + refusals?: HygieneMediaRefusal[]; + files: Array<{ + path: string; + state: HygieneMediaFileState; + }>; + copySha256?: string; + undo: { + available: boolean; + reason?: string; + path?: string; + }; + } + HygieneMediaRefusal (packages/ui-sdk/src/protocol.ts) + export interface HygieneMediaRefusal { + code: string; + path?: string; + line?: number; + limit?: string; + effective?: number; + observed?: number; + } HygienePreviewRequest (packages/ui-sdk/src/protocol.ts) export interface HygienePreviewRequest { itemId: string; @@ -6986,6 +7096,7 @@ signatures (every public export and the types it is made of) example?: string; }; preview?: HygieneDiff; + media?: HygieneMediaPlan; } InboxQueueItem (packages/ui-sdk/src/protocol.ts) export type InboxQueueItem = InboxItemBase & { @@ -12542,6 +12653,52 @@ signatures (every public export and the types it is made of) field: z.ZodString; message: z.ZodString; }, z.core.$strict>>; + media: 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>>; reason: z.ZodOptional; status: z.ZodEnum<{ applying: "applying"; @@ -12549,6 +12706,7 @@ signatures (every public export and the types it is made of) deferred: "deferred"; dismissed: "dismissed"; fixed: "fixed"; + kept: "kept"; not_detected: "not_detected"; refused: "refused"; snoozed: "snoozed"; @@ -12575,12 +12733,17 @@ signatures (every public export and the types it is made of) }, z.core.$strict>; hygieneEffectSchema (packages/ui-sdk/src/schemas.ts) const hygieneEffectSchema: z.ZodObject<{ + destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; handler: z.ZodOptional; input: z.ZodOptional, z.ZodNull]>>; kind: z.ZodLiteral<"hygiene">; operation: z.ZodEnum<{ + "media-delete": "media-delete"; + "media-keep-copy": "media-keep-copy"; + "media-move": "media-move"; + "media-persist": "media-persist"; check: "check"; defer: "defer"; dismiss: "dismiss"; @@ -12588,11 +12751,146 @@ signatures (every public export and the types it is made of) snooze: "snooze"; undo: "undo"; }>; + premiseDigest: z.ZodOptional; previewToken: z.ZodOptional; undoToken: z.ZodOptional; }, z.core.$strict>; hygieneInputSchema (packages/ui-sdk/src/schemas.ts) const hygieneInputSchema: z.ZodUnion, z.ZodNull]>; + hygieneMediaPlanSchema (packages/ui-sdk/src/schemas.ts) + const hygieneMediaPlanSchema: z.ZodObject<{ + action: z.ZodEnum<{ + "keep-copy": "keep-copy"; + delete: "delete"; + move: "move"; + persist: "persist"; + }>; + blockers: z.ZodArray>; + captureBytes: z.ZodNumber; + configDiff: z.ZodNullable; + before: z.ZodArray; + }, z.core.$strict>; + path: z.ZodString; + track: z.ZodObject<{ + after: z.ZodArray; + before: z.ZodArray; + }, z.core.$strict>; + }, z.core.$strict>>; + copy: z.ZodNullable; + sha256: z.ZodString; + }, z.core.$strict>>; + destination: z.ZodNullable; + files: z.ZodArray; + before: z.ZodNullable; + bytes: z.ZodNumber; + path: z.ZodString; + role: z.ZodEnum<{ + config: "config"; + destination: "destination"; + directory: "directory"; + note: "note"; + source: "source"; + }>; + }, z.core.$strict>>; + links: z.ZodObject<{ + conversations: z.ZodNumber; + state: z.ZodEnum<{ + linked: "linked"; + unknown: "unknown"; + unlinked: "unlinked"; + }>; + }, z.core.$strict>; + premiseDigest: z.ZodString; + references: z.ZodObject<{ + complete: z.ZodBoolean; + count: z.ZodNumber; + }, z.core.$strict>; + refusals: z.ZodArray; + limit: z.ZodOptional; + line: z.ZodOptional; + observed: z.ZodOptional; + path: z.ZodOptional; + }, z.core.$strict>>; + resultClass: z.ZodNullable>; + rewrites: z.ZodArray>; + }, z.core.$strip>; + hygieneMediaReceiptSchema (packages/ui-sdk/src/schemas.ts) + const hygieneMediaReceiptSchema: z.ZodObject<{ + action: z.ZodEnum<{ + "keep-copy": "keep-copy"; + delete: "delete"; + move: "move"; + persist: "persist"; + }>; + 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>; + hygieneMediaRefusalSchema (packages/ui-sdk/src/schemas.ts) + const hygieneMediaRefusalSchema: z.ZodObject<{ + code: z.ZodString; + effective: z.ZodOptional; + limit: z.ZodOptional; + line: z.ZodOptional; + observed: z.ZodOptional; + path: z.ZodOptional; + }, z.core.$strict>; hygieneOutcomeSchema (packages/ui-sdk/src/schemas.ts) const hygieneOutcomeSchema: z.ZodObject<{ code: z.ZodOptional; @@ -12600,6 +12898,52 @@ signatures (every public export and the types it is made of) field: z.ZodString; message: z.ZodString; }, z.core.$strict>>; + media: 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>>; reason: z.ZodOptional; status: z.ZodEnum<{ applying: "applying"; @@ -12607,6 +12951,7 @@ signatures (every public export and the types it is made of) deferred: "deferred"; dismissed: "dismissed"; fixed: "fixed"; + kept: "kept"; not_detected: "not_detected"; refused: "refused"; snoozed: "snoozed"; @@ -12651,6 +12996,52 @@ signatures (every public export and the types it is made of) field: z.ZodString; message: z.ZodString; }, z.core.$strict>>; + media: 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>>; reason: z.ZodOptional; status: z.ZodEnum<{ applying: "applying"; @@ -12658,6 +13049,7 @@ signatures (every public export and the types it is made of) deferred: "deferred"; dismissed: "dismissed"; fixed: "fixed"; + kept: "kept"; not_detected: "not_detected"; refused: "refused"; snoozed: "snoozed"; @@ -12684,12 +13076,17 @@ signatures (every public export and the types it is made of) }, z.core.$loose>>; }, z.core.$loose>; }, z.core.$loose>, z.ZodObject<{ + destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; handler: z.ZodOptional; input: z.ZodOptional, z.ZodNull]>>; kind: z.ZodLiteral<"hygiene">; operation: z.ZodEnum<{ + "media-delete": "media-delete"; + "media-keep-copy": "media-keep-copy"; + "media-move": "media-move"; + "media-persist": "media-persist"; check: "check"; defer: "defer"; dismiss: "dismiss"; @@ -12697,6 +13094,7 @@ signatures (every public export and the types it is made of) snooze: "snooze"; undo: "undo"; }>; + premiseDigest: z.ZodOptional; previewToken: z.ZodOptional; undoToken: z.ZodOptional; }, z.core.$loose>, z.ZodObject<{ @@ -12737,6 +13135,83 @@ signatures (every public export and the types it is made of) values: z.ZodOptional>; }, z.core.$strict>>; label: z.ZodString; + media: z.ZodOptional; + blockers: z.ZodArray>; + captureBytes: z.ZodNumber; + configDiff: z.ZodNullable; + before: z.ZodArray; + }, z.core.$strict>; + path: z.ZodString; + track: z.ZodObject<{ + after: z.ZodArray; + before: z.ZodArray; + }, z.core.$strict>; + }, z.core.$strict>>; + copy: z.ZodNullable; + sha256: z.ZodString; + }, z.core.$strict>>; + destination: z.ZodNullable; + files: z.ZodArray; + before: z.ZodNullable; + bytes: z.ZodNumber; + path: z.ZodString; + role: z.ZodEnum<{ + config: "config"; + destination: "destination"; + directory: "directory"; + note: "note"; + source: "source"; + }>; + }, z.core.$strict>>; + links: z.ZodObject<{ + conversations: z.ZodNumber; + state: z.ZodEnum<{ + linked: "linked"; + unknown: "unknown"; + unlinked: "unlinked"; + }>; + }, z.core.$strict>; + premiseDigest: z.ZodString; + references: z.ZodObject<{ + complete: z.ZodBoolean; + count: z.ZodNumber; + }, z.core.$strict>; + refusals: z.ZodArray; + limit: z.ZodOptional; + line: z.ZodOptional; + observed: z.ZodOptional; + path: z.ZodOptional; + }, z.core.$strict>>; + resultClass: z.ZodNullable>; + rewrites: z.ZodArray>; + }, z.core.$strip>>; preview: z.ZodOptional>; + media: 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>>; reason: z.ZodOptional; status: z.ZodEnum<{ applying: "applying"; @@ -12905,6 +13426,7 @@ signatures (every public export and the types it is made of) deferred: "deferred"; dismissed: "dismissed"; fixed: "fixed"; + kept: "kept"; not_detected: "not_detected"; refused: "refused"; snoozed: "snoozed"; @@ -12931,12 +13453,17 @@ signatures (every public export and the types it is made of) }, z.core.$loose>>; }, z.core.$loose>; }, z.core.$loose>, z.ZodObject<{ + destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; handler: z.ZodOptional; input: z.ZodOptional, z.ZodNull]>>; kind: z.ZodLiteral<"hygiene">; operation: z.ZodEnum<{ + "media-delete": "media-delete"; + "media-keep-copy": "media-keep-copy"; + "media-move": "media-move"; + "media-persist": "media-persist"; check: "check"; defer: "defer"; dismiss: "dismiss"; @@ -12944,6 +13471,7 @@ signatures (every public export and the types it is made of) snooze: "snooze"; undo: "undo"; }>; + premiseDigest: z.ZodOptional; previewToken: z.ZodOptional; undoToken: z.ZodOptional; }, z.core.$loose>, z.ZodObject<{ @@ -12984,6 +13512,83 @@ signatures (every public export and the types it is made of) values: z.ZodOptional>; }, z.core.$strict>>; label: z.ZodString; + media: z.ZodOptional; + blockers: z.ZodArray>; + captureBytes: z.ZodNumber; + configDiff: z.ZodNullable; + before: z.ZodArray; + }, z.core.$strict>; + path: z.ZodString; + track: z.ZodObject<{ + after: z.ZodArray; + before: z.ZodArray; + }, z.core.$strict>; + }, z.core.$strict>>; + copy: z.ZodNullable; + sha256: z.ZodString; + }, z.core.$strict>>; + destination: z.ZodNullable; + files: z.ZodArray; + before: z.ZodNullable; + bytes: z.ZodNumber; + path: z.ZodString; + role: z.ZodEnum<{ + config: "config"; + destination: "destination"; + directory: "directory"; + note: "note"; + source: "source"; + }>; + }, z.core.$strict>>; + links: z.ZodObject<{ + conversations: z.ZodNumber; + state: z.ZodEnum<{ + linked: "linked"; + unknown: "unknown"; + unlinked: "unlinked"; + }>; + }, z.core.$strict>; + premiseDigest: z.ZodString; + references: z.ZodObject<{ + complete: z.ZodBoolean; + count: z.ZodNumber; + }, z.core.$strict>; + refusals: z.ZodArray; + limit: z.ZodOptional; + line: z.ZodOptional; + observed: z.ZodOptional; + path: z.ZodOptional; + }, z.core.$strict>>; + resultClass: z.ZodNullable>; + rewrites: z.ZodArray>; + }, z.core.$strip>>; preview: z.ZodOptional>; + media: 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>>; reason: z.ZodOptional; status: z.ZodEnum<{ applying: "applying"; @@ -13175,6 +13826,7 @@ signatures (every public export and the types it is made of) deferred: "deferred"; dismissed: "dismissed"; fixed: "fixed"; + kept: "kept"; not_detected: "not_detected"; refused: "refused"; snoozed: "snoozed"; @@ -13201,12 +13853,17 @@ signatures (every public export and the types it is made of) }, z.core.$loose>>; }, z.core.$loose>; }, z.core.$loose>, z.ZodObject<{ + destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; handler: z.ZodOptional; input: z.ZodOptional, z.ZodNull]>>; kind: z.ZodLiteral<"hygiene">; operation: z.ZodEnum<{ + "media-delete": "media-delete"; + "media-keep-copy": "media-keep-copy"; + "media-move": "media-move"; + "media-persist": "media-persist"; check: "check"; defer: "defer"; dismiss: "dismiss"; @@ -13214,6 +13871,7 @@ signatures (every public export and the types it is made of) snooze: "snooze"; undo: "undo"; }>; + premiseDigest: z.ZodOptional; previewToken: z.ZodOptional; undoToken: z.ZodOptional; }, z.core.$loose>, z.ZodObject<{ @@ -13254,6 +13912,83 @@ signatures (every public export and the types it is made of) values: z.ZodOptional>; }, z.core.$strict>>; label: z.ZodString; + media: z.ZodOptional; + blockers: z.ZodArray>; + captureBytes: z.ZodNumber; + configDiff: z.ZodNullable; + before: z.ZodArray; + }, z.core.$strict>; + path: z.ZodString; + track: z.ZodObject<{ + after: z.ZodArray; + before: z.ZodArray; + }, z.core.$strict>; + }, z.core.$strict>>; + copy: z.ZodNullable; + sha256: z.ZodString; + }, z.core.$strict>>; + destination: z.ZodNullable; + files: z.ZodArray; + before: z.ZodNullable; + bytes: z.ZodNumber; + path: z.ZodString; + role: z.ZodEnum<{ + config: "config"; + destination: "destination"; + directory: "directory"; + note: "note"; + source: "source"; + }>; + }, z.core.$strict>>; + links: z.ZodObject<{ + conversations: z.ZodNumber; + state: z.ZodEnum<{ + linked: "linked"; + unknown: "unknown"; + unlinked: "unlinked"; + }>; + }, z.core.$strict>; + premiseDigest: z.ZodString; + references: z.ZodObject<{ + complete: z.ZodBoolean; + count: z.ZodNumber; + }, z.core.$strict>; + refusals: z.ZodArray; + limit: z.ZodOptional; + line: z.ZodOptional; + observed: z.ZodOptional; + path: z.ZodOptional; + }, z.core.$strict>>; + resultClass: z.ZodNullable>; + rewrites: z.ZodArray>; + }, z.core.$strip>>; preview: z.ZodOptional>; + media: 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>>; reason: z.ZodOptional; status: z.ZodEnum<{ applying: "applying"; @@ -13453,6 +14234,7 @@ signatures (every public export and the types it is made of) deferred: "deferred"; dismissed: "dismissed"; fixed: "fixed"; + kept: "kept"; not_detected: "not_detected"; refused: "refused"; snoozed: "snoozed"; @@ -13479,12 +14261,17 @@ signatures (every public export and the types it is made of) }, z.core.$loose>>; }, z.core.$loose>; }, z.core.$loose>, z.ZodObject<{ + destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; handler: z.ZodOptional; input: z.ZodOptional, z.ZodNull]>>; kind: z.ZodLiteral<"hygiene">; operation: z.ZodEnum<{ + "media-delete": "media-delete"; + "media-keep-copy": "media-keep-copy"; + "media-move": "media-move"; + "media-persist": "media-persist"; check: "check"; defer: "defer"; dismiss: "dismiss"; @@ -13492,6 +14279,7 @@ signatures (every public export and the types it is made of) snooze: "snooze"; undo: "undo"; }>; + premiseDigest: z.ZodOptional; previewToken: z.ZodOptional; undoToken: z.ZodOptional; }, z.core.$loose>, z.ZodObject<{ @@ -13532,6 +14320,83 @@ signatures (every public export and the types it is made of) values: z.ZodOptional>; }, z.core.$strict>>; label: z.ZodString; + media: z.ZodOptional; + blockers: z.ZodArray>; + captureBytes: z.ZodNumber; + configDiff: z.ZodNullable; + before: z.ZodArray; + }, z.core.$strict>; + path: z.ZodString; + track: z.ZodObject<{ + after: z.ZodArray; + before: z.ZodArray; + }, z.core.$strict>; + }, z.core.$strict>>; + copy: z.ZodNullable; + sha256: z.ZodString; + }, z.core.$strict>>; + destination: z.ZodNullable; + files: z.ZodArray; + before: z.ZodNullable; + bytes: z.ZodNumber; + path: z.ZodString; + role: z.ZodEnum<{ + config: "config"; + destination: "destination"; + directory: "directory"; + note: "note"; + source: "source"; + }>; + }, z.core.$strict>>; + links: z.ZodObject<{ + conversations: z.ZodNumber; + state: z.ZodEnum<{ + linked: "linked"; + unknown: "unknown"; + unlinked: "unlinked"; + }>; + }, z.core.$strict>; + premiseDigest: z.ZodString; + references: z.ZodObject<{ + complete: z.ZodBoolean; + count: z.ZodNumber; + }, z.core.$strict>; + refusals: z.ZodArray; + limit: z.ZodOptional; + line: z.ZodOptional; + observed: z.ZodOptional; + path: z.ZodOptional; + }, z.core.$strict>>; + resultClass: z.ZodNullable>; + rewrites: z.ZodArray>; + }, z.core.$strip>>; preview: z.ZodOptional>; + media: 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>>; reason: z.ZodOptional; status: z.ZodEnum<{ applying: "applying"; @@ -13728,6 +14639,7 @@ signatures (every public export and the types it is made of) deferred: "deferred"; dismissed: "dismissed"; fixed: "fixed"; + kept: "kept"; not_detected: "not_detected"; refused: "refused"; snoozed: "snoozed"; @@ -13754,12 +14666,17 @@ signatures (every public export and the types it is made of) }, z.core.$loose>>; }, z.core.$loose>; }, z.core.$loose>, z.ZodObject<{ + destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; handler: z.ZodOptional; input: z.ZodOptional, z.ZodNull]>>; kind: z.ZodLiteral<"hygiene">; operation: z.ZodEnum<{ + "media-delete": "media-delete"; + "media-keep-copy": "media-keep-copy"; + "media-move": "media-move"; + "media-persist": "media-persist"; check: "check"; defer: "defer"; dismiss: "dismiss"; @@ -13767,6 +14684,7 @@ signatures (every public export and the types it is made of) snooze: "snooze"; undo: "undo"; }>; + premiseDigest: z.ZodOptional; previewToken: z.ZodOptional; undoToken: z.ZodOptional; }, z.core.$loose>, z.ZodObject<{ @@ -13807,6 +14725,83 @@ signatures (every public export and the types it is made of) values: z.ZodOptional>; }, z.core.$strict>>; label: z.ZodString; + media: z.ZodOptional; + blockers: z.ZodArray>; + captureBytes: z.ZodNumber; + configDiff: z.ZodNullable; + before: z.ZodArray; + }, z.core.$strict>; + path: z.ZodString; + track: z.ZodObject<{ + after: z.ZodArray; + before: z.ZodArray; + }, z.core.$strict>; + }, z.core.$strict>>; + copy: z.ZodNullable; + sha256: z.ZodString; + }, z.core.$strict>>; + destination: z.ZodNullable; + files: z.ZodArray; + before: z.ZodNullable; + bytes: z.ZodNumber; + path: z.ZodString; + role: z.ZodEnum<{ + config: "config"; + destination: "destination"; + directory: "directory"; + note: "note"; + source: "source"; + }>; + }, z.core.$strict>>; + links: z.ZodObject<{ + conversations: z.ZodNumber; + state: z.ZodEnum<{ + linked: "linked"; + unknown: "unknown"; + unlinked: "unlinked"; + }>; + }, z.core.$strict>; + premiseDigest: z.ZodString; + references: z.ZodObject<{ + complete: z.ZodBoolean; + count: z.ZodNumber; + }, z.core.$strict>; + refusals: z.ZodArray; + limit: z.ZodOptional; + line: z.ZodOptional; + observed: z.ZodOptional; + path: z.ZodOptional; + }, z.core.$strict>>; + resultClass: z.ZodNullable>; + rewrites: z.ZodArray>; + }, z.core.$strip>>; preview: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; handler: z.ZodOptional; input: z.ZodOptional, z.ZodNull]>>; kind: z.ZodLiteral<"hygiene">; operation: z.ZodEnum<{ + "media-delete": "media-delete"; + "media-keep-copy": "media-keep-copy"; + "media-move": "media-move"; + "media-persist": "media-persist"; check: "check"; defer: "defer"; dismiss: "dismiss"; @@ -13864,6 +14864,7 @@ signatures (every public export and the types it is made of) snooze: "snooze"; undo: "undo"; }>; + premiseDigest: z.ZodOptional; previewToken: z.ZodOptional; undoToken: z.ZodOptional; }, z.core.$strict>, z.ZodObject<{ @@ -13914,6 +14915,83 @@ signatures (every public export and the types it is made of) values: z.ZodOptional>; }, z.core.$strict>>; label: z.ZodString; + media: z.ZodOptional; + blockers: z.ZodArray>; + captureBytes: z.ZodNumber; + configDiff: z.ZodNullable; + before: z.ZodArray; + }, z.core.$strict>; + path: z.ZodString; + track: z.ZodObject<{ + after: z.ZodArray; + before: z.ZodArray; + }, z.core.$strict>; + }, z.core.$strict>>; + copy: z.ZodNullable; + sha256: z.ZodString; + }, z.core.$strict>>; + destination: z.ZodNullable; + files: z.ZodArray; + before: z.ZodNullable; + bytes: z.ZodNumber; + path: z.ZodString; + role: z.ZodEnum<{ + config: "config"; + destination: "destination"; + directory: "directory"; + note: "note"; + source: "source"; + }>; + }, z.core.$strict>>; + links: z.ZodObject<{ + conversations: z.ZodNumber; + state: z.ZodEnum<{ + linked: "linked"; + unknown: "unknown"; + unlinked: "unlinked"; + }>; + }, z.core.$strict>; + premiseDigest: z.ZodString; + references: z.ZodObject<{ + complete: z.ZodBoolean; + count: z.ZodNumber; + }, z.core.$strict>; + refusals: z.ZodArray; + limit: z.ZodOptional; + line: z.ZodOptional; + observed: z.ZodOptional; + path: z.ZodOptional; + }, z.core.$strict>>; + resultClass: z.ZodNullable>; + rewrites: z.ZodArray>; + }, z.core.$strip>>; preview: z.ZodOptional>; + media: 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>>; reason: z.ZodOptional; status: z.ZodEnum<{ applying: "applying"; @@ -14161,6 +15285,7 @@ signatures (every public export and the types it is made of) deferred: "deferred"; dismissed: "dismissed"; fixed: "fixed"; + kept: "kept"; not_detected: "not_detected"; refused: "refused"; snoozed: "snoozed"; @@ -14187,12 +15312,17 @@ signatures (every public export and the types it is made of) }, z.core.$loose>>; }, z.core.$loose>; }, z.core.$loose>, z.ZodObject<{ + destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; handler: z.ZodOptional; input: z.ZodOptional, z.ZodNull]>>; kind: z.ZodLiteral<"hygiene">; operation: z.ZodEnum<{ + "media-delete": "media-delete"; + "media-keep-copy": "media-keep-copy"; + "media-move": "media-move"; + "media-persist": "media-persist"; check: "check"; defer: "defer"; dismiss: "dismiss"; @@ -14200,6 +15330,7 @@ signatures (every public export and the types it is made of) snooze: "snooze"; undo: "undo"; }>; + premiseDigest: z.ZodOptional; previewToken: z.ZodOptional; undoToken: z.ZodOptional; }, z.core.$loose>, z.ZodObject<{ @@ -14240,6 +15371,83 @@ signatures (every public export and the types it is made of) values: z.ZodOptional>; }, z.core.$strict>>; label: z.ZodString; + media: z.ZodOptional; + blockers: z.ZodArray>; + captureBytes: z.ZodNumber; + configDiff: z.ZodNullable; + before: z.ZodArray; + }, z.core.$strict>; + path: z.ZodString; + track: z.ZodObject<{ + after: z.ZodArray; + before: z.ZodArray; + }, z.core.$strict>; + }, z.core.$strict>>; + copy: z.ZodNullable; + sha256: z.ZodString; + }, z.core.$strict>>; + destination: z.ZodNullable; + files: z.ZodArray; + before: z.ZodNullable; + bytes: z.ZodNumber; + path: z.ZodString; + role: z.ZodEnum<{ + config: "config"; + destination: "destination"; + directory: "directory"; + note: "note"; + source: "source"; + }>; + }, z.core.$strict>>; + links: z.ZodObject<{ + conversations: z.ZodNumber; + state: z.ZodEnum<{ + linked: "linked"; + unknown: "unknown"; + unlinked: "unlinked"; + }>; + }, z.core.$strict>; + premiseDigest: z.ZodString; + references: z.ZodObject<{ + complete: z.ZodBoolean; + count: z.ZodNumber; + }, z.core.$strict>; + refusals: z.ZodArray; + limit: z.ZodOptional; + line: z.ZodOptional; + observed: z.ZodOptional; + path: z.ZodOptional; + }, z.core.$strict>>; + resultClass: z.ZodNullable>; + rewrites: z.ZodArray>; + }, z.core.$strip>>; preview: z.ZodOptional | null | undefined, request: PermissionRequest, options?: RequestToolPermissionOptions): Promise; resolutionEffectSchema (packages/ui-sdk/src/schemas.ts) const resolutionEffectSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ + destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; handler: z.ZodOptional; input: z.ZodOptional, z.ZodNull]>>; kind: z.ZodLiteral<"hygiene">; operation: z.ZodEnum<{ + "media-delete": "media-delete"; + "media-keep-copy": "media-keep-copy"; + "media-move": "media-move"; + "media-persist": "media-persist"; check: "check"; defer: "defer"; dismiss: "dismiss"; @@ -14816,6 +16029,7 @@ signatures (every public export and the types it is made of) snooze: "snooze"; undo: "undo"; }>; + premiseDigest: z.ZodOptional; previewToken: z.ZodOptional; undoToken: z.ZodOptional; }, z.core.$strict>, z.ZodObject<{ @@ -18182,6 +19396,52 @@ signatures (every public export and the types it is made of) field: z.ZodString; message: z.ZodString; }, z.core.$strict>>; + media: 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>>; reason: z.ZodOptional; status: z.ZodEnum<{ applying: "applying"; @@ -18189,6 +19449,7 @@ signatures (every public export and the types it is made of) deferred: "deferred"; dismissed: "dismissed"; fixed: "fixed"; + kept: "kept"; not_detected: "not_detected"; refused: "refused"; snoozed: "snoozed"; @@ -18215,12 +19476,17 @@ signatures (every public export and the types it is made of) }, z.core.$loose>>; }, z.core.$loose>; }, z.core.$loose>, z.ZodObject<{ + destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; handler: z.ZodOptional; input: z.ZodOptional, z.ZodNull]>>; kind: z.ZodLiteral<"hygiene">; operation: z.ZodEnum<{ + "media-delete": "media-delete"; + "media-keep-copy": "media-keep-copy"; + "media-move": "media-move"; + "media-persist": "media-persist"; check: "check"; defer: "defer"; dismiss: "dismiss"; @@ -18228,6 +19494,7 @@ signatures (every public export and the types it is made of) snooze: "snooze"; undo: "undo"; }>; + premiseDigest: z.ZodOptional; previewToken: z.ZodOptional; undoToken: z.ZodOptional; }, z.core.$loose>, z.ZodObject<{ @@ -18268,6 +19535,83 @@ signatures (every public export and the types it is made of) values: z.ZodOptional>; }, z.core.$strict>>; label: z.ZodString; + media: z.ZodOptional; + blockers: z.ZodArray>; + captureBytes: z.ZodNumber; + configDiff: z.ZodNullable; + before: z.ZodArray; + }, z.core.$strict>; + path: z.ZodString; + track: z.ZodObject<{ + after: z.ZodArray; + before: z.ZodArray; + }, z.core.$strict>; + }, z.core.$strict>>; + copy: z.ZodNullable; + sha256: z.ZodString; + }, z.core.$strict>>; + destination: z.ZodNullable; + files: z.ZodArray; + before: z.ZodNullable; + bytes: z.ZodNumber; + path: z.ZodString; + role: z.ZodEnum<{ + config: "config"; + destination: "destination"; + directory: "directory"; + note: "note"; + source: "source"; + }>; + }, z.core.$strict>>; + links: z.ZodObject<{ + conversations: z.ZodNumber; + state: z.ZodEnum<{ + linked: "linked"; + unknown: "unknown"; + unlinked: "unlinked"; + }>; + }, z.core.$strict>; + premiseDigest: z.ZodString; + references: z.ZodObject<{ + complete: z.ZodBoolean; + count: z.ZodNumber; + }, z.core.$strict>; + refusals: z.ZodArray; + limit: z.ZodOptional; + line: z.ZodOptional; + observed: z.ZodOptional; + path: z.ZodOptional; + }, z.core.$strict>>; + resultClass: z.ZodNullable>; + rewrites: z.ZodArray>; + }, z.core.$strip>>; preview: z.ZodOptional>; + media: 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>>; reason: z.ZodOptional; status: z.ZodEnum<{ applying: "applying"; @@ -18476,6 +19866,7 @@ signatures (every public export and the types it is made of) deferred: "deferred"; dismissed: "dismissed"; fixed: "fixed"; + kept: "kept"; not_detected: "not_detected"; refused: "refused"; snoozed: "snoozed"; @@ -18502,12 +19893,17 @@ signatures (every public export and the types it is made of) }, z.core.$loose>>; }, z.core.$loose>; }, z.core.$loose>, z.ZodObject<{ + destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; handler: z.ZodOptional; input: z.ZodOptional, z.ZodNull]>>; kind: z.ZodLiteral<"hygiene">; operation: z.ZodEnum<{ + "media-delete": "media-delete"; + "media-keep-copy": "media-keep-copy"; + "media-move": "media-move"; + "media-persist": "media-persist"; check: "check"; defer: "defer"; dismiss: "dismiss"; @@ -18515,6 +19911,7 @@ signatures (every public export and the types it is made of) snooze: "snooze"; undo: "undo"; }>; + premiseDigest: z.ZodOptional; previewToken: z.ZodOptional; undoToken: z.ZodOptional; }, z.core.$loose>, z.ZodObject<{ @@ -18555,6 +19952,83 @@ signatures (every public export and the types it is made of) values: z.ZodOptional>; }, z.core.$strict>>; label: z.ZodString; + media: z.ZodOptional; + blockers: z.ZodArray>; + captureBytes: z.ZodNumber; + configDiff: z.ZodNullable; + before: z.ZodArray; + }, z.core.$strict>; + path: z.ZodString; + track: z.ZodObject<{ + after: z.ZodArray; + before: z.ZodArray; + }, z.core.$strict>; + }, z.core.$strict>>; + copy: z.ZodNullable; + sha256: z.ZodString; + }, z.core.$strict>>; + destination: z.ZodNullable; + files: z.ZodArray; + before: z.ZodNullable; + bytes: z.ZodNumber; + path: z.ZodString; + role: z.ZodEnum<{ + config: "config"; + destination: "destination"; + directory: "directory"; + note: "note"; + source: "source"; + }>; + }, z.core.$strict>>; + links: z.ZodObject<{ + conversations: z.ZodNumber; + state: z.ZodEnum<{ + linked: "linked"; + unknown: "unknown"; + unlinked: "unlinked"; + }>; + }, z.core.$strict>; + premiseDigest: z.ZodString; + references: z.ZodObject<{ + complete: z.ZodBoolean; + count: z.ZodNumber; + }, z.core.$strict>; + refusals: z.ZodArray; + limit: z.ZodOptional; + line: z.ZodOptional; + observed: z.ZodOptional; + path: z.ZodOptional; + }, z.core.$strict>>; + resultClass: z.ZodNullable>; + rewrites: z.ZodArray>; + }, z.core.$strip>>; preview: z.ZodOptional; v1ResolutionEffectSchema (packages/ui-sdk/src/schemas.ts) const v1ResolutionEffectSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ + destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; handler: z.ZodOptional; input: z.ZodOptional, z.ZodNull]>>; kind: z.ZodLiteral<"hygiene">; operation: z.ZodEnum<{ + "media-delete": "media-delete"; + "media-keep-copy": "media-keep-copy"; + "media-move": "media-move"; + "media-persist": "media-persist"; check: "check"; defer: "defer"; dismiss: "dismiss"; @@ -20313,6 +21792,7 @@ signatures (every public export and the types it is made of) snooze: "snooze"; undo: "undo"; }>; + premiseDigest: z.ZodOptional; previewToken: z.ZodOptional; undoToken: z.ZodOptional; }, z.core.$strict>, z.ZodObject<{ diff --git a/docs/configuration.md b/docs/configuration.md index 077b7dbdfa..9cc65c8a83 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -901,7 +901,7 @@ the capability you need and read its command's requirements. | `TYPESAFE_API_KEY` | `brain sync` | The Jev judgments a sync asks. Without it every judgment takes its conservative default. See [`sync`](#sync). | | `GOOGLE_API_KEY` | upstream Gemini SDK | Not a brain-kit key input. Providers pass their selected key explicitly; the SDK may emit a cosmetic dual-key warning. The variable is not temporarily unset. | | `BRAIN_MEDIA_PINNED_PATH_LIMIT` | `brain hygiene`, `brain sync` | Trusted host bound on the conversation-pinned scratch paths one media inventory reads. Default `5000`. Past it, review reports that conversation links were not fully checked. A value that is not a positive integer stops media detection. | -| `BRAIN_MEDIA_REFERENCE_LIMITS` | `brain hygiene`, `brain sync` | Trusted host bounds on the declared reference scan behind every media finding, as `=` pairs: `notes` (50000), `noteBytes` (256 MiB), `perNote` (4 MiB, at most `noteBytes`), `scanTime` in ms (20000) and `refsPerFinding` (500). Past a limit the scan is refused and nothing claims the references were checked. An invalid value stops media detection. | +| `BRAIN_MEDIA_REFERENCE_LIMITS` | `brain hygiene`, `brain sync` | Trusted host bounds on the declared reference scan behind every media finding, as `=` pairs: `notes` (50000), `noteBytes` (256 MiB), `perNote` (4 MiB, at most `noteBytes`), `scanTime` in ms (20000), `refsPerFinding` (500), and for a media effect's plan `rewrittenNotes` (200) and `preview` in bytes (1 MiB). Past a limit the scan or plan is refused and nothing claims the references were checked. An invalid value stops media detection. | | `BRAIN_RERANK_MODE` | search | Selects `jev`, `heuristic` or `none`. An explicit `--rerank` still wins; neither can enable model judgment while `reranker.enabled` is false. | | `TYPESAFE_API_KEY` | search | Key for the built-in `jev` reranker (default name; `reranker.apiKeyEnv` can point elsewhere). Model search also requires `reranker.enabled: true`; absent key → the `heuristic` ordering. | | `XDG_BIN_HOME` | `brain setup`, `brain doctor` | Where the `brain` symlink is written. Default `~/.local/bin`. | diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 5ce79feee2..c6f2b6c24e 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -64,7 +64,7 @@ next to it. of this binary. The only version probe in the server is for the `brain` CLI (`Probe the selected content CLI`, `packages/ui-server/src/brain/client.ts:152-220`, called at - `probeBrainCliVersion(config.brainPath`, `packages/ui-server/src/app.ts:442`). + `probeBrainCliVersion(config.brainPath`, `packages/ui-server/src/app.ts:443`). `brain doctor` runs `claude mcp list` from `PATH` (`which("claude")`, `packages/core/src/cli/commands/doctor.ts:503-507`) — the user's own Claude Code on their own machine, to check the MCP registration, not the server's @@ -212,7 +212,7 @@ unnecessary. `node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs`. The boot probe below turns either into a refusal to start, for the same reason a missing backend refuses to boot (`A missing (or unrecognized) agent backend`, - `packages/ui-server/src/app.ts:380-385`). + `packages/ui-server/src/app.ts:381-386`). - **The published range is still a caret, and that bounds what this repo can guarantee.** `@schlessera/brain-backend-claude` depends on `^0.3.241`, and a host resolves it in its own lockfile. A host can bump the SDK — and so the diff --git a/docs/decisions/http-api-boundary.md b/docs/decisions/http-api-boundary.md index e82378d919..3f82bfcfe1 100644 --- a/docs/decisions/http-api-boundary.md +++ b/docs/decisions/http-api-boundary.md @@ -46,11 +46,11 @@ explicit supported rows, not silently excluded by this distinction. The source audit on 2026-09-30 used `e0875269b21b707482545be9e94901acb897893b`. The public health mount precedes auth -(`createHealthRoutes`, `packages/ui-server/src/app.ts:884`), the API guard follows -public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:905`), and the -WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1095`). +(`createHealthRoutes`, `packages/ui-server/src/app.ts:885`), the API guard follows +public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:906`), and the +WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1106`). Static serving is conditional (`if (options.staticRoot)`, -`packages/ui-server/src/app.ts:1115-1136`). That order establishes access; +`packages/ui-server/src/app.ts:1126-1147`). That order establishes access; it does not select compatibility status. A hermetic real-app launch, with temporary brain root, in-memory database, diff --git a/docs/decisions/hygiene-review.md b/docs/decisions/hygiene-review.md index 9bbb297a99..bb1c7fc31c 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:221-223`). +(`hygieneCommand`, `packages/core/src/cli/commands/hygiene.ts:241-243`). ## Selection: severity and known urgency, then age and identity @@ -227,10 +227,22 @@ Each Q1 limit is checked before the work it bounds; past one, or on a note that is not UTF-8, the whole scan is refused and the `refs` field records `too-large` or `unscannable`, never a digest. The digest leaves line numbers out, so an unrelated edit does not reopen a decision -(`referenceDigest`, `packages/core/src/lib/media-references.ts:435-441`). +(`referenceDigest`, `packages/core/src/lib/media-references.ts:441-447`). The contract is in [media awaiting review](../integration-contract/package-api.md#media-awaiting-review-additive-2780). +**Media effects (#2781, rev 4 §5-§7, Rollback A).** Delete, Move, Persist here +and Keep a permanent copy are planned by the CLI against the current files, +with every file's expected bytes before and after in one premise, and applied +only while that premise still holds. Capture comes first: the server retains +every pre-image in the bounded change journal before the CLI writes, and +refuses when the journal cannot hold it. Compensation, Undo and restart +recovery share one per-file rule: a file is put back only while it still holds +what the effect wrote, so a later edit is never overwritten and the outcome is +`partial` instead (`restore`, `packages/ui-server/src/inbox/media-effects.ts:107-129`). +No all-file atomicity is claimed. The contract is in +[media review effects](../integration-contract/package-api.md#media-review-effects-additive-2781). + ## A disposition is not a repair or an authority grant Dismiss and Snooze do not change the document, acknowledge a successful repair diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 3194de6862..d60e022ad5 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -400,7 +400,7 @@ selects undone copy. Markdown findings and the host's by core's ordinal rules (severity, known urgency, age, identity), and every operation that names a host finding goes to the host, never to the CLI -(`async function cli(args`, `packages/ui-server/src/inbox/hygiene-review.ts:40-52`). +(`async function cli(args`, `packages/ui-server/src/inbox/hygiene-review.ts:45-57`). A retained or failed worktree offers one repair, `delete-worktree`; an unknown one offers none and stays kept and charged, and "check again" assesses it afresh, after a failed removal too. Selection assesses its winner again before diff --git a/docs/decisions/scheduled-tasks.md b/docs/decisions/scheduled-tasks.md index 56e193bfef..0d4efe75da 100644 --- a/docs/decisions/scheduled-tasks.md +++ b/docs/decisions/scheduled-tasks.md @@ -23,7 +23,7 @@ Source inspected at `b5c30c180df5584584f261b446c4d440380d2441`: (`else if (item.status === "scheduled"`, `packages/ui-server/src/inbox/actions.ts:196-197`). The runtime ticks every minute (`INBOX_TICK_MS`, `packages/ui-server/src/inbox/runtime.ts:11-13`). - Production app wiring supplies recovery and budgets, without a dispatcher - (`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:506-522`). + (`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:507-523`). A scripted nonempty ready-item test still reports no claim, attempt or Activity root. That proves disabled wiring, not safe execution of a schedule. - Headless plumbing checks backend support, a usable principal, lifetime and diff --git a/docs/decisions/session-principals.md b/docs/decisions/session-principals.md index 0cc59b0be6..1600a8edc1 100644 --- a/docs/decisions/session-principals.md +++ b/docs/decisions/session-principals.md @@ -96,9 +96,9 @@ Both reviewers verified every row below against the source. | Cookie verify | `auth.ts:265-296` | strict `^(\d+)\.(\d+)$`, safe integers, future/expired rejection, `cookieEpoch === sessionsEpoch(db)` | | Global epoch | `auth.ts:302-318` | `settings` row; missing = 0; non-integer **throws** | | Global revoke | `auth.ts:321-330` | `setSetting` (overflow-guarded) + `clients.closeAll(1008, …)` | -| Auth routes | `authRoutes`, `app.ts:890` | mounted **before** the guard at `authGuard(authMode`, `app.ts:905`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | -| Passkey management | `passkeyManagementRoutes`, `app.ts:915` | mounted **after** the guard ("Mount AFTER the auth guard") | -| WS guard | `"/ws"`, `app.ts:1095-1112` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | +| Auth routes | `authRoutes`, `app.ts:891` | mounted **before** the guard at `authGuard(authMode`, `app.ts:906`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | +| Passkey management | `passkeyManagementRoutes`, `app.ts:916` | mounted **after** the guard ("Mount AFTER the auth guard") | +| WS guard | `"/ws"`, `app.ts:1106-1123` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | | WS upgrade | `ws/connection.ts:262-264` | `createWsUpgrade` ignores the request context | | WS admission | `ws/connection.ts:84` | `clients.add(ws)` — the socket's identity is unknown | | Turn record | `ws/run-session.ts:136-144` | recorder built from `{turnId, sessionId, billing}`; `RunningTurn` (`ws/turns.ts:55-77`) has no actor | diff --git a/docs/integration-contract/cli.md b/docs/integration-contract/cli.md index 45576c31c1..b77893c118 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 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 | | `brain travel photo --to [--name ] [--date YYYY-MM-DD] [--force-date] --json` | `{ "photo": { "files": [{ "source", "output", "width", "height", "bytes", "captured_at": string \| null, "location": { "lat", "lon" } \| null, "date_source": "exif" \| "flag" \| "none" }], "errors": [{ "source", "message" }] } }` — [photo and naming contract](frontmatter.md#travel-photo-copies); exit `0` for complete success, `2` for input failures, `1` for usage/output-directory refusal without an envelope | diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 96c7ecbfaa..3fd08326ff 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -1566,7 +1566,8 @@ refused. One scan of the brain's `*.md` notes outside hidden directories and reference definitions, wiki links and embeds, frontmatter values and HTML `src`/`href`/`poster`; code is never a reference. Its bounds are `BRAIN_MEDIA_REFERENCE_LIMITS` (`notes` 50,000, `noteBytes` 256 MiB, `perNote` -4 MiB, `scanTime` 20 s, `refsPerFinding` 500). Replacing the earlier +4 MiB, `scanTime` 20 s, `refsPerFinding` 500; and for an effect's plan, +`rewrittenNotes` 200 and `preview` 1 MiB, #2781). Replacing the earlier `unscanned` value reopens every media disposition once. A fifth log state, `kept`, holds a media original whose permanent copy was @@ -1605,6 +1606,60 @@ a new pass and clears the list), `deferred: [{ findingId, fingerprint }]`, a from the last selection. A stored row without them reads as `0` or `[]`. Hygiene effects gain operation `defer`, and outcomes gain status `deferred`. + + +## Media review effects (additive, #2781) + +A media finding's four governed effects are Delete, Move, Persist here and +Keep a permanent copy. The CLI plans and writes them +(`brain hygiene media`, [cli.md](cli.md)); the UI server owns capture, +compensation, Undo and recovery, in the bounded change journal (Rollback A). + +- **Capture before mutation.** Under the exclusive writer gate, a user + journal turn covers every file the plan lists, and each pre-image (the + media bytes for Delete and Move, each rewritten note, the config) is + retained and verified by SHA-256 before the CLI is asked to write. A + capture the journal's 10 GiB shared cap, or its per-file copy bound, cannot + hold refuses as `capture-capacity`, with nothing written. +- **Per-file compensation.** A file is put back only while it still holds + exactly what the effect wrote. Anything else is `conflict` (or + `left-changed` for a folder no longer empty) and is left alone; the outcome + is then `partial`. No all-file atomicity is claimed. +- **Undo** first checks that every retained pre-image still exists and every + file still holds its post-image, and refuses before any write otherwise + (`rollback-evicted`, `changed-since` with the path). It then applies the + same per-file rule. Undo is not guaranteed for any period: the journal may + evict rollback data under pressure. +- **Recovery** after a restart compensates an interrupted apply, or finishes + an interrupted Undo, from the durable operation row. It never re-applies. +- **Keep a permanent copy** records its `kept` entry with + `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. + +Additive shapes in `@schlessera/brain-ui-sdk`: + +| Surface | Change | +| --- | --- | +| `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 | +| `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 +permanent copy… (scratch only) and Delete…, before Leave pending. Persist and +Delete are planned when the card is prepared; Move and Keep a copy when a +destination is previewed (`POST /hygiene/review/preview` with the path as +`input`). A plan with refusals keeps them on the option and has no +`premiseDigest`, so it cannot be confirmed. Confirming applies exactly the +previewed plan: an applied effect resolves the card as `fixed`, a kept copy +as `kept` (the review's `kept` counter); `stale` and `refused` leave it +pending; `compensated` and `partial` are `check_failed` with that code. An +old server that cannot parse `kept` fails closed as `check_failed`. Recovery +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. + ## Module hygiene context (breaking, #699) diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index f19212fff9..4594575508 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:1051-1069`). +(`turnJournalSummarySchema`, `packages/ui-sdk/src/schemas.ts:1077-1095`). `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:3822-3828`) and -(`serverUsageSchema`, `packages/ui-sdk/src/schemas.ts:1890-1892`). +(`ServerUsage`, `packages/ui-sdk/src/protocol.ts:3872-3878`) and +(`serverUsageSchema`, `packages/ui-sdk/src/schemas.ts:1916-1918`). 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/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index decf177cf9..46150a43c3 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -226,7 +226,7 @@ Stated before the requirements because five of them derive from it. that is the shape to copy, including its `close()` lifecycle. - R19. **The cron backstop has independent authorization before the general guard.** Mount it on the existing listener before - (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:905`). + (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:906`). Authorize a boot-minted ephemeral token, rotated each boot and stored in a 0600 runtime file, with the actual socket address as an additional check. Proxy headers cannot authorize it. The poke succeeds in every auth mode diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index 8f30360a60..d013c312dc 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -131,7 +131,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. owns manual triggers/history; it does not tick the inbox. - **Two connections:** (`export function createUiDb(`, `packages/ui-server/src/db/client.ts:27-44`) sets WAL, foreign keys and a 5-second busy timeout. Claims are immediate transactions. -- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:905`) follows public routes; +- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:906`) follows public routes; (`export function authGuard(`, `packages/ui-server/src/middleware/auth.ts:184-244`) binds principals in each auth mode. An internal poke needs independent token authorization before this guard. - **Permission parking:** (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge.ts:362-456`). Timeout unwind is diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index 78ff9c5144..61a87c4634 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -267,7 +267,7 @@ Preserve the existing bounded-wait ownership distinction during that drain. writers; rejection retains the original cleanup continuation, writer and reader until genuine settlement, rather than authorizing their replacement (`guardSqliteCleanup`, `packages/ui-server/src/db/write-worker.ts:206-234`; -`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1205-1254`). +`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1216-1265`). The native lease manager retains its own pending operations and durable unknown root outcomes through close (`return { client, writer, recoverDeadOwners`, `packages/ui-server/src/brain/native-brain-leases.ts:274-287`). A caller deadline diff --git a/docs/plans/navigation-recovery.md b/docs/plans/navigation-recovery.md index 593611c5a9..cea8f4d17a 100644 --- a/docs/plans/navigation-recovery.md +++ b/docs/plans/navigation-recovery.md @@ -397,7 +397,7 @@ implementation. Any PR moving these lines owns their citation repairs. - Activity resolution: (`.get("/activity/runs", (c) => {`, `packages/ui-server/src/routes/activity.ts:145-283`). -- API authorization: (`app.use("/api/*", authGuard(authMode, auth, db));`, `packages/ui-server/src/app.ts:905`). +- API authorization: (`app.use("/api/*", authGuard(authMode, auth, db));`, `packages/ui-server/src/app.ts:906`). - Queued acceptance: (`// Queue it as the session's next turn; report queued immediately.`, `packages/ui-server/src/ws/run-session.ts:1102-1147`). diff --git a/docs/plans/storage-accounting.md b/docs/plans/storage-accounting.md index f90b09c73c..d840bdb47b 100644 --- a/docs/plans/storage-accounting.md +++ b/docs/plans/storage-accounting.md @@ -67,7 +67,7 @@ Source anchors, checked against the reviewed commit: The completed #94 and #398 provide existing stats/maintenance foundations. - C: snapshot fields (`snapshotOf`, `packages/core/src/lib/stats-history.ts:132-172`), thinning (`thin`, `packages/core/src/lib/stats-history.ts:232-244`). -- D: effective path/journal resolution (`createApp`, `packages/ui-server/src/app.ts:301-337`), +- D: effective path/journal resolution (`createApp`, `packages/ui-server/src/app.ts:302-338`), WAL store (`createUiDb`, `packages/ui-server/src/db/client.ts:27-44`), and private locations (`statePaths`, `packages/ui-server/src/brain/operational-state.ts:108-114`). - E: live/archive paths (`transcriptPaths`, `packages/ui-backend-claude/src/transcript-archive.ts:30-39`). diff --git a/packages/core/README.md b/packages/core/README.md index 246b5a806b..4cc9223f83 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -30,7 +30,7 @@ to touch `process.env`. | `BRAIN_AGENT_RUNNER_UNAVAILABLE` | Internal: set to `1` by the worker launcher in a credential-free maintenance worker, such as the one hosted `brain sync` runs in, where no agent can log in. The configured agent runner is then treated as absent: bare `brain sync` hands nothing to an agent and reports that judgment is unavailable, so a conflict it leaves is resolved by hand; set by the worker launcher, not an operator input. | the configured agent runner is used | | `BRAIN_CHROME_NO_SANDBOX` | "1" launches the render Chrome without its sandbox (required when running as root). | sandbox on | | `BRAIN_MEDIA_PINNED_PATH_LIMIT` | Trusted host bound on the distinct conversation-pinned scratch paths one media inventory reads (`brain hygiene`, review and `brain sync`'s media count). A positive integer; past it the inventory reports that conversation links were not fully checked, and never claims an exhaustive scan. Anything else stops media detection rather than being guessed. | 5000 | -| `BRAIN_MEDIA_REFERENCE_LIMITS` | Trusted host bounds on the declared reference scan behind every media finding (`brain hygiene`, review and `brain sync`'s media count): comma-separated `=` pairs over `notes` (50000), `noteBytes` (268435456), `perNote` (4194304), `scanTime` in milliseconds (20000) and `refsPerFinding` (500), with `perNote` at most `noteBytes`. Past a limit the scan is refused and nothing claims the references were checked. Anything else stops media detection rather than being guessed. | the Q1 defaults | +| `BRAIN_MEDIA_REFERENCE_LIMITS` | Trusted host bounds on the declared reference scan behind every media finding (`brain hygiene`, review and `brain sync`'s media count): comma-separated `=` pairs over `notes` (50000), `noteBytes` (268435456), `perNote` (4194304), `scanTime` in milliseconds (20000), `refsPerFinding` (500), and for a media effect's plan `rewrittenNotes` (200) and `preview` in bytes (1048576), with `perNote` at most `noteBytes`. Past a limit the scan or plan is refused and nothing claims the references were checked. Anything else stops media detection rather than being guessed. | the Q1 defaults | | `BRAIN_PROVIDER_RELAY_SOCKET` | Internal: absolute path of the server's provider relay socket in a governed or strict agent worker or a relayed maintenance worker. A built-in Gemini, Anthropic or OpenAI image provider whose key the server withheld sends its native request there, and the server adds the key, meters the request and refuses it once a budget is blocked; set by the worker launcher, not an operator input. | no relay; a provider uses its key from the environment | | `BRAIN_RERANK_MODE` | Search reranker mode: "jev", "heuristic" or "none". Overrides the configured `reranker.provider`; an explicit --rerank still wins. Cannot enable model reranking: reranker.enabled must be true. | the configured provider when enabled and available, else heuristic | | `BRAIN_ROOT` | Brain repository root, overriding cwd-based discovery. | nearest ancestor with brain.config.* or .git, else cwd | diff --git a/packages/core/src/cli/commands/hygiene.ts b/packages/core/src/cli/commands/hygiene.ts index d57b41882f..9ac316d751 100644 --- a/packages/core/src/cli/commands/hygiene.ts +++ b/packages/core/src/cli/commands/hygiene.ts @@ -1,4 +1,5 @@ import { existsSync, readFileSync } from "fs"; +import { relative, sep } from "path"; import { loadAuditDocs } from "../../lib/auditor.js"; import { openDatabase } from "../../lib/db.js"; @@ -20,10 +21,13 @@ import { selectHygieneNext } from "../../lib/hygiene-next.js"; import { checkHygiene, CONFIG_BLOCKER_ID, repairHandlers, resolveHygiene, undoHygiene } from "../../lib/hygiene-repair.js"; import { indexAll } from "../../lib/indexer.js"; import { mediaPolicy } from "../../lib/media.js"; +import type { MediaAction } from "../../lib/media-effects.js"; +import { mediaReferenceLimits } from "../../lib/media-references.js"; +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 @@ -88,6 +92,22 @@ const HELP = `brain hygiene --expect-fingerprint [--to ] + [--dry-run | --expect-premise --journal ] + A media finding's effect (#2781). --dry-run plans it and writes nothing: + { "status": "preview", "id", "action", "fingerprint", "source", "destination", + "links", "references", "rewrites", "blockers", "configDiff", "captureBytes", + "copy", "resultClass", "files", "premiseDigest", "refusals" }. move and + keep-copy need --to. Apply needs the preview's premiseDigest and the + caller's journal ID: the caller retains every listed pre-image first and + compensates from it; this command never does. Apply returns { "status": + "applied"|"stale"|"refused"|"interrupted", "id", "action", "journal", + "reason", "refusals", "files": [{ ..., "state" }], "copySha256" }. + keep-copy writes the copy and its config only; brain hygiene keep-copy + records the kept entry after the caller has verified it. +`; + const REPAIR_HELP = ` resolve --handler link-suggested|link-note|link-text|required-field --input --expect-fingerprint [--dry-run | --expect-preview ] @@ -220,7 +240,7 @@ function dispositionRequest(sub: "dismiss" | "snooze" | "keep-copy", pos: string export const hygieneCommand: CoreCommand = { summary: "Reconcile, read and triage the content-hygiene log", - helpBlock: HELP + REPAIR_HELP, + helpBlock: HELP + MEDIA_HELP + REPAIR_HELP, async run(args, cli) { const { args: pos, flags } = parseArgs(args); const sub = pos[0]; @@ -295,6 +315,31 @@ export const hygieneCommand: CoreCommand = { return ["fixed", "preview", "undone"].includes(result.status) ? 0 : 1; } + if (sub === "media") { + // Loaded only for this verb: the effect module's dependencies stay out of every other one. + const { applyMediaEffect, MEDIA_ACTIONS, planMediaEffect } = await import("../../lib/media-effects.js"); + const action = pos[1], id = pos[2]; + if (!MEDIA_ACTIONS.includes(action as MediaAction) || !id || pos.length !== 3) { + throw new UsageError("Usage: brain hygiene media --expect-fingerprint [--to ] [--dry-run | --expect-premise --journal ]"); + } + if (typeof flags["expect-fingerprint"] !== "string") throw new UsageError("media needs --expect-fingerprint "); + if (flags.to !== undefined && typeof flags.to !== "string") throw new UsageError("--to needs a repo-relative path"); + if (cli.configError) throw new UsageError(`Invalid brain.config: ${cli.configError}; no changes made`); + const request = { id, action: action as MediaAction, expectFingerprint: flags["expect-fingerprint"], ...(typeof flags.to === "string" ? { destination: flags.to } : {}) }; + const configPath = cli.brain.configPath === null ? null : relative(cli.brain.root, cli.brain.configPath).split(sep).join("/"); + const ctx = { root: cli.brain.root, policy: mediaPolicy(cli.brain.config), configPath, limits: mediaReferenceLimits(resolveEnv().mediaReferenceLimits) }; + let result; + if (flags["dry-run"] === true) result = planMediaEffect(ctx, request); + else { + if (typeof flags["expect-premise"] !== "string" || typeof flags.journal !== "string") { + throw new UsageError("Preview with --dry-run first, then apply with --expect-premise --journal "); + } + result = applyMediaEffect(ctx, { ...request, expectPremise: flags["expect-premise"], journal: flags.journal }); + } + emit(cli.json, result, () => console.log(JSON.stringify(result, null, 2))); + return ["preview", "applied"].includes(result.status) ? 0 : 1; + } + if (sub === "list") { const state = flags.state; if (state !== undefined && !STATES.includes(state as HygieneState)) { @@ -344,7 +389,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/cli/io.ts b/packages/core/src/cli/io.ts index 44a782ce8d..dd023aa7f6 100644 --- a/packages/core/src/cli/io.ts +++ b/packages/core/src/cli/io.ts @@ -80,7 +80,7 @@ export const VALUE_FLAGS = new Set([ "prompt", "at", "cron", "time-zone", "client-time-zone", "end-at", "scope-file", "attempt-timeout-ms", "max-operations", "id", "cursor", "pins-file", "finding", "expect-fingerprint", "until", "reason", "handler", "input", "expect-preview", "defer", - "copy", "copy-sha256", "journal", + "copy", "copy-sha256", "journal", "to", "expect-premise", ]); const KNOWN_FLAGS = new Set([...BOOLEAN_FLAGS, ...VALUE_FLAGS]); diff --git a/packages/core/src/config/env.ts b/packages/core/src/config/env.ts index 9abf4fcdff..79d0882b6c 100644 --- a/packages/core/src/config/env.ts +++ b/packages/core/src/config/env.ts @@ -51,7 +51,7 @@ export const ENV_VARS: readonly EnvVarSpec[] = [ { name: "BRAIN_PROVIDER_RELAY_SOCKET", description: "Internal: absolute path of the server's provider relay socket in a governed or strict agent worker or a relayed maintenance worker. A built-in Gemini, Anthropic or OpenAI image provider whose key the server withheld sends its native request there, and the server adds the key, meters the request and refuses it once a budget is blocked; set by the worker launcher, not an operator input.", default: "no relay; a provider uses its key from the environment", required: false }, { name: "BRAIN_AGENT_RUNNER_UNAVAILABLE", description: "Internal: set to `1` by the worker launcher in a credential-free maintenance worker, such as the one hosted `brain sync` runs in, where no agent can log in. The configured agent runner is then treated as absent: bare `brain sync` hands nothing to an agent and reports that judgment is unavailable, so a conflict it leaves is resolved by hand; set by the worker launcher, not an operator input.", default: "the configured agent runner is used", required: false }, { name: "BRAIN_MEDIA_PINNED_PATH_LIMIT", description: "Trusted host bound on the distinct conversation-pinned scratch paths one media inventory reads (`brain hygiene`, review and `brain sync`'s media count). A positive integer; past it the inventory reports that conversation links were not fully checked, and never claims an exhaustive scan. Anything else stops media detection rather than being guessed.", default: "5000", required: false }, - { name: "BRAIN_MEDIA_REFERENCE_LIMITS", description: "Trusted host bounds on the declared reference scan behind every media finding (`brain hygiene`, review and `brain sync`'s media count): comma-separated `=` pairs over `notes` (50000), `noteBytes` (268435456), `perNote` (4194304), `scanTime` in milliseconds (20000) and `refsPerFinding` (500), with `perNote` at most `noteBytes`. Past a limit the scan is refused and nothing claims the references were checked. Anything else stops media detection rather than being guessed.", default: "the Q1 defaults", required: false }, + { name: "BRAIN_MEDIA_REFERENCE_LIMITS", description: "Trusted host bounds on the declared reference scan behind every media finding (`brain hygiene`, review and `brain sync`'s media count): comma-separated `=` pairs over `notes` (50000), `noteBytes` (268435456), `perNote` (4194304), `scanTime` in milliseconds (20000), `refsPerFinding` (500), and for a media effect's plan `rewrittenNotes` (200) and `preview` in bytes (1048576), with `perNote` at most `noteBytes`. Past a limit the scan or plan is refused and nothing claims the references were checked. Anything else stops media detection rather than being guessed.", default: "the Q1 defaults", required: false }, { name: "BRAIN_WORKER_OUTPUT_ALLOWANCE", description: "Internal: JSON `{\"bytes\":N,\"setting\":\"NAME\"}` naming the size of a maintenance worker's private writable output stage and the host setting that controls it. When `brain maintain`'s git packing runs out of space, its `git` step names that allowance and setting; set by the worker launcher, not an operator input.", default: "the step reports the space shortfall without a setting", required: false }, { name: "BRAIN_WORKER_CONFIG_ROOT", description: "Internal immutable configuration execution root for maintenance and hosted turn workers, supplied by the trusted worker launch. Root discovery maps it to BRAIN_WORKER_DATA_ROOT; configuration loading maps the data root back here.", required: false }, { diff --git a/packages/core/src/lib/media-config-edit.ts b/packages/core/src/lib/media-config-edit.ts new file mode 100644 index 0000000000..348e225bac --- /dev/null +++ b/packages/core/src/lib/media-config-edit.ts @@ -0,0 +1,173 @@ +/** + * The `media` lists of `brain.config`, read and edited as syntax only (#2781, + * epic #1777, design rev 4 §7). The config is parsed with the TypeScript + * parser and never evaluated: only string literals in literal arrays of a + * literal `media` object, in a directly exported object literal, are read or + * changed. Anything else refuses with `config-not-literal`, so the owner + * edits it by hand. An edit is a minimal splice; every other byte is kept. + */ +import ts from "typescript"; + +/** Why the config's `media` lists cannot be read or edited as literals. */ +export class MediaConfigNotLiteral extends Error { + readonly code = "config-not-literal"; +} + +export interface MediaPolicyLists { + track: string[]; + ignore: string[]; +} + +/** One approved change: add an exact `media.track` entry, and remove an exact `media.ignore` entry with it. */ +export interface MediaPolicyEdit { + addTrack?: string; + removeIgnore?: string; +} + +function refuse(reason: string): never { + throw new MediaConfigNotLiteral(reason); +} + +function unwrap(node: ts.Expression): ts.Expression { + while (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node) || ts.isNonNullExpression(node)) { + node = node.expression; + } + return node; +} + +function literalObject(node: ts.Expression, what: string): ts.ObjectLiteralExpression { + const value = unwrap(node); + if (!ts.isObjectLiteralExpression(value)) refuse(`${what} is not an object literal`); + return value; +} + +function properties(node: ts.ObjectLiteralExpression, what: string): Map { + const found = new Map(); + for (const p of node.properties) { + if (!ts.isPropertyAssignment(p) || !(ts.isIdentifier(p.name) || ts.isStringLiteralLike(p.name))) { + refuse(`${what} uses a spread, computed key, method or shorthand`); + } + if (found.has(p.name.text)) refuse(`${what} has a duplicate ${JSON.stringify(p.name.text)}`); + found.set(p.name.text, p); + } + return found; +} + +function stringArray(node: ts.Expression, what: string): ts.ArrayLiteralExpression { + const value = unwrap(node); + if (!ts.isArrayLiteralExpression(value) || value.elements.some((e) => !ts.isStringLiteralLike(e))) { + refuse(`${what} is not an array of string literals`); + } + return value; +} + +interface Parsed { + file: ts.SourceFile; + prefix: string; + input: string; + root: ts.ObjectLiteralExpression; + media: ts.ObjectLiteralExpression | null; + track: ts.ArrayLiteralExpression | null; + ignore: ts.ArrayLiteralExpression | null; +} + +function parse(source: string, format: "ts" | "json"): Parsed { + if (format === "json") { + try { + JSON.parse(source); + } catch { + refuse("brain.config.json is not valid JSON"); + } + } + const prefix = format === "json" ? "export default " : ""; + const input = prefix + source; + const file = ts.createSourceFile("brain.config.ts", input, ts.ScriptTarget.Latest, true); + const diagnostics = ts.transpileModule(input, { reportDiagnostics: true }).diagnostics ?? []; + if (diagnostics.some((d) => d.category === ts.DiagnosticCategory.Error)) refuse("the config has a syntax error"); + const exports = file.statements.filter(ts.isExportAssignment); + if (exports.length !== 1 || exports[0]!.isExportEquals) refuse("the config has no direct default-exported literal"); + let expression = unwrap(exports[0]!.expression); + if (ts.isCallExpression(expression)) { + if (!ts.isIdentifier(expression.expression) || expression.expression.text !== "defineConfig" || expression.arguments.length !== 1) { + refuse("the default export is not a direct defineConfig literal"); + } + expression = expression.arguments[0]!; + } + const root = literalObject(expression, "the config"); + const mediaProp = properties(root, "the config").get("media"); + if (!mediaProp) return { file, prefix, input, root, media: null, track: null, ignore: null }; + const media = literalObject(mediaProp.initializer, "media"); + const lists = properties(media, "media"); + const track = lists.get("track"); + const ignore = lists.get("ignore"); + return { + file, prefix, input, root, media, + track: track ? stringArray(track.initializer, "media.track") : null, + ignore: ignore ? stringArray(ignore.initializer, "media.ignore") : null, + }; +} + +const values = (array: ts.ArrayLiteralExpression | null) => (array ? array.elements.map((e) => (e as ts.StringLiteralLike).text) : []); + +/** The literal `media.track` and `media.ignore` lists; absent lists are empty. */ +export function readMediaPolicyLists(source: string, format: "ts" | "json"): MediaPolicyLists { + const parsed = parse(source, format); + return { track: values(parsed.track), ignore: values(parsed.ignore) }; +} + +/** Insert `text` as a new last property of `node`. */ +function appendProperty(input: string, node: ts.ObjectLiteralExpression, file: ts.SourceFile, text: string): { at: number; insert: string } { + const last = node.properties.at(-1); + if (!last) { + const open = node.getStart(file) + 1; + return { at: open, insert: ` ${text} ` }; + } + // A trailing comma stays where it is: the new property follows it. + const comma = input.slice(last.end).match(/^\s*,/); + return comma ? { at: last.end + comma[0].length, insert: ` ${text},` } : { at: last.end, insert: `, ${text}` }; +} + +/** + * The config text with `edit` applied, and the lists it leaves. Adding a + * pattern already listed changes nothing; removing one not listed refuses. + * Both edits are planned against the original text and spliced from the end, + * so neither moves the other. + */ +export function planMediaPolicyEdit(source: string, format: "ts" | "json", edit: MediaPolicyEdit): { text: string; lists: MediaPolicyLists } { + const parsed = parse(source, format); + const { file, input } = parsed; + const splices: Array<{ start: number; end: number; text: string }> = []; + const track = values(parsed.track), ignore = values(parsed.ignore); + if (edit.addTrack !== undefined && !track.includes(edit.addTrack)) { + const literal = JSON.stringify(edit.addTrack); + if (parsed.track) { + const last = parsed.track.elements.at(-1); + if (last) splices.push({ start: last.end, end: last.end, text: `, ${literal}` }); + else splices.push({ start: parsed.track.getStart(file), end: parsed.track.end, text: `[${literal}]` }); + } else if (parsed.media) { + const { at, insert } = appendProperty(input, parsed.media, file, `"track": [${literal}]`); + splices.push({ start: at, end: at, text: insert }); + } else { + const { at, insert } = appendProperty(input, parsed.root, file, `"media": { "track": [${literal}] }`); + splices.push({ start: at, end: at, text: insert }); + } + track.push(edit.addTrack); + } + if (edit.removeIgnore !== undefined) { + const elements = parsed.ignore?.elements ?? ([] as unknown as ts.NodeArray); + const i = elements.findIndex((e) => (e as ts.StringLiteralLike).text === edit.removeIgnore); + if (i < 0) refuse(`media.ignore does not list ${JSON.stringify(edit.removeIgnore)}`); + const el = elements[i]!; + if (elements.length === 1) splices.push({ start: parsed.ignore!.getStart(file), end: parsed.ignore!.end, text: "[]" }); + else if (i < elements.length - 1) splices.push({ start: el.getStart(file), end: elements[i + 1]!.getStart(file), text: "" }); + else splices.push({ start: elements[i - 1]!.end, end: el.end, text: "" }); + ignore.splice(ignore.indexOf(edit.removeIgnore), 1); + } + let text = input; + for (const s of splices.sort((a, b) => b.start - a.start)) text = text.slice(0, s.start) + s.text + text.slice(s.end); + text = text.slice(parsed.prefix.length); + // The result must read back as exactly the intended lists. + const after = readMediaPolicyLists(text, format); + if (JSON.stringify(after) !== JSON.stringify({ track, ignore })) refuse("the edited config does not read back as the intended lists"); + return { text, lists: after }; +} diff --git a/packages/core/src/lib/media-effects.ts b/packages/core/src/lib/media-effects.ts new file mode 100644 index 0000000000..8b51160b7c --- /dev/null +++ b/packages/core/src/lib/media-effects.ts @@ -0,0 +1,627 @@ +/** + * What the four media review actions do to files, references and config + * (#2781, epic #1777, design rev 4 §5-§7): Delete, Move, Persist here and + * Keep a permanent copy. Planning reads only; applying writes only what the + * plan named, after its premise is recomputed and matches. + * + * Capture, compensation and Undo are not here. They belong to the caller + * that holds the bounded change journal (the UI server): it retains every + * pre-image a plan lists *before* it asks for the apply, and restores per + * file from those retained versions, only where a file still holds what + * this apply wrote. So an apply never compensates by itself, and the CLI + * refuses to apply without the caller's `--journal` identity. The one thing + * it cleans up is its own private `.part` copy. + * + * No all-file atomicity is claimed. Each step is checked against the + * plan's expected version before it writes, and a step that cannot proceed + * stops the apply with the files written so far, for the caller to + * compensate. + */ +import { createHash } from "crypto"; +import { + closeSync, constants, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readdirSync, readSync, statfsSync, unlinkSync, writeSync, +} from "fs"; +import { posix } from "path"; + +import { canonicalFindings, type HygieneFinding } from "./hygiene.js"; +import { caseFold } from "./case-fold.js"; +import { mediaPolicyClass, type MediaPolicy } from "./media.js"; +import { planMediaPolicyEdit, MediaConfigNotLiteral, readMediaPolicyLists, type MediaPolicyEdit } from "./media-config-edit.js"; +import { buildMediaInventory, mediaCandidates, SCRATCH_PREFIX, type MediaInventory, type MediaItem } from "./media-inventory.js"; +import { DEFAULT_MEDIA_REFERENCE_LIMITS, noteReferences, type MediaReference, type MediaReferenceLimits } from "./media-references.js"; +import { SENSITIVE_PATTERNS } from "./sync/assess.js"; +import { matchesAnyPattern } from "./tool-leftovers.js"; +import { writeFileSafely } from "./safe-path.js"; + +export const MEDIA_ACTIONS = ["delete", "move", "persist", "keep-copy"] as const; +export type MediaAction = (typeof MEDIA_ACTIONS)[number]; + +/** Where the share flow stages files (`SHARE_STAGING_DIR` in the UI SDK); its owner, not review, decides them. */ +export const SHARE_STAGING_PREFIX = ".brain-ui/inbox/"; +/** Destinations that are not a final location: protected state and agent-writable workspaces. */ +const NOT_FINAL = [".brain/", ".brain-ui/", ".brain-index/", ".brain-cache/", ".git/", "workspaces/", "context/hygiene/", "node_modules/"]; +const MAX_TARGET = 4096; + +/** One file or directory an effect writes, in apply order. `before`/`after` are SHA-256, `directory`, or null for absent. */ +export interface MediaEffectFile { + path: string; + role: "source" | "destination" | "note" | "config" | "directory"; + before: string | null; + after: string | null; + /** Bytes of the pre-image the caller must retain (0 when there is none). */ + bytes: number; +} + +export interface MediaRefusal { + code: string; + path?: string; + line?: number; + limit?: string; + effective?: number; + observed?: number; +} + +export interface MediaRewrite { + note: string; + line: number; + kind: MediaReference["kind"]; + before: string; + after: string; +} + +export interface MediaEffectPlan { + status: "preview"; + id: string; + action: MediaAction; + fingerprint: string; + source: { path: string; sha256: string; bytes: number; kind: "content" | "scratch" | "share-staged" }; + destination: string | null; + /** Conversation links: `linked` with a count, `unlinked`, or `unknown` when the pin snapshot cannot say. */ + links: { state: "linked" | "unlinked" | "unknown"; conversations: number }; + /** Whether every declared reference was checked; a refused scan is never "no references". */ + references: { complete: boolean; count: number }; + rewrites: MediaRewrite[]; + /** References a Move cannot rewrite, and a Delete will break. */ + blockers: Array<{ note: string; line: number; kind: MediaReference["kind"]; target: string }>; + configDiff: { path: string; track: { before: string[]; after: string[] }; ignore: { before: string[]; after: string[] } } | null; + /** Bytes the caller must retain before any write: removed or overwritten pre-images. */ + captureBytes: number; + copy: { bytes: number; sha256: string; diskFreeAdvisory: number | null } | null; + /** The class sync gives the file where it ends up: `TRACK` is committed, null still awaits review. */ + resultClass: "TRACK" | "ARTIFACT" | null; + files: MediaEffectFile[]; + premiseDigest: string; + refusals: MediaRefusal[]; +} + +export interface MediaEffectFileResult extends MediaEffectFile { + state: "created" | "changed" | "removed" | "unchanged"; +} + +export interface MediaEffectResult { + /** + * `applied`: every step wrote and the result verified. `stale`/`refused`: + * nothing was written. `interrupted`: a step failed after earlier ones + * wrote; the caller compensates `files` from its retained pre-images. + */ + status: "applied" | "stale" | "refused" | "interrupted"; + id: string; + action: MediaAction; + journal: string | null; + reason?: string; + refusals?: MediaRefusal[]; + files: MediaEffectFileResult[]; + /** For a copy: the SHA-256 the copy was verified to hold. */ + copySha256?: string; +} + +export interface MediaEffectRequest { + id: string; + action: MediaAction; + expectFingerprint: string; + destination?: string; +} + +export interface MediaEffectContext { + root: string; + policy: MediaPolicy; + /** Repo-relative config path, or null without a config. */ + configPath: string | null; + /** The Q1 bounds this plan enforces (`rewrittenNotes`, `preview`); the scan's own come with the inventory. */ + limits?: MediaReferenceLimits; + /** Tests inject the inventory; otherwise it is built afresh. */ + inventory?: MediaInventory; +} + +const sha256 = (data: string | Uint8Array) => createHash("sha256").update(data).digest("hex"); +const digest = (value: unknown) => sha256(JSON.stringify(value)); + +// --------------------------------------------------------------------------- +// Descriptor-anchored file access (Linux): every component is opened +// O_DIRECTORY|O_NOFOLLOW from the root, so no symlink is ever followed. + +const DIRECTORY = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW; +const at = (fd: number, name: string) => `/proc/self/fd/${fd}/${name}`; + +class Unsafe extends Error { + constructor(readonly code: string, readonly path: string) { super(`${code}: ${path}`); } +} + +/** Open `dir` (repo-relative, "" for the root) anchored at `root`; with `create`, missing components are made and reported. */ +function openDir(root: string, dir: string, create?: string[]): number { + let fd = openSync(root, DIRECTORY); + const parts = dir === "" ? [] : dir.split("/"); + try { + for (let i = 0; i < parts.length; i++) { + const name = parts[i]!; + let next: number; + try { + next = openSync(at(fd, name), DIRECTORY); + } catch (e) { + const code = (e as NodeJS.ErrnoException).code; + if (code !== "ENOENT" || !create) throw new Unsafe(code === "ENOENT" ? "missing" : "not-contained", parts.slice(0, i + 1).join("/")); + mkdirSync(at(fd, name), { mode: 0o755 }); + create.push(parts.slice(0, i + 1).join("/")); + next = openSync(at(fd, name), DIRECTORY); + } + closeSync(fd); + fd = next; + } + return fd; + } catch (e) { + closeSync(fd); + throw e; + } +} + +/** SHA-256 of a regular file reached without following any link, or null when it is absent. Anything else is unsafe. */ +export function anchoredSha256(root: string, path: string): string | null { + const dir = posix.dirname(path) === "." ? "" : posix.dirname(path), name = posix.basename(path); + let parent: number; + try { + parent = openDir(root, dir); + } catch (e) { + if (e instanceof Unsafe && e.code === "missing") return null; + throw e; + } + try { + const info = lstatSync(at(parent, name), { throwIfNoEntry: false }); + if (!info) return null; + if (!info.isFile()) throw new Unsafe("not-contained", path); + const fd = openSync(at(parent, name), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + try { + const hash = createHash("sha256"), buffer = Buffer.alloc(64 * 1024); + let read: number; + while ((read = readSync(fd, buffer, 0, buffer.length, null)) > 0) hash.update(buffer.subarray(0, read)); + return hash.digest("hex"); + } finally { + closeSync(fd); + } + } finally { + closeSync(parent); + } +} + +function readAnchored(root: string, path: string): Buffer { + const parent = openDir(root, posix.dirname(path) === "." ? "" : posix.dirname(path)); + try { + const fd = openSync(at(parent, posix.basename(path)), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + try { + if (!fstatSync(fd).isFile()) throw new Unsafe("not-contained", path); + const chunks: Buffer[] = [], buffer = Buffer.alloc(64 * 1024); + let read: number; + while ((read = readSync(fd, buffer, 0, buffer.length, null)) > 0) chunks.push(Buffer.from(buffer.subarray(0, read))); + return Buffer.concat(chunks); + } finally { + closeSync(fd); + } + } finally { + closeSync(parent); + } +} + +// --------------------------------------------------------------------------- +// Planning + +function validPath(path: string): boolean { + return path !== "" && Buffer.byteLength(path) <= MAX_TARGET && !path.startsWith("/") && !/[\\\u0000-\u001f\u007f]/u.test(path) && + path.split("/").every((part) => part !== "" && part !== "." && part !== ".."); +} + +/** The source's owner and conversation links, from the inventory's pin snapshot. */ +function sourceKind(item: MediaItem, inventory: MediaInventory) { + const kind: MediaEffectPlan["source"]["kind"] = item.path.startsWith(SHARE_STAGING_PREFIX) ? "share-staged" : item.path.startsWith(SCRATCH_PREFIX) ? "scratch" : "content"; + const links: MediaEffectPlan["links"] = item.pins.length > 0 ? { state: "linked", conversations: item.pins.length } + : kind === "scratch" && inventory.links.state !== "complete" ? { state: "unknown", conversations: 0 } : { state: "unlinked", conversations: 0 }; + return { kind, links }; +} + +/** The availability matrix (rev 4 §4.2): the first refusal for this action on this source, or null. */ +function eligibility(action: MediaAction, kind: MediaEffectPlan["source"]["kind"], links: MediaEffectPlan["links"]): MediaRefusal | null { + if (kind === "share-staged") return { code: "share-staged" }; + if (action === "persist" && kind === "scratch") return { code: "not-final-location" }; + if (action === "move" && kind === "scratch") { + if (links.state === "linked") return { code: "pinned-scratch" }; + if (links.state === "unknown") return { code: "pins-unknown" }; + } + if (action === "keep-copy" && (kind !== "scratch" || links.state === "unlinked")) return { code: "not-linked-scratch" }; + return null; +} + +/** Destination guards (rev 4 §5.2, §6): contained, final, absent, no sibling that differs only by case or normalization, no secret name. */ +function destinationChecks(root: string, destination: string, source: string): { refusal: MediaRefusal | null; created: string[] } { + if (!validPath(destination)) return { refusal: { code: "not-contained", path: destination }, created: [] }; + if (NOT_FINAL.some((p) => destination.startsWith(p))) return { refusal: { code: "not-final-location", path: destination }, created: [] }; + if (destination === source) return { refusal: { code: "exists", path: destination }, created: [] }; + if (matchesAnyPattern(destination, SENSITIVE_PATTERNS)) return { refusal: { code: "secret-name", path: destination }, created: [] }; + const parts = destination.split("/"), name = parts.pop()!; + // Walk what exists of the parent chain; the rest would be created. + const created: string[] = []; + let existing = ""; + for (let i = 0; i < parts.length; i++) { + const rel = parts.slice(0, i + 1).join("/"); + const info = lstatSync(posix.join(root, rel), { throwIfNoEntry: false }); + if (!info) { for (let j = i; j < parts.length; j++) created.push(parts.slice(0, j + 1).join("/")); break; } + if (!info.isDirectory()) return { refusal: { code: "not-contained", path: rel }, created: [] }; + existing = rel; + } + if (created.length === 0) { + const info = lstatSync(posix.join(root, destination), { throwIfNoEntry: false }); + if (info) return { refusal: { code: "exists", path: destination }, created: [] }; + const fold = (s: string) => caseFold(s.normalize("NFC")); + for (const sibling of readdirSync(posix.join(root, existing || "."))) { + if (sibling !== name && fold(sibling) === fold(name)) return { refusal: { code: "name-collision", path: posix.join(existing, sibling) }, created: [] }; + } + } + return { refusal: null, created }; +} + +/** The new destination text for one rewritable reference, keeping its style; null to leave it as it is. */ +function rewriteTarget(ref: MediaReference, destination: string): string | null { + if (ref.kind === "wiki" || ref.kind === "embed") { + // A bare name matches by basename: it still does when the name is kept. + if (!ref.target.includes("/") && posix.basename(destination) === ref.target) return null; + return destination; + } + const raw = ref.target; + const cut = raw.search(/[?#]/); + const pathPart = cut < 0 ? raw : raw.slice(0, cut), suffix = cut < 0 ? "" : raw.slice(cut); + let decoded = pathPart; + try { decoded = decodeURI(pathPart); } catch { /* written literally */ } + const encoded = decoded !== pathPart; + let next = pathPart.startsWith("/") ? `/${destination}` : posix.relative(posix.dirname(ref.note), destination); + if (encoded || /[\s()<>]/.test(next)) next = encodeURI(next); + return next + suffix; +} + +function configFormat(path: string): "ts" | "json" { + return path.endsWith(".json") ? "json" : "ts"; +} + +/** + * The config change that makes `target` TRACK (rev 4 §7, M1 A), or why it + * cannot be made here: already tracked needs none; a root-level name or a + * `*` has no exact form (`not-expressible`); an ignore entry other than + * this exact path needs a broader, separately approved adjustment. + */ +function trackEdit(target: string, policy: MediaPolicy): { edit: MediaPolicyEdit | null; refusal: MediaRefusal | null } { + const ignores = policy.ignore.filter((p) => matchesAnyPattern(target, [p])); + if (ignores.length === 0 && mediaPolicyClass(target, policy) === "TRACK") return { edit: null, refusal: null }; + if (!target.includes("/") || target.includes("*")) return { edit: null, refusal: { code: "not-expressible", path: target } }; + if (ignores.length > 0 && !(ignores.length === 1 && ignores[0] === target)) return { edit: null, refusal: { code: "ignore-adjustment-required", path: ignores.join("\n") } }; + return { edit: { addTrack: target, ...(ignores.length === 1 ? { removeIgnore: target } : {}) }, refusal: null }; +} + +/** The media finding `id` names, with its inventory item, or null when it is not detected. */ +function mediaFinding(ctx: MediaEffectContext, inventory: MediaInventory, id: string): { finding: HygieneFinding; item: MediaItem } | null { + const finding = canonicalFindings(mediaCandidates(inventory)).get(id); + const item = finding ? inventory.items.find((i) => i.path === finding.path) : undefined; + return finding && item ? { finding, item } : null; +} + +/** Plan `request` against the brain as it is now. Reads only. */ +export function planMediaEffect(ctx: MediaEffectContext, request: MediaEffectRequest): MediaEffectPlan | { status: "stale" | "refused"; id: string; action: MediaAction; reason: string; refusals: MediaRefusal[] } { + const { root, policy } = ctx; + const limits = ctx.limits ?? DEFAULT_MEDIA_REFERENCE_LIMITS; + const inventory = ctx.inventory ?? buildMediaInventory(root, policy); + const found = mediaFinding(ctx, inventory, request.id); + const base = { id: request.id, action: request.action }; + if (!found) return { ...base, status: "refused", reason: "not-detected", refusals: [{ code: "not-detected" }] }; + if (found.finding.fingerprint !== request.expectFingerprint) return { ...base, status: "stale", reason: "stale-fingerprint", refusals: [{ code: "stale" }] }; + const { finding, item } = found; + const { kind, links } = sourceKind(item, inventory); + const refusals: MediaRefusal[] = []; + const add = (r: MediaRefusal | null) => { if (r) refusals.push(r); }; + add(eligibility(request.action, kind, links)); + if (item.sha256 === "unreadable") add({ code: "source-changed", path: item.path }); + + const scan = inventory.references; + const refs = scan.status === "complete" ? scan.references.get(item.path) ?? [] : []; + if (scan.status === "refused" && request.action !== "delete") { + const r = scan.refusal; + add(r.code === "inventory-too-large" ? { code: r.code, limit: r.limit, effective: r.effective, observed: r.observed } : { code: r.code, path: r.path }); + } + + const needsDestination = request.action === "move" || request.action === "keep-copy"; + let destination: string | null = null, created: string[] = []; + if (needsDestination) { + if (!request.destination) add({ code: "destination-required" }); + else { + destination = request.destination; + const checked = destinationChecks(root, destination, item.path); + add(checked.refusal); + created = checked.created; + } + } else if (request.destination !== undefined) add({ code: "destination-unexpected" }); + + const rewrites: MediaRewrite[] = [], blockers: MediaEffectPlan["blockers"] = []; + const files: MediaEffectFile[] = []; + for (const ref of refs) { + if (!ref.rewritable) { blockers.push({ note: ref.note, line: ref.line, kind: ref.kind, target: ref.target }); continue; } + if (request.action !== "move" || !destination) continue; + const after = rewriteTarget(ref, destination); + if (after === null) continue; + if (Buffer.byteLength(after) > MAX_TARGET) add({ code: "ref-unsupported", path: ref.note, line: ref.line }); + rewrites.push({ note: ref.note, line: ref.line, kind: ref.kind, before: ref.target, after }); + } + if (request.action === "move") for (const b of blockers) add({ code: "ref-unsupported", path: b.note, line: b.line }); + + // Config for Persist here, and for a copy that sync must keep. + let configDiff: MediaEffectPlan["configDiff"] = null, configFile: MediaEffectFile | null = null; + const tracked = request.action === "persist" ? item.path : request.action === "keep-copy" ? destination : null; + let resultClass: MediaEffectPlan["resultClass"] = request.action === "delete" ? null : mediaPolicyClass(destination ?? item.path, policy); + if (tracked && refusals.length === 0) { + const { edit, refusal } = trackEdit(tracked, policy); + add(refusal); + if (edit) { + if (!ctx.configPath || !validPath(ctx.configPath)) add({ code: "config-not-literal" }); + else { + try { + const before = readAnchored(root, ctx.configPath); + const text = before.toString("utf8"); + const planned = planMediaPolicyEdit(text, configFormat(ctx.configPath), edit); + const lists = readMediaPolicyLists(text, configFormat(ctx.configPath)); + configDiff = { path: ctx.configPath, track: { before: lists.track, after: planned.lists.track }, ignore: { before: lists.ignore, after: planned.lists.ignore } }; + configFile = { path: ctx.configPath, role: "config", before: sha256(before), after: sha256(planned.text), bytes: before.length }; + resultClass = mediaPolicyClass(tracked, { ...policy, track: [...policy.track, edit.addTrack!], ignore: policy.ignore.filter((p) => p !== edit.removeIgnore) }); + } catch (e) { + add({ code: e instanceof MediaConfigNotLiteral ? "config-not-literal" : "config-invalid", path: ctx.configPath }); + } + } + } + } + + // Notes a Move rewrites: each one's current and planned bytes. + const byNote = new Map(); + for (const r of rewrites) byNote.set(r.note, [...(byNote.get(r.note) ?? []), r]); + if (byNote.size > limits.rewrittenNotes) add({ code: "inventory-too-large", limit: "rewrittenNotes", effective: limits.rewrittenNotes, observed: byNote.size }); + + if (refusals.length === 0) { + if (request.action === "delete") files.push({ path: item.path, role: "source", before: item.sha256, after: null, bytes: item.bytes }); + if (request.action === "move" || request.action === "keep-copy") { + for (const dir of created) files.push({ path: dir, role: "directory", before: null, after: "directory", bytes: 0 }); + files.push({ path: destination!, role: "destination", before: null, after: item.sha256, bytes: 0 }); + } + if (request.action === "move") { + files.push({ path: item.path, role: "source", before: item.sha256, after: null, bytes: item.bytes }); + for (const note of [...byNote.keys()].sort()) { + try { + const before = readAnchored(root, note); + const after = rewriteNote(note, before.toString("utf8"), item.path, destination!); + if (after === null) { add({ code: "stale", path: note }); continue; } + files.push({ path: note, role: "note", before: sha256(before), after: sha256(after), bytes: before.length }); + } catch { + add({ code: "inventory-unscannable", path: note }); + } + } + } + if (configFile) files.push(configFile); + } + + let diskFreeAdvisory: number | null = null; + if (request.action === "keep-copy") { + try { const s = statfsSync(root); diskFreeAdvisory = Number(s.bavail) * Number(s.bsize); } catch { diskFreeAdvisory = null; } + } + const plan: MediaEffectPlan = { + status: "preview", + id: request.id, + action: request.action, + fingerprint: finding.fingerprint, + source: { path: item.path, sha256: item.sha256, bytes: item.bytes, kind }, + destination, + links, + references: { complete: scan.status === "complete", count: refs.length }, + rewrites, + blockers, + configDiff, + captureBytes: files.reduce((n, f) => n + (f.role === "directory" || f.before === null ? 0 : f.bytes), 0), + copy: request.action === "keep-copy" ? { bytes: item.bytes, sha256: item.sha256, diskFreeAdvisory } : null, + resultClass, + files: refusals.length === 0 ? files : [], + premiseDigest: "", + refusals, + }; + // The premise binds everything apply depends on: the finding, every file's + // expected bytes, the pins and the media policy (rev 4 §6). + plan.premiseDigest = digest({ id: plan.id, action: plan.action, fingerprint: plan.fingerprint, destination, files: plan.files, pins: item.pins, links, policy: { track: policy.track, ignore: policy.ignore } }); + const size = Buffer.byteLength(JSON.stringify(plan)); + if (size > limits.preview) { + return { ...base, status: "refused", reason: "inventory-too-large", refusals: [{ code: "inventory-too-large", limit: "preview", effective: limits.preview, observed: size }] }; + } + return plan; +} + +/** `text` with every rewritable reference to `source` pointed at `destination`, or null when nothing changes. */ +function rewriteNote(note: string, text: string, source: string, destination: string): string | null { + const refs = noteReferences(note, text, new Set([source])).filter((r) => r.rewritable && r.span); + let out = text, changed = false; + for (const ref of [...refs].sort((a, b) => b.span![0] - a.span![0])) { + const after = rewriteTarget(ref, destination); + if (after === null) continue; + out = out.slice(0, ref.span![0]) + after + out.slice(ref.span![1]); + changed = true; + } + return changed ? out : null; +} + +// --------------------------------------------------------------------------- +// Applying + +class StepFailed extends Error { + constructor(readonly reason: string) { super(reason); } +} + +/** Replace a regular file's bytes only while it still holds `expected` (temp file, then rename). */ +function replaceExpected(root: string, path: string, expected: string, text: string): void { + if (anchoredSha256(root, path) !== expected) throw new StepFailed("premise-changed"); + writeFileSafely(posix.join(root, path), text, { + beforePublish: () => { if (anchoredSha256(root, path) !== expected) throw new StepFailed("premise-changed"); }, + }); +} + +/** 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 { + 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`; + let input: number | undefined, output: number | undefined, partMade = false; + try { + input = openSync(at(srcParent, posix.basename(source)), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + const startStat = fstatSync(input); + if (!startStat.isFile()) throw new StepFailed("source-changed"); + output = openSync(at(dstParent, part), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o644); + partMade = true; + const hash = createHash("sha256"), buffer = Buffer.alloc(64 * 1024); + let read: number, position = 0; + while ((read = readSync(input, buffer, 0, buffer.length, position)) > 0) { + hash.update(buffer.subarray(0, read)); + let written = 0; + while (written < read) written += writeSync(output, buffer, written, read - written, position + written); + position += read; + } + 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; + 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; + fsyncSync(dstParent); + } finally { + if (output !== undefined) closeSync(output); + if (input !== undefined) closeSync(input); + // The private part is this apply's own: it never outlives a failure. + if (partMade) { try { unlinkSync(at(dstParent, part)); } catch { /* already gone */ } } + closeSync(srcParent); closeSync(dstParent); + } +} + +/** Move by link(2) then unlink(2): never overwrites, and refuses across file systems (`exdev`) before anything is removed. */ +function moveExclusive(root: string, source: string, destination: string, expected: string): void { + const srcParent = openDir(root, posix.dirname(source) === "." ? "" : posix.dirname(source)); + const dstParent = openDir(root, posix.dirname(destination) === "." ? "" : posix.dirname(destination)); + try { + if (anchoredSha256(root, source) !== expected) throw new StepFailed("source-changed"); + try { linkSync(at(srcParent, posix.basename(source)), at(dstParent, posix.basename(destination))); } + catch (e) { + const code = (e as NodeJS.ErrnoException).code; + throw new StepFailed(code === "EXDEV" ? "exdev" : code === "EEXIST" ? "exists" : "move-failed"); + } + fsyncSync(dstParent); + // The source must still be the file just linked before it is removed. + if (anchoredSha256(root, destination) !== expected) throw new StepFailed("source-changed"); + unlinkSync(at(srcParent, posix.basename(source))); + fsyncSync(srcParent); + } finally { + closeSync(srcParent); closeSync(dstParent); + } +} + +function removeExpected(root: string, path: string, expected: string): void { + const parent = openDir(root, posix.dirname(path) === "." ? "" : posix.dirname(path)); + try { + if (anchoredSha256(root, path) !== expected) throw new StepFailed("source-changed"); + unlinkSync(at(parent, posix.basename(path))); + fsyncSync(parent); + } finally { + closeSync(parent); + } +} + +/** + * Apply a plan the caller previewed. The plan is recomputed first; a + * different premise is `stale` and nothing is written. Then each file is + * written in plan order, each checked against its expected pre-image. + * `verify` runs after the last write with the post-apply policy. + */ +export function applyMediaEffect(ctx: MediaEffectContext, request: MediaEffectRequest & { expectPremise: string; journal: string }): MediaEffectResult { + const base = { id: request.id, action: request.action, journal: request.journal }; + if (process.platform !== "linux") return { ...base, status: "refused", reason: "platform-unsupported", files: [] }; + if (!/^[A-Za-z0-9._-]{1,128}$/.test(request.journal)) return { ...base, status: "refused", reason: "invalid-journal", files: [] }; + const plan = planMediaEffect(ctx, request); + if (plan.status !== "preview") return { ...base, status: plan.status, reason: plan.reason, refusals: plan.refusals, files: [] }; + if (plan.refusals.length > 0) return { ...base, status: "refused", reason: plan.refusals[0]!.code, refusals: plan.refusals, files: [] }; + if (plan.premiseDigest !== request.expectPremise) return { ...base, status: "stale", reason: "premise-changed", files: [] }; + + const results: MediaEffectFileResult[] = plan.files.map((f) => ({ ...f, state: "unchanged" })); + const mark = (path: string, state: MediaEffectFileResult["state"]) => { for (const r of results) if (r.path === path) r.state = state; }; + const written = () => results.some((r) => r.state !== "unchanged"); + const { root } = ctx; + try { + const source = plan.source.path, sha = plan.source.sha256; + const createdDirs = plan.files.filter((f) => f.role === "directory").map((f) => f.path); + if (createdDirs.length > 0) { + const made: string[] = []; + try { closeSync(openDir(root, createdDirs.at(-1)!, made)); } + finally { for (const dir of made) mark(dir, "created"); } + if (made.join("\n") !== createdDirs.join("\n")) throw new StepFailed("premise-changed"); + } + if (request.action === "delete") { removeExpected(root, source, sha); mark(source, "removed"); } + if (request.action === "move") { + moveExclusive(root, source, plan.destination!, sha); + mark(plan.destination!, "created"); mark(source, "removed"); + for (const note of plan.files.filter((f) => f.role === "note")) { + const text = readAnchored(root, note.path).toString("utf8"); + const next = rewriteNote(note.path, text, source, plan.destination!); + if (next === null || sha256(next) !== note.after) throw new StepFailed("premise-changed"); + replaceExpected(root, note.path, note.before!, next); + mark(note.path, "changed"); + } + } + if (request.action === "keep-copy") { + copyExclusive(root, source, plan.destination!, sha, request.journal); + mark(plan.destination!, "created"); + } + const config = plan.files.find((f) => f.role === "config"); + let policy = ctx.policy; + if (config && plan.configDiff) { + const text = readAnchored(root, config.path).toString("utf8"); + const tracked = request.action === "persist" ? source : plan.destination!; + const edit = trackEdit(tracked, ctx.policy).edit; + if (!edit) throw new StepFailed("premise-changed"); + const planned = planMediaPolicyEdit(text, configFormat(config.path), edit); + if (sha256(planned.text) !== config.after) throw new StepFailed("premise-changed"); + replaceExpected(root, config.path, config.before!, planned.text); + mark(config.path, "changed"); + // Reload: what the written config now reads as, never what was meant. + const lists = readMediaPolicyLists(readAnchored(root, config.path).toString("utf8"), configFormat(config.path)); + if (JSON.stringify(lists) !== JSON.stringify({ track: plan.configDiff.track.after, ignore: plan.configDiff.ignore.after })) throw new StepFailed("config-invalid"); + policy = { ...ctx.policy, track: lists.track, ignore: lists.ignore }; + } + // Verify: every file holds what the plan said, and the result classes as intended. + for (const f of plan.files) { + if (f.role === "directory") continue; + if (anchoredSha256(root, f.path) !== f.after) throw new StepFailed("verification-failed"); + } + if (request.action === "keep-copy" && anchoredSha256(root, source) !== sha) throw new StepFailed("source-changed"); + if ((request.action === "persist" || request.action === "keep-copy") && mediaPolicyClass(request.action === "persist" ? source : plan.destination!, policy) !== "TRACK") { + throw new StepFailed("verification-failed"); + } + return { ...base, status: "applied", files: results, ...(request.action === "keep-copy" ? { copySha256: sha } : {}) }; + } catch (e) { + const reason = e instanceof StepFailed ? e.reason : e instanceof Unsafe ? e.code : "write-failed"; + // Nothing written yet: a refusal, never a compensation. + if (!written()) return { ...base, status: ["exdev", "exists", "source-changed"].includes(reason) ? "refused" : "stale", reason, files: results }; + return { ...base, status: "interrupted", reason, files: results }; + } +} diff --git a/packages/core/src/lib/media-references.ts b/packages/core/src/lib/media-references.ts index 4e3f449e7b..f1badba93e 100644 --- a/packages/core/src/lib/media-references.ts +++ b/packages/core/src/lib/media-references.ts @@ -44,15 +44,21 @@ export interface MediaReferenceLimits { scanTime: number; /** Reference entries kept for one finding. */ refsPerFinding: number; + /** Distinct notes one Move rewrites (checked when the effect is planned, #2781). */ + rewrittenNotes: number; + /** UTF-8 bytes of one serialized effect preview. */ + preview: number; } -/** Q1 A defaults: 50,000 notes, 256 MiB, 4 MiB per note, 20 s, 500 references per finding. */ +/** Q1 A defaults: 50,000 notes, 256 MiB, 4 MiB per note, 20 s, 500 references per finding, 200 rewritten notes, 1 MiB preview. */ export const DEFAULT_MEDIA_REFERENCE_LIMITS: Readonly = Object.freeze({ notes: 50_000, noteBytes: 256 * 1024 * 1024, perNote: 4 * 1024 * 1024, scanTime: 20_000, refsPerFinding: 500, + rewrittenNotes: 200, + preview: 1024 * 1024, }); const LIMIT_KEYS = Object.keys(DEFAULT_MEDIA_REFERENCE_LIMITS) as Array; diff --git a/packages/core/src/lib/media-review.ts b/packages/core/src/lib/media-review.ts index d757fa3fc1..bfcf0ee1c8 100644 --- a/packages/core/src/lib/media-review.ts +++ b/packages/core/src/lib/media-review.ts @@ -39,7 +39,7 @@ export function syncMediaCounts(root: string, policy: MediaPolicy, assessed: rea try { references = { limits: mediaReferenceLimits(resolveEnv().mediaReferenceLimits) }; } catch { - references = { limits: { notes: 0, noteBytes: 1, perNote: 1, scanTime: 1, refsPerFinding: 1 } }; + references = { limits: { notes: 0, noteBytes: 1, perNote: 1, scanTime: 1, refsPerFinding: 1, rewrittenNotes: 1, preview: 1 } }; } const findings = canonicalFindings(mediaCandidates(mediaInventory(root, policy, assessed, pins, references))); let entries: HygieneLogEntry[] = []; diff --git a/packages/core/tests/media-effects.test.ts b/packages/core/tests/media-effects.test.ts new file mode 100644 index 0000000000..045b6ed6d5 --- /dev/null +++ b/packages/core/tests/media-effects.test.ts @@ -0,0 +1,298 @@ +/** + * The four media review effects (#2781, rev 4 §5-§7): Delete, Move, Persist + * here and Keep a permanent copy. Each is planned read-only, then applied + * only against the premise it previewed, and the actual file, reference and + * config bytes are inspected after. Compensation and Undo belong to the + * journal holder (ui-server), so here an apply never restores anything. + * Real Git and files, offline; Odysseus's cast, the day 2026-07-12. + */ +import { afterEach, describe, expect, test } from "bun:test"; +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; + +import { canonicalFindings, type HygieneFinding } from "../src/lib/hygiene"; +import { DEFAULT_MEDIA_POLICY, type MediaPolicy } from "../src/lib/media"; +import { planMediaPolicyEdit, readMediaPolicyLists } from "../src/lib/media-config-edit"; +import { applyMediaEffect, planMediaEffect, type MediaEffectContext, type MediaEffectPlan, type MediaEffectRequest } from "../src/lib/media-effects"; +import { buildMediaInventory, mediaCandidates } from "../src/lib/media-inventory"; +import { DEFAULT_MEDIA_REFERENCE_LIMITS } from "../src/lib/media-references"; + +const LOOM = "photos/penelope-loom.png"; +const SCRATCH = ".brain/scratch/2026-07-12/harbour-dawn.jpg"; +const sha = (s: string | Buffer) => createHash("sha256").update(s).digest("hex"); + +const dirs: string[] = []; +afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); + +function git(cwd: string, ...args: string[]) { + const r = Bun.spawnSync(["git", "-C", cwd, ...args]); + if (r.exitCode !== 0) throw new Error(r.stderr.toString()); +} +function put(root: string, path: string, bytes: string | Buffer) { + mkdirSync(dirname(join(root, path)), { recursive: true }); + writeFileSync(join(root, path), bytes); +} +const read = (root: string, path: string) => readFileSync(join(root, path), "utf8"); + +function brain(config = "{}\n"): string { + const root = mkdtempSync(join(tmpdir(), "brain-media-effects-")); + dirs.push(root); + git(root, "init", "-q", "-b", "main"); + put(root, ".gitignore", ".brain/\n"); + put(root, "brain.config.json", config); + put(root, "places/ithaca.md", "# Ithaca\n"); + git(root, "add", "-A"); + git(root, "-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.test", "commit", "-qm", "fixture"); + put(root, LOOM, "loom bytes"); + return root; +} +function pin(root: string, path: string, ready = true) { + put(root, path, "dawn bytes"); + put(root, ".brain/scratch-pins/pins.json", JSON.stringify({ version: 1, ready, sessions: { '["claude","ithaca"]': [path], '["claude","troy"]': [path] } })); +} + +function policyOf(root: string): MediaPolicy { + const lists = readMediaPolicyLists(read(root, "brain.config.json"), "json"); + return { ...DEFAULT_MEDIA_POLICY, ...lists }; +} +const ctx = (root: string, over: Partial = {}): MediaEffectContext => ({ root, policy: policyOf(root), configPath: "brain.config.json", ...over }); +function finding(root: string, path: string): HygieneFinding { + return [...canonicalFindings(mediaCandidates(buildMediaInventory(root, policyOf(root)))).values()].find((f) => f.path === path)!; +} +function plan(root: string, action: MediaEffectRequest["action"], path: string, destination?: string, over: Partial = {}) { + const f = finding(root, path); + const request: MediaEffectRequest = { id: f.id, action, expectFingerprint: f.fingerprint, ...(destination ? { destination } : {}) }; + return { request, preview: planMediaEffect(ctx(root, over), request) as MediaEffectPlan }; +} +function apply(root: string, request: MediaEffectRequest, preview: MediaEffectPlan, over: Partial = {}) { + return applyMediaEffect(ctx(root, over), { ...request, expectPremise: preview.premiseDigest, journal: "odysseus-0001" }); +} + +describe("Delete", () => { + test("previews the file and its references, then removes exactly that file", () => { + const root = brain(); + put(root, "journeys/return.md", "# Return\n\n![loom](../photos/penelope-loom.png)\n\n"); + const { request, preview } = plan(root, "delete", LOOM); + expect(preview.refusals).toEqual([]); + expect(preview.files, "DELETE_PLAN_FILES").toEqual([{ path: LOOM, role: "source", before: sha("loom bytes"), after: null, bytes: 10 }]); + expect(preview.captureBytes).toBe(10); + expect(preview.references).toEqual({ complete: true, count: 2 }); + expect(preview.blockers.map((b) => b.kind), "DELETE_LISTS_DETECTED_ONLY").toEqual(["html"]); + expect(existsSync(join(root, LOOM)), "PREVIEW_WRITES_NOTHING").toBe(true); + const result = apply(root, request, preview); + expect(result).toMatchObject({ status: "applied", files: [{ path: LOOM, state: "removed" }] }); + expect(existsSync(join(root, LOOM)), "DELETE_REMOVED").toBe(false); + expect(read(root, "journeys/return.md"), "DELETE_LEAVES_NOTES").toContain("penelope-loom.png"); + }); + + test("a file edited after the preview is stale, and nothing is removed", () => { + const root = brain(); + const { request, preview } = plan(root, "delete", LOOM); + put(root, LOOM, "Athena's later loom"); + expect(apply(root, request, preview), "DELETE_STALE_FINGERPRINT").toMatchObject({ status: "stale", files: [] }); + expect(read(root, LOOM)).toBe("Athena's later loom"); + }); + + test("a premise that differs from the previewed one is stale even with the same fingerprint", () => { + const root = brain(); + const { request, preview } = plan(root, "delete", LOOM); + const result = applyMediaEffect(ctx(root), { ...request, expectPremise: "0".repeat(64), journal: "odysseus-0001" }); + expect(result, "DELETE_PREMISE_BINDING").toMatchObject({ status: "stale", reason: "premise-changed" }); + expect(read(root, LOOM)).toBe("loom bytes"); + expect(preview.premiseDigest).toMatch(/^[0-9a-f]{64}$/); + }); +}); + +describe("Move", () => { + const NOTE = [ + "# Return", + "", + "![loom](../photos/penelope-loom.png)", + "![root](/photos/penelope-loom.png?w=320#top)", + "[angle](<../photos/penelope-loom.png>)", + "![[penelope-loom.png|240]]", + "[[photos/penelope-loom.png]]", + "`../photos/penelope-loom.png` stays code", + "", + "[loom]: ../photos/penelope-loom.png", + "", + ].join("\n"); + + test("rewrites every declared reference in its own style and leaves code alone", () => { + const root = brain(); + put(root, "journeys/return.md", NOTE); + const { request, preview } = plan(root, "move", LOOM, "places/ithaca/loom.png"); + expect(preview.refusals).toEqual([]); + expect(preview.files.map((f) => [f.role, f.path]), "MOVE_PLAN_ORDER").toEqual([ + ["directory", "places/ithaca"], ["destination", "places/ithaca/loom.png"], ["source", LOOM], ["note", "journeys/return.md"]]); + const result = apply(root, request, preview); + expect(result.status, result.reason).toBe("applied"); + expect(read(root, "places/ithaca/loom.png"), "MOVE_BYTES").toBe("loom bytes"); + expect(existsSync(join(root, LOOM))).toBe(false); + expect(read(root, "journeys/return.md"), "MOVE_GOLDEN_REWRITE").toBe([ + "# Return", + "", + "![loom](../places/ithaca/loom.png)", + "![root](/places/ithaca/loom.png?w=320#top)", + "[angle](<../places/ithaca/loom.png>)", + "![[places/ithaca/loom.png|240]]", + "[[places/ithaca/loom.png]]", + "`../photos/penelope-loom.png` stays code", + "", + "[loom]: ../places/ithaca/loom.png", + "", + ].join("\n")); + }); + + test("a bare wiki name that still matches by basename is left as written", () => { + const root = brain(); + put(root, "journeys/return.md", "![[penelope-loom.png]]\n"); + const { request, preview } = plan(root, "move", LOOM, "places/penelope-loom.png"); + expect(preview.rewrites).toEqual([]); + expect(apply(root, request, preview).status).toBe("applied"); + expect(read(root, "journeys/return.md"), "MOVE_MINIMAL_EDIT").toBe("![[penelope-loom.png]]\n"); + }); + + test("detected-only references refuse the move before any write", () => { + const root = brain(); + put(root, "journeys/return.md", "---\ntitle: Return\ncover: ../photos/penelope-loom.png\n---\n# Return\n"); + const { request, preview } = plan(root, "move", LOOM, "places/loom.png"); + expect(preview.refusals, "MOVE_REF_UNSUPPORTED").toEqual([{ code: "ref-unsupported", path: "journeys/return.md", line: 3 }]); + expect(preview.files).toEqual([]); + expect(apply(root, request, preview).status).toBe("refused"); + expect(read(root, LOOM)).toBe("loom bytes"); + }); + + test("destination guards: final location, existing file, case/normalization sibling, secret name, containment", () => { + const root = brain(); + put(root, "places/Loom.png", "another loom"); + const codes = (to: string) => plan(root, "move", LOOM, to).preview.refusals.map((r) => r.code); + expect(codes(".brain/scratch/loom.png"), "MOVE_NOT_FINAL").toEqual(["not-final-location"]); + expect(codes("workspaces/athena/loom.png")).toEqual(["not-final-location"]); + expect(codes("places/Loom.png"), "MOVE_NO_OVERWRITE").toEqual(["exists"]); + expect(codes("places/loom.png"), "MOVE_NAME_COLLISION").toEqual(["name-collision"]); + expect(codes("places/ithaca.md/loom.png")).toEqual(["not-contained"]); + expect(codes("../outside.png")).toEqual(["not-contained"]); + expect(codes("places/loom.key"), "MOVE_SECRET_NAME").toEqual(["secret-name"]); + expect(read(root, LOOM)).toBe("loom bytes"); + }); + + test("the rewritten-notes bound admits its limit and refuses one past it", () => { + const root = brain(); + for (const n of [1, 2, 3]) put(root, `journeys/day-${n}.md`, "![loom](../photos/penelope-loom.png)\n"); + const at = plan(root, "move", LOOM, "places/loom.png", { limits: { ...DEFAULT_MEDIA_REFERENCE_LIMITS, rewrittenNotes: 3 } }).preview; + expect(at.refusals, "REWRITTEN_NOTES_BOUNDARY").toEqual([]); + const over = plan(root, "move", LOOM, "places/loom.png", { limits: { ...DEFAULT_MEDIA_REFERENCE_LIMITS, rewrittenNotes: 2 } }).preview; + expect(over.refusals, "REWRITTEN_NOTES_PLUS_ONE").toEqual([{ code: "inventory-too-large", limit: "rewrittenNotes", effective: 2, observed: 3 }]); + }); + + test("the preview bound admits its own size and refuses one byte less", () => { + const root = brain(); + const size = Buffer.byteLength(JSON.stringify(plan(root, "delete", LOOM).preview)); + expect(plan(root, "delete", LOOM, undefined, { limits: { ...DEFAULT_MEDIA_REFERENCE_LIMITS, preview: size } }).preview.status, "PREVIEW_BOUNDARY").toBe("preview"); + const over = planMediaEffect(ctx(root, { limits: { ...DEFAULT_MEDIA_REFERENCE_LIMITS, preview: size - 1 } }), plan(root, "delete", LOOM).request); + expect(over, "PREVIEW_PLUS_ONE").toMatchObject({ status: "refused", refusals: [{ code: "inventory-too-large", limit: "preview", effective: size - 1, observed: size }] }); + }); + + test("a note edited after the preview makes the apply stale with nothing moved", () => { + const root = brain(); + put(root, "journeys/return.md", "![loom](../photos/penelope-loom.png)\n"); + const { request, preview } = plan(root, "move", LOOM, "places/loom.png"); + put(root, "journeys/return.md", "![loom](../photos/penelope-loom.png)\nAthena's later line\n"); + expect(apply(root, request, preview), "MOVE_NOTE_PREMISE").toMatchObject({ status: "stale", reason: "premise-changed", files: [] }); + expect(read(root, LOOM)).toBe("loom bytes"); + expect(existsSync(join(root, "places/loom.png"))).toBe(false); + }); + + test("linked scratch refuses Move, and unknown links refuse it too", () => { + const root = brain(); + pin(root, SCRATCH); + expect(plan(root, "move", SCRATCH, "places/dawn.jpg").preview.refusals.map((r) => r.code), "MOVE_LINKED_SCRATCH").toEqual(["pinned-scratch"]); + const other = brain(); + pin(other, SCRATCH, false); + expect(plan(other, "move", SCRATCH, "places/dawn.jpg").preview.refusals.map((r) => r.code)).toEqual(["pinned-scratch"]); + }); +}); + +describe("Persist here", () => { + test("adds the exact media.track entry by a minimal splice and the file classes TRACK", () => { + const root = brain('{\n "title": "Ithaca"\n}\n'); + const { request, preview } = plan(root, "persist", LOOM); + expect(preview.configDiff, "PERSIST_DIFF").toEqual({ path: "brain.config.json", track: { before: [], after: [LOOM] }, ignore: { before: [], after: [] } }); + expect(preview.resultClass).toBe("TRACK"); + expect(apply(root, request, preview).status).toBe("applied"); + expect(read(root, "brain.config.json"), "PERSIST_CONFIG_BYTES").toBe('{\n "title": "Ithaca", "media": { "track": ["photos/penelope-loom.png"] }\n}\n'); + expect(read(root, LOOM)).toBe("loom bytes"); + expect(finding(root, LOOM), "PERSIST_NO_LONGER_PENDING").toBeUndefined(); + }); + + test("an exact ignore of this path is removed in the same edit; a broader ignore is not adjusted here", () => { + const root = brain(`{ "media": { "ignore": ["${LOOM}", "*.psd"] } }\n`); + put(root, LOOM, "loom bytes"); + // Ignored media is not pending; plan against an explicit finding by making it visible first. + expect(planMediaPolicyEdit(read(root, "brain.config.json"), "json", { addTrack: LOOM, removeIgnore: LOOM }).text, "PERSIST_REMOVES_EXACT_IGNORE") + .toBe(`{ "media": { "ignore": ["*.psd"], "track": ["${LOOM}"] } }\n`); + }); + + test("root-level files have no exact form; non-literal configs are refused", () => { + const root = brain(); + put(root, "map.png", "map bytes"); + expect(plan(root, "persist", "map.png").preview.refusals, "PERSIST_ROOT_NOT_EXPRESSIBLE").toEqual([{ code: "not-expressible", path: "map.png" }]); + const ts = brain(); + rmSync(join(ts, "brain.config.json")); + put(ts, "brain.config.ts", "const media = { track: [] };\nexport default { media };\n"); + const f = [...canonicalFindings(mediaCandidates(buildMediaInventory(ts, DEFAULT_MEDIA_POLICY))).values()].find((v) => v.path === LOOM)!; + const refused = planMediaEffect({ root: ts, policy: DEFAULT_MEDIA_POLICY, configPath: "brain.config.ts" }, { id: f.id, action: "persist", expectFingerprint: f.fingerprint }) as MediaEffectPlan; + expect(refused.refusals, "PERSIST_CONFIG_NOT_LITERAL").toEqual([{ code: "config-not-literal", path: "brain.config.ts" }]); + expect(read(ts, "brain.config.ts")).toBe("const media = { track: [] };\nexport default { media };\n"); + }); + + test("a defineConfig TypeScript literal keeps every other byte", () => { + const source = 'import { defineConfig } from "@schlessera/brain";\n\nexport default defineConfig({\n media: {\n track: ["places/**"], // committed\n },\n});\n'; + expect(planMediaPolicyEdit(source, "ts", { addTrack: LOOM }).text, "PERSIST_TS_SPLICE") + .toBe('import { defineConfig } from "@schlessera/brain";\n\nexport default defineConfig({\n media: {\n track: ["places/**", "photos/penelope-loom.png"], // committed\n },\n});\n'); + }); + + test("scratch is never persisted in place", () => { + const root = brain(); + pin(root, SCRATCH); + expect(plan(root, "persist", SCRATCH).preview.refusals.map((r) => r.code), "PERSIST_SCRATCH").toEqual(["not-final-location"]); + }); +}); + +describe("Keep a permanent copy", () => { + test("copies a linked scratch original, tracks the copy, and leaves the original and its pins untouched", () => { + const root = brain(); + pin(root, SCRATCH); + const pins = read(root, ".brain/scratch-pins/pins.json"); + const { request, preview } = plan(root, "keep-copy", SCRATCH, "places/ithaca/harbour-dawn.jpg"); + expect(preview.refusals).toEqual([]); + expect(preview.links, "KEEP_LINKS").toEqual({ state: "linked", conversations: 2 }); + expect(preview.copy?.sha256).toBe(sha("dawn bytes")); + // Only the config's pre-image is captured: the original is never modified. + expect(preview.captureBytes, "KEEP_NEVER_CAPTURES_ORIGINAL").toBe(Buffer.byteLength("{}\n")); + const result = apply(root, request, preview); + expect(result).toMatchObject({ status: "applied", copySha256: sha("dawn bytes") }); + expect(read(root, "places/ithaca/harbour-dawn.jpg"), "KEEP_COPY_BYTES").toBe("dawn bytes"); + expect(read(root, SCRATCH), "KEEP_ORIGINAL_BYTES").toBe("dawn bytes"); + expect(read(root, ".brain/scratch-pins/pins.json"), "KEEP_PINS_BYTES").toBe(pins); + expect(readMediaPolicyLists(read(root, "brain.config.json"), "json").track).toEqual(["places/ithaca/harbour-dawn.jpg"]); + expect(readdirSync(join(root, "places/ithaca")), "KEEP_NO_PART_RESIDUE").toEqual(["harbour-dawn.jpg"]); + }); + + test("a copy destination that appears after the preview is never overwritten", () => { + const root = brain(); + pin(root, SCRATCH); + const { request, preview } = plan(root, "keep-copy", SCRATCH, "places/harbour-dawn.jpg"); + put(root, "places/harbour-dawn.jpg", "Telemachus's own photo"); + expect(apply(root, request, preview), "KEEP_NO_OVERWRITE").toMatchObject({ status: "refused", refusals: [{ code: "exists", path: "places/harbour-dawn.jpg" }], files: [] }); + expect(read(root, "places/harbour-dawn.jpg")).toBe("Telemachus's own photo"); + }); + + 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"]); + }); +}); diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index 07e73395ab..0c8a356b37 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -3558,21 +3558,69 @@ export interface HygieneDiff { } export interface HygieneEffect { kind: "hygiene"; - /** `defer` is Leave pending (#2780): host-only, skipped for the rest of this review pass. */ - operation: "resolve" | "check" | "undo" | "dismiss" | "snooze" | "defer"; + /** + * `defer` is Leave pending (#2780): host-only, skipped for the rest of this + * review pass. The `media-*` operations (#2781) are a media finding's + * governed effects, applied only with a current previewed plan. + */ + operation: "resolve" | "check" | "undo" | "dismiss" | "snooze" | "defer" | "media-delete" | "media-move" | "media-persist" | "media-keep-copy"; findingId: string; fingerprint: string; handler?: string; input?: HygieneInput; previewToken?: string; undoToken?: string; + /** A Move's or copy's destination, as previewed (#2781). */ + destination?: string; + /** The previewed media plan's premise; apply refuses `stale` when the brain no longer matches it. */ + premiseDigest?: string; +} +/** A media finding's four effects (#2781). */ +export type HygieneMediaAction = "delete" | "move" | "persist" | "keep-copy"; +/** A named refusal: a result the domain expects, never an error (rev 5 §11). */ +export interface HygieneMediaRefusal { code: string; path?: string; line?: number; limit?: string; effective?: number; observed?: number } +/** What a media effect will do, from `brain hygiene media … --dry-run` (#2781, rev 4 §9). */ +export interface HygieneMediaPlan { + action: HygieneMediaAction; + premiseDigest: string; + destination: string | null; + /** Every file or directory the effect writes, in apply order; `before`/`after` are SHA-256, `directory`, or null for absent. */ + files: Array<{ path: string; role: "source" | "destination" | "note" | "config" | "directory"; before: string | null; after: string | null; bytes: number }>; + /** Bytes the journal retains before any write. */ + captureBytes: number; + links: { state: "linked" | "unlinked" | "unknown"; conversations: number }; + references: { complete: boolean; count: number }; + rewrites: Array<{ note: string; line: number; kind: string; before: string; after: string }>; + blockers: Array<{ note: string; line: number; kind: string; target: string }>; + configDiff: { path: string; track: { before: string[]; after: string[] }; ignore: { before: string[]; after: string[] } } | null; + copy: { bytes: number; sha256: string; diskFreeAdvisory: number | null } | null; + resultClass: "TRACK" | "ARTIFACT" | null; + refusals: HygieneMediaRefusal[]; +} +export type HygieneMediaFileState = "created" | "changed" | "removed" | "restored" | "unchanged" | "left-changed" | "conflict"; +/** + * A media effect's receipt (#2781, rev 4 §9). `compensated`: nothing remains + * of it. `partial`: some file could not be put back and is listed as + * `conflict` or `left-changed`. Undo availability is read when asked, from + * the journal's retained data and the files' current bytes. + */ +export interface HygieneMediaReceipt { + journalId: string; + action: HygieneMediaAction; + outcome: "pending" | "applied" | "kept" | "compensated" | "partial" | "refused" | "stale" | "undone"; + reason?: string; + refusals?: HygieneMediaRefusal[]; + files: Array<{ path: string; state: HygieneMediaFileState }>; + copySha256?: string; + undo: { available: boolean; reason?: string; path?: string }; } export interface HygieneAction { findingId: string; fingerprint: string; /** Supported CLI projection, retained as display data. */ finding: Record; - outcome?: { version: 1; status: "applying" | "fixed" | "stale" | "refused" | "check_failed" | "still_detected" | "not_detected" | "undone" | "dismissed" | "snoozed" | "superseded" | "deferred"; supersededBy?: string; reason?: string; code?: string; undoToken?: string; fieldError?: { field: string; message: string } }; + /** `kept` (#2781) is a confirmed Keep a permanent copy; `media` is a media effect's receipt. */ + outcome?: { version: 1; status: "applying" | "fixed" | "stale" | "refused" | "check_failed" | "still_detected" | "not_detected" | "undone" | "dismissed" | "snoozed" | "superseded" | "deferred" | "kept"; supersededBy?: string; reason?: string; code?: string; undoToken?: string; fieldError?: { field: string; message: string }; media?: HygieneMediaReceipt }; } export interface HygieneReviewState { version: 1; @@ -3651,6 +3699,8 @@ export interface InboxOption { /** CLI-owned input descriptor; no client-selected effect. */ input?: { type: "none" | "string" | "enum" | "date" | "strings" | "path"; values?: string[]; example?: string }; preview?: HygieneDiff; + /** A media effect's previewed plan (#2781); the option applies only with it. */ + media?: HygieneMediaPlan; } export interface InboxItemBase { diff --git a/packages/ui-sdk/src/schemas.ts b/packages/ui-sdk/src/schemas.ts index 58ff0ec0cf..230b576e6b 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, HygieneReviewCommand, HygienePreviewRequest, HygieneReviewState, HygieneReviewRead, HygieneWorktreeDetailsRead } from "./protocol.js"; +import type { HygieneAction, HygieneDiff, HygieneEffect, HygieneMediaPlan, HygieneMediaReceipt, HygieneMediaRefusal, HygieneReviewCommand, HygienePreviewRequest, HygieneReviewState, HygieneReviewRead, HygieneWorktreeDetailsRead } from "./protocol.js"; import { sharedFileMetaSchema } from "./track-schemas.js"; export { sharedFileMetaSchema } from "./track-schemas.js"; // ============================================================ @@ -691,11 +691,37 @@ export const inboxWorkPayloadSchema = z.strictObject({ export const hygieneInputSchema = z.union([z.string().max(4096), z.array(z.string().max(256)).max(128), z.null()]); export const hygieneDiffSchema = z.strictObject({ path: inboxTargetPath, before: z.string().max(MAX_PROMPT_CHARS), after: z.string().max(MAX_PROMPT_CHARS), changes: z.array(z.strictObject({ before: z.string().max(MAX_PROMPT_CHARS), after: z.string().max(MAX_PROMPT_CHARS), line: z.number().int().min(1) })).max(1024) }) satisfies z.ZodType; export const hygieneEffectSchema = z.strictObject({ - kind: z.literal("hygiene"), operation: z.enum(["resolve", "check", "undo", "dismiss", "snooze", "defer"]), + kind: z.literal("hygiene"), operation: z.enum(["resolve", "check", "undo", "dismiss", "snooze", "defer", "media-delete", "media-move", "media-persist", "media-keep-copy"]), findingId: id, fingerprint: id, handler: id.optional(), input: hygieneInputSchema.optional(), previewToken: id.optional(), undoToken: z.string().regex(/^[a-f0-9]{32}$/).optional(), + destination: z.string().min(1).max(4096).optional(), premiseDigest: z.string().regex(/^[a-f0-9]{64}$/).optional(), }) satisfies z.ZodType; -export const hygieneOutcomeSchema = z.strictObject({ version: z.literal(1), status: z.enum(["applying", "fixed", "stale", "refused", "check_failed", "still_detected", "not_detected", "undone", "dismissed", "snoozed", "superseded", "deferred"]), supersededBy: id.optional(), reason: z.string().max(4096).optional(), code: z.string().max(4096).optional(), undoToken: z.string().regex(/^[a-f0-9]{32}$/).optional(), fieldError: z.strictObject({ field: id, message: z.string().max(4096) }).optional() }); +const mediaPath = z.string().min(1).max(4096); +const sha256OrNull = z.string().regex(/^([a-f0-9]{64}|directory)$/).nullable(); +export const hygieneMediaRefusalSchema = z.strictObject({ code: z.string().min(1).max(64), path: z.string().max(65_536).optional(), line: z.number().int().min(1).optional(), limit: z.string().max(64).optional(), effective: z.number().int().min(0).optional(), observed: z.number().int().min(0).optional() }) satisfies z.ZodType; +/** A media plan as the CLI previews it; unknown CLI keys are dropped, every kept one is bounded. */ +export const hygieneMediaPlanSchema = z.object({ + action: z.enum(["delete", "move", "persist", "keep-copy"]), premiseDigest: z.string().regex(/^[a-f0-9]{64}$/), destination: mediaPath.nullable(), + files: z.array(z.strictObject({ path: mediaPath, role: z.enum(["source", "destination", "note", "config", "directory"]), before: sha256OrNull, after: sha256OrNull, bytes: z.number().int().min(0) })).max(10_000), + captureBytes: z.number().int().min(0), + links: z.strictObject({ state: z.enum(["linked", "unlinked", "unknown"]), conversations: z.number().int().min(0) }), + references: z.strictObject({ complete: z.boolean(), count: z.number().int().min(0) }), + rewrites: z.array(z.strictObject({ note: mediaPath, line: z.number().int().min(1), kind: z.string().max(32), before: z.string().max(4096), after: z.string().max(4096) })).max(10_000), + blockers: z.array(z.strictObject({ note: mediaPath, line: z.number().int().min(1), kind: z.string().max(32), target: z.string().max(65_536) })).max(10_000), + configDiff: z.strictObject({ path: mediaPath, track: z.strictObject({ before: z.array(z.string().max(4096)).max(10_000), after: z.array(z.string().max(4096)).max(10_000) }), ignore: z.strictObject({ before: z.array(z.string().max(4096)).max(10_000), after: z.array(z.string().max(4096)).max(10_000) }) }).nullable(), + copy: z.strictObject({ bytes: z.number().int().min(0), sha256: z.string().regex(/^[a-f0-9]{64}$/), diskFreeAdvisory: z.number().min(0).nullable() }).nullable(), + resultClass: z.enum(["TRACK", "ARTIFACT"]).nullable(), + refusals: z.array(hygieneMediaRefusalSchema).max(10_000), +}) satisfies z.ZodType; +export const hygieneMediaReceiptSchema = z.strictObject({ + journalId: z.string().regex(/^[A-Za-z0-9._-]{16,96}$/), action: z.enum(["delete", "move", "persist", "keep-copy"]), + outcome: z.enum(["pending", "applied", "kept", "compensated", "partial", "refused", "stale", "undone"]), reason: z.string().max(4096).optional(), + refusals: z.array(hygieneMediaRefusalSchema).max(10_000).optional(), + files: z.array(z.strictObject({ path: mediaPath, state: z.enum(["created", "changed", "removed", "restored", "unchanged", "left-changed", "conflict"]) })).max(10_000), + copySha256: z.string().regex(/^[a-f0-9]{64}$/).optional(), + undo: z.strictObject({ available: z.boolean(), reason: z.string().max(4096).optional(), path: mediaPath.optional() }), +}) satisfies z.ZodType; +export const hygieneOutcomeSchema = z.strictObject({ version: z.literal(1), status: z.enum(["applying", "fixed", "stale", "refused", "check_failed", "still_detected", "not_detected", "undone", "dismissed", "snoozed", "superseded", "deferred", "kept"]), supersededBy: id.optional(), reason: z.string().max(4096).optional(), code: z.string().max(4096).optional(), undoToken: z.string().regex(/^[a-f0-9]{32}$/).optional(), fieldError: z.strictObject({ field: id, message: z.string().max(4096) }).optional(), media: hygieneMediaReceiptSchema.optional() }); export const hygieneActionSchema = z.strictObject({ findingId: id, fingerprint: id, finding: z.record(z.string(), z.unknown()), outcome: hygieneOutcomeSchema.optional() }) satisfies z.ZodType; export const hygieneReviewStateSchema = z.strictObject({ version: z.literal(1), status: z.enum(["idle", "active", "paused", "complete", "blocked"]), position: inboxSeq, fixed: inboxSeq, dismissed: inboxSeq, snoozed: inboxSeq, pendingActionId: id.optional(), pauseReason: z.strictObject({ kind: z.literal("actions-limit"), retiredActionId: id, retirementReceiptId: id }).optional(), counts: z.strictObject({ eligibleRemaining: inboxSeq, fixed: inboxSeq, dismissed: inboxSeq, snoozed: inboxSeq, nextSnoozeDueAt: z.string().nullable(), informationalNotShown: inboxSeq, kept: inboxSeq.default(0) }).optional(), blocker: z.record(z.string(), z.unknown()).optional(), // Additive in #2780: a row stored before these fields parses with their defaults. @@ -723,7 +749,7 @@ export const resolutionEffectSchema = z.discriminatedUnion("kind", [ export const v1ResolutionEffectSchema = z.discriminatedUnion("kind", [ hygieneEffectSchema, enqueueEffectSchema, cancelBlockedEffectSchema, snoozeEffectSchema, dismissEffectSchema, ]) satisfies z.ZodType; -export const inboxOptionSchema = z.strictObject({ id, label: inboxText, effect: resolutionEffectSchema, input: z.strictObject({ type: z.enum(["none", "string", "enum", "date", "strings", "path"]), values: z.array(z.string()).optional(), example: z.string().optional() }).optional(), preview: hygieneDiffSchema.optional() }) satisfies z.ZodType; +export const inboxOptionSchema = z.strictObject({ id, label: inboxText, effect: resolutionEffectSchema, input: z.strictObject({ type: z.enum(["none", "string", "enum", "date", "strings", "path"]), values: z.array(z.string()).optional(), example: z.string().optional() }).optional(), preview: hygieneDiffSchema.optional(), media: hygieneMediaPlanSchema.optional() }) satisfies z.ZodType; // Compare exact JSON values, independent of object key order. An approved // operation binds the entire input and target, rather than just a tool name. diff --git a/packages/ui-server/migrations/075_hygiene_media_operations.journal.sql b/packages/ui-server/migrations/075_hygiene_media_operations.journal.sql new file mode 100644 index 0000000000..8fa2156b39 --- /dev/null +++ b/packages/ui-server/migrations/075_hygiene_media_operations.journal.sql @@ -0,0 +1,13 @@ +-- Media review effects (#2781): one row per Delete, Move, Persist here or +-- Keep a permanent copy, and per Undo of one. Charged by the journal's +-- existing allocation owner, like attachment removal. The row records the +-- planned files and their retained pre-images before the first write, so a +-- restart compensates from it and never re-applies. +CREATE TABLE journal.turn_journal_media_operations ( + id TEXT PRIMARY KEY, principal_id TEXT NOT NULL, finding_id TEXT NOT NULL, fingerprint TEXT NOT NULL, + action TEXT NOT NULL, source_id TEXT, journal_turn_id TEXT NOT NULL, state TEXT NOT NULL, + pid INTEGER NOT NULL, pid_start TEXT NOT NULL, requested_at INTEGER NOT NULL, + plan TEXT NOT NULL, versions TEXT NOT NULL, receipt TEXT NOT NULL +); +-- Admission refuses a second active operation (a check in the same write). +CREATE INDEX journal.turn_journal_media_state ON turn_journal_media_operations(state); diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 82f9abf59b..430fb9ffd7 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -102,6 +102,7 @@ import { createInboxBridgeTools } from "./inbox/bridge-tools.js"; import { createInboxStore } from "./inbox/store.js"; import { registerInboxWrites } from "./inbox/write-runtime.js"; import { createHygieneReview } from "./inbox/hygiene-review.js"; +import { createMediaEffects } from "./inbox/media-effects.js"; import { createHygieneReviewRoutes } from "./routes/hygiene-review.js"; import { createInboxStream } from "./inbox/stream.js"; import { isUsablePrincipal, prunePrincipals, resolvePrincipal } from "./db/principals.js"; @@ -1029,6 +1030,16 @@ export async function createApp(options: CreateAppOptions = {}): Promise reverts.close()); host.turnReverts = reverts; + // Media review effects (#2781) capture in this same journal under the same + // writer gate. Once attached, an effect a restart interrupted is compensated. + const mediaGate = hostExecution.gate(); + if (mediaGate && brain.hygiene) { + const hygieneCli = brain.hygiene.bind(brain); + hygieneReview.attachMedia(createMediaEffects(db, { brainPath: config.brainPath, journal, gate: mediaGate, lock: host.workerLock, + cli: args => hygieneCli(args), + authorized(id) { const principal = resolvePrincipal(db, id); return !!principal && ["owner", "ambient"].includes(principal.kind) && isUsablePrincipal(principal, Date.now()); } })); + await hygieneReview.recover(); + } app.route("/api", createTurnRevertRoutes(reverts)); // Only where server_hello advertises it: elsewhere the route is absent, // which a client reads as a host too old to answer (#964). diff --git a/packages/ui-server/src/brain/client.ts b/packages/ui-server/src/brain/client.ts index 9129f956bb..b9e2148ee2 100644 --- a/packages/ui-server/src/brain/client.ts +++ b/packages/ui-server/src/brain/client.ts @@ -104,10 +104,10 @@ interface ExecResult { export const INDEX_DIRECTORY_CLI_VERSION = "0.44.0"; /** - * First core release with media hygiene findings and `hygiene next --defer` - * (#2780). Review sends `--defer` only to leave a media finding pending, and - * only a CLI at or past this release reports media findings, so an older CLI - * is never asked for it. The release that ships it raises + * First core release with media findings, `hygiene next --defer`, `keep-copy` + * (#2780) and `hygiene media` (#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 * lockstep version at or past this one while the floor is lower. */ diff --git a/packages/ui-server/src/inbox/hygiene-review.ts b/packages/ui-server/src/inbox/hygiene-review.ts index 70a9977957..0d959a4f1f 100644 --- a/packages/ui-server/src/inbox/hygiene-review.ts +++ b/packages/ui-server/src/inbox/hygiene-review.ts @@ -3,8 +3,10 @@ * 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, HygieneWorktreeDetailsRead, InboxActionItem, InboxItem, InboxOption } from "@schlessera/brain-ui-sdk/protocol"; -import { hygieneEffectSchema, hygieneInputSchema, hygieneReviewStateSchema, inboxOptionSchema } from "@schlessera/brain-ui-sdk/schemas"; +import { createHash } from "node:crypto"; +import type { ClientInboxResolve, HygieneAction, HygieneEffect, HygieneInput, HygieneMediaPlan, HygieneMediaReceipt, HygieneReviewRead, HygieneReviewState, HygieneWorktreeDetailsRead, InboxActionItem, InboxItem, InboxOption } from "@schlessera/brain-ui-sdk/protocol"; +import { hygieneEffectSchema, hygieneInputSchema, hygieneMediaPlanSchema, hygieneReviewStateSchema, inboxOptionSchema } from "@schlessera/brain-ui-sdk/schemas"; +import type { MediaEffects } from "./media-effects.js"; import type { BrainClient } from "../brain/client.js"; import type { ReferenceWorktreeHygiene } from "../brain/reference-worktree-hygiene.js"; import { isUsablePrincipal, resolvePrincipal } from "../db/principals.js"; @@ -20,10 +22,13 @@ export function createHygieneReview(db: Database, deps: { brain: BrainClient; no /** Host-only managed worktree findings (#2431), joined into the same review queue. */ worktrees?: ReferenceWorktreeHygiene; /** The gated dispatcher's current exact-operation envelope (#689); default empty. */ - allowedOperations?: Parameters[1]["allowedOperations"] }) { + allowedOperations?: Parameters[1]["allowedOperations"]; + /** The journal-backed media effects (#2781); without them no media effect is offered. */ + media?: MediaEffects }) { const now = deps.now ?? Date.now, store = createInboxStore(db, { now }); const write = hygieneWrites(db, deps.timeZone); const resolver = createInboxResolver(db, { now, timeZone: deps.timeZone, allowedOperations: deps.allowedOperations ?? (() => []), applyHygiene: apply }); + let media = deps.media; let preparing: Promise | null = null; let pauseGeneration = 0; const inFlight = new Set(); @@ -95,6 +100,16 @@ export function createHygieneReview(db: Database, deps: { brain: BrainClient; no function effect(f: { id: string; fingerprint: string }, operation: HygieneEffect["operation"]): HygieneEffect { return { kind: "hygiene", operation, findingId: f.id, fingerprint: f.fingerprint }; } + /** A media effect's CLI plan, or null when the CLI could not plan it (not detected, stale). */ + async function mediaPlan(f: { id: string; fingerprint: string }, operation: MediaOperation, destination?: string): Promise { + const parsed = hygieneMediaPlanSchema.safeParse(await cli(["media", MEDIA_ACTIONS[operation], f.id, "--expect-fingerprint", f.fingerprint, ...(destination !== undefined ? ["--to", destination] : []), "--dry-run"])); + return parsed.success ? parsed.data : null; + } + /** The options' media plan: only a plan without refusals carries the premise that lets it apply. */ + function withPlan(option: InboxOption, plan: HygieneMediaPlan | null, destination?: string): InboxOption { + const e = option.effect as HygieneEffect; + return { ...option, effect: { ...e, destination, premiseDigest: plan && plan.refusals.length === 0 ? plan.premiseDigest : undefined }, media: plan ?? undefined }; + } /** A repair that takes no input but has no confirmed preview cannot be applied. */ const missingPreview = (options: InboxOption[]) => options.some(o => o.effect.kind === "hygiene" && o.effect.operation === "resolve" && o.input?.type === "none" && !o.preview); async function prepareOptions(finding: z.infer | null) { @@ -112,6 +127,19 @@ export function createHygieneReview(db: Database, deps: { brain: BrainClient; no } options.push(inboxOptionSchema.parse(option)); } + // Media effects (#2781, rev 4 §4.2), in the card's order. Persist and + // Delete take no input and are planned now; Move and Keep a copy are + // planned when a destination is previewed. A plan's refusals stay on + // the option, so an unavailable action shows why. + if (finding.category === "media" && media) { + const scratch = finding.path.startsWith(".brain/scratch/"); + const rows: Array<[MediaOperation, string, boolean]> = [["media-persist", "Persist here", false], ["media-move", "Move to a final location…", true], + ...(scratch ? [["media-keep-copy", "Keep a permanent copy…", true] as [MediaOperation, string, boolean]] : []), ["media-delete", "Delete…", false]]; + for (const [operation, label, needsPath] of rows) { + const option: InboxOption = { id: operation, label, effect: effect(finding, operation), ...(needsPath ? { input: { type: "path" as const } } : {}) }; + options.push(inboxOptionSchema.parse(needsPath ? option : withPlan(option, await mediaPlan(finding, operation)))); + } + } // Media (#2780) can always be left pending for the rest of this pass. if (finding.category === "media") options.push({ id: "leave-pending", label: "Leave pending", effect: effect(finding, "defer") }); options.push({ id: "check", label: "Done, check again", effect: effect(finding, "check") }, @@ -185,15 +213,28 @@ export function createHygieneReview(db: Database, deps: { brain: BrainClient; no 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 }); if (item.version !== request.expectedVersion || item.status !== "pending" || busy(item.id)) throw new Error("Inbox version conflict"); + if (selected.kind === "hygiene" && isMediaOperation(selected.operation)) { + if (!media) throw new Error("Media effects are unavailable"); + const destination = typeof request.input === "string" ? request.input : undefined; + const plan = await mediaPlan({ id: selected.findingId, fingerprint: selected.fingerprint }, selected.operation, destination); + authority(principalId); + await write("mediaPreview", now(), principalId, item, request, option.id, withPlan(option, plan, destination)); + return action(item.id); + } if (selected.kind !== "hygiene" || selected.operation !== "resolve" || !selected.handler) throw new Error("Not a repair option"); const result = resultSchema.parse(await cli(["resolve", "--handler", selected.handler, "--input", JSON.stringify(request.input), "--expect-fingerprint", selected.fingerprint, "--dry-run", "--", selected.findingId])); authority(principalId); await write("preview", now(), principalId, item, request, option, selected, result); return action(item.id); } - async function dispatch(e: HygieneEffect, request: ClientInboxResolve, waitUntil: number | null, principalId: string): Promise { + async function dispatch(e: HygieneEffect, request: ClientInboxResolve, waitUntil: number | null, principalId: string, attemptId: string): Promise { // Leave pending is review state only: nothing is sent to the CLI. if (e.operation === "defer") return { id: e.findingId, status: "deferred" }; + if (isMediaOperation(e.operation)) { + const plan = action(request.itemId).options.find(o => o.id === request.optionId)?.media; + if (!media || !plan) return { id: e.findingId, status: "refused", reason: "media-effects-unavailable" }; + return mediaResult(e.findingId, await media.apply({ id: mediaOperationId(attemptId), principalId, findingId: e.findingId, fingerprint: e.fingerprint, plan })); + } const args = e.operation === "resolve" ? ["resolve", "--handler", e.handler!, "--input", JSON.stringify(e.input), "--expect-fingerprint", e.fingerprint, "--expect-preview", e.previewToken!, "--", e.findingId] : e.operation === "undo" ? ["undo", "--", e.undoToken!] : e.operation === "check" ? ["check", "--", e.findingId] @@ -223,7 +264,7 @@ export function createHygieneReview(db: Database, deps: { brain: BrainClient; no if (!admitted) return { replay: true, followUpId: undefined }; inFlight.add(request.itemId); let result: Result; - try { authority(principalId); result = await dispatch(hygieneEffectSchema.parse(JSON.parse(admitted.effect_json)), request, admitted.wait_until, principalId); } + try { authority(principalId); result = await dispatch(hygieneEffectSchema.parse(JSON.parse(admitted.effect_json)), request, admitted.wait_until, principalId, admitted.id); } catch { // Unknown dispatch receipt stays journaled. Recovery checks; it never retries. await write("unknown", now(), request.itemId); @@ -253,6 +294,19 @@ export function createHygieneReview(db: Database, deps: { brain: BrainClient; no const entry = listed.entries.find(v => v.id === e.findingId); const matches = entry?.fingerprint === e.fingerprint && entry.state === (e.operation === "dismiss" ? "dismissed" : "snoozed") && (e.operation !== "snooze" || Date.parse(entry.dueAt ?? "") === attempt.wait_until); result = { id: e.findingId, status: matches ? e.operation === "dismiss" ? "dismissed" : "snoozed" : "check_failed", code: matches ? undefined : "receipt-unknown" }; + } else if (isMediaOperation(e.operation)) { + // Until the journal-backed effects attach, an interrupted media effect stays started. + if (!media) continue; + // Recovery compensates an interrupted effect from its journal row; it never re-applies one. + await media.recover(); + const receipt = media.receipt(mediaOperationId(attempt.id), attempt.principal_id); + if (!receipt || receipt.outcome === "pending") result = { id: e.findingId, status: "check_failed", code: "receipt-unknown" }; + else if (e.operation === "media-keep-copy" && receipt.outcome === "kept") { + // A copy is kept only when its entry, fingerprint and copy SHA-256 all match (rev 6 §1). + const listed = z.object({ entries: z.array(z.looseObject({ id, state: text, fingerprint: text.nullable(), copySha256: text.nullable().optional() })) }).parse(await cli(["list"])); + const entry = listed.entries.find(v => v.id === e.findingId); + result = entry?.state === "kept" && entry.fingerprint === e.fingerprint && entry.copySha256 === receipt.copySha256 ? mediaResult(e.findingId, receipt) : { id: e.findingId, status: "check_failed", code: "receipt-unknown", media: receipt }; + } else result = mediaResult(e.findingId, receipt); } else if (e.operation === "defer") { // Host-only and idempotent: the deferral is recorded when this attempt finishes. result = { id: e.findingId, status: "deferred" }; @@ -261,6 +315,23 @@ 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, preview, resolver, recover, + /** The app attaches the journal-backed media effects once its journal is ready. */ + attachMedia(effects: MediaEffects) { media = effects; } }; +} + +/** The four media review effects (#2781) and the `brain hygiene media` action each one runs. */ +const MEDIA_ACTIONS = { "media-delete": "delete", "media-move": "move", "media-persist": "persist", "media-keep-copy": "keep-copy" } as const; +type MediaOperation = keyof typeof MEDIA_ACTIONS; +/** Narrows an effect to a media one, so the generic disposition argv can never carry one. */ +const isMediaOperation = (operation: HygieneEffect["operation"]): operation is MediaOperation => Object.hasOwn(MEDIA_ACTIONS, operation); + +/** A media effect's operation identity, derived from the review attempt that admitted it. */ +export const mediaOperationId = (attemptId: string) => `media-${createHash("sha256").update(attemptId).digest("hex").slice(0, 40)}`; + +/** The review outcome for a media receipt: applied is `fixed`, a kept copy `kept`, anything undone by halves `check_failed`. */ +export function mediaResult(findingId: string, receipt: HygieneMediaReceipt): Result { + const status = receipt.outcome === "applied" ? "fixed" : receipt.outcome === "kept" ? "kept" : receipt.outcome === "stale" ? "stale" : receipt.outcome === "refused" ? "refused" : "check_failed"; + return { id: findingId, status, ...(receipt.reason ? { reason: receipt.reason } : {}), ...(status === "check_failed" ? { code: receipt.outcome === "pending" ? "receipt-unknown" : receipt.outcome } : {}), media: receipt }; } export type HygieneReview = ReturnType; diff --git a/packages/ui-server/src/inbox/hygiene-writes.ts b/packages/ui-server/src/inbox/hygiene-writes.ts index fd2fdfe89b..3837e0ddf6 100644 --- a/packages/ui-server/src/inbox/hygiene-writes.ts +++ b/packages/ui-server/src/inbox/hygiene-writes.ts @@ -4,7 +4,7 @@ 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 { hygieneDiffSchema, hygieneEffectSchema, hygieneOutcomeSchema, hygieneReviewStateSchema } from "@schlessera/brain-ui-sdk/schemas"; +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"; import { createInboxResolver, inboxSnoozeUntil } from "./resolve.js"; @@ -20,7 +20,7 @@ export const nextSchema = z.union([z.object({ blocker: z.record(z.string(), z.un export const mediaOf = (next: z.infer) => "media" in next && next.media ? { awaitingReview: next.media.awaitingReview, setAside: next.media.setAside, kept: next.media.kept } : undefined; /** A fresh review's state. */ export const IDLE_REVIEW: HygieneReviewState = { version: 1, status: "idle", position: 0, fixed: 0, dismissed: 0, snoozed: 0, kept: 0, pass: 0, deferred: [] }; -export const resultSchema = z.looseObject({ status: z.enum(["preview", "fixed", "stale", "refused", "check_failed", "undone", "still_detected", "not_detected", "dismissed", "snoozed", "deferred"]), id: text, reason: text.nullable().optional(), code: text.optional(), fieldError: z.object({ field: text, message: text }).optional(), diff: hygieneDiffSchema.optional(), previewToken: id.optional(), undoToken: z.string().regex(/^[0-9a-f]{32}$/).optional() }); +export const resultSchema = z.looseObject({ status: z.enum(["preview", "fixed", "stale", "refused", "check_failed", "undone", "still_detected", "not_detected", "dismissed", "snoozed", "deferred", "kept"]), id: text, reason: text.nullable().optional(), code: text.optional(), fieldError: z.object({ field: text, message: text }).optional(), diff: hygieneDiffSchema.optional(), previewToken: id.optional(), undoToken: z.string().regex(/^[0-9a-f]{32}$/).optional(), media: hygieneMediaReceiptSchema.optional() }); export type Result = z.infer; export interface Attempt { id: string; item_id: string; principal_id: string; request_json: string; effect_json: string; wait_until: number | null } export class HygieneAuthorityError extends Error {} @@ -60,9 +60,9 @@ export function setup(db: Database, { timeZone }: { timeZone?: string }): WriteP } function busy(itemId: string) { return db.query("SELECT 1 FROM hygiene_effect_attempts WHERE item_id = ? AND status = 'started'").get(itemId) !== null; } function outcome(result: Result): NonNullable { - const { status, reason, code, undoToken, fieldError } = result; + const { status, reason, code, undoToken, fieldError, media } = result; if (status === "preview") throw new Error("Preview is not an outcome"); - return hygieneOutcomeSchema.parse({ version: 1, status, reason: reason ?? undefined, code, undoToken, fieldError }); + return hygieneOutcomeSchema.parse({ version: 1, status, reason: reason ?? undefined, code, undoToken, fieldError, media }); } const missingPreview = (options: InboxOption[]) => options.some(o => o.effect.kind === "hygiene" && o.effect.operation === "resolve" && o.input?.type === "none" && !o.preview); return { @@ -152,6 +152,17 @@ export function setup(db: Database, { timeZone }: { timeZone?: string }): WriteP } else update(current, outcome(result)); }).immediate(); }, + /** A media option's fresh plan (#2781), installed only on the card it was previewed for. */ + mediaPreview(time: number, principalId: string, item: InboxActionItem, request: { itemId: string; optionId: string; expectedVersion: number }, optionId: string, planned: InboxOption) { + at = time; + authority(principalId); + return db.transaction(() => { + if (busy(item.id)) throw new Error("Effect in progress"); + const current = action(item.id); + if (current.version !== request.expectedVersion || current.status !== "pending") throw new Error("Inbox version conflict"); + update(current, undefined, current.options.map(o => o.id === optionId ? inboxOptionSchema.parse(planned) : o)); + }).immediate(); + }, finish(time: number, attempt: Attempt, result: Result, options: InboxOption[]) { at = time; const e = hygieneEffectSchema.parse(JSON.parse(attempt.effect_json)); @@ -168,7 +179,9 @@ export function setup(db: Database, { timeZone }: { timeZone?: string }): WriteP } update(item, outcome(result), options); const current = action(item.id); - const confirmed = (e.operation === "resolve" && result.status === "fixed") || (e.operation === "check" && result.status === "not_detected") || (e.operation === "dismiss" && result.status === "dismissed") || (e.operation === "snooze" && result.status === "snoozed"); + const confirmed = (e.operation === "resolve" && result.status === "fixed") || (e.operation === "check" && result.status === "not_detected") || (e.operation === "dismiss" && result.status === "dismissed") || (e.operation === "snooze" && result.status === "snoozed") + // A media effect resolves its card once applied and verified, or kept (#2781); compensated and partial stay pending. + || (e.operation.startsWith("media-") && (result.status === "fixed" || (e.operation === "media-keep-copy" && result.status === "kept"))); if (e.operation === "defer" && result.status === "deferred") { // Leave pending (#2780): nonterminal and untimed. The finding is // skipped for the rest of this pass at this fingerprint; a new pass @@ -184,7 +197,7 @@ export function setup(db: Database, { timeZone }: { timeZone?: string }): WriteP if (e.operation !== "snooze") store.commit([{ kind: "resolution", id: inboxIdentity("resolution", item.id), itemId: item.id, optionId: request.optionId, principalId: attempt.principal_id, reason: request.reason }]); store.commit([{ kind: "transition", itemId: item.id, expectedVersion: current.version, to: e.operation === "dismiss" ? "dismissed" : e.operation === "snooze" ? "snoozed" : "resolved", ...(attempt.wait_until !== null ? { waitUntil: attempt.wait_until } : {}) }]); const review = state(); - if (review.pendingActionId === item.id) save({ ...review, pendingActionId: undefined, fixed: review.fixed + (e.operation === "resolve" || e.operation === "check" ? 1 : 0), dismissed: review.dismissed + (e.operation === "dismiss" ? 1 : 0), snoozed: review.snoozed + (e.operation === "snooze" ? 1 : 0) }); + if (review.pendingActionId === item.id) save({ ...review, pendingActionId: undefined, fixed: review.fixed + (e.operation === "resolve" || e.operation === "check" || (e.operation.startsWith("media-") && result.status === "fixed") ? 1 : 0), dismissed: review.dismissed + (e.operation === "dismiss" ? 1 : 0), snoozed: review.snoozed + (e.operation === "snooze" ? 1 : 0), kept: (review.kept ?? 0) + (result.status === "kept" ? 1 : 0) }); } if (result.status === "undone") { // An inverse restores the defect. Require a new preview before another write. @@ -208,6 +221,8 @@ export function setup(db: Database, { timeZone }: { timeZone?: string }): WriteP if (busy(item.id)) return null; if (item.status !== "pending" || item.expiresAt <= now()) throw new Error("Action is not resolvable"); if (e.operation === "resolve" && (!e.handler || e.input === undefined || !e.previewToken || !option.preview)) throw new Error("Confirm a valid preview first"); + // A media effect applies only the plan it previewed, without refusals (#2781). + if (e.operation.startsWith("media-") && (!e.premiseDigest || option.media?.premiseDigest !== e.premiseDigest || option.media.refusals.length > 0 || (["media-move", "media-keep-copy"].includes(e.operation) && option.media.destination !== e.destination))) throw new Error("Confirm a valid preview first"); if (e.operation === "undo" && (!e.undoToken || !option.preview || item.hygiene.outcome?.status !== "check_failed")) throw new Error("No confirmed inverse available"); const waitUntil = e.operation === "snooze" ? inboxSnoozeUntil(now(), thread.stakes, item.version, timeZone) : null; const attempt: Attempt = { id: inboxIdentity("hygiene-attempt", item.id, String(item.version), option.id), item_id: item.id, principal_id: principalId, request_json: JSON.stringify(request), effect_json: JSON.stringify(e), wait_until: waitUntil }; diff --git a/packages/ui-server/src/inbox/media-effects.ts b/packages/ui-server/src/inbox/media-effects.ts new file mode 100644 index 0000000000..68c106b507 --- /dev/null +++ b/packages/ui-server/src/inbox/media-effects.ts @@ -0,0 +1,322 @@ +/** + * The host side of the four media review effects (#2781, epic #1777, rev 4 + * §5-§6, ruling Rollback A): capture before mutation in the bounded change + * journal, per-file compensation, Undo and restart recovery. The CLI plans + * and writes (`brain hygiene media`); this module owns everything that needs + * the journal. + * + * - **Capture first.** Under the exclusive writer gate, a journal turn + * covers every file the plan lists, and each existing pre-image is retained + * and verified against the plan's SHA-256 *before* the CLI writes. A + * capture that cannot fit the journal's shared cap (or its per-file copy + * bound) refuses as `capture-capacity`, with nothing written. + * - **Per-file compensation.** Each file is put back only while it still + * holds exactly what this effect wrote; anything else is a `conflict`, left + * as it is, and the outcome is `partial`. No all-file atomicity is claimed. + * - **Undo** is the same per-file rule, after a preflight that every + * retained pre-image still exists and every file still holds its + * post-image. Rollback data the journal evicted disables Undo honestly. + * - **Recovery** after a restart compensates an interrupted apply or + * finishes an interrupted Undo from the durable operation row. It never + * re-applies an effect. + */ +import type { Database } from "bun:sqlite"; +import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, rmdirSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { posix } from "node:path"; +import type { JournalVersion, HygieneMediaPlan, HygieneMediaReceipt, HygieneMediaFileState } from "@schlessera/brain-ui-sdk/protocol"; +import { hygieneMediaPlanSchema } from "@schlessera/brain-ui-sdk/schemas"; +import { BRAIN_LOCK_KEY, type KeyedLock } from "@schlessera/brain-ui-sdk/server"; +import { GIT_LOCK_KEY } from "@schlessera/brain-ui-sdk/internal"; +import { z } from "zod"; +import type { TurnJournal } from "../brain/turn-journal.js"; +import { journalCheck, journalStatement, JournalStatementRefused } from "../brain/journal-store.js"; +import { processAlive, SELF, type WriterGate } from "../brain/writer-gate.js"; +import { restoreJournalPath } from "../brain/revert-files.js"; + +type PlanFile = HygieneMediaPlan["files"][number]; +type Row = { id: string; principal_id: string; finding_id: string; fingerprint: string; action: string; source_id: string | null; journal_turn_id: string; + state: string; pid: number; pid_start: string; requested_at: number; plan: string; versions: string; receipt: string }; +const ACTIVE = ["capturing", "applying", "undoing"]; +const DIRECTORY = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW; +const at = (fd: number, name: string) => `/proc/self/fd/${fd}/${name}`; + +const applyResultSchema = z.looseObject({ + status: z.enum(["applied", "stale", "refused", "interrupted"]), reason: z.string().nullable().optional(), + refusals: z.array(z.looseObject({ code: z.string() })).optional(), copySha256: z.string().regex(/^[0-9a-f]{64}$/).optional(), +}); +const keptSchema = z.looseObject({ status: z.string(), reason: z.string().nullable().optional() }); + +export class MediaEffectUnavailable extends Error {} + +/** The current version of a brain file as the journal records one, read without following links; null when absent. */ +function currentVersion(brain: string, path: string): JournalVersion | null | "other" { + const parts = path.split("/"), name = parts.pop()!; + let dir = openSync(brain, DIRECTORY); + try { + for (const part of parts) { + let next: number; + try { next = openSync(at(dir, part), DIRECTORY); } + catch (e) { if ((e as NodeJS.ErrnoException).code === "ENOENT") return null; return "other"; } + closeSync(dir); dir = next; + } + const info = lstatSync(at(dir, name), { throwIfNoEntry: false }); + if (!info) return null; + if (info.isDirectory()) return { kind: "other", mode: info.mode & 0o7777, bytes: 0, ignored: false }; + if (!info.isFile() || info.nlink !== 1) return "other"; + const fd = openSync(at(dir, name), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + try { + const hash = createHash("sha256"), buffer = Buffer.alloc(64 * 1024); + let read: number, bytes = 0; + while ((read = readSync(fd, buffer, 0, buffer.length, null)) > 0) { hash.update(buffer.subarray(0, read)); bytes += read; } + return { kind: "file", mode: fstatSync(fd).mode & 0o7777, bytes, hash: hash.digest("hex"), ignored: false }; + } finally { closeSync(fd); } + } finally { closeSync(dir); } +} + +const shaOf = (v: JournalVersion | null | "other") => v === null ? null : v === "other" ? "other" : v.kind === "other" ? "directory" : v.hash ?? "other"; + +export function createMediaEffects(db: Database, options: { + brainPath: string; journal: TurnJournal; gate: WriterGate; lock: KeyedLock; + /** The hygiene CLI (`brain hygiene --json …`). */ + cli(args: string[]): Promise; + authorized(principalId: string): boolean; + now?: () => number; +}) { + const { brainPath: brain, journal } = options; + const now = options.now ?? Date.now; + const runningHere = new Set(); + // Reads use the UI connection the journal file is attached to; every write is an accounted journal write. + const rowOf = (id: string) => db.query("SELECT * FROM turn_journal_media_operations WHERE id=?").get(id) as Row | null; + const save = async (row: Row, state: string, receipt: HygieneMediaReceipt, versions?: Record) => { + const v = versions ? JSON.stringify(versions) : row.versions; + await journal.writeOperation([journalStatement("UPDATE turn_journal_media_operations SET state=?,receipt=?,versions=? WHERE id=?", state, JSON.stringify(receipt), v, row.id)]); + row.state = state; row.receipt = JSON.stringify(receipt); row.versions = v; + }; + async function exclusive(purpose: string, apply: () => Promise): Promise { + const hold = await options.gate.acquire("exclusive", purpose, { queueTurns: true }); + try { return await options.lock.withLock(BRAIN_LOCK_KEY, () => options.lock.withLock(GIT_LOCK_KEY, apply)); } + finally { await hold.release(); } + } + + /** + * Put each file back to its pre-image, in reverse plan order, only where it + * still holds the post-image this effect wrote. A file already at its + * pre-image needs nothing; anything else is a conflict and is left alone. + */ + async function restore(files: PlanFile[], versions: Record, sourceTurnId: string): Promise { + const out: HygieneMediaReceipt["files"] = []; + for (const f of [...files].reverse()) { + let state: HygieneMediaFileState; + try { + if (f.role === "directory") { + try { rmdirSync(posix.join(brain, f.path)); state = "restored"; } + catch (e) { state = (e as NodeJS.ErrnoException).code === "ENOENT" ? "restored" : "left-changed"; } + } else { + const current = currentVersion(brain, f.path), sha = shaOf(current); + if (sha === f.before) state = "unchanged"; + else if (sha !== f.after || current === "other") state = "conflict"; + else { + const desired = f.before === null ? null : versions[f.path] ?? null; + if (f.before !== null && (!desired || !journal.hasRetainedVersion(sourceTurnId, desired))) state = "conflict"; + else state = await journal.withRetainedVersion(desired, copy => restoreJournalPath(brain, f.path, current as JournalVersion | null, desired, copy)); + } + } + } catch { state = "conflict"; } + out.unshift({ path: f.path, state }); + } + return out; + } + + function undoAvailability(row: Row): HygieneMediaReceipt["undo"] { + const receipt = JSON.parse(row.receipt) as HygieneMediaReceipt; + if (row.source_id !== null || !["applied", "kept"].includes(receipt.outcome)) return { available: false, reason: "no-confirmed-effect" }; + if (row.state === "undone" || row.state === "undo-partial") return { available: false, reason: "already-undone" }; + const plan = hygieneMediaPlanSchema.parse(JSON.parse(row.plan)), versions = JSON.parse(row.versions) as Record; + for (const f of plan.files) { + if (f.role === "directory" || f.before === null) continue; + const v = versions[f.path]; + if (!v || !journal.hasRetainedVersion(row.journal_turn_id, v)) return { available: false, reason: "rollback-evicted" }; + } + for (const f of plan.files) { + if (f.role === "directory") continue; + if (shaOf(currentVersion(brain, f.path)) !== f.after) return { available: false, reason: "changed-since", path: f.path }; + } + return { available: true }; + } + + function receiptOf(row: Row): HygieneMediaReceipt { + const receipt = JSON.parse(row.receipt) as HygieneMediaReceipt; + return { ...receipt, undo: undoAvailability(row) }; + } + + async function admit(id: string, principalId: string, findingId: string, fingerprint: string, action: string, sourceId: string | null, plan: HygieneMediaPlan): Promise { + if (!/^[A-Za-z0-9._-]{16,96}$/.test(id)) throw new MediaEffectUnavailable("Invalid media operation identity."); + const turnId = `media_${id}`; + const receipt: HygieneMediaReceipt = { journalId: id, action: plan.action, outcome: "pending", files: [], undo: { available: false, reason: "no-confirmed-effect" } }; + await journal.writeOperation([ + journalCheck(`SELECT 1 WHERE NOT EXISTS (SELECT 1 FROM turn_journal_media_operations WHERE state IN (${ACTIVE.map(s => `'${s}'`).join(",")}))`, "Another media effect is in progress."), + journalStatement("INSERT INTO turn_journal_media_operations (id,principal_id,finding_id,fingerprint,action,source_id,journal_turn_id,state,pid,pid_start,requested_at,plan,versions,receipt) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + id, principalId, findingId, fingerprint, action, sourceId, sourceId ? `media_undo_${id}` : turnId, sourceId ? "undoing" : "capturing", SELF.pid, SELF.start, now(), JSON.stringify(plan), "{}", JSON.stringify(receipt)), + ]).catch(error => { throw error instanceof JournalStatementRefused ? new MediaEffectUnavailable(error.message) : error; }); + return rowOf(id)!; + } + + /** Begin a user journal turn covering the plan's files; a refused admission is a capture refusal. */ + async function begin(turnId: string, files: PlanFile[]) { + let failure: Error | undefined; + await journal.begin(turnId, { sessionId: null, actor: "user", model: null, profile: "strict", policyHash: null, coveredPaths: files.filter(f => f.role !== "directory").map(f => f.path) }, error => { failure = error; }); + return () => failure; + } + + 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" } }; + } + + /** + * Apply one previewed plan. Returns the receipt; nothing is retried, and a + * refusal before capture or apply writes nothing. + */ + async function apply(request: { id: string; principalId: string; findingId: string; fingerprint: string; plan: HygieneMediaPlan; destination?: string }): Promise { + if (!options.authorized(request.principalId)) throw new MediaEffectUnavailable("Human review authority is required."); + const existing = rowOf(request.id); + if (existing) { + if (existing.principal_id !== request.principalId || existing.finding_id !== request.findingId || existing.plan !== JSON.stringify(request.plan)) throw new MediaEffectUnavailable("Operation identity belongs to another request."); + return receiptOf(existing); + } + const plan = request.plan; + const row = await admit(request.id, request.principalId, request.findingId, request.fingerprint, plan.action, null, plan); + runningHere.add(row.id); + let observed = false; + const refused = (outcome: "refused" | "stale", reason: string, refusals?: HygieneMediaReceipt["refusals"]): HygieneMediaReceipt => + ({ journalId: row.id, action: plan.action, outcome, reason, ...(refusals ? { refusals } : {}), files: plan.files.map(f => ({ path: f.path, state: "unchanged" as const })), undo: { available: false, reason: "no-confirmed-effect" } }); + let receipt: HygieneMediaReceipt; + try { + receipt = await exclusive(`media:${row.id}`, async () => { + if (!options.authorized(request.principalId)) return refused("refused", "authorization-changed"); + let failed: () => Error | undefined; + try { failed = await begin(row.journal_turn_id, plan.files); observed = true; } + catch (error) { return refused("refused", (error as { reason?: string }).reason === "journal_capacity" ? "capture-capacity" : "journal-unavailable"); } + // Capture before mutation: every pre-image the plan names, verified by SHA-256. + const versions: Record = {}; + for (const f of plan.files) { + if (f.role === "directory" || f.before === null) continue; + let retained: JournalVersion | null; + try { retained = await journal.retainBefore(row.journal_turn_id, f.path); } + catch (error) { + const capacity = (error as { reason?: string }).reason === "journal_capacity" || /bounded recovery copy size/.test(String((error as Error).message)); + return refused("refused", capacity ? "capture-capacity" : "capture-unavailable", capacity ? [{ code: "capture-capacity", path: f.path }] : undefined); + } + if (!retained || retained.hash !== f.before || !journal.hasRetainedVersion(row.journal_turn_id, retained)) return refused("stale", "capture-premise-changed", [{ code: "stale", path: f.path }]); + versions[f.path] = retained; + } + if (failed()) return refused("refused", "journal-unavailable"); + // Durable intent, with the retained versions, precedes the first write. + await save(row, "applying", { ...refused("refused", "applying"), outcome: "pending" }, versions); + let result: z.infer; + try { + result = applyResultSchema.parse(await options.cli(["media", plan.action, request.findingId, "--expect-fingerprint", request.fingerprint, + ...(plan.destination ? ["--to", plan.destination] : []), "--expect-premise", plan.premiseDigest, "--journal", row.id])); + } catch { await journal.observe(); return compensate(row, plan, "apply-receipt-unknown"); } + await journal.observe(); + if (result.status === "stale" || result.status === "refused") return refused(result.status, result.reason ?? result.status, result.refusals as HygieneMediaReceipt["refusals"]); + if (result.status === "interrupted") return compensate(row, plan, result.reason ?? "interrupted"); + const written = plan.files.map(f => ({ path: f.path, state: (f.before === null ? "created" : f.after === null ? "removed" : "changed") as HygieneMediaFileState })); + if (plan.action !== "keep-copy") return { journalId: row.id, action: plan.action, outcome: "applied", files: written, undo: { available: false } }; + // Step 6b (rev 5 §5.7): record the kept entry only after the copy verified; a refusal removes the copy. + let kept: z.infer; + try { + kept = keptSchema.parse(await options.cli(["keep-copy", "--expect-fingerprint", request.fingerprint, "--copy", plan.destination!, "--copy-sha256", result.copySha256 ?? "", "--journal", row.id, "--", request.findingId])); + } catch { kept = { status: "refused", reason: "keep-receipt-unknown" }; } + if (kept.status !== "kept") { const compensated = await compensate(row, plan, kept.reason ?? "keep-refused"); await journal.observe(); return compensated; } + return { journalId: row.id, action: plan.action, outcome: "kept", files: written, copySha256: result.copySha256, undo: { available: false } }; + }); + } catch (error) { + receipt = { ...refused("refused", error instanceof MediaEffectUnavailable ? "authorization-changed" : "operation-unavailable") }; + if (row.state === "applying") receipt = await compensate(row, plan, "operation-unavailable").catch(() => ({ ...receipt, outcome: "partial" as const, reason: "compensation-unavailable" })); + } finally { + if (observed) { try { await journal.finish(row.journal_turn_id); } catch { /* the turn stays partial; Undo checks retained data itself */ } } + runningHere.delete(row.id); + } + await save(row, receipt.outcome, receipt); + return receiptOf(row); + } + + /** Undo a confirmed effect: preflight every retained pre-image and post-image, then restore per file. */ + async function undo(request: { id: string; principalId: string; sourceId: string }): Promise { + if (!options.authorized(request.principalId)) throw new MediaEffectUnavailable("Human review authority is required."); + const source = rowOf(request.sourceId); + if (!source || source.principal_id !== request.principalId) throw new MediaEffectUnavailable("Media receipt unavailable."); + const existing = rowOf(request.id); + if (existing) { + if (existing.source_id !== request.sourceId || existing.principal_id !== request.principalId) throw new MediaEffectUnavailable("Operation identity belongs to another request."); + return receiptOf(existing); + } + const plan = hygieneMediaPlanSchema.parse(JSON.parse(source.plan)); + const preflight = undoAvailability(source); + if (!preflight.available) { + // Refused before any write: nothing is restored by halves. + return { journalId: source.id, action: plan.action, outcome: "refused", reason: preflight.reason, files: [], undo: preflight }; + } + const row = await admit(request.id, request.principalId, source.finding_id, source.fingerprint, `undo-${plan.action}`, source.id, plan); + runningHere.add(row.id); + let receipt: HygieneMediaReceipt; + let observed = false; + try { + receipt = await exclusive(`media-undo:${row.id}`, async () => { + const again = undoAvailability(source); + if (!again.available || !options.authorized(request.principalId)) return { journalId: row.id, action: plan.action, outcome: "refused", reason: again.reason ?? "authorization-changed", files: [], undo: again }; + await begin(row.journal_turn_id, plan.files); observed = true; + 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" } }; + }); + } catch { + receipt = { journalId: row.id, action: plan.action, outcome: "partial", reason: "operation-unavailable", files: [], undo: { available: false } }; + } finally { + if (observed) { try { await journal.finish(row.journal_turn_id); } catch { /* partial turn */ } } + runningHere.delete(row.id); + } + await save(row, receipt.outcome, receipt); + if (["undone", "partial"].includes(receipt.outcome)) await save(source, receipt.outcome === "undone" ? "undone" : "undo-partial", JSON.parse(source.receipt)); + return receipt; + } + + /** + * After a restart: an interrupted capture wrote nothing and is refused; an + * interrupted apply is compensated per file; an interrupted Undo finishes by + * the same per-file rule. Each runs once, under the writer gate. + */ + async function recover(): Promise { + const rows = db.query(`SELECT * FROM turn_journal_media_operations WHERE state IN (${ACTIVE.map(s => `'${s}'`).join(",")}) ORDER BY requested_at,rowid`).all() as Row[]; + for (const row of rows) { + if (runningHere.has(row.id) || (processAlive(row.pid, row.pid_start) && !(row.pid === SELF.pid && row.pid_start === SELF.start))) continue; + const plan = hygieneMediaPlanSchema.parse(JSON.parse(row.plan)); + let receipt: HygieneMediaReceipt; + if (row.state === "capturing") { + receipt = { journalId: row.id, action: plan.action, outcome: "refused", reason: "interrupted-before-effect", files: plan.files.map(f => ({ path: f.path, state: "unchanged" as const })), undo: { available: false, reason: "no-confirmed-effect" } }; + } else { + const source = row.source_id ? rowOf(row.source_id) : null; + 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" } }; + }); + if (source && ["undone", "partial"].includes(receipt.outcome)) await save(source, receipt.outcome === "undone" ? "undone" : "undo-partial", JSON.parse(source.receipt)); + } + await save(row, receipt.outcome, receipt); + } + } + return { + apply, undo, recover, + receipt(id: string, principalId: string): HygieneMediaReceipt | null { + const row = rowOf(id); + return row && row.principal_id === principalId ? receiptOf(row) : null; + }, + }; +} +export type MediaEffects = ReturnType; diff --git a/packages/ui-server/tests/cli-inventory.test.ts b/packages/ui-server/tests/cli-inventory.test.ts index ee20c76817..08bb862cdb 100644 --- a/packages/ui-server/tests/cli-inventory.test.ts +++ b/packages/ui-server/tests/cli-inventory.test.ts @@ -20,6 +20,11 @@ const available: Record = { "module enable": "0.40.0", "module disable": "0.40.0", "module settings": "0.40.0", "hygiene list": "0.39.0", "hygiene next": "0.41.0", "hygiene resolve": "0.41.0", "hygiene check": "0.41.0", "hygiene undo": "0.41.0", "hygiene dismiss": "0.41.0", "hygiene snooze": "0.41.0", + // #2781: the media review effects, planned and applied by `brain hygiene + // media`, and step 6b of a kept copy (`keep-copy`, #2780). Unreleased until + // 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", }; // Dynamic branches may overapproximate a command's flags. Record availability // within its namespace; this inventory enforces versions, not valid usage. @@ -34,10 +39,19 @@ const commandFlags: Record> = { module: { "--stdin": "0.40.0", "--preview": "0.40.0", "--migrate": "0.40.0", "--revision": "0.40.0", "--action": "0.40.0" }, hygiene: { "--finding": "0.41.0", "--dry-run": "0.41.0", "--handler": "0.41.0", "--input": "0.41.0", "--expect-fingerprint": "0.41.0", "--expect-preview": "0.41.0", "--reason": "0.41.0", "--until": "0.41.0", // #2780: sent only to leave a media finding pending, which only this release reports. - "--defer": "0.45.0" }, + "--defer": "0.45.0", + // #2781: media effect destinations, apply premise and journal identity; a kept copy's identity (#2780). + "--to": "0.45.0", "--expect-premise": "0.45.0", "--journal": "0.45.0", "--copy": "0.45.0", "--copy-sha256": "0.45.0" }, }; -/** Flags gated by a feature floor above the baseline: never sent to a CLI that cannot report what needs them. */ -const featureFloors: Record = { "hygiene next --defer": HYGIENE_MEDIA_CLI_VERSION }; +/** + * Commands and flags gated by a feature floor above the baseline: never sent + * to a CLI that cannot report what needs them. A command's floor also bounds + * 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 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" }; const root = resolve(import.meta.dir, "../../.."); @@ -66,6 +80,10 @@ function inventory() { const checker = program.getTypeChecker(); const found = new Map>(); const sites = new Set(); + let mediaSites = 0, boundHygiene = 0; + /** `brain.hygiene` itself: BrainClient's hygiene CLI method, not a hygiene state field. */ + const hygieneMethod = (node: ts.PropertyAccessExpression) => node.name.text === "hygiene" + && !!checker.getSymbolAtLocation(node.name)?.declarations?.some(d => d.getSourceFile().fileName === resolve(root, "packages/ui-server/src/brain/client.ts")); let selections = 0; let probes = 0; function strings(node: ts.Expression): string[] { @@ -95,10 +113,10 @@ function inventory() { const first = elements[0]; if (!first || !ts.isExpression(first)) throw new Error("Missing CLI command"); const commands = strings(first).flatMap(command => { - if (["module", "skills", "scratch", "storage", "config"].includes(command)) { + if ((prefix === "hygiene " ? ["media"] : ["module", "skills", "scratch", "storage", "config"]).includes(command)) { const sub = elements[1]; if (!sub || !ts.isExpression(sub)) throw new Error(`Missing ${command} subcommand`); - return strings(sub).map(value => `${command} ${value}`); + return strings(sub).map(value => `${prefix}${command} ${value}`); } return [prefix + command]; }); @@ -139,7 +157,10 @@ function inventory() { } }); } - if (call === "execBrain" || call === "cli") { + // The media effects reach the same hygiene CLI through their injected option (#2781). + const mediaCli = call === "options.cli" && path.endsWith("/inbox/media-effects.ts"); + if (mediaCli) mediaSites++; + if (call === "execBrain" || call === "cli" || mediaCli) { sites.add(path.slice(root.length + 1)); const arg = node.arguments[0]; if (!arg) throw new Error("Missing CLI argv"); @@ -154,7 +175,21 @@ function inventory() { const floor = options.properties.find(property => ts.isPropertyAssignment(property) && property.name.getText() === "minimumVersion"); expect(floor && ts.isPropertyAssignment(floor) && floor.initializer.getText()).toBe("STORAGE_PACK_CLI_VERSION"); } - inspect(arg, call === "cli" ? "hygiene " : ""); + inspect(arg, call === "execBrain" ? "" : "hygiene "); + } + if (ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "bind" && ts.isPropertyAccessExpression(node.expression.expression) && hygieneMethod(node.expression.expression)) { + // The one bound hygiene CLI is the media effects' injected `cli`, scanned above. + expect(path).toBe(resolve(root, "packages/ui-server/src/app.ts")); + const bound = node.parent; + if (!ts.isVariableDeclaration(bound) || !ts.isIdentifier(bound.name)) throw new Error("Unscanned bound hygiene CLI"); + const uses: string[] = []; + walk(scope(node), value => { + if (!ts.isIdentifier(value) || value === bound.name || checker.getSymbolAtLocation(value) !== checker.getSymbolAtLocation(bound.name)) return; + const property = value.parent.parent.parent, call = property.parent.parent; + uses.push(`${ts.isCallExpression(call) ? call.expression.getText() : "?"}(${property.getText()})`); + }); + expect(uses).toEqual([`createMediaEffects(cli: args => ${bound.name.text}(args))`]); + boundHygiene++; } if (ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "hygiene") { // All dynamic hygiene argv must pass through the scanned cli wrapper. @@ -196,7 +231,10 @@ function inventory() { // pass (#1668) and its taxonomy read, `config check --json` (#2694). 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"]); + 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); + 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"); return found; @@ -207,7 +245,7 @@ test("every server CLI command and flag is available at its enforced baseline or expect([...found.keys()].filter(command => command !== "--version").sort()).toEqual(Object.keys(available).sort()); const tooNew: string[] = []; for (const [command, flags] of found) { - const floor = command === "storage pack" ? STORAGE_PACK_CLI_VERSION : MIN_BRAIN_CLI_VERSION; + const floor = command === "storage pack" ? STORAGE_PACK_CLI_VERSION : featureFloors[command] ?? MIN_BRAIN_CLI_VERSION; const commandVersion = command === "--version" ? globalFlags[command]! : available[command]; expect(commandVersion, `Record release evidence for brain ${command}`).toBeDefined(); if (Bun.semver.order(commandVersion!, floor) > 0) tooNew.push(`${command} requires ${commandVersion}`); diff --git a/packages/ui-server/tests/hygiene-media-effects.test.ts b/packages/ui-server/tests/hygiene-media-effects.test.ts new file mode 100644 index 0000000000..4e61cb2e71 --- /dev/null +++ b/packages/ui-server/tests/hygiene-media-effects.test.ts @@ -0,0 +1,233 @@ +/** + * The host side of the media review effects (#2781, Rollback A): capture + * before mutation in the real change journal, per-file compensation with an + * honest `partial`, Undo and restart recovery, over the real offline core CLI + * and real files. Every assertion inspects the actual bytes. The brain + * client runs the CLI directly (no worker boundary), so this suite runs on + * any Linux host. Odysseus's cast; nothing reaches the network. + */ +import { afterEach, expect, test } from "bun:test"; +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; +import { hygieneMediaPlanSchema } from "@schlessera/brain-ui-sdk/schemas"; +import type { HygieneMediaPlan } from "@schlessera/brain-ui-sdk/protocol"; +import { createUiDb } from "../src/db/client.js"; +import { createTurnJournal } from "../src/brain/turn-journal.js"; +import { createWriterGate } from "../src/brain/writer-gate.js"; +import { journalStatement } from "../src/brain/journal-store.js"; +import { createMediaEffects } from "../src/inbox/media-effects.js"; +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"; +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"; + +const CORE_CLI = resolve(import.meta.dir, "../../core/src/cli/brain.ts"); +const LOOM = "photos/penelope-loom.png", NOTE = "journeys/return.md", SCRATCH = ".brain/scratch/2026-07-12/harbour-dawn.jpg"; +const sha = (s: string | Buffer) => createHash("sha256").update(s).digest("hex"); +const clean: Array<() => Promise | void> = []; +afterEach(async () => { for (const fn of clean.splice(0).reverse()) await fn(); }); + +function run(cwd: string, ...args: string[]) { + const r = Bun.spawnSync(args, { cwd, env: { PATH: process.env.PATH ?? "", HOME: cwd, BRAIN_ROOT: cwd, GIT_CONFIG_NOSYSTEM: "1" } }); + return { code: r.exitCode, stdout: r.stdout.toString(), stderr: r.stderr.toString() }; +} +function put(root: string, path: string, text: string) { mkdirSync(dirname(join(root, path)), { recursive: true }); writeFileSync(join(root, path), text); } +const read = (root: string, path: string) => readFileSync(join(root, path), "utf8"); + +async function setup(options: { capBytes?: number; wrap?: (args: string[], real: (args: string[]) => unknown) => unknown } = {}) { + const directory = mkdtempSync(join(tmpdir(), "brain-media-effects-host-")); + const root = join(directory, "brain"); mkdirSync(root); + run(root, "git", "init", "-q", "-b", "main"); + put(root, ".gitignore", ".brain/\nbrain.db*\n.brain-index/\n.bun/\n"); + put(root, "brain.config.json", "{}\n"); + put(root, "places/ithaca.md", "# Ithaca\n"); + run(root, "git", "add", "-A"); + run(root, "git", "-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.test", "commit", "-qm", "fixture"); + put(root, LOOM, "loom bytes"); + put(root, NOTE, "# Return\n\n![loom](../photos/penelope-loom.png)\n"); + const real = (args: string[]) => { + const r = run(root, process.execPath, CORE_CLI, "hygiene", "--json", ...args); + if (![0, 1].includes(r.code ?? -1)) throw new Error(`brain hygiene ${args.join(" ")} exited ${r.code}: ${r.stderr}`); + return JSON.parse(r.stdout); + }; + const cli = async (args: string[]) => options.wrap ? options.wrap(args, real) : real(args); + const dbPath = join(directory, "ui.sqlite"), db = createUiDb(dbPath), native = createNativeJournalFixture(root, directory); + const journal = createTurnJournal(db, { nativeManager: native.manager, brainPath: root, dbPath, objectsRoot: join(directory, "objects"), ...(options.capBytes ? { capBytes: options.capBytes } : {}) }); + await journal.ready; + const gate = createWriterGate(db, root, { pollMs: 1 }); + let authorized = true; + const reviewer = createPrincipal(db, { authMethod: "password", label: "Odysseus", ttlSeconds: 86400 }); + const effects = createMediaEffects(db, { brainPath: root, journal, gate, lock: createKeyedLock(), cli, authorized: id => authorized && (id === "odysseus" || id === reviewer.id) }); + const review = createHygieneReview(db, { brain: { hygiene: async (args: readonly string[]) => cli([...args]) } as unknown as BrainClient, media: effects }); + clean.push(async () => { await journal.close(); await native.close(); db.close(); rmSync(directory, { recursive: true, force: true }); }); + let n = 0; + async function plan(path: string, action: HygieneMediaPlan["action"], to?: string) { + const finding = (real(["list"]) as { entries: Array<{ id: string; path: string; fingerprint: string }> }).entries.find(e => e.path === path) + ?? (real(["reconcile"]), (real(["list"]) as { entries: Array<{ id: string; path: string; fingerprint: string }> }).entries.find(e => e.path === path))!; + const raw = real(["media", action, finding.id, "--expect-fingerprint", finding.fingerprint, ...(to ? ["--to", to] : []), "--dry-run"]); + return { finding, plan: hygieneMediaPlanSchema.parse(raw) }; + } + async function apply(path: string, action: HygieneMediaPlan["action"], to?: string) { + const { finding, plan: p } = await plan(path, action, to); + expect(p.refusals).toEqual([]); + return effects.apply({ id: `odysseus-media-${String(++n).padStart(4, "0")}`, principalId: "odysseus", findingId: finding.id, fingerprint: finding.fingerprint, plan: p }); + } + return { root, directory, db, journal, effects, plan, apply, review, reviewer, revoke() { authorized = false; }, undo: (sourceId: string) => effects.undo({ id: `${sourceId}-undo`, principalId: "odysseus", sourceId }) }; +} + +test("Delete captures the bytes first, removes the file, and Undo puts back the exact bytes", async () => { + const f = await setup(); + const receipt = await f.apply(LOOM, "delete"); + expect(receipt, "MEDIA_DELETE_APPLIED").toMatchObject({ outcome: "applied", files: [{ path: LOOM, state: "removed" }], undo: { available: true } }); + expect(existsSync(join(f.root, LOOM))).toBe(false); + const undone = await f.undo(receipt.journalId); + expect(undone, "MEDIA_DELETE_UNDONE").toMatchObject({ outcome: "undone", files: [{ path: LOOM, state: "restored" }] }); + expect(read(f.root, LOOM), "MEDIA_DELETE_UNDO_BYTES").toBe("loom bytes"); + expect(f.effects.receipt(receipt.journalId, "odysseus")?.undo, "MEDIA_UNDO_ONCE").toEqual({ available: false, reason: "already-undone" }); +}); + +test("Move rewrites the note; Undo restores the source, the note and removes the created folder", async () => { + const f = await setup(); + const receipt = await f.apply(LOOM, "move", "places/ithaca/loom.png"); + expect(receipt.outcome).toBe("applied"); + expect(read(f.root, "places/ithaca/loom.png")).toBe("loom bytes"); + expect(read(f.root, NOTE), "MEDIA_MOVE_NOTE_BYTES").toBe("# Return\n\n![loom](../places/ithaca/loom.png)\n"); + const undone = await f.undo(receipt.journalId); + expect(undone.outcome, "MEDIA_MOVE_UNDONE").toBe("undone"); + expect(read(f.root, LOOM)).toBe("loom bytes"); + expect(read(f.root, NOTE), "MEDIA_MOVE_UNDO_NOTE").toBe("# Return\n\n![loom](../photos/penelope-loom.png)\n"); + expect(existsSync(join(f.root, "places/ithaca")), "MEDIA_MOVE_UNDO_DIRECTORY").toBe(false); +}); + +test("Persist here edits the config; Undo restores its exact bytes", async () => { + const f = await setup(); + const receipt = await f.apply(LOOM, "persist"); + expect(receipt.outcome).toBe("applied"); + expect(read(f.root, "brain.config.json"), "MEDIA_PERSIST_CONFIG").toBe('{ "media": { "track": ["photos/penelope-loom.png"] } }\n'); + expect((await f.undo(receipt.journalId)).outcome).toBe("undone"); + expect(read(f.root, "brain.config.json"), "MEDIA_PERSIST_UNDO_CONFIG").toBe("{}\n"); +}); + +test("Keep a permanent copy records the kept entry after the copy verifies; Undo removes the copy and keeps the 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] } })); + const pins = read(f.root, ".brain/scratch-pins/pins.json"); + const receipt = await f.apply(SCRATCH, "keep-copy", "places/ithaca/harbour-dawn.jpg"); + expect(receipt, "MEDIA_KEEP_KEPT").toMatchObject({ outcome: "kept", copySha256: sha("dawn bytes") }); + expect(read(f.root, "places/ithaca/harbour-dawn.jpg")).toBe("dawn bytes"); + expect(read(f.root, "context/hygiene/kept.md"), "MEDIA_KEEP_ENTRY").toContain("- copy: `places/ithaca/harbour-dawn.jpg`"); + expect(read(f.root, SCRATCH), "MEDIA_KEEP_ORIGINAL").toBe("dawn bytes"); + expect(read(f.root, ".brain/scratch-pins/pins.json"), "MEDIA_KEEP_PINS").toBe(pins); + expect((await f.undo(receipt.journalId)).outcome, "MEDIA_KEEP_UNDONE").toBe("undone"); + 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"); +}); + +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"); + put(f.root, ".brain/scratch-pins/pins.json", JSON.stringify({ version: 1, ready: true, sessions: { '["claude","ithaca"]': [SCRATCH] } })); + const receipt = await f.apply(SCRATCH, "keep-copy", "places/harbour-dawn.jpg"); + expect(receipt, "MEDIA_KEEP_6B_COMPENSATED").toMatchObject({ outcome: "compensated", reason: "copy-changed" }); + expect(existsSync(join(f.root, "places/harbour-dawn.jpg")), "MEDIA_KEEP_6B_NO_COPY").toBe(false); + expect(read(f.root, "brain.config.json")).toBe("{}\n"); + expect(existsSync(join(f.root, "context/hygiene/kept.md"))).toBe(false); +}); + +test("capture that cannot fit the journal refuses before any write", async () => { + const f = await setup({ capBytes: 1024 * 1024 }); + const loom = "L".repeat(2 * 1024 * 1024); + put(f.root, LOOM, loom); + const receipt = await f.apply(LOOM, "delete"); + expect(receipt, "MEDIA_CAPTURE_CAPACITY").toMatchObject({ outcome: "refused", reason: "capture-capacity" }); + expect(read(f.root, LOOM) === loom, "MEDIA_CAPTURE_BEFORE_WRITE").toBe(true); +}); + +test("an interrupted apply is compensated per file, and a concurrent edit is left as a conflict (partial)", async () => { + let concurrent = false; + const f = await setup({ wrap: (args, real) => { + if (args[0] !== "media" || args.includes("--dry-run")) return real(args); + const result = real(args) as { status: string }; + if (result.status !== "applied") return result; + if (concurrent) put(f.root, NOTE, "Penelope's own later edit\n"); + return { ...result, status: "interrupted", reason: "write-failed" }; + } }); + const whole = await f.apply(LOOM, "move", "places/loom.png"); + expect(whole, "MEDIA_COMPENSATED").toMatchObject({ outcome: "compensated" }); + expect(read(f.root, LOOM)).toBe("loom bytes"); + expect(read(f.root, NOTE)).toBe("# Return\n\n![loom](../photos/penelope-loom.png)\n"); + expect(existsSync(join(f.root, "places/loom.png"))).toBe(false); + concurrent = true; + const partial = await f.apply(LOOM, "move", "places/loom.png"); + expect(partial.outcome, "MEDIA_PARTIAL").toBe("partial"); + expect(partial.files.find(x => x.path === NOTE)?.state, "MEDIA_PARTIAL_CONFLICT").toBe("conflict"); + expect(read(f.root, NOTE), "MEDIA_PARTIAL_NO_OVERWRITE").toBe("Penelope's own later edit\n"); + expect(read(f.root, LOOM), "MEDIA_PARTIAL_SOURCE_RESTORED").toBe("loom bytes"); +}); + +test("Undo refuses before any write when a file changed since, or when rollback data was evicted", async () => { + const f = await setup(); + const moved = await f.apply(LOOM, "move", "places/loom.png"); + put(f.root, NOTE, "Telemachus edited this\n"); + expect(f.effects.receipt(moved.journalId, "odysseus")?.undo, "MEDIA_UNDO_CHANGED_SINCE").toEqual({ available: false, reason: "changed-since", path: NOTE }); + expect((await f.undo(moved.journalId)).outcome).toBe("refused"); + expect(read(f.root, "places/loom.png"), "MEDIA_UNDO_REFUSAL_WRITES_NOTHING").toBe("loom bytes"); + expect(read(f.root, NOTE)).toBe("Telemachus edited this\n"); + + const g = await setup(); + const deleted = await g.apply(LOOM, "delete"); + for (const name of readdirSync(join(g.directory, "objects"))) if (name === sha("loom bytes")) rmSync(join(g.directory, "objects", name)); + expect(g.effects.receipt(deleted.journalId, "odysseus")?.undo, "MEDIA_UNDO_EVICTED").toEqual({ available: false, reason: "rollback-evicted" }); + expect((await g.undo(deleted.journalId)).outcome).toBe("refused"); + expect(existsSync(join(g.root, LOOM))).toBe(false); +}); + +test("a restart compensates an interrupted Move from its durable intent and never re-applies it", async () => { + const f = await setup(); + const moved = await f.apply(LOOM, "move", "places/loom.png"); + // As if the server died after the files were written, before the outcome committed. + await f.journal.writeOperation([journalStatement("UPDATE turn_journal_media_operations SET state='applying',pid=?,pid_start=? WHERE id=?", 2 ** 22 + 7, "0", moved.journalId)]); + await f.effects.recover(); + expect(f.effects.receipt(moved.journalId, "odysseus"), "MEDIA_RECOVERY_COMPENSATED").toMatchObject({ outcome: "compensated", reason: "interrupted" }); + expect(read(f.root, LOOM)).toBe("loom bytes"); + expect(read(f.root, NOTE)).toBe("# Return\n\n![loom](../photos/penelope-loom.png)\n"); + expect(existsSync(join(f.root, "places/loom.png"))).toBe(false); + await f.effects.recover(); + expect(read(f.root, LOOM), "MEDIA_RECOVERY_ONCE").toBe("loom bytes"); +}); + +test("a revoked reviewer cannot apply, and an operation identity cannot be reused for another plan", async () => { + const f = await setup(); + const { finding, plan } = await f.plan(LOOM, "delete"); + f.revoke(); + await expect(f.effects.apply({ id: "odysseus-media-revoked", principalId: "odysseus", findingId: finding.id, fingerprint: finding.fingerprint, plan })).rejects.toThrow("authority"); + expect(read(f.root, LOOM)).toBe("loom bytes"); +}); + +test("review offers the media effects with their plans, applies one through the resolver, and resolves the card with its receipt", async () => { + const f = await setup(); + // Notes without frontmatter would be selected first, as errors. + rmSync(join(f.root, NOTE)); rmSync(join(f.root, "places/ithaca.md")); + const card = (await f.review.command(f.reviewer.id, "start")).action!; + expect(card.options.map(o => o.id), "MEDIA_REVIEW_OPTIONS").toEqual(["media-persist", "media-move", "media-delete", "leave-pending", "check", "later", "dismiss"]); + const del = card.options.find(o => o.id === "media-delete")!; + expect(del.media?.files, "MEDIA_REVIEW_PLANNED").toEqual([{ path: LOOM, role: "source", before: sha("loom bytes"), after: null, bytes: 10 }]); + // Move needs a previewed destination first. + await expect(f.review.resolver.resolveAsync(f.reviewer.id, { type: "inbox_resolve", itemId: card.id, optionId: "media-move" }), "MEDIA_REVIEW_PREVIEW_REQUIRED").rejects.toThrow("preview"); + const previewed = await f.review.preview(f.reviewer.id, { itemId: card.id, optionId: "media-move", expectedVersion: card.version, input: "places/loom.png" }); + expect(previewed.options.find(o => o.id === "media-move")?.media?.destination).toBe("places/loom.png"); + await f.review.resolver.resolveAsync(f.reviewer.id, { type: "inbox_resolve", itemId: card.id, optionId: "media-move" }); + const done = f.review.read(); + expect(read(f.root, "places/loom.png"), "MEDIA_REVIEW_MOVED").toBe("loom bytes"); + const resolved = createInboxStoreRead(f.db, card.id); + expect(resolved?.status, "MEDIA_REVIEW_RESOLVED").toBe("resolved"); + expect(resolved?.hygiene?.outcome, "MEDIA_REVIEW_RECEIPT").toMatchObject({ status: "fixed", media: { outcome: "applied", action: "move", undo: { available: true } } }); + expect(done.review.fixed).toBe(1); +}); From dd50bf087ee734b3ff66cc56def7607657780758 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 14:43:39 +0100 Subject: [PATCH 2/2] CONTRACT: feat: undo a confirmed media effect from hygiene review, removing a kept copy's entry with it (#2781) (#3472) * 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 * 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 * 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 --------- 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/src/lib/media-effects.ts | 12 +- packages/core/tests/hygiene-media.test.ts | 37 ++++++ packages/core/tests/media-effects.test.ts | 24 ++++ 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 | 122 ++++++++++++++++++ 23 files changed, 532 insertions(+), 32 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/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/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/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"]); 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..4550a44de6 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,26 @@ 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 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 () => { @@ -231,3 +254,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); +});