From c0a67a9c49829b6b48a0df4fe95993df283ec94c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 14:18:12 +0000 Subject: [PATCH 1/2] CONTRACT: feat(core): brain config media and a broader Persist here rule, previewed with their matches (#2781) `brain config media - ` changes one media list entry in a literal brain.config by a minimal splice, never evaluating it. `--dry-run` previews the diff, the files sync sees now that the pattern matches (with their class before and after) and an approval digest over the config SHA-256, the diff and those matches. Apply needs the preview's `--expect-sha`, and optionally its `--expect-approval`; a config or match change since is `stale` or `stale-approval`, with nothing written. A config that does not read back as the intended lists is put back to its pre-image. `brain hygiene media persist|keep-copy --pattern ` tracks the file by a broader `media.track` rule that matches it, and `--ignore-adjust ` removes the one broader `media.ignore` entry that would still win (M1 A). Such a change previews `matches` and an `approvalDigest`, which apply needs back. Exact changes are unchanged. The splice now supports all four list edits. Contract: docs/integration-contract/cli.md (`brain config media` row and the `hygiene media` row's new flags, fields and refusals). Co-Authored-By: Claude Opus 5.5 --- docs/configuration.md | 8 ++ docs/decisions/hygiene-review.md | 2 +- docs/integration-contract/cli.md | 3 +- docs/media.md | 7 + packages/core/src/cli/brain.ts | 4 +- packages/core/src/cli/commands/config.ts | 52 ++++++- packages/core/src/cli/commands/hygiene.ts | 30 +++- packages/core/src/cli/io.ts | 1 + packages/core/src/lib/media-config-edit.ts | 48 ++++--- packages/core/src/lib/media-config.ts | 153 +++++++++++++++++++++ packages/core/src/lib/media-effects.ts | 94 +++++++++++-- packages/core/src/lib/media-matches.ts | 99 +++++++++++++ packages/core/tests/media-config.test.ts | 146 ++++++++++++++++++++ packages/core/tests/media-effects.test.ts | 77 +++++++++++ 14 files changed, 680 insertions(+), 44 deletions(-) create mode 100644 packages/core/src/lib/media-config.ts create mode 100644 packages/core/src/lib/media-matches.ts create mode 100644 packages/core/tests/media-config.test.ts diff --git a/docs/configuration.md b/docs/configuration.md index 9cc65c8a83..b4c083c0d7 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -768,6 +768,14 @@ characters, and a glob with no `/` also matches the file name alone. media: { ignore: ["assets/renders/*"], track: ["me/*.jpg"] } ``` +`brain config media +` changes one entry without running the config: it previews the +change with `--dry-run`, including the files sync sees now that the pattern +matches, then applies it with `--expect-sha` from that preview. It works only +when the lists are literal arrays in a directly exported object; anything +else is refused, for you to edit by hand +([cli.md](integration-contract/cli.md)). + ## `sync` How `brain sync` integrates remote commits and settles what git cannot: a diff --git a/docs/decisions/hygiene-review.md b/docs/decisions/hygiene-review.md index e5062feea9..843f254f4b 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:250-252`). +(`hygieneCommand`, `packages/core/src/cli/commands/hygiene.ts:257-259`). ## Selection: severity and known urgency, then age and identity diff --git a/docs/integration-contract/cli.md b/docs/integration-contract/cli.md index 9de7bfd888..5bd991a8fa 100644 --- a/docs/integration-contract/cli.md +++ b/docs/integration-contract/cli.md @@ -425,6 +425,7 @@ resumption. The host must retain a successful complete export at least every | `brain module list --json` | `{ "enabled": [{ "name", "key", "description", "types", "commands", "tools": string[], "cron": [{ "name", "schedule", "command" }], "state": "active" \| "dormant", "contextTokens": number }], "available": [{ "key", "description", "enabled": false }] }` — Existing fields and envelope are retained. The historical `enabled` array includes every configured module, even dormant ones. `key` is the module's `brain.config` key. `types` and `commands` are its declared type names and CLI words; `tools` stays the declared canonical names. `description` is from package.json, or null. Each configured module additionally includes `version: string | null` from package.json and `renderers: Record` (empty object when absent). Dormant modules retain their declared renderer metadata; only active modules participate in dispatch. `/api/modules` passes through this metadata. `available` lists declared packages absent from config. `cron` is shape-constrained and empty for dormant modules. `contextTokens` is a nonnegative integer active-context estimate (see Module dormancy below). | | `brain module enable --json` / `disable --json` | `{ "module": string, "state": "active" \| "dormant", "changed": boolean, "context": { "entered": string[], "left": string[] } }` — Toggle a configured manifest name, preserving domain config and documents. Synchronize managed skills and owned instruction regions. Unchanged repeated commands return changed:false. Errors use the existing nonzero-exit/stderr convention. | | `brain --version` | text: the core package's SemVer version and a newline, nothing else (`0.37.0`). `-v` is the same. Only as the first argument | +| `brain config media (--dry-run \| --expect-sha [--expect-approval ]) --json` | Additive in 0.45.0 (#2781). One change to `media.track` or `media.ignore` in a literal `brain.config`, parsed as syntax and never evaluated; a minimal splice keeps every other byte. `--dry-run` writes nothing: `{ "status": "preview", "op", "pattern", "scope": "exact"\|"pattern", "config": { "path", "sha256" }, "configDiff": { "path", "track": { "before", "after" }, "ignore": { "before", "after" } }, "matches": { "pattern", "anyFolder", "count", "bytes", "changed", "ignoredStill", "sensitive", "largest": [{ "path", "bytes", "before", "after" }], "digest" }, "approvalDigest", "refusals": [] }`. `scope` is `exact` for one full path (a `/` and no `*`), `pattern` otherwise; a pattern without `/` matches by name in every folder (`anyFolder`), now and in future. `matches` lists the files `brain sync assess` sees now that the pattern matches, with the class the lists give each before and after (`TRACK`, `ARTIFACT`, `SENSITIVE` or `null`), the five largest first; `ignoredStill` counts those an ignore entry still makes `ARTIFACT`, `sensitive` the secret-shaped ones sync never commits; `digest` covers every match. `approvalDigest` binds the config SHA-256, the diff and `matches.digest`. Apply writes only while the config still holds `--expect-sha` (otherwise `stale`) and, with `--expect-approval`, while the approval is the same (otherwise `stale-approval`), then reads the config back and restores its pre-image when it does not read as the intended lists (`config-invalid`): `{ "status": "applied", "op", "pattern", "config": { "path", "before", "after" }, "configDiff" }`. Every refusal exits `1` with nothing written: `{ "status": "refused"\|"stale", "op", "pattern", "reason", "refusals": [{ "code", "path"? }] }`, reasons `stale`, `stale-approval`, `already-listed`, `not-listed`, `not-expressible` (a `!` negation), `invalid-pattern`, `config-not-literal` and `config-invalid` | | `brain config check --json` | `{ "valid": true, "path": string \| null, "taxonomy": { "types": Record, "inbox", "canonical", "dirAnchors", "modules": string[] } }`, or `{ "valid": false, "error" }` with exit 1 when the config does not load. `prefixes` are each type's effective `match` prefixes (default `[dir]`), normalized to end in `/`; `inbox` is the fallback type for paths outside every prefix. Unchanged since the initial release; documented in 0.44.0 because hosted turns translate provider `types` selectors with `taxonomy.types[*].prefixes` and `taxonomy.inbox` ([which selectors](../supported-inputs.md#governance-policy), #2694). | | `brain doctor --json` | `{ "checks": [{ "id", "status": "pass"\|"warn"\|"fail", "detail", "fix"? }] }` (new in brain-kit). Check ids other than `instructions-weight` are not part of this contract, and `detail` is prose. `instructions-weight` (added in 0.38.0, additively) estimates the tokens always loaded into a session (`CLAUDE.md` with its in-brain `@` imports, `AGENTS.md`, model-invocable skill descriptions), and is `warn` above the optional `brain.config` key `instructions.maxTokens` (default `8000`) | | `brain init --check` | `{ "bun": { "version", "ok" }, "git": { "repo" }, "hooksPath": { "set", "value" }, "config": { "exists", "valid", "initialized", "path", "error"? }, "contentDirs": { "present", "missing" }, "keys": { "GEMINI_API_KEY", "ANTHROPIC_API_KEY" } }` (new in brain-kit). `bun.version` is `null` when not running under Bun. `git.repo` says whether the root is inside a git work tree. `hooksPath.value` is git's `core.hooksPath`, `null` when unset. `config.path` is `null` when there is no config, and `error` is present only when the config failed to load (`valid: false`). `initialized` is true only when the config declares something (profile, taxonomy, modules, embeddings), so a brain holding the template's empty starter config reads as `exists: true, initialized: false` (added in 0.37.0). `contentDirs` splits the core types' directories into those that exist and those that do not. Each `keys` entry is a boolean — whether that variable is set — never the key | @@ -446,7 +447,7 @@ resumption. The host must retain a successful complete export at least every | `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 hygiene media --expect-fingerprint [--to ] [--pattern [--ignore-adjust ]] (--dry-run \| --expect-premise --journal [--expect-approval ]) --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, "scope": "exact"\|"pattern"\|null, "pattern"\|null, "ignoreAdjust"\|null, "matches": { "track", "ignore"\|null }\|null, "approvalDigest"\|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 `*`; or a `!` pattern), `ignore-adjustment-required` (an ignore entry other than this exact path matches; several are named, one per line), `pattern-mismatch` (`--pattern` does not match the file), `invalid-pattern`, `pattern-unexpected` (`--pattern` or `--ignore-adjust` on Delete or Move), `ignore-adjust-unneeded` (`--ignore-adjust` names no entry that conflicts), `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`. Additive in 0.45.0 (#2781): `--pattern` splices that broader `media.track` rule instead, which must match the file; `--ignore-adjust ` also removes the one broader `media.ignore` entry that would still win. Such a broader change (`"scope": "pattern"`, or a non-null `ignoreAdjust`) previews `matches` (each a `brain config media` `matches` object: `track` for the added entry, `ignore` for the removed one) and an `approvalDigest` over the config SHA-256, the diff and every match. Apply then needs `--expect-approval `: without it `"status": "refused", "reason": "approval-required"`, with another `"status": "stale", "reason": "stale-approval"`, nothing written either way. An exact change previews `"matches": null, "approvalDigest": null` and needs no approval. `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/media.md b/docs/media.md index 71684e41b7..830379a503 100644 --- a/docs/media.md +++ b/docs/media.md @@ -67,6 +67,13 @@ A brain usually hits the pain well before those limits. the file name alone. `ignore` wins over `track`, and a secret-shaped name is never tracked, whatever `track` says. See [configuration.md](configuration.md#media). + + `brain config media add-track "me/*.jpg" --dry-run` previews one change to + these lists: the files it affects now, the largest first, and which an + `ignore` entry still wins over. Applying it with the preview's + `--expect-sha` edits only that entry and leaves every other byte of the + config as it was. In hygiene review, *Persist with a broader rule…* does the + same for one media file, and asks you to approve the rule with its matches. - **The template's `.gitignore`** has a commented media section to start from. ## Git LFS for large masters diff --git a/packages/core/src/cli/brain.ts b/packages/core/src/cli/brain.ts index b852b32654..8db3e2ccaf 100755 --- a/packages/core/src/cli/brain.ts +++ b/packages/core/src/cli/brain.ts @@ -80,8 +80,10 @@ function beforeTerminator(args: string[]): string[] { // reports, and rewrites frontmatter only with --apply and no --dry-run; // `brain hygiene` writes under `reconcile` without --dry-run, and under // `dismiss` and `snooze`; -// `brain registry` rewrites index tables unless --check. +// `brain registry` rewrites index tables unless --check; +// `brain config media` edits the config unless --dry-run. const MUTATING_WITH_FLAGS: Record boolean> = { + config: (args) => args[0] === "media" && !args.includes("--dry-run"), geo: (args) => args[0] === "map", tags: (args) => args.includes("--apply") && !args.includes("--dry-run"), hygiene: (args) => (args[0] === "reconcile" && !args.includes("--dry-run")) || args[0] === "dismiss" || args[0] === "snooze", diff --git a/packages/core/src/cli/commands/config.ts b/packages/core/src/cli/commands/config.ts index 1a5c9225f4..cb8d049780 100644 --- a/packages/core/src/cli/commands/config.ts +++ b/packages/core/src/cli/commands/config.ts @@ -1,10 +1,30 @@ +import { relative, sep } from "path"; + import type { CoreCommand, CliContext } from "../types.js"; import { emit, parseArgs, UsageError } from "../io.js"; +import { mediaPolicy } from "../../lib/media.js"; -const HELP = `brain config +const HELP = `brain config check Validate the config and print the effective taxonomy summary - get Print a resolved config value as JSON (used by skills)`; + get Print a resolved config value as JSON (used by skills) + media + [--dry-run | --expect-sha [--expect-approval ]] + Change one media.track or media.ignore entry by a minimal + splice; the config is edited as syntax and never evaluated. + --dry-run previews: { "status": "preview", "op", "pattern", + "scope": "exact"|"pattern", "config": { "path", "sha256" }, + "configDiff", "matches": { "pattern", "anyFolder", "count", + "bytes", "changed", "ignoredStill", "sensitive", "largest", + "digest" }, "approvalDigest", "refusals" }. Apply needs the + preview's config sha256, and with --expect-approval its + approvalDigest: { "status": "applied", "op", "pattern", + "config": { "path", "before", "after" }, "configDiff" }. + Otherwise { "status": "refused"|"stale", "op", "pattern", + "reason", "refusals" } and nothing is written; reasons are + stale, stale-approval, already-listed, not-listed, + not-expressible, invalid-pattern, config-not-literal and + config-invalid.`; /** Effective-taxonomy summary for `config check`. */ function taxonomySummary(cli: CliContext): Record { @@ -36,7 +56,7 @@ export const configCommand: CoreCommand = { summary: "Validate config / read effective taxonomy and config values", helpBlock: HELP, async run(args, cli): Promise { - const { args: pos } = parseArgs(args); + const { args: pos, flags } = parseArgs(args); const sub = pos[0]; if (sub === "check") { @@ -75,6 +95,30 @@ export const configCommand: CoreCommand = { return; } - throw new UsageError("Usage: brain config "); + if (sub === "media") { + // Loaded only for this verb: the edit's dependencies stay out of every other one. + const { applyMediaConfigChange, MEDIA_CONFIG_OPS, planMediaConfigChange } = await import("../../lib/media-config.js"); + const op = pos[1], pattern = pos[2]; + if (!MEDIA_CONFIG_OPS.includes(op as (typeof MEDIA_CONFIG_OPS)[number]) || pattern === undefined || pos.length !== 3) { + throw new UsageError("Usage: brain config media [--dry-run | --expect-sha [--expect-approval ]]"); + } + if (cli.configError) throw new UsageError(`Invalid brain.config: ${cli.configError}; no changes made`); + 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 }; + const kind = op as (typeof MEDIA_CONFIG_OPS)[number]; + let result; + if (flags["dry-run"] === true) result = planMediaConfigChange(ctx, kind, pattern); + else { + const sha = flags["expect-sha"], approval = flags["expect-approval"]; + if (typeof sha !== "string" || (approval !== undefined && typeof approval !== "string")) { + throw new UsageError("Preview with --dry-run first, then apply with --expect-sha [--expect-approval ]"); + } + result = applyMediaConfigChange(ctx, kind, pattern, { sha256: sha, ...(typeof approval === "string" ? { approval } : {}) }); + } + emit(cli.json, result, () => console.log(JSON.stringify(result, null, 2))); + return ["preview", "applied"].includes(result.status) ? 0 : 1; + } + + throw new UsageError("Usage: brain config "); }, }; diff --git a/packages/core/src/cli/commands/hygiene.ts b/packages/core/src/cli/commands/hygiene.ts index 0e388828cf..5971c16c45 100644 --- a/packages/core/src/cli/commands/hygiene.ts +++ b/packages/core/src/cli/commands/hygiene.ts @@ -103,12 +103,19 @@ const HELP = `brain hygiene --expect-fingerprint [--to ] - [--dry-run | --expect-premise --journal ] + [--pattern [--ignore-adjust ]] + [--dry-run | --expect-premise --journal [--expect-approval ]] 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", + "links", "references", "rewrites", "blockers", "configDiff", "scope", + "pattern", "ignoreAdjust", "matches", "approvalDigest", "captureBytes", "copy", "resultClass", "files", "premiseDigest", "refusals" }. move and - keep-copy need --to. Apply needs the preview's premiseDigest and the + keep-copy need --to. persist and keep-copy track the file by its exact + path; --pattern tracks it by a broader media.track rule that matches it, + and --ignore-adjust removes the one broader media.ignore entry that would + still win. A broader change previews its current matches ("matches") and + an approvalDigest that apply needs back as --expect-approval; a change + since is "stale-approval". 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", @@ -329,12 +336,20 @@ export const hygieneCommand: CoreCommand = { 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 ]"); + throw new UsageError("Usage: brain hygiene media --expect-fingerprint [--to ] [--pattern [--ignore-adjust ]] [--dry-run | --expect-premise --journal [--expect-approval ]]"); + } + for (const flag of ["pattern", "ignore-adjust", "expect-approval"]) { + if (flags[flag] !== undefined && typeof flags[flag] !== "string") throw new UsageError(`--${flag} needs a value`); } 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 request = { + id, action: action as MediaAction, expectFingerprint: flags["expect-fingerprint"], + ...(typeof flags.to === "string" ? { destination: flags.to } : {}), + ...(typeof flags.pattern === "string" ? { pattern: flags.pattern } : {}), + ...(typeof flags["ignore-adjust"] === "string" ? { ignoreAdjust: flags["ignore-adjust"] } : {}), + }; 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; @@ -343,7 +358,10 @@ export const hygieneCommand: CoreCommand = { 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 }); + result = applyMediaEffect(ctx, { + ...request, expectPremise: flags["expect-premise"], journal: flags.journal, + ...(typeof flags["expect-approval"] === "string" ? { expectApproval: flags["expect-approval"] } : {}), + }); } emit(cli.json, result, () => console.log(JSON.stringify(result, null, 2))); return ["preview", "applied"].includes(result.status) ? 0 : 1; diff --git a/packages/core/src/cli/io.ts b/packages/core/src/cli/io.ts index dd023aa7f6..120a935565 100644 --- a/packages/core/src/cli/io.ts +++ b/packages/core/src/cli/io.ts @@ -81,6 +81,7 @@ export const VALUE_FLAGS = new Set([ "attempt-timeout-ms", "max-operations", "id", "cursor", "pins-file", "finding", "expect-fingerprint", "until", "reason", "handler", "input", "expect-preview", "defer", "copy", "copy-sha256", "journal", "to", "expect-premise", + "expect-sha", "expect-approval", "pattern", "ignore-adjust", ]); const KNOWN_FLAGS = new Set([...BOOLEAN_FLAGS, ...VALUE_FLAGS]); diff --git a/packages/core/src/lib/media-config-edit.ts b/packages/core/src/lib/media-config-edit.ts index 348e225bac..ea66da4d8d 100644 --- a/packages/core/src/lib/media-config-edit.ts +++ b/packages/core/src/lib/media-config-edit.ts @@ -18,9 +18,16 @@ export interface MediaPolicyLists { ignore: string[]; } -/** One approved change: add an exact `media.track` entry, and remove an exact `media.ignore` entry with it. */ +/** + * One approved change to the two lists: at most one entry added and at most + * one removed, on different lists. Persist here adds a `media.track` entry + * and may remove the `media.ignore` entry that would still win over it; + * `brain config media` makes one change of any of the four kinds. + */ export interface MediaPolicyEdit { addTrack?: string; + removeTrack?: string; + addIgnore?: string; removeIgnore?: string; } @@ -136,38 +143,45 @@ function appendProperty(input: string, node: ts.ObjectLiteralExpression, file: t export function planMediaPolicyEdit(source: string, format: "ts" | "json", edit: MediaPolicyEdit): { text: string; lists: MediaPolicyLists } { const parsed = parse(source, format); const { file, input } = parsed; + const adds = (["track", "ignore"] as const).filter((l) => edit[l === "track" ? "addTrack" : "addIgnore"] !== undefined); + const removes = (["track", "ignore"] as const).filter((l) => edit[l === "track" ? "removeTrack" : "removeIgnore"] !== undefined); + if (adds.length > 1 || removes.length > 1 || (adds.length === 1 && adds[0] === removes[0])) refuse("one edit adds at most one entry and removes at most one, on different lists"); 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); + const lists: MediaPolicyLists = { track: values(parsed.track), ignore: values(parsed.ignore) }; + for (const list of adds) { + const pattern = (list === "track" ? edit.addTrack : edit.addIgnore)!; + if (lists[list].includes(pattern)) continue; + const literal = JSON.stringify(pattern), array = parsed[list]; + if (array) { + const last = array.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 splices.push({ start: array.getStart(file), end: array.end, text: `[${literal}]` }); } else if (parsed.media) { - const { at, insert } = appendProperty(input, parsed.media, file, `"track": [${literal}]`); + const { at, insert } = appendProperty(input, parsed.media, file, `"${list}": [${literal}]`); splices.push({ start: at, end: at, text: insert }); } else { - const { at, insert } = appendProperty(input, parsed.root, file, `"media": { "track": [${literal}] }`); + const { at, insert } = appendProperty(input, parsed.root, file, `"media": { "${list}": [${literal}] }`); splices.push({ start: at, end: at, text: insert }); } - track.push(edit.addTrack); + lists[list].push(pattern); } - 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)}`); + for (const list of removes) { + const pattern = (list === "track" ? edit.removeTrack : edit.removeIgnore)!; + const array = parsed[list]; + const elements = array?.elements ?? ([] as unknown as ts.NodeArray); + const i = elements.findIndex((e) => (e as ts.StringLiteralLike).text === pattern); + if (i < 0) refuse(`media.${list} does not list ${JSON.stringify(pattern)}`); const el = elements[i]!; - if (elements.length === 1) splices.push({ start: parsed.ignore!.getStart(file), end: parsed.ignore!.end, text: "[]" }); + if (elements.length === 1) splices.push({ start: array!.getStart(file), end: array!.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); + lists[list].splice(lists[list].indexOf(pattern), 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"); + if (JSON.stringify(after) !== JSON.stringify(lists)) refuse("the edited config does not read back as the intended lists"); return { text, lists: after }; } diff --git a/packages/core/src/lib/media-config.ts b/packages/core/src/lib/media-config.ts new file mode 100644 index 0000000000..247cf3ab6b --- /dev/null +++ b/packages/core/src/lib/media-config.ts @@ -0,0 +1,153 @@ +/** + * `brain config media - ` (#2781, epic + * #1777, design rev 4 §7): one change to the media lists of `brain.config`, + * previewed with its current matches and applied only against the config + * bytes and match inventory the approval saw. The config is edited as syntax + * (`media-config-edit.ts`) and never evaluated here. + * + * - **Preview** reads only: the diff, the pattern's current matches (count, + * bytes, the five largest, what an ignore still wins over, what is secret + * shaped) and the approval digest binding the config SHA-256, the diff and + * the match-inventory digest. + * - **Apply** needs the previewed config SHA-256 (`--expect-sha`); with + * `--expect-approval` it also needs the same diff and matches. A + * different config is `stale`, a different approval `stale-approval`, and + * nothing is written. The write is a minimal splice, published by rename + * only while the file still holds the previewed bytes; then the config is + * read back, and a config that does not read as the intended lists is put + * back to its pre-image. + */ +import { createHash } from "crypto"; +import { posix } from "path"; + +import type { MediaPolicy } from "./media.js"; +import { MediaConfigNotLiteral, planMediaPolicyEdit, readMediaPolicyLists, type MediaPolicyEdit } from "./media-config-edit.js"; +import { anchoredSha256, readAnchored, type MediaRefusal } from "./media-effects.js"; +import { mediaMatches, patternRefusal, patternScope, type MediaMatches } from "./media-matches.js"; +import { writeFileSafely } from "./safe-path.js"; + +export const MEDIA_CONFIG_OPS = ["add-track", "remove-track", "add-ignore", "remove-ignore"] as const; +export type MediaConfigOp = (typeof MEDIA_CONFIG_OPS)[number]; + +export interface MediaConfigDiff { + path: string; + track: { before: string[]; after: string[] }; + ignore: { before: string[]; after: string[] }; +} + +export interface MediaConfigPlan { + status: "preview"; + op: MediaConfigOp; + pattern: string; + /** `exact` is one full path (it has a `/` and no `*`); anything else is a broader rule. */ + scope: "exact" | "pattern"; + config: { path: string; sha256: string }; + configDiff: MediaConfigDiff; + matches: MediaMatches; + approvalDigest: string; + refusals: MediaRefusal[]; +} + +export interface MediaConfigRefused { + status: "refused" | "stale"; + op: MediaConfigOp; + pattern: string; + reason: string; + refusals: MediaRefusal[]; +} + +export interface MediaConfigApplied { + status: "applied"; + op: MediaConfigOp; + pattern: string; + config: { path: string; before: string; after: string }; + configDiff: MediaConfigDiff; +} + +export interface MediaConfigContext { + root: string; + policy: MediaPolicy; + /** Repo-relative config path, or null without a config. */ + configPath: string | null; +} + +const sha256 = (data: string | Uint8Array) => createHash("sha256").update(data).digest("hex"); +const format = (path: string): "ts" | "json" => (path.endsWith(".json") ? "json" : "ts"); + +/** The approval digest (rev 3 §5.4): config SHA-256, the exact diff, every match. The host binds the principal. */ +export function mediaApprovalDigest(configSha: string, diff: MediaConfigDiff, matches: MediaMatches[]): string { + return sha256(JSON.stringify({ config: configSha, diff, matches: matches.map((m) => m.digest) })); +} + +function editOf(op: MediaConfigOp, pattern: string): MediaPolicyEdit { + return op === "add-track" ? { addTrack: pattern } : op === "remove-track" ? { removeTrack: pattern } : op === "add-ignore" ? { addIgnore: pattern } : { removeIgnore: pattern }; +} + +/** Preview one change. Reads only. */ +export function planMediaConfigChange(ctx: MediaConfigContext, op: MediaConfigOp, pattern: string): MediaConfigPlan | MediaConfigRefused { + const refused = (code: string, path?: string): MediaConfigRefused => ({ status: "refused", op, pattern, reason: code, refusals: [{ code, ...(path ? { path } : {}) }] }); + const invalid = patternRefusal(pattern); + if (invalid) return refused(invalid, pattern); + const configPath = ctx.configPath; + if (!configPath || configPath.startsWith("../") || configPath.startsWith("/")) return refused("config-not-literal"); + let text: string, before: Buffer; + try { + before = readAnchored(ctx.root, configPath); + text = before.toString("utf8"); + } catch { + return refused("config-invalid", configPath); + } + let lists, planned; + try { + lists = readMediaPolicyLists(text, format(configPath)); + const list = op.endsWith("track") ? lists.track : lists.ignore; + if (op.startsWith("add") && list.includes(pattern)) return refused("already-listed", pattern); + if (op.startsWith("remove") && !list.includes(pattern)) return refused("not-listed", pattern); + planned = planMediaPolicyEdit(text, format(configPath), editOf(op, pattern)); + } catch (e) { + return refused(e instanceof MediaConfigNotLiteral ? "config-not-literal" : "config-invalid", configPath); + } + const configDiff: MediaConfigDiff = { path: configPath, track: { before: lists.track, after: planned.lists.track }, ignore: { before: lists.ignore, after: planned.lists.ignore } }; + const after: MediaPolicy = { ...ctx.policy, track: planned.lists.track, ignore: planned.lists.ignore }; + const matches = mediaMatches(ctx.root, pattern, { ...ctx.policy, track: lists.track, ignore: lists.ignore }, after); + const configSha = sha256(before); + return { + status: "preview", op, pattern, scope: patternScope(pattern), + config: { path: configPath, sha256: configSha }, + configDiff, matches, + approvalDigest: mediaApprovalDigest(configSha, configDiff, [matches]), + refusals: [], + }; +} + +/** Apply one change against the previewed config bytes (and, when given, the previewed approval). */ +export function applyMediaConfigChange( + ctx: MediaConfigContext, op: MediaConfigOp, pattern: string, expect: { sha256: string; approval?: string }, +): MediaConfigApplied | MediaConfigRefused { + const plan = planMediaConfigChange(ctx, op, pattern); + if (plan.status !== "preview") return plan; + const stale = (code: "stale" | "stale-approval"): MediaConfigRefused => ({ status: "stale", op, pattern, reason: code, refusals: [{ code, path: plan.config.path }] }); + const path = plan.config.path, abs = posix.join(ctx.root, path); + // The bytes this apply edits are the ones previewed, and the ones the plan was made from. + const before = readAnchored(ctx.root, path); + if (sha256(before) !== expect.sha256 || plan.config.sha256 !== expect.sha256) return stale("stale"); + if (expect.approval !== undefined && plan.approvalDigest !== expect.approval) return stale("stale-approval"); + const { text } = planMediaPolicyEdit(before.toString("utf8"), format(path), editOf(op, pattern)); + const holds = (sha: string) => { if (anchoredSha256(ctx.root, path) !== sha) throw new Error("premise-changed"); }; + try { + // Published only while the file still holds the bytes just read and edited. + writeFileSafely(abs, text, { beforePublish: () => holds(sha256(before)) }); + } catch { + return stale("stale"); + } + // Reload: what the written config now reads as, never what was meant. + let reread: { track: string[]; ignore: string[] } | null = null; + try { reread = readMediaPolicyLists(readAnchored(ctx.root, path).toString("utf8"), format(path)); } catch { reread = null; } + const intended = { track: plan.configDiff.track.after, ignore: plan.configDiff.ignore.after }; + if (JSON.stringify(reread) !== JSON.stringify(intended)) { + // Put the pre-image back, but only over the bytes this apply wrote. + try { writeFileSafely(abs, before, { beforePublish: () => holds(sha256(text)) }); } catch { /* left as written: reported below */ } + return { status: "refused", op, pattern, reason: "config-invalid", refusals: [{ code: "config-invalid", path }] }; + } + return { status: "applied", op, pattern, config: { path, before: expect.sha256, after: sha256(text) }, configDiff: plan.configDiff }; +} diff --git a/packages/core/src/lib/media-effects.ts b/packages/core/src/lib/media-effects.ts index 876c04abe3..cd359c26d6 100644 --- a/packages/core/src/lib/media-effects.ts +++ b/packages/core/src/lib/media-effects.ts @@ -27,6 +27,7 @@ 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 { mediaMatches, patternRefusal, patternScope, type MediaMatches } from "./media-matches.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"; @@ -84,6 +85,26 @@ export interface MediaEffectPlan { /** 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; + /** + * The config change's scope (rev 4 §7): `exact` adds one full path, + * `pattern` a broader rule; null when no config change is planned. + */ + scope: "exact" | "pattern" | null; + /** The `media.track` entry the change adds, or null. */ + pattern: string | null; + /** A broader `media.ignore` entry the change removes so the entry can win (M1 A), or null. */ + ignoreAdjust: string | null; + /** + * What a broader change does to the files sync sees now: the added track + * entry's matches, and the removed ignore entry's. Null for an exact change. + */ + matches: { track: MediaMatches; ignore: MediaMatches | null } | null; + /** + * Set when the change is broader than this one file: the approval binds + * the config SHA-256, the diff and every match, and apply needs it back + * (`stale-approval` otherwise). The host binds the principal. + */ + approvalDigest: 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; @@ -120,6 +141,10 @@ export interface MediaEffectRequest { action: MediaAction; expectFingerprint: string; destination?: string; + /** Persist here or a copy's tracking by a broader `media.track` rule that matches the file (rev 4 §7). */ + pattern?: string; + /** The one broader `media.ignore` entry to remove so the track entry wins (M1 A). */ + ignoreAdjust?: string; } export interface MediaEffectContext { @@ -208,7 +233,8 @@ export function anchoredSha256(root: string, path: string): string | null { } } -function readAnchored(root: string, path: string): Buffer { +/** A regular file's bytes, reached without following any link. */ +export 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); @@ -306,18 +332,38 @@ function configFormat(path: string): "ts" | "json" { /** * 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. + * cannot be made here: already tracked needs none; without a `pattern`, a + * root-level name or a `*` has no exact form (`not-expressible`). A + * `pattern` is a broader rule and must match `target`. An ignore entry other + * than this exact path is removed only when it is the one entry named as + * `ignoreAdjust`; several conflicting entries always refuse, named. */ -function trackEdit(target: string, policy: MediaPolicy): { edit: MediaPolicyEdit | null; refusal: MediaRefusal | null } { +function trackEdit(target: string, policy: MediaPolicy, rule: { pattern?: string; ignoreAdjust?: string } = {}): { edit: MediaPolicyEdit | null; refusal: MediaRefusal | null } { + const refuse = (code: string, path: string) => ({ edit: null, refusal: { code, path } }); + if (rule.pattern !== undefined) { + const invalid = patternRefusal(rule.pattern); + if (invalid) return refuse(invalid, rule.pattern); + if (!matchesAnyPattern(target, [rule.pattern])) return refuse("pattern-mismatch", rule.pattern); + } 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 }; + if (ignores.length === 0 && mediaPolicyClass(target, policy) === "TRACK") { + return rule.ignoreAdjust === undefined ? { edit: null, refusal: null } : refuse("ignore-adjust-unneeded", rule.ignoreAdjust); + } + if (rule.pattern === undefined && (!target.includes("/") || target.includes("*"))) return refuse("not-expressible", target); + let removeIgnore: string | undefined; + if (ignores.length === 1 && (ignores[0] === target || ignores[0] === rule.ignoreAdjust)) removeIgnore = ignores[0]; + else if (ignores.length > 0) return refuse("ignore-adjustment-required", ignores.join("\n")); + if (rule.ignoreAdjust !== undefined && removeIgnore !== rule.ignoreAdjust) return refuse("ignore-adjust-unneeded", rule.ignoreAdjust); + return { edit: { addTrack: rule.pattern ?? target, ...(removeIgnore !== undefined ? { removeIgnore } : {}) }, refusal: null }; } +/** The policy an edit leaves. */ +const editedPolicy = (policy: MediaPolicy, edit: MediaPolicyEdit): MediaPolicy => ({ + ...policy, + track: policy.track.includes(edit.addTrack!) ? policy.track : [...policy.track, edit.addTrack!], + ignore: policy.ignore.filter((p) => p !== edit.removeIgnore), +}); + /** 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); @@ -359,6 +405,8 @@ export function planMediaEffect(ctx: MediaEffectContext, request: MediaEffectReq created = checked.created; } } else if (request.destination !== undefined) add({ code: "destination-unexpected" }); + const rule = { ...(request.pattern !== undefined ? { pattern: request.pattern } : {}), ...(request.ignoreAdjust !== undefined ? { ignoreAdjust: request.ignoreAdjust } : {}) }; + if ((request.pattern !== undefined || request.ignoreAdjust !== undefined) && request.action !== "persist" && request.action !== "keep-copy") add({ code: "pattern-unexpected" }); const rewrites: MediaRewrite[] = [], blockers: MediaEffectPlan["blockers"] = []; const files: MediaEffectFile[] = []; @@ -374,10 +422,11 @@ export function planMediaEffect(ctx: MediaEffectContext, request: MediaEffectReq // Config for Persist here, and for a copy that sync must keep. let configDiff: MediaEffectPlan["configDiff"] = null, configFile: MediaEffectFile | null = null; + let change: Pick = { scope: null, pattern: null, ignoreAdjust: null, matches: null, approvalDigest: 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); + const { edit, refusal } = trackEdit(tracked, policy, rule); add(refusal); if (edit) { if (!ctx.configPath || !validPath(ctx.configPath)) add({ code: "config-not-literal" }); @@ -389,7 +438,16 @@ export function planMediaEffect(ctx: MediaEffectContext, request: MediaEffectReq 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) }); + const edited = editedPolicy(policy, edit); + resultClass = mediaPolicyClass(tracked, edited); + const broaderIgnore = edit.removeIgnore !== undefined && edit.removeIgnore !== tracked ? edit.removeIgnore : null; + change = { scope: edit.addTrack === tracked && patternScope(tracked) === "exact" ? "exact" : "pattern", pattern: edit.addTrack!, ignoreAdjust: broaderIgnore, matches: null, approvalDigest: null }; + // A change broader than this one file is shown with its current matches and approved as a whole (rev 3 §5.2-§5.4). + if (change.scope === "pattern" || broaderIgnore !== null) { + const matches = { track: mediaMatches(root, edit.addTrack!, policy, edited), ignore: broaderIgnore === null ? null : mediaMatches(root, broaderIgnore, policy, edited) }; + change.matches = matches; + change.approvalDigest = digest({ config: configFile.before, diff: configDiff, matches: [matches.track.digest, matches.ignore?.digest ?? null] }); + } } catch (e) { add({ code: e instanceof MediaConfigNotLiteral ? "config-not-literal" : "config-invalid", path: ctx.configPath }); } @@ -440,6 +498,7 @@ export function planMediaEffect(ctx: MediaEffectContext, request: MediaEffectReq rewrites, blockers, configDiff, + ...change, 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, @@ -449,7 +508,7 @@ export function planMediaEffect(ctx: MediaEffectContext, request: MediaEffectReq }; // 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 } }); + 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 }, approval: plan.approvalDigest }); 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 }] }; @@ -562,13 +621,18 @@ function removeExpected(root: string, path: string, expected: string): void { * 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 { +export function applyMediaEffect(ctx: MediaEffectContext, request: MediaEffectRequest & { expectPremise: string; journal: string; expectApproval?: 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: [] }; + // A broader change applies only as it was approved: the config, the diff and every match (rev 3 §5.4). + if (plan.approvalDigest !== null && request.expectApproval === undefined) return { ...base, status: "refused", reason: "approval-required", refusals: [{ code: "approval-required" }], files: [] }; + if (request.expectApproval !== undefined && plan.approvalDigest !== request.expectApproval) { + return { ...base, status: "stale", reason: "stale-approval", refusals: [{ code: "stale-approval", ...(plan.configDiff ? { path: plan.configDiff.path } : {}) }], files: [] }; + } if (plan.premiseDigest !== request.expectPremise) return { ...base, status: "stale", reason: "premise-changed", files: [] }; const results: MediaEffectFileResult[] = plan.files.map((f) => ({ ...f, state: "unchanged" })); @@ -605,7 +669,9 @@ export function applyMediaEffect(ctx: MediaEffectContext, request: MediaEffectRe 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; + const edit = trackEdit(tracked, ctx.policy, { + ...(request.pattern !== undefined ? { pattern: request.pattern } : {}), ...(request.ignoreAdjust !== undefined ? { ignoreAdjust: request.ignoreAdjust } : {}), + }).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"); diff --git a/packages/core/src/lib/media-matches.ts b/packages/core/src/lib/media-matches.ts new file mode 100644 index 0000000000..d0d7241ebd --- /dev/null +++ b/packages/core/src/lib/media-matches.ts @@ -0,0 +1,99 @@ +/** + * What a `media.track` or `media.ignore` change does to the files sync sees + * now (#2781, epic #1777, design rev 3 §5.2-§5.4, carried by rev 4 §7): the + * current matches of the pattern being added or removed, with the class sync + * gives each one before and after the change. Their digest is the + * match-inventory digest an approval binds, so a file that starts or stops + * matching between preview and apply makes the approval stale. + * + * Only files `sync assess` reports are matched: committed, unchanged files + * are not re-classified by a policy change, and git-ignored or protected + * state (`.brain/`) never reaches sync. Future files are not listed, only + * named: a pattern with no `/` matches every same-named file in any folder. + * Reads only. + */ +import { createHash } from "crypto"; +import { lstatSync } from "fs"; +import { join } from "path"; + +import { mediaPolicyClass, type MediaPolicy } from "./media.js"; +import { assess } from "./sync/assess.js"; +import { matchesAnyPattern } from "./tool-leftovers.js"; + +/** The class a policy gives a file, as far as the lists decide it: null is sync's ordinary rules. */ +export type MediaListClass = "TRACK" | "ARTIFACT" | "SENSITIVE" | null; + +export interface MediaMatch { + path: string; + /** Bytes on disk, or null when the file is gone or unreadable. */ + bytes: number | null; + before: MediaListClass; + after: MediaListClass; +} + +export interface MediaMatches { + pattern: string; + /** A pattern without `/` matches by file name in every folder, now and in future. */ + anyFolder: boolean; + /** Files sync sees now that the pattern matches. */ + count: number; + /** Their bytes on disk. */ + bytes: number; + /** Matches whose class the change alters. */ + changed: number; + /** Matches an ignore entry still makes `ARTIFACT` after a track change. */ + ignoredStill: number; + /** Matches with a secret-shaped name: always `SENSITIVE`, never committed. */ + sensitive: number; + /** The five largest matches, largest first, then by path. */ + largest: MediaMatch[]; + /** SHA-256 over every match, in path order: what an approval binds. */ + digest: string; +} + +const LARGEST = 5; + +/** + * The current matches of `pattern` among the files sync sees, classed under + * `before` and `after`, from a fresh `sync assess` of `root`. + */ +export function mediaMatches(root: string, pattern: string, before: MediaPolicy, after: MediaPolicy): MediaMatches { + const rows = assess(root, before) + .filter((f) => f.status !== "D") + .map((f) => ({ path: f.path, sensitive: f.class === "SENSITIVE" })) + .filter((f) => matchesAnyPattern(f.path, [pattern])) + .map((f): MediaMatch => { + const info = lstatSync(join(root, f.path), { throwIfNoEntry: false }); + const klass = (policy: MediaPolicy): MediaListClass => (f.sensitive ? "SENSITIVE" : mediaPolicyClass(f.path, policy)); + return { path: f.path, bytes: info?.isFile() ? info.size : null, before: klass(before), after: klass(after) }; + }) + .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)); + const largest = [...rows].sort((a, b) => (b.bytes ?? -1) - (a.bytes ?? -1) || (a.path < b.path ? -1 : 1)).slice(0, LARGEST); + return { + pattern, + anyFolder: !pattern.includes("/"), + count: rows.length, + bytes: rows.reduce((n, r) => n + (r.bytes ?? 0), 0), + changed: rows.filter((r) => r.before !== r.after).length, + ignoredStill: rows.filter((r) => r.after === "ARTIFACT" && after.track.includes(pattern)).length, + sensitive: rows.filter((r) => r.before === "SENSITIVE").length, + largest, + digest: createHash("sha256").update(JSON.stringify(rows)).digest("hex"), + }; +} + +/** + * Why `pattern` cannot be a list entry, or null. Patterns are literal except + * `*`; there is no negation, and an entry is a relative path or a file name. + */ +export function patternRefusal(pattern: string): string | null { + if (pattern === "" || Buffer.byteLength(pattern) > 4096 || /[\\\u0000-\u001f\u007f]/u.test(pattern)) return "invalid-pattern"; + if (pattern.startsWith("!")) return "not-expressible"; + if (pattern.startsWith("/") || pattern.split("/").some((part) => part === "" || part === "." || part === "..")) return "invalid-pattern"; + return null; +} + +/** The scope of a list entry: one exact path (it has a `/` and no `*`), or a rule that can match more (rev 4 §7). */ +export function patternScope(pattern: string): "exact" | "pattern" { + return pattern.includes("/") && !pattern.includes("*") ? "exact" : "pattern"; +} diff --git a/packages/core/tests/media-config.test.ts b/packages/core/tests/media-config.test.ts new file mode 100644 index 0000000000..0d99c48ad4 --- /dev/null +++ b/packages/core/tests/media-config.test.ts @@ -0,0 +1,146 @@ +/** + * `brain config media - ` (#2781, rev 4 + * §7): one media list change, previewed with its current matches and applied + * only against the config bytes and the approval the preview gave. The + * config's actual bytes are inspected after every apply and refusal. + * 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 { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; + +import { DEFAULT_MEDIA_POLICY, type MediaPolicy } from "../src/lib/media"; +import { planMediaPolicyEdit, readMediaPolicyLists } from "../src/lib/media-config-edit"; +import { applyMediaConfigChange, planMediaConfigChange, type MediaConfigOp, type MediaConfigPlan } from "../src/lib/media-config"; +import { cleanup, runCli } from "./cli-harness"; + +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) { + mkdirSync(dirname(join(root, path)), { recursive: true }); + writeFileSync(join(root, path), bytes); +} +const read = (root: string, path: string) => readFileSync(join(root, path), "utf8"); + +/** A brain with three maps sync sees now: one at the root, two in folders. */ +function brain(config = "{}\n"): string { + const root = mkdtempSync(join(tmpdir(), "brain-media-config-")); + 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, "map.png", "x".repeat(2400)); + put(root, "places/map.png", "x".repeat(1100)); + put(root, "trips/map.png", "x".repeat(800)); + put(root, "trips/troy.png", "x".repeat(300)); + return root; +} +const policyOf = (root: string): MediaPolicy => ({ ...DEFAULT_MEDIA_POLICY, ...readMediaPolicyLists(read(root, "brain.config.json"), "json") }); +const ctx = (root: string) => ({ root, policy: policyOf(root), configPath: "brain.config.json" }); +const preview = (root: string, op: MediaConfigOp, pattern: string) => planMediaConfigChange(ctx(root), op, pattern) as MediaConfigPlan; + +describe("brain config media: preview", () => { + test("a basename rule lists every current match in any folder, largest first, and names the future scope", () => { + const root = brain(); + const plan = preview(root, "add-track", "map.png"); + expect(plan.scope, "CONFIG_BASENAME_IS_BROADER").toBe("pattern"); + expect(plan.configDiff).toEqual({ path: "brain.config.json", track: { before: [], after: ["map.png"] }, ignore: { before: [], after: [] } }); + expect(plan.matches, "CONFIG_MATCHES").toMatchObject({ pattern: "map.png", anyFolder: true, count: 3, bytes: 4300, changed: 3, ignoredStill: 0, sensitive: 0 }); + expect(plan.matches.largest.map((m) => [m.path, m.bytes, m.before, m.after])).toEqual([ + ["map.png", 2400, null, "TRACK"], ["places/map.png", 1100, null, "TRACK"], ["trips/map.png", 800, null, "TRACK"], + ]); + expect(plan.config.sha256).toBe(sha(read(root, "brain.config.json"))); + expect(read(root, "brain.config.json"), "CONFIG_PREVIEW_WRITES_NOTHING").toBe("{}\n"); + }); + + test("an exact path is exact; an ignore entry that still wins and a secret-shaped name are counted", () => { + const root = brain('{ "media": { "ignore": ["trips/*"] } }\n'); + put(root, "trips/.env", "SECRET=1\n"); + expect(preview(root, "add-track", "places/map.png").scope).toBe("exact"); + const broad = preview(root, "add-track", "trips/*"); + expect(broad.matches, "CONFIG_IGNORE_STILL_WINS").toMatchObject({ count: 3, ignoredStill: 2, sensitive: 1, changed: 0 }); + }); + + test("refusals name the reason and write nothing", () => { + const root = brain('{ "media": { "track": ["places/map.png"] } }\n'); + const codes = (op: MediaConfigOp, pattern: string) => (planMediaConfigChange(ctx(root), op, pattern) as { refusals: Array<{ code: string }> }).refusals.map((r) => r.code); + expect(codes("add-track", "places/map.png"), "CONFIG_ALREADY_LISTED").toEqual(["already-listed"]); + expect(codes("remove-ignore", "trips/*"), "CONFIG_NOT_LISTED").toEqual(["not-listed"]); + expect(codes("add-track", "!map.png"), "CONFIG_NO_NEGATION").toEqual(["not-expressible"]); + expect(codes("add-track", "../outside.png")).toEqual(["invalid-pattern"]); + expect(codes("add-track", "/abs.png")).toEqual(["invalid-pattern"]); + const ts = brain(); + rmSync(join(ts, "brain.config.json")); + put(ts, "brain.config.ts", "const media = { track: [] };\nexport default { media };\n"); + expect(planMediaConfigChange({ root: ts, policy: DEFAULT_MEDIA_POLICY, configPath: "brain.config.ts" }, "add-track", "map.png").refusals.map((r) => r.code), "CONFIG_NOT_LITERAL") + .toEqual(["config-not-literal"]); + expect(read(ts, "brain.config.ts")).toBe("const media = { track: [] };\nexport default { media };\n"); + }); +}); + +describe("brain config media: apply", () => { + test("each of the four edits is a minimal splice that reads back as the intended lists", () => { + const root = brain('{\n "title": "Ithaca",\n "media": { "track": ["places/**"], "ignore": ["trips/*", "*.psd"] }\n}\n'); + const step = (op: MediaConfigOp, pattern: string) => { + const plan = preview(root, op, pattern); + const result = applyMediaConfigChange(ctx(root), op, pattern, { sha256: plan.config.sha256, approval: plan.approvalDigest }); + expect(result.status, `${op} ${pattern}`).toBe("applied"); + return read(root, "brain.config.json"); + }; + expect(step("add-track", "map.png"), "CONFIG_ADD_TRACK_BYTES").toBe('{\n "title": "Ithaca",\n "media": { "track": ["places/**", "map.png"], "ignore": ["trips/*", "*.psd"] }\n}\n'); + expect(step("remove-ignore", "trips/*"), "CONFIG_REMOVE_IGNORE_BYTES").toBe('{\n "title": "Ithaca",\n "media": { "track": ["places/**", "map.png"], "ignore": ["*.psd"] }\n}\n'); + expect(step("add-ignore", "trips/troy.png"), "CONFIG_ADD_IGNORE_BYTES").toBe('{\n "title": "Ithaca",\n "media": { "track": ["places/**", "map.png"], "ignore": ["*.psd", "trips/troy.png"] }\n}\n'); + expect(step("remove-track", "places/**"), "CONFIG_REMOVE_TRACK_BYTES").toBe('{\n "title": "Ithaca",\n "media": { "track": ["map.png"], "ignore": ["*.psd", "trips/troy.png"] }\n}\n'); + }); + + test("a TypeScript defineConfig literal keeps every comment and byte around the splice", () => { + const source = 'import { defineConfig } from "@schlessera/brain";\n\nexport default defineConfig({\n media: {\n ignore: ["assets/renders/*"], // generated\n },\n});\n'; + expect(planMediaPolicyEdit(source, "ts", { addTrack: "places/map.png" }).text, "CONFIG_TS_ADD_LIST") + .toBe('import { defineConfig } from "@schlessera/brain";\n\nexport default defineConfig({\n media: {\n ignore: ["assets/renders/*"], "track": ["places/map.png"], // generated\n },\n});\n'); + expect(() => planMediaPolicyEdit(source, "ts", { addTrack: "a/b.png", addIgnore: "a/c.png" }), "CONFIG_ONE_ADD").toThrow(); + }); + + test("a config edited after the preview is stale, and a different match inventory is a stale approval; nothing is written", () => { + const root = brain(); + const plan = preview(root, "add-track", "map.png"); + put(root, "brain.config.json", '{ "title": "Ithaca" }\n'); + expect(applyMediaConfigChange(ctx(root), "add-track", "map.png", { sha256: plan.config.sha256 }), "CONFIG_STALE_SHA").toMatchObject({ status: "stale", reason: "stale" }); + expect(read(root, "brain.config.json")).toBe('{ "title": "Ithaca" }\n'); + + const again = preview(root, "add-track", "map.png"); + put(root, "harbour/map.png", "a fourth map"); + const stale = applyMediaConfigChange(ctx(root), "add-track", "map.png", { sha256: again.config.sha256, approval: again.approvalDigest }); + expect(stale, "CONFIG_STALE_APPROVAL").toMatchObject({ status: "stale", reason: "stale-approval" }); + expect(read(root, "brain.config.json")).toBe('{ "title": "Ithaca" }\n'); + }); + + test("the CLI previews and applies through its --json envelope", async () => { + const root = brain(); + try { + const dry = await runCli(root, ["config", "media", "add-track", "places/map.png", "--dry-run", "--json"]); + expect(dry.code, dry.stderr).toBe(0); + const plan = JSON.parse(dry.stdout); + expect(Object.keys(plan), "CONFIG_CLI_PREVIEW_ENVELOPE").toEqual(["status", "op", "pattern", "scope", "config", "configDiff", "matches", "approvalDigest", "refusals"]); + const refused = await runCli(root, ["config", "media", "add-track", "places/map.png", "--expect-sha", "0".repeat(64), "--json"]); + expect(refused.code).toBe(1); + expect(JSON.parse(refused.stdout), "CONFIG_CLI_STALE").toEqual({ status: "stale", op: "add-track", pattern: "places/map.png", reason: "stale", refusals: [{ code: "stale", path: "brain.config.json" }] }); + const applied = await runCli(root, ["config", "media", "add-track", "places/map.png", "--expect-sha", plan.config.sha256, "--expect-approval", plan.approvalDigest, "--json"]); + expect(applied.code, applied.stderr).toBe(0); + expect(JSON.parse(applied.stdout), "CONFIG_CLI_APPLIED").toMatchObject({ status: "applied", config: { path: "brain.config.json", before: plan.config.sha256 } }); + expect(read(root, "brain.config.json")).toBe('{ "media": { "track": ["places/map.png"] } }\n'); + } finally { + cleanup(root); + } + }); +}); diff --git a/packages/core/tests/media-effects.test.ts b/packages/core/tests/media-effects.test.ts index 55b8f08e61..bb5aca417e 100644 --- a/packages/core/tests/media-effects.test.ts +++ b/packages/core/tests/media-effects.test.ts @@ -262,6 +262,83 @@ describe("Persist here", () => { }); }); +describe("Persist here: broader rule and ignore adjustment", () => { + function broader(root: string, action: MediaEffectRequest["action"], path: string, extra: Partial) { + const f = finding(root, path); + const request: MediaEffectRequest = { id: f.id, action, expectFingerprint: f.fingerprint, ...extra }; + return { request, preview: planMediaEffect(ctx(root), request) as MediaEffectPlan }; + } + + test("a root-level file is tracked by the basename rule it is offered, with every current match listed and approved", () => { + const root = brain(); + put(root, "map.png", "map bytes, Ithaca"); + put(root, "trips/map.png", "map bytes, Troy"); + const { request, preview } = broader(root, "persist", "map.png", { pattern: "map.png" }); + expect(preview.refusals).toEqual([]); + expect(preview, "BROADER_PLAN").toMatchObject({ scope: "pattern", pattern: "map.png", ignoreAdjust: null, resultClass: "TRACK" }); + expect(preview.matches?.track, "BROADER_MATCHES").toMatchObject({ pattern: "map.png", anyFolder: true, count: 2, changed: 2 }); + expect(preview.matches?.track.largest.map((m) => m.path)).toEqual(["map.png", "trips/map.png"]); + expect(preview.approvalDigest).toMatch(/^[0-9a-f]{64}$/); + expect(apply(root, request, preview), "BROADER_NEEDS_APPROVAL").toMatchObject({ status: "refused", reason: "approval-required", files: [] }); + expect(read(root, "brain.config.json")).toBe("{}\n"); + const result = applyMediaEffect(ctx(root), { ...request, expectPremise: preview.premiseDigest, journal: "odysseus-0002", expectApproval: preview.approvalDigest! }); + expect(result.status, result.reason).toBe("applied"); + expect(read(root, "brain.config.json"), "BROADER_CONFIG_BYTES").toBe('{ "media": { "track": ["map.png"] } }\n'); + expect(read(root, "map.png")).toBe("map bytes, Ithaca"); + // The rule covers the other current match too, and any future one. + expect(finding(root, "trips/map.png"), "BROADER_COVERS_MATCHES").toBeUndefined(); + put(root, "harbour/map.png", "a later map"); + expect(finding(root, "harbour/map.png"), "BROADER_COVERS_FUTURE").toBeUndefined(); + }); + + test("a file that starts matching after the approval makes it stale, and nothing is written", () => { + const root = brain(); + const { request, preview } = broader(root, "persist", LOOM, { pattern: "photos/*" }); + expect(preview.scope).toBe("pattern"); + put(root, "photos/suitors.png", "suitor bytes"); + const result = applyMediaEffect(ctx(root), { ...request, expectPremise: preview.premiseDigest, journal: "odysseus-0003", expectApproval: preview.approvalDigest! }); + expect(result, "BROADER_STALE_APPROVAL").toMatchObject({ status: "stale", reason: "stale-approval", files: [] }); + expect(read(root, "brain.config.json")).toBe("{}\n"); + }); + + test("a rule must match the file; negation and an unneeded ignore adjustment are refused", () => { + const root = brain(); + const codes = (extra: Partial) => broader(root, "persist", LOOM, extra).preview.refusals.map((r) => r.code); + expect(codes({ pattern: "places/*" }), "BROADER_MUST_MATCH").toEqual(["pattern-mismatch"]); + expect(codes({ pattern: "!photos/*" })).toEqual(["not-expressible"]); + expect(codes({ ignoreAdjust: "*.psd" })).toEqual(["ignore-adjust-unneeded"]); + // The exact path given as the pattern is still the exact scope, with no approval. + expect(broader(root, "persist", LOOM, { pattern: LOOM }).preview, "BROADER_EXACT_PATTERN").toMatchObject({ scope: "exact", approvalDigest: null, matches: null }); + expect(broader(root, "delete", LOOM, { pattern: "photos/*" }).preview.refusals.map((r) => r.code)).toContain("pattern-unexpected"); + }); + + test("a copy whose destination a broader ignore covers needs that ignore adjusted, previewed with what stops being ignored", () => { + const root = brain('{ "media": { "ignore": ["places/renders/*"] } }\n'); + pin(root, SCRATCH); + put(root, "places/renders/ithaca-sketch.png", "sketch bytes"); + const destination = "places/renders/harbour-dawn.jpg"; + expect(broader(root, "keep-copy", SCRATCH, { destination }).preview.refusals, "ADJUST_REQUIRED").toEqual([{ code: "ignore-adjustment-required", path: "places/renders/*" }]); + const { request, preview } = broader(root, "keep-copy", SCRATCH, { destination, ignoreAdjust: "places/renders/*" }); + expect(preview.refusals).toEqual([]); + expect(preview, "ADJUST_PLAN").toMatchObject({ scope: "exact", pattern: destination, ignoreAdjust: "places/renders/*" }); + expect(preview.configDiff).toEqual({ path: "brain.config.json", track: { before: [], after: [destination] }, ignore: { before: ["places/renders/*"], after: [] } }); + expect(preview.matches?.ignore, "ADJUST_STOPS_IGNORING").toMatchObject({ pattern: "places/renders/*", count: 1, changed: 1 }); + expect(preview.matches?.ignore?.largest[0]).toMatchObject({ path: "places/renders/ithaca-sketch.png", before: "ARTIFACT", after: null }); + const result = applyMediaEffect(ctx(root), { ...request, expectPremise: preview.premiseDigest, journal: "odysseus-0004", expectApproval: preview.approvalDigest! }); + expect(result.status, result.reason).toBe("applied"); + expect(read(root, "brain.config.json"), "ADJUST_CONFIG_BYTES").toBe(`{ "media": { "ignore": [], "track": ["${destination}"] } }\n`); + expect(read(root, destination)).toBe("dawn bytes"); + expect(read(root, SCRATCH)).toBe("dawn bytes"); + }); + + test("several conflicting ignore entries are refused, each named", () => { + const root = brain('{ "media": { "ignore": ["places/renders/*", "*.jpg"] } }\n'); + pin(root, SCRATCH); + const { preview } = broader(root, "keep-copy", SCRATCH, { destination: "places/renders/harbour-dawn.jpg", ignoreAdjust: "*.jpg" }); + expect(preview.refusals, "ADJUST_SEVERAL").toEqual([{ code: "ignore-adjustment-required", path: "places/renders/*\n*.jpg" }]); + }); +}); + 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(); From 826b4e7182da7060355064c9e953f47e06b0ca14 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 14:18:12 +0000 Subject: [PATCH 2/2] CONTRACT: feat: Persist with a broader rule in hygiene review, approved by the principal who previewed it (#2781) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A media card that is not in scratch or staged by a share offers "Persist with a broader rule…" (option `media-persist-rule`, effect `media-persist`), previewed with the `media.track` pattern as its input. A copy or rule whose track entry would still lose to exactly one broader `media.ignore` entry is previewed with that ignore removed and the files it stops ignoring. A plan with an approval digest records the previewing principal as `effect.approvedBy`; confirming it as anyone else is `stale-approval`, and the CLI refuses the same when the config, the diff or any match changed since (rev 3 §5.4). UI SDK (additive): `HygieneMediaMatches` and `hygieneMediaMatchesSchema`; optional `scope`, `pattern`, `ignoreAdjust`, `matches` and `approvalDigest` on `HygieneMediaPlan`; `approvedBy` on `HygieneEffect`. Contract: docs/integration-contract/package-api.md (media review effects). Decision record: hygiene-review.md. Moved citations updated in managed-worktrees.md and wire.md. Changeset: media-config-broader-rule.md. Co-Authored-By: Claude Opus 5.5 --- .changeset/media-config-broader-rule.md | 13 + api-report/ui-sdk.txt | 638 ++++++++++++++++++ docs/decisions/hygiene-review.md | 12 + docs/decisions/managed-worktrees.md | 2 +- docs/integration-contract/package-api.md | 19 +- docs/integration-contract/wire.md | 6 +- packages/ui-sdk/src/protocol.ts | 32 + packages/ui-sdk/src/schemas.ts | 15 +- .../ui-server/src/inbox/hygiene-review.ts | 49 +- packages/ui-server/src/inbox/media-effects.ts | 5 +- .../ui-server/tests/cli-inventory.test.ts | 4 +- .../tests/hygiene-media-effects.test.ts | 63 +- 12 files changed, 837 insertions(+), 21 deletions(-) create mode 100644 .changeset/media-config-broader-rule.md diff --git a/.changeset/media-config-broader-rule.md b/.changeset/media-config-broader-rule.md new file mode 100644 index 0000000000..ae9b15786e --- /dev/null +++ b/.changeset/media-config-broader-rule.md @@ -0,0 +1,13 @@ +--- +"@schlessera/brain": minor +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +--- + +The media lists in `brain.config` can now be changed one entry at a time (#2781). `brain config media --dry-run --json` previews the change: the diff, the files sync sees now that the pattern matches (count, bytes, the five largest, which an ignore entry still wins over, which are secret-shaped), and an approval digest. Applying it with `--expect-sha ` from that preview, and optionally `--expect-approval `, splices only that entry into a literal config, without running it, and refuses `stale` or `stale-approval` with nothing written when the config or its matches changed. + +Persist here can track a file by a broader rule. `brain hygiene media persist --pattern ` (and `keep-copy … --pattern`) adds that `media.track` rule instead of the exact path, and `--ignore-adjust ` removes the one broader `media.ignore` entry that would still win. The preview adds `scope`, `pattern`, `ignoreAdjust`, `matches` and `approvalDigest`; apply needs `--expect-approval` back. Exact changes are unchanged and need no approval. Several conflicting ignore entries are still refused, now each named. + +Hygiene review offers *Persist with a broader rule…* on a media card that is not in scratch or staged by a share, previewed with the rule as its input. A copy destination under one broader ignore is previewed with that ignore removed and the files it stops ignoring. Only the principal who previewed a broader change can confirm it; anyone else gets `stale-approval`. + +The UI SDK adds `HygieneMediaMatches` and `hygieneMediaMatchesSchema`, the optional `scope`, `pattern`, `ignoreAdjust`, `matches` and `approvalDigest` on `HygieneMediaPlan`, and `approvedBy` on `HygieneEffect`. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 5dbdc06207..b252cd0f29 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -176,6 +176,7 @@ export "." (./src/index.ts) type HygieneInput type HygieneMediaAction type HygieneMediaFileState + type HygieneMediaMatches type HygieneMediaPlan type HygieneMediaReceipt type HygieneMediaRefusal @@ -649,6 +650,7 @@ export "./client" (./src/client/index.ts) type HygieneInput type HygieneMediaAction type HygieneMediaFileState + type HygieneMediaMatches type HygieneMediaPlan type HygieneMediaReceipt type HygieneMediaRefusal @@ -1477,6 +1479,7 @@ export "./protocol" (./src/protocol.ts) type HygieneInput type HygieneMediaAction type HygieneMediaFileState + type HygieneMediaMatches type HygieneMediaPlan type HygieneMediaReceipt type HygieneMediaRefusal @@ -1802,6 +1805,7 @@ export "./schemas" (./src/schemas.ts) hygieneDiffSchema hygieneEffectSchema hygieneInputSchema + hygieneMediaMatchesSchema hygieneMediaPlanSchema hygieneMediaReceiptSchema hygieneMediaRefusalSchema @@ -2177,6 +2181,7 @@ export "./server" (./src/server/index.ts) type HygieneInput type HygieneMediaAction type HygieneMediaFileState + type HygieneMediaMatches type HygieneMediaPlan type HygieneMediaReceipt type HygieneMediaRefusal @@ -6860,6 +6865,7 @@ signatures (every public export and the types it is made of) undoToken?: string; destination?: string; premiseDigest?: string; + approvedBy?: string; } HygieneInput (packages/ui-sdk/src/protocol.ts) export type HygieneInput = string | string[] | null; @@ -6867,6 +6873,23 @@ signatures (every public export and the types it is made of) 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"; + HygieneMediaMatches (packages/ui-sdk/src/protocol.ts) + export interface HygieneMediaMatches { + pattern: string; + anyFolder: boolean; + count: number; + bytes: number; + changed: number; + ignoredStill: number; + sensitive: number; + largest: Array<{ + path: string; + bytes: number | null; + before: "TRACK" | "ARTIFACT" | "SENSITIVE" | null; + after: "TRACK" | "ARTIFACT" | "SENSITIVE" | null; + }>; + digest: string; + } HygieneMediaPlan (packages/ui-sdk/src/protocol.ts) export interface HygieneMediaPlan { action: HygieneMediaAction; @@ -6912,6 +6935,14 @@ signatures (every public export and the types it is made of) after: string[]; }; } | null; + scope?: "exact" | "pattern" | null; + pattern?: string | null; + ignoreAdjust?: string | null; + matches?: { + track: HygieneMediaMatches; + ignore: HygieneMediaMatches | null; + } | null; + approvalDigest?: string | null; copy: { bytes: number; sha256: string; @@ -12853,6 +12884,7 @@ 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<{ + approvedBy: z.ZodOptional; destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; @@ -12877,6 +12909,31 @@ signatures (every public export and the types it is made of) }, z.core.$strict>; hygieneInputSchema (packages/ui-sdk/src/schemas.ts) const hygieneInputSchema: z.ZodUnion, z.ZodNull]>; + hygieneMediaMatchesSchema (packages/ui-sdk/src/schemas.ts) + const hygieneMediaMatchesSchema: z.ZodObject<{ + anyFolder: z.ZodBoolean; + bytes: z.ZodNumber; + changed: z.ZodNumber; + count: z.ZodNumber; + digest: z.ZodString; + ignoredStill: z.ZodNumber; + largest: z.ZodArray>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>; hygieneMediaPlanSchema (packages/ui-sdk/src/schemas.ts) const hygieneMediaPlanSchema: z.ZodObject<{ action: z.ZodEnum<{ @@ -12885,6 +12942,7 @@ signatures (every public export and the types it is made of) move: "move"; persist: "persist"; }>; + approvalDigest: z.ZodOptional>; blockers: z.ZodArray; }, z.core.$strict>>; + ignoreAdjust: z.ZodOptional>; links: z.ZodObject<{ conversations: z.ZodNumber; state: z.ZodEnum<{ @@ -12930,6 +12989,57 @@ signatures (every public export and the types it is made of) unlinked: "unlinked"; }>; }, z.core.$strict>; + matches: z.ZodOptional>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>>; + track: z.ZodObject<{ + anyFolder: z.ZodBoolean; + bytes: z.ZodNumber; + changed: z.ZodNumber; + count: z.ZodNumber; + digest: z.ZodString; + ignoredStill: z.ZodNumber; + largest: z.ZodArray>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>; + }, z.core.$strict>>>; + pattern: z.ZodOptional>; premiseDigest: z.ZodString; references: z.ZodObject<{ complete: z.ZodBoolean; @@ -12954,6 +13064,10 @@ signatures (every public export and the types it is made of) line: z.ZodNumber; note: z.ZodString; }, z.core.$strict>>; + scope: z.ZodOptional>>; }, z.core.$strip>; hygieneMediaReceiptSchema (packages/ui-sdk/src/schemas.ts) const hygieneMediaReceiptSchema: z.ZodObject<{ @@ -13201,6 +13315,7 @@ signatures (every public export and the types it is made of) }, z.core.$loose>>; }, z.core.$loose>; }, z.core.$loose>, z.ZodObject<{ + approvedBy: z.ZodOptional; destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; @@ -13267,6 +13382,7 @@ signatures (every public export and the types it is made of) move: "move"; persist: "persist"; }>; + approvalDigest: z.ZodOptional>; blockers: z.ZodArray; }, z.core.$strict>>; + ignoreAdjust: z.ZodOptional>; links: z.ZodObject<{ conversations: z.ZodNumber; state: z.ZodEnum<{ @@ -13312,6 +13429,57 @@ signatures (every public export and the types it is made of) unlinked: "unlinked"; }>; }, z.core.$strict>; + matches: z.ZodOptional>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>>; + track: z.ZodObject<{ + anyFolder: z.ZodBoolean; + bytes: z.ZodNumber; + changed: z.ZodNumber; + count: z.ZodNumber; + digest: z.ZodString; + ignoredStill: z.ZodNumber; + largest: z.ZodArray>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>; + }, z.core.$strict>>>; + pattern: z.ZodOptional>; premiseDigest: z.ZodString; references: z.ZodObject<{ complete: z.ZodBoolean; @@ -13336,6 +13504,10 @@ signatures (every public export and the types it is made of) line: z.ZodNumber; note: z.ZodString; }, z.core.$strict>>; + scope: z.ZodOptional>>; }, z.core.$strip>>; preview: z.ZodOptional>; }, z.core.$loose>; }, z.core.$loose>, z.ZodObject<{ + approvedBy: z.ZodOptional; destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; @@ -13702,6 +13875,7 @@ signatures (every public export and the types it is made of) move: "move"; persist: "persist"; }>; + approvalDigest: z.ZodOptional>; blockers: z.ZodArray; }, z.core.$strict>>; + ignoreAdjust: z.ZodOptional>; links: z.ZodObject<{ conversations: z.ZodNumber; state: z.ZodEnum<{ @@ -13747,6 +13922,57 @@ signatures (every public export and the types it is made of) unlinked: "unlinked"; }>; }, z.core.$strict>; + matches: z.ZodOptional>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>>; + track: z.ZodObject<{ + anyFolder: z.ZodBoolean; + bytes: z.ZodNumber; + changed: z.ZodNumber; + count: z.ZodNumber; + digest: z.ZodString; + ignoredStill: z.ZodNumber; + largest: z.ZodArray>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>; + }, z.core.$strict>>>; + pattern: z.ZodOptional>; premiseDigest: z.ZodString; references: z.ZodObject<{ complete: z.ZodBoolean; @@ -13771,6 +13997,10 @@ signatures (every public export and the types it is made of) line: z.ZodNumber; note: z.ZodString; }, z.core.$strict>>; + scope: z.ZodOptional>>; }, z.core.$strip>>; preview: z.ZodOptional>; }, z.core.$loose>; }, z.core.$loose>, z.ZodObject<{ + approvedBy: z.ZodOptional; destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; @@ -14102,6 +14333,7 @@ signatures (every public export and the types it is made of) move: "move"; persist: "persist"; }>; + approvalDigest: z.ZodOptional>; blockers: z.ZodArray; }, z.core.$strict>>; + ignoreAdjust: z.ZodOptional>; links: z.ZodObject<{ conversations: z.ZodNumber; state: z.ZodEnum<{ @@ -14147,6 +14380,57 @@ signatures (every public export and the types it is made of) unlinked: "unlinked"; }>; }, z.core.$strict>; + matches: z.ZodOptional>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>>; + track: z.ZodObject<{ + anyFolder: z.ZodBoolean; + bytes: z.ZodNumber; + changed: z.ZodNumber; + count: z.ZodNumber; + digest: z.ZodString; + ignoredStill: z.ZodNumber; + largest: z.ZodArray>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>; + }, z.core.$strict>>>; + pattern: z.ZodOptional>; premiseDigest: z.ZodString; references: z.ZodObject<{ complete: z.ZodBoolean; @@ -14171,6 +14455,10 @@ signatures (every public export and the types it is made of) line: z.ZodNumber; note: z.ZodString; }, z.core.$strict>>; + scope: z.ZodOptional>>; }, z.core.$strip>>; preview: z.ZodOptional>; }, z.core.$loose>; }, z.core.$loose>, z.ZodObject<{ + approvedBy: z.ZodOptional; destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; @@ -14510,6 +14799,7 @@ signatures (every public export and the types it is made of) move: "move"; persist: "persist"; }>; + approvalDigest: z.ZodOptional>; blockers: z.ZodArray; }, z.core.$strict>>; + ignoreAdjust: z.ZodOptional>; links: z.ZodObject<{ conversations: z.ZodNumber; state: z.ZodEnum<{ @@ -14555,6 +14846,57 @@ signatures (every public export and the types it is made of) unlinked: "unlinked"; }>; }, z.core.$strict>; + matches: z.ZodOptional>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>>; + track: z.ZodObject<{ + anyFolder: z.ZodBoolean; + bytes: z.ZodNumber; + changed: z.ZodNumber; + count: z.ZodNumber; + digest: z.ZodString; + ignoredStill: z.ZodNumber; + largest: z.ZodArray>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>; + }, z.core.$strict>>>; + pattern: z.ZodOptional>; premiseDigest: z.ZodString; references: z.ZodObject<{ complete: z.ZodBoolean; @@ -14579,6 +14921,10 @@ signatures (every public export and the types it is made of) line: z.ZodNumber; note: z.ZodString; }, z.core.$strict>>; + scope: z.ZodOptional>>; }, z.core.$strip>>; preview: z.ZodOptional>; }, z.core.$loose>; }, z.core.$loose>, z.ZodObject<{ + approvedBy: z.ZodOptional; destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; @@ -14915,6 +15262,7 @@ signatures (every public export and the types it is made of) move: "move"; persist: "persist"; }>; + approvalDigest: z.ZodOptional>; blockers: z.ZodArray; }, z.core.$strict>>; + ignoreAdjust: z.ZodOptional>; links: z.ZodObject<{ conversations: z.ZodNumber; state: z.ZodEnum<{ @@ -14960,6 +15309,57 @@ signatures (every public export and the types it is made of) unlinked: "unlinked"; }>; }, z.core.$strict>; + matches: z.ZodOptional>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>>; + track: z.ZodObject<{ + anyFolder: z.ZodBoolean; + bytes: z.ZodNumber; + changed: z.ZodNumber; + count: z.ZodNumber; + digest: z.ZodString; + ignoredStill: z.ZodNumber; + largest: z.ZodArray>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>; + }, z.core.$strict>>>; + pattern: z.ZodOptional>; premiseDigest: z.ZodString; references: z.ZodObject<{ complete: z.ZodBoolean; @@ -14984,6 +15384,10 @@ signatures (every public export and the types it is made of) line: z.ZodNumber; note: z.ZodString; }, z.core.$strict>>; + scope: z.ZodOptional>>; }, z.core.$strip>>; preview: z.ZodOptional; destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; @@ -15105,6 +15510,7 @@ signatures (every public export and the types it is made of) move: "move"; persist: "persist"; }>; + approvalDigest: z.ZodOptional>; blockers: z.ZodArray; }, z.core.$strict>>; + ignoreAdjust: z.ZodOptional>; links: z.ZodObject<{ conversations: z.ZodNumber; state: z.ZodEnum<{ @@ -15150,6 +15557,57 @@ signatures (every public export and the types it is made of) unlinked: "unlinked"; }>; }, z.core.$strict>; + matches: z.ZodOptional>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>>; + track: z.ZodObject<{ + anyFolder: z.ZodBoolean; + bytes: z.ZodNumber; + changed: z.ZodNumber; + count: z.ZodNumber; + digest: z.ZodString; + ignoredStill: z.ZodNumber; + largest: z.ZodArray>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>; + }, z.core.$strict>>>; + pattern: z.ZodOptional>; premiseDigest: z.ZodString; references: z.ZodObject<{ complete: z.ZodBoolean; @@ -15174,6 +15632,10 @@ signatures (every public export and the types it is made of) line: z.ZodNumber; note: z.ZodString; }, z.core.$strict>>; + scope: z.ZodOptional>>; }, z.core.$strip>>; preview: z.ZodOptional>; }, z.core.$loose>; }, z.core.$loose>, z.ZodObject<{ + approvedBy: z.ZodOptional; destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; @@ -15561,6 +16024,7 @@ signatures (every public export and the types it is made of) move: "move"; persist: "persist"; }>; + approvalDigest: z.ZodOptional>; blockers: z.ZodArray; }, z.core.$strict>>; + ignoreAdjust: z.ZodOptional>; links: z.ZodObject<{ conversations: z.ZodNumber; state: z.ZodEnum<{ @@ -15606,6 +16071,57 @@ signatures (every public export and the types it is made of) unlinked: "unlinked"; }>; }, z.core.$strict>; + matches: z.ZodOptional>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>>; + track: z.ZodObject<{ + anyFolder: z.ZodBoolean; + bytes: z.ZodNumber; + changed: z.ZodNumber; + count: z.ZodNumber; + digest: z.ZodString; + ignoredStill: z.ZodNumber; + largest: z.ZodArray>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>; + }, z.core.$strict>>>; + pattern: z.ZodOptional>; premiseDigest: z.ZodString; references: z.ZodObject<{ complete: z.ZodBoolean; @@ -15630,6 +16146,10 @@ signatures (every public export and the types it is made of) line: z.ZodNumber; note: z.ZodString; }, z.core.$strict>>; + scope: z.ZodOptional>>; }, 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<{ + approvedBy: z.ZodOptional; destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; @@ -19671,6 +20192,7 @@ signatures (every public export and the types it is made of) }, z.core.$loose>>; }, z.core.$loose>; }, z.core.$loose>, z.ZodObject<{ + approvedBy: z.ZodOptional; destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; @@ -19737,6 +20259,7 @@ signatures (every public export and the types it is made of) move: "move"; persist: "persist"; }>; + approvalDigest: z.ZodOptional>; blockers: z.ZodArray; }, z.core.$strict>>; + ignoreAdjust: z.ZodOptional>; links: z.ZodObject<{ conversations: z.ZodNumber; state: z.ZodEnum<{ @@ -19782,6 +20306,57 @@ signatures (every public export and the types it is made of) unlinked: "unlinked"; }>; }, z.core.$strict>; + matches: z.ZodOptional>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>>; + track: z.ZodObject<{ + anyFolder: z.ZodBoolean; + bytes: z.ZodNumber; + changed: z.ZodNumber; + count: z.ZodNumber; + digest: z.ZodString; + ignoredStill: z.ZodNumber; + largest: z.ZodArray>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>; + }, z.core.$strict>>>; + pattern: z.ZodOptional>; premiseDigest: z.ZodString; references: z.ZodObject<{ complete: z.ZodBoolean; @@ -19806,6 +20381,10 @@ signatures (every public export and the types it is made of) line: z.ZodNumber; note: z.ZodString; }, z.core.$strict>>; + scope: z.ZodOptional>>; }, z.core.$strip>>; preview: z.ZodOptional>; }, z.core.$loose>; }, z.core.$loose>, z.ZodObject<{ + approvedBy: z.ZodOptional; destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; @@ -20154,6 +20734,7 @@ signatures (every public export and the types it is made of) move: "move"; persist: "persist"; }>; + approvalDigest: z.ZodOptional>; blockers: z.ZodArray; }, z.core.$strict>>; + ignoreAdjust: z.ZodOptional>; links: z.ZodObject<{ conversations: z.ZodNumber; state: z.ZodEnum<{ @@ -20199,6 +20781,57 @@ signatures (every public export and the types it is made of) unlinked: "unlinked"; }>; }, z.core.$strict>; + matches: z.ZodOptional>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>>; + track: z.ZodObject<{ + anyFolder: z.ZodBoolean; + bytes: z.ZodNumber; + changed: z.ZodNumber; + count: z.ZodNumber; + digest: z.ZodString; + ignoredStill: z.ZodNumber; + largest: z.ZodArray>; + before: z.ZodNullable>; + bytes: z.ZodNullable; + path: z.ZodString; + }, z.core.$strict>>; + pattern: z.ZodString; + sensitive: z.ZodNumber; + }, z.core.$strict>; + }, z.core.$strict>>>; + pattern: z.ZodOptional>; premiseDigest: z.ZodString; references: z.ZodObject<{ complete: z.ZodBoolean; @@ -20223,6 +20856,10 @@ signatures (every public export and the types it is made of) line: z.ZodNumber; note: z.ZodString; }, z.core.$strict>>; + scope: z.ZodOptional>>; }, z.core.$strip>>; preview: z.ZodOptional; v1ResolutionEffectSchema (packages/ui-sdk/src/schemas.ts) const v1ResolutionEffectSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ + approvedBy: z.ZodOptional; destination: z.ZodOptional; findingId: z.ZodString; fingerprint: z.ZodString; diff --git a/docs/decisions/hygiene-review.md b/docs/decisions/hygiene-review.md index 843f254f4b..812a87356b 100644 --- a/docs/decisions/hygiene-review.md +++ b/docs/decisions/hygiene-review.md @@ -255,6 +255,18 @@ 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`. +**Broader config changes (#2781, rev 3 §5.2-§5.4, rev 4 §7).** Persist here +tracks one exact path by default. A broader `media.track` rule, or removing +the one broader `media.ignore` entry that would still win (M1 A), changes how +sync treats other files too, now and later. So its preview lists the files +sync sees now that it matches, and the approval binds the config's bytes, the +exact diff and a digest of those matches. A config edited, or a file that +starts or stops matching, before apply makes the approval `stale-approval`. +The host binds the principal: only the person who previewed a broader change +can confirm it. Several conflicting ignore entries are never adjusted; they +are named, for the owner to edit. `brain config media` is the same edit +outside review, previewed and applied against the config's SHA-256. + ## 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 d60e022ad5..ac3691d0cc 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:45-57`). +(`async function cli(args`, `packages/ui-server/src/inbox/hygiene-review.ts:46-58`). 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/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 11ed2e102f..f12a7b36a1 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -1711,18 +1711,29 @@ 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`) | +| `HygieneEffect.operation` | gains `media-delete`, `media-move`, `media-persist`, `media-keep-copy`; the effect may carry `destination`, `premiseDigest` and `approvedBy` (the principal who previewed a broader config change, below) | +| `InboxOption.media` | `HygieneMediaPlan`: the CLI plan (`action`, `premiseDigest`, `destination`, `files`, `captureBytes`, `links`, `references`, `rewrites`, `blockers`, `configDiff`, `copy`, `resultClass`, `refusals`), and optionally `scope` (`exact`\|`pattern`\|null), `pattern`, `ignoreAdjust`, `matches` (`{ track, ignore }` of `HygieneMediaMatches`) and `approvalDigest`, which a CLI before them omits | +| `HygieneMediaMatches`, `hygieneMediaMatchesSchema` | new (0.45.0): `{ pattern, anyFolder, count, bytes, changed, ignoredStill, sensitive, largest: [{ path, bytes, before, after }] (at most 5), digest }`, a list pattern's current matches among the files sync sees, with the class (`TRACK`\|`ARTIFACT`\|`SENSITIVE`\|null) the lists give each before and after | | `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 +A media finding's card offers Persist here, Persist with a broader rule… +(not for scratch or share-staged files), 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 +`input`), and the broader rule (option `media-persist-rule`, effect +`media-persist`) when its `media.track` pattern is previewed as `input`. +When a previewed track entry would still lose to exactly one broader +`media.ignore` entry, the preview plans that ignore's removal too +(`ignoreAdjust`), with the files it stops ignoring in `matches.ignore`; +several such entries stay refused as `ignore-adjustment-required`. A plan +with an `approvalDigest` (a broader rule or ignore adjustment) records the +previewing principal as `effect.approvedBy`; confirming it as anyone else is +`stale` with reason `stale-approval`, and the CLI refuses the same reason +when the config, the diff or any match changed since. 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 diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index bd4eef3d3a..9631bbce9e 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:1082-1101`). +(`turnJournalSummarySchema`, `packages/ui-sdk/src/schemas.ts:1095-1114`). `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:3954-3960`) and -(`serverUsageSchema`, `packages/ui-sdk/src/schemas.ts:1928-1930`). +(`ServerUsage`, `packages/ui-sdk/src/protocol.ts:3986-3992`) and +(`serverUsageSchema`, `packages/ui-sdk/src/schemas.ts:1941-1943`). 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/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index 9cf1a54c93..7958491de0 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -3642,6 +3642,11 @@ export interface HygieneEffect { destination?: string; /** The previewed media plan's premise; apply refuses `stale` when the brain no longer matches it. */ premiseDigest?: string; + /** + * The principal who previewed a broader config change (#2781, rev 3 §5.4). + * Only that principal can confirm it; anyone else gets `stale-approval`. + */ + approvedBy?: string; } /** A media finding's four effects (#2781). */ export type HygieneMediaAction = "delete" | "move" | "persist" | "keep-copy"; @@ -3661,10 +3666,37 @@ export interface HygieneMediaPlan { 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; + /** The config change's scope (#2781, rev 4 §7): one exact path, or a broader rule; absent or null without a config change. */ + scope?: "exact" | "pattern" | null; + /** The `media.track` entry the change adds. */ + pattern?: string | null; + /** A broader `media.ignore` entry the change removes so the track entry wins (M1 A). */ + ignoreAdjust?: string | null; + /** A broader change's current matches: the added track entry's, and the removed ignore entry's. */ + matches?: { track: HygieneMediaMatches; ignore: HygieneMediaMatches | null } | null; + /** Set for a broader change: what its approval binds (config SHA-256, diff, every match). */ + approvalDigest?: string | null; copy: { bytes: number; sha256: string; diskFreeAdvisory: number | null } | null; resultClass: "TRACK" | "ARTIFACT" | null; refusals: HygieneMediaRefusal[]; } +/** + * The files sync sees now that a media list pattern matches (#2781, rev 3 + * §5.2), with the class the lists give each before and after the change. + * `anyFolder`: a pattern without `/` matches by file name everywhere, now and + * in future. + */ +export interface HygieneMediaMatches { + pattern: string; + anyFolder: boolean; + count: number; + bytes: number; + changed: number; + ignoredStill: number; + sensitive: number; + largest: Array<{ path: string; bytes: number | null; before: "TRACK" | "ARTIFACT" | "SENSITIVE" | null; after: "TRACK" | "ARTIFACT" | "SENSITIVE" | null }>; + digest: string; +} export type HygieneMediaFileState = "created" | "changed" | "removed" | "restored" | "unchanged" | "left-changed" | "conflict"; /** * A media effect's receipt (#2781, rev 4 §9). `compensated`: nothing remains diff --git a/packages/ui-sdk/src/schemas.ts b/packages/ui-sdk/src/schemas.ts index ace70a5888..b58dc6ba0d 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, HygieneReviewMediaUndoCommand, HygieneReviewRequest, HygienePreviewRequest, HygieneReviewState, HygieneReviewRead, HygieneWorktreeDetailsRead } from "./protocol.js"; +import type { HygieneAction, HygieneDiff, HygieneEffect, HygieneMediaMatches, 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"; // ============================================================ @@ -696,10 +696,18 @@ export const hygieneEffectSchema = z.strictObject({ 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(), + approvedBy: id.optional(), }) satisfies z.ZodType; 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; +const listClass = z.enum(["TRACK", "ARTIFACT", "SENSITIVE"]).nullable(); +export const hygieneMediaMatchesSchema = z.strictObject({ + pattern: z.string().min(1).max(4096), anyFolder: z.boolean(), count: z.number().int().min(0), bytes: z.number().int().min(0), + changed: z.number().int().min(0), ignoredStill: z.number().int().min(0), sensitive: z.number().int().min(0), + largest: z.array(z.strictObject({ path: mediaPath, bytes: z.number().int().min(0).nullable(), before: listClass, after: listClass })).max(5), + digest: z.string().regex(/^[a-f0-9]{64}$/), +}) 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(), @@ -710,6 +718,11 @@ export const hygieneMediaPlanSchema = z.object({ 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(), + // Additive (#2781): a broader config change and what its approval binds; a CLI before it omits them. + scope: z.enum(["exact", "pattern"]).nullable().optional(), pattern: z.string().min(1).max(4096).nullable().optional(), + ignoreAdjust: z.string().min(1).max(4096).nullable().optional(), + matches: z.strictObject({ track: hygieneMediaMatchesSchema, ignore: hygieneMediaMatchesSchema.nullable() }).nullable().optional(), + approvalDigest: z.string().regex(/^[a-f0-9]{64}$/).nullable().optional(), 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), diff --git a/packages/ui-server/src/inbox/hygiene-review.ts b/packages/ui-server/src/inbox/hygiene-review.ts index b95e173efc..fc2377f90d 100644 --- a/packages/ui-server/src/inbox/hygiene-review.ts +++ b/packages/ui-server/src/inbox/hygiene-review.ts @@ -5,6 +5,7 @@ import type { Database } from "bun:sqlite"; import { z } from "zod"; 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 { SHARE_STAGING_DIR } 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"; @@ -100,15 +101,31 @@ 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"])); + /** + * A media effect's CLI plan, or null when the CLI could not plan it (not + * detected, stale). With `previewed`, a person asked for this preview: the + * one broader ignore entry that would still win over the track entry is + * then planned as an adjustment, shown with what stops being ignored and + * approved with the rest (M1 A). Several such entries stay refused. + */ + async function mediaPlan(f: { id: string; fingerprint: string }, operation: MediaOperation, input: { destination?: string; pattern?: string; previewed?: boolean } = {}): Promise { + const to = input.destination !== undefined ? ["--to", input.destination] : [], rule = input.pattern !== undefined ? ["--pattern", input.pattern] : []; + let parsed = hygieneMediaPlanSchema.safeParse(await cli(["media", MEDIA_ACTIONS[operation], f.id, "--expect-fingerprint", f.fingerprint, ...to, ...rule, "--dry-run"])); + const only = parsed.success && parsed.data.refusals.length === 1 ? parsed.data.refusals[0]! : null; + if (input.previewed && only?.code === "ignore-adjustment-required" && only.path && !only.path.includes("\n")) { + parsed = hygieneMediaPlanSchema.safeParse(await cli(["media", MEDIA_ACTIONS[operation], f.id, "--expect-fingerprint", f.fingerprint, ...to, ...rule, "--ignore-adjust", only.path, "--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 { + /** + * The options' media plan: only a plan without refusals carries the premise + * that lets it apply. A broader change is bound to the principal who + * previewed it (rev 3 §5.4); no one else can confirm it. + */ + function withPlan(option: InboxOption, plan: HygieneMediaPlan | null, destination?: string, principalId?: 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 }; + const ready = plan !== null && plan.refusals.length === 0; + return { ...option, effect: { ...e, destination, premiseDigest: ready ? plan.premiseDigest : undefined, approvedBy: ready && plan.approvalDigest ? principalId : 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); @@ -138,6 +155,11 @@ export function createHygieneReview(db: Database, deps: { brain: BrainClient; no 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)))); + // Persist by a broader media.track rule (rev 4 §7): the person enters the + // rule, and its preview lists every current match before approval. + if (operation === "media-persist" && !scratch && !finding.path.startsWith(`${SHARE_STAGING_DIR}/`)) { + options.push(inboxOptionSchema.parse({ id: PERSIST_RULE, label: "Persist with a broader rule…", input: { type: "string", example: ruleExample(finding.path) }, effect: effect(finding, operation) })); + } } } // Media (#2780) can always be left pending for the rest of this pass. @@ -236,10 +258,12 @@ export function createHygieneReview(db: Database, deps: { brain: BrainClient; no 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); + const text = typeof request.input === "string" ? request.input : undefined; + const rule = option.id === PERSIST_RULE, destination = rule ? undefined : text; + if (rule && text === undefined) throw new Error("A broader rule needs its pattern"); + const plan = await mediaPlan({ id: selected.findingId, fingerprint: selected.fingerprint }, selected.operation, { destination, pattern: rule ? text : undefined, previewed: true }); authority(principalId); - await write("mediaPreview", now(), principalId, item, request, option.id, withPlan(option, plan, destination)); + await write("mediaPreview", now(), principalId, item, request, option.id, withPlan(option, plan, destination, principalId)); return action(item.id); } if (selected.kind !== "hygiene" || selected.operation !== "resolve" || !selected.handler) throw new Error("Not a repair option"); @@ -254,6 +278,8 @@ export function createHygieneReview(db: Database, deps: { brain: BrainClient; no 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" }; + // A broader change applies only for the principal who previewed and approved it. + if (plan.approvalDigest && e.approvedBy !== principalId) return { id: e.findingId, status: "stale", reason: "stale-approval" }; 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] @@ -341,6 +367,11 @@ export function createHygieneReview(db: Database, deps: { brain: BrainClient; no attachMedia(effects: MediaEffects) { media = effects; } }; } +/** Persist here by a broader `media.track` rule (#2781): the same effect, with the person's pattern. */ +const PERSIST_RULE = "media-persist-rule"; +/** The rule a person most likely means: every file in the same folder, or the name in any folder at the root. */ +const ruleExample = (path: string) => path.includes("/") ? `${path.slice(0, path.lastIndexOf("/"))}/*` : path; + /** 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; diff --git a/packages/ui-server/src/inbox/media-effects.ts b/packages/ui-server/src/inbox/media-effects.ts index ee7ee2bf5e..107b17cc5e 100644 --- a/packages/ui-server/src/inbox/media-effects.ts +++ b/packages/ui-server/src/inbox/media-effects.ts @@ -236,7 +236,10 @@ export function createMediaEffects(db: Database, options: { 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])); + ...(plan.destination ? ["--to", plan.destination] : []), + // A broader change (#2781, rev 4 §7) is applied as it was planned and approved. + ...(plan.scope === "pattern" && plan.pattern ? ["--pattern", plan.pattern] : []), ...(plan.ignoreAdjust ? ["--ignore-adjust", plan.ignoreAdjust] : []), + "--expect-premise", plan.premiseDigest, "--journal", row.id, ...(plan.approvalDigest ? ["--expect-approval", plan.approvalDigest] : [])])); } 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"]); diff --git a/packages/ui-server/tests/cli-inventory.test.ts b/packages/ui-server/tests/cli-inventory.test.ts index 506e721d61..3a23453e9b 100644 --- a/packages/ui-server/tests/cli-inventory.test.ts +++ b/packages/ui-server/tests/cli-inventory.test.ts @@ -43,7 +43,9 @@ const commandFlags: Record> = { // #2780: sent only to leave a media finding pending, which only this release reports. "--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" }, + "--to": "0.45.0", "--expect-premise": "0.45.0", "--journal": "0.45.0", "--copy": "0.45.0", "--copy-sha256": "0.45.0", + // #2781: Persist here by a broader rule, the one broader ignore it adjusts, and the approval it binds. + "--pattern": "0.45.0", "--ignore-adjust": "0.45.0", "--expect-approval": "0.45.0" }, }; /** * Commands and flags gated by a feature floor above the baseline: never sent diff --git a/packages/ui-server/tests/hygiene-media-effects.test.ts b/packages/ui-server/tests/hygiene-media-effects.test.ts index 4550a44de6..f95c96358e 100644 --- a/packages/ui-server/tests/hygiene-media-effects.test.ts +++ b/packages/ui-server/tests/hygiene-media-effects.test.ts @@ -239,7 +239,7 @@ test("review offers the media effects with their plans, applies one through the // 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"]); + expect(card.options.map(o => o.id), "MEDIA_REVIEW_OPTIONS").toEqual(["media-persist", "media-persist-rule", "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. @@ -332,6 +332,67 @@ test("undo-media of a kept copy from review removes the copy, its rule and its k expect(result.review.kept, "MEDIA_REVIEW_UNDO_KEPT_COUNTER").toBe(0); }); +test("review previews a broader Persist rule with its current matches, applies it for the principal who approved it, and Undo restores the config", async () => { + const f = await setup(); + const card = await reviewWithTwo(f); + const rule = card.options.find(o => o.id === "media-persist-rule")!; + expect(rule, "MEDIA_RULE_OPTION").toMatchObject({ label: "Persist with a broader rule…", input: { type: "string", example: "photos/*" }, effect: { operation: "media-persist" } }); + const previewed = await f.review.preview(f.reviewer.id, { itemId: card.id, optionId: "media-persist-rule", expectedVersion: card.version, input: "photos/*" }); + const option = previewed.options.find(o => o.id === "media-persist-rule")!; + expect(option.media, "MEDIA_RULE_PLAN").toMatchObject({ scope: "pattern", pattern: "photos/*", refusals: [], configDiff: { track: { before: [], after: ["photos/*"] } } }); + expect(option.media?.matches?.track, "MEDIA_RULE_MATCHES").toMatchObject({ count: 2, changed: 2, anyFolder: false }); + expect(option.media?.approvalDigest).toMatch(/^[0-9a-f]{64}$/); + expect(option.effect, "MEDIA_RULE_APPROVED_BY").toMatchObject({ approvedBy: f.reviewer.id }); + // The plain Persist here option is unchanged: the exact path, no approval. + expect(previewed.options.find(o => o.id === "media-persist")?.media, "MEDIA_RULE_EXACT_UNCHANGED").toMatchObject({ scope: "exact", approvalDigest: null }); + expect(read(f.root, "brain.config.json")).toBe("{}\n"); + await resolveWith(f, card.id, "media-persist-rule"); + expect(createInboxStoreRead(f.db, card.id)!.hygiene?.outcome, "MEDIA_RULE_APPLIED").toMatchObject({ status: "fixed", media: { outcome: "applied", action: "persist" } }); + expect(read(f.root, "brain.config.json"), "MEDIA_RULE_CONFIG").toBe('{ "media": { "track": ["photos/*"] } }\n'); + // The rule also covers the other current match: nothing is left to review. + expect(f.review.read().action, "MEDIA_RULE_COVERS_MATCHES").toBeFalsy(); + const result = await f.review.undoMedia(f.reviewer.id, createInboxStoreRead(f.db, card.id)!.hygiene!.outcome!.media!.journalId); + expect(result.mediaUndo.outcome).toBe("undone"); + expect(read(f.root, "brain.config.json"), "MEDIA_RULE_UNDO_CONFIG").toBe("{}\n"); +}); + +test("a broader rule another principal previewed is a stale approval, and a match that appears after the preview is too; nothing is written", async () => { + const f = await setup(); + const card = await reviewWithTwo(f); + const other = createPrincipal(f.db, { authMethod: "password", label: "Telemachus", ttlSeconds: 86400 }); + await f.review.preview(other.id, { itemId: card.id, optionId: "media-persist-rule", expectedVersion: card.version, input: "photos/*" }); + await resolveWith(f, card.id, "media-persist-rule"); + expect(createInboxStoreRead(f.db, card.id)!.hygiene?.outcome, "MEDIA_RULE_OTHER_PRINCIPAL").toMatchObject({ status: "stale", reason: "stale-approval" }); + expect(read(f.root, "brain.config.json")).toBe("{}\n"); + + const g = await setup(); + const next = await reviewWithTwo(g); + await g.review.preview(g.reviewer.id, { itemId: next.id, optionId: "media-persist-rule", expectedVersion: next.version, input: "photos/*" }); + put(g.root, "photos/suitors.png", "suitor bytes"); + await resolveWith(g, next.id, "media-persist-rule"); + expect(createInboxStoreRead(g.db, next.id)!.hygiene?.outcome, "MEDIA_RULE_STALE_MATCHES").toMatchObject({ status: "stale", media: { outcome: "stale", reason: "stale-approval" } }); + expect(read(g.root, "brain.config.json")).toBe("{}\n"); +}); + +test("a copy destination under a broader ignore is previewed with that ignore adjusted and what stops being ignored, then applied as approved", 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, "brain.config.json", '{ "media": { "ignore": ["places/renders/*"] } }\n'); + put(f.root, "places/renders/ithaca-sketch.png", "sketch bytes"); + 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!; + const previewed = await f.review.preview(f.reviewer.id, { itemId: card.id, optionId: "media-keep-copy", expectedVersion: card.version, input: "places/renders/harbour-dawn.jpg" }); + const plan = previewed.options.find(o => o.id === "media-keep-copy")!.media!; + expect(plan, "MEDIA_ADJUST_PLAN").toMatchObject({ refusals: [], scope: "exact", ignoreAdjust: "places/renders/*", configDiff: { ignore: { before: ["places/renders/*"], after: [] } } }); + expect(plan.matches?.ignore, "MEDIA_ADJUST_MATCHES").toMatchObject({ count: 1, changed: 1 }); + await resolveWith(f, card.id, "media-keep-copy"); + expect(createInboxStoreRead(f.db, card.id)!.hygiene?.outcome?.status, "MEDIA_ADJUST_KEPT").toBe("kept"); + expect(read(f.root, "brain.config.json"), "MEDIA_ADJUST_CONFIG").toBe('{ "media": { "ignore": [], "track": ["places/renders/harbour-dawn.jpg"] } }\n'); + expect(read(f.root, "places/renders/harbour-dawn.jpg")).toBe("dawn bytes"); + expect(read(f.root, SCRATCH)).toBe("dawn bytes"); +}); + 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);