diff --git a/.changeset/ui-react-default-root-wrappers.md b/.changeset/ui-react-default-root-wrappers.md new file mode 100644 index 0000000000..c946913b81 --- /dev/null +++ b/.changeset/ui-react-default-root-wrappers.md @@ -0,0 +1,4 @@ +--- +"@schlessera/brain-ui-react": patch +--- +Remove nine internal default-root wrappers that no entry point exported and nothing called. The public API is unchanged. diff --git a/.changeset/ui-unused-module-exports.md b/.changeset/ui-unused-module-exports.md new file mode 100644 index 0000000000..e0742fbf32 --- /dev/null +++ b/.changeset/ui-unused-module-exports.md @@ -0,0 +1,6 @@ +--- +"@schlessera/brain-ui-server": patch +"@schlessera/brain-ui-kit": patch +"@schlessera/brain-ui-react": patch +--- +Removed: the `export` keyword from 478 module-level names that no other file imported and no entry point reaches. Names that were also unused in their own file were deleted. No entry point's exports changed. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a8db400f83..d08c2b1e2b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -449,6 +449,14 @@ internal: no compatibility promise, valid only at the same lockstep version. import of gray-matter. The reason is in [docs/decisions/frontmatter-parsing.md](docs/decisions/frontmatter-parsing.md). +In ui-server, ui-kit and ui-react, `bun run lint` refuses an `export` in `src/` +that no other file imports (`scripts/check-unused-exports.ts`). Drop the +keyword, or delete the declaration if its own file does not use it either. An +entry point's own exports and the declarations its api-report signatures +record are exempt. Anything else that has to stay exported, such as a type +that another file's declaration emit infers, gets an allowlist entry with a +one-line reason in that script. + The invisible-character and leakage gates here are brain-kit's own. A deployment keeps its own copies with its own patterns, and a copy that runs before `bun install` stays dependency-free. diff --git a/bun.lock b/bun.lock index fa79dd7aab..07b4834a0b 100644 --- a/bun.lock +++ b/bun.lock @@ -9,7 +9,6 @@ "@modelcontextprotocol/sdk": "^1.29.0", "@types/bun": "^1.4.2", "axe-core": "^4.13.0", - "claude-agent-sdk-research-292": "npm:@anthropic-ai/claude-agent-sdk@0.3.292", "github-slugger": "^2.0.0", "mdast-util-to-string": "^4.0.0", "oxlint": "^1.79.0", @@ -504,21 +503,21 @@ "@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.3.293", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.293", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.293", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.293", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.293", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.293", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.293", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.293", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.293" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-DVfn46SmpfB7xaKuUHsAC+qwY27hOLHNbvF7FoNOAXLZPRTeCr68SjhBjlFOtk+jz5Nf7pfUwnIUDFcdVih6Dg=="], - "@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/claude-agent-sdk-darwin-arm64@0.3.292", "", { "os": "darwin", "cpu": "arm64" }, "sha512-VbE0eqQoAast5oQW0ZQleVkX/hJhjuTJfVrFlTlF7b7gdybl08UguRugezVS8fAZfePVo0rJYAnkafxL0API+g=="], + "@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/claude-agent-sdk-darwin-arm64@0.3.293", "", { "os": "darwin", "cpu": "arm64" }, "sha512-E2rwiiHr3LwYzBuTROVDpJkts4QmYCrW39ZIN1qixVSNQhSEiz5LjaKxzrwq0xgPgQDU0vd2fLMG1k72BgD24w=="], - "@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/claude-agent-sdk-darwin-x64@0.3.292", "", { "os": "darwin", "cpu": "x64" }, "sha512-z1ChVMQC5uFrCsMUleQ67B1w+v8vLJNoHjl/qowv0DqVbTLWQ8Qz1ejQWdrZPezdT10BTpyss8kNf8G4wOrsOA=="], + "@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/claude-agent-sdk-darwin-x64@0.3.293", "", { "os": "darwin", "cpu": "x64" }, "sha512-UJD8kX1XDhMqs/0LLxD012h+S9U3Q8XPbRSNcnPQEMNAoEF+lh898xPbVnkUgPKl3jUOUyqYRwFRwDiUJD+GJg=="], - "@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/claude-agent-sdk-linux-arm64@0.3.292", "", { "os": "linux", "cpu": "arm64" }, "sha512-ziGXVP0Kjjg531fUNZh/1lkT8MQKc77qFinqvQ7N7ZbR7Kr/wVRhs3kSb2s7A1+z/3TNsPiQJManEmbw61U+Hw=="], + "@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/claude-agent-sdk-linux-arm64@0.3.293", "", { "os": "linux", "cpu": "arm64" }, "sha512-B3M5gw6pPH/ckMtrLtGg4ZY1adLVnPoXkEV+Ruu0j/gdFzwuLWR64Spa0RCsbo7BXVN6w5NTqkuZk+HBfsPUZA=="], - "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/claude-agent-sdk-linux-arm64-musl@0.3.292", "", { "os": "linux", "cpu": "arm64" }, "sha512-6UIxxeHsQQcHheip8P+6q1kf5UQ1D7RJgso423IZeMjyBX1pMlX6LII8b59/1sBfaO1Q5YZ8JKDGr7f4+GtE0A=="], + "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/claude-agent-sdk-linux-arm64-musl@0.3.293", "", { "os": "linux", "cpu": "arm64" }, "sha512-l5Nfwox69bBMEccSQfPQFOq9hbSqQIMsi4H/UXaMSsqgnxunXuKEBXb5klXZJwk4vUt/NzeqAjB/UFbKqW29HQ=="], - "@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/claude-agent-sdk-linux-x64@0.3.292", "", { "os": "linux", "cpu": "x64" }, "sha512-dnMVyLxpg8mUzEqAtxhv+5oBxdiYjCLIBHLPFM4z7cuk+Se6SwgyHPRGipp8rOociJBS8yyB7QXJh+RO41y+Kg=="], + "@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/claude-agent-sdk-linux-x64@0.3.293", "", { "os": "linux", "cpu": "x64" }, "sha512-MtqXROSQiuqOCNXfC4k3/3DVfgTNLEdaT5jp/omaZeiPtnRtfCz2KTtBTVG4IwbEDFaKsqfzPsPFzN7X6avwkg=="], - "@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/claude-agent-sdk-linux-x64-musl@0.3.292", "", { "os": "linux", "cpu": "x64" }, "sha512-5XA1nW1/OAUBxaJNFmttfJov9CrqYanOqlmP6yvXWx+iSEWKICNv2ghnnipYEJXUeof6JjZlarS8IHaJol1trA=="], + "@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/claude-agent-sdk-linux-x64-musl@0.3.293", "", { "os": "linux", "cpu": "x64" }, "sha512-5N30l2Y17ZV9q0TGCMXtrkTleX+RVtUMoOL+48qQ7ZrKWGYYBtVDS59cIXDv+TAGqoyYVmklw0W2Sy4dA40BwQ=="], - "@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/claude-agent-sdk-win32-arm64@0.3.292", "", { "os": "win32", "cpu": "arm64" }, "sha512-feA6NlAVnbGBGgnJ6VkYldofuCwW5H6wt+6sWuLDVIasn013X3sWrCSS4awseN3tyey4/0UKG/+ElNATaZaN4w=="], + "@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/claude-agent-sdk-win32-arm64@0.3.293", "", { "os": "win32", "cpu": "arm64" }, "sha512-WvPf8cXna446bTx2U4WVQc5+iUgDn94ve8aauvWwcG8n9oa+1wNCKNGFxk8HvS7DQJhF8dfrCbcF068uNFqYNw=="], - "@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/claude-agent-sdk-win32-x64@0.3.292", "", { "os": "win32", "cpu": "x64" }, "sha512-hIXHmaaV1FIH7AVhw7PFX7TW13hPRGsSj/wP/Bio9N03sqbaOg6lLidKn4qC8xtvAlDTpC+6nGieLjjQQB7SwA=="], + "@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/claude-agent-sdk-win32-x64@0.3.293", "", { "os": "win32", "cpu": "x64" }, "sha512-SVaIDHtpCwM0r0m9jzue1U7yktIZ1eJhR1O3e0UCHYTJluaIXty5m6DzqhG4rjnEoNlEAl9rQLqPigS/R5+IiQ=="], "@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.124.0", "", { "dependencies": { "json-schema-to-ts": "^3.1.1", "standardwebhooks": "^1.0.0" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-cN5O8i9UVxHeOQAzj/XjshWXG8KiibJDw9OGpH2Z/eR3n/RBxdoLxDJOcfqAJWvjaMDFfHTBADU04hWRJVkDyA=="], @@ -1480,8 +1479,6 @@ "chromium-bidi": ["chromium-bidi@17.0.2", "", { "dependencies": { "mitt": "^3.0.1", "zod": "^3.24.1" }, "peerDependencies": { "devtools-protocol": "*" } }, "sha512-5v9GQFhTktFvotn/OFNJBmKLKRAb6n9r0bVCwf7sHgWc3/JryK0bj1nn93L3pHFrfgcsu6Be6EWsDi+1XHTGDg=="], - "claude-agent-sdk-research-292": ["@anthropic-ai/claude-agent-sdk@0.3.292", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.292", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.292", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.292", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.292", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.292", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.292", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.292", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.292" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-C5XI/19uArTg3jjgayN9CSQxJilRciBko007AdPmHXwQqbAzdUldaPUQtDp8Pm6QJg5Aw3jI1G1eIJOBrx4xKQ=="], - "cliui": ["cliui@9.0.1", "", { "dependencies": { "string-width": "^7.2.0", "strip-ansi": "^7.1.0", "wrap-ansi": "^9.0.0" } }, "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w=="], "clone": ["clone@2.1.2", "", {}, "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w=="], @@ -2578,22 +2575,6 @@ "@antfu/install-pkg/package-manager-detector": ["package-manager-detector@1.8.0", "", {}, "sha512-yQA4H19AmPEoMUeavPMDIe1higySl/gH/yaQrkT/s07Qp+7pp2hYz30N3z2l5BkjVkF9Ow6o0wjJamm2y7Sn0A=="], - "@anthropic-ai/claude-agent-sdk/@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/claude-agent-sdk-darwin-arm64@0.3.293", "", { "os": "darwin", "cpu": "arm64" }, "sha512-E2rwiiHr3LwYzBuTROVDpJkts4QmYCrW39ZIN1qixVSNQhSEiz5LjaKxzrwq0xgPgQDU0vd2fLMG1k72BgD24w=="], - - "@anthropic-ai/claude-agent-sdk/@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/claude-agent-sdk-darwin-x64@0.3.293", "", { "os": "darwin", "cpu": "x64" }, "sha512-UJD8kX1XDhMqs/0LLxD012h+S9U3Q8XPbRSNcnPQEMNAoEF+lh898xPbVnkUgPKl3jUOUyqYRwFRwDiUJD+GJg=="], - - "@anthropic-ai/claude-agent-sdk/@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/claude-agent-sdk-linux-arm64@0.3.293", "", { "os": "linux", "cpu": "arm64" }, "sha512-B3M5gw6pPH/ckMtrLtGg4ZY1adLVnPoXkEV+Ruu0j/gdFzwuLWR64Spa0RCsbo7BXVN6w5NTqkuZk+HBfsPUZA=="], - - "@anthropic-ai/claude-agent-sdk/@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/claude-agent-sdk-linux-arm64-musl@0.3.293", "", { "os": "linux", "cpu": "arm64" }, "sha512-l5Nfwox69bBMEccSQfPQFOq9hbSqQIMsi4H/UXaMSsqgnxunXuKEBXb5klXZJwk4vUt/NzeqAjB/UFbKqW29HQ=="], - - "@anthropic-ai/claude-agent-sdk/@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/claude-agent-sdk-linux-x64@0.3.293", "", { "os": "linux", "cpu": "x64" }, "sha512-MtqXROSQiuqOCNXfC4k3/3DVfgTNLEdaT5jp/omaZeiPtnRtfCz2KTtBTVG4IwbEDFaKsqfzPsPFzN7X6avwkg=="], - - "@anthropic-ai/claude-agent-sdk/@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/claude-agent-sdk-linux-x64-musl@0.3.293", "", { "os": "linux", "cpu": "x64" }, "sha512-5N30l2Y17ZV9q0TGCMXtrkTleX+RVtUMoOL+48qQ7ZrKWGYYBtVDS59cIXDv+TAGqoyYVmklw0W2Sy4dA40BwQ=="], - - "@anthropic-ai/claude-agent-sdk/@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/claude-agent-sdk-win32-arm64@0.3.293", "", { "os": "win32", "cpu": "arm64" }, "sha512-WvPf8cXna446bTx2U4WVQc5+iUgDn94ve8aauvWwcG8n9oa+1wNCKNGFxk8HvS7DQJhF8dfrCbcF068uNFqYNw=="], - - "@anthropic-ai/claude-agent-sdk/@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/claude-agent-sdk-win32-x64@0.3.293", "", { "os": "win32", "cpu": "x64" }, "sha512-SVaIDHtpCwM0r0m9jzue1U7yktIZ1eJhR1O3e0UCHYTJluaIXty5m6DzqhG4rjnEoNlEAl9rQLqPigS/R5+IiQ=="], - "@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1138.0", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/nested-clients": "^3.997.46", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-GpyAr0DD63YOEmYFM6Df+gJuIgC92MMTiBK4FTKfxii5MJ9ge20epR7LyroulscYlG89J+ZB2ivFDPjvfQhzdw=="], "@babel/code-frame/js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], diff --git a/docs/decisions/action-notifications.md b/docs/decisions/action-notifications.md index 13bc9840da..db9d9ce09a 100644 --- a/docs/decisions/action-notifications.md +++ b/docs/decisions/action-notifications.md @@ -197,9 +197,9 @@ Collection for a chat environment is not authenticated notification-zone binding or lifecycle freshness proof. Existing activity digest generation serializes its transaction -(`generateActivityDigest`, `packages/ui-server/src/activity/digest.ts:31-39`) +(`generateActivityDigest`, `packages/ui-server/src/activity/digest.ts:30-38`) and owns an activity-specific window/coverage marker -(`generateInTx`, `packages/ui-server/src/activity/digest.ts:41-101`). +(`generateInTx`, `packages/ui-server/src/activity/digest.ts:40-100`). Those mechanisms provide prior art; that global marker cannot represent client-context waiting episodes or discard older unreported decisions. diff --git a/docs/decisions/agent-observability.md b/docs/decisions/agent-observability.md index 301514ca72..370b46b6e9 100644 --- a/docs/decisions/agent-observability.md +++ b/docs/decisions/agent-observability.md @@ -139,7 +139,7 @@ interpretation layer added by this proposal. The existing generator reads per-run rollups, computes counts and costs, and selects notable failures (`generateInTx`, -`packages/ui-server/src/activity/digest.ts:41-102`). Those counts and the failure +`packages/ui-server/src/activity/digest.ts:40-101`). Those counts and the failure list do not justify the model cost and latency of an additional prose pass. It would also need factual validation to keep the summary faithful to the rollups, plus a fallback when the model is unavailable or returns unusable diff --git a/docs/decisions/answer-delivery.md b/docs/decisions/answer-delivery.md index 1d2a37918e..fad0ebb679 100644 --- a/docs/decisions/answer-delivery.md +++ b/docs/decisions/answer-delivery.md @@ -126,7 +126,7 @@ that fails leaves the card editable and sends nothing, because sending an answer that would not survive a reload breaks the promise the queued state makes. After a reconnect or a takeover, every held answer asks for its status first and is sent again only while the host reports it `pending` -(`function replay(entry`, `manager.ts:321-325`). +(`function replay(entry`, `manager.ts:319-323`). Admission against Queue A is decided, and its storage write committed, under one lock that every tab shares. The count and byte totals are read from what @@ -174,7 +174,7 @@ A host hello can arrive while startup is still reading the previously stored principal. The completed storage read is only a fallback: it cannot replace the newer host identity, even with an empty first-visit value. A read begun before logout or disposal cannot restore admission authority (`async function -restore`, `packages/ui-react/src/lib/answer-delivery/manager.ts:705-725`). Without +restore`, `packages/ui-react/src/lib/answer-delivery/manager.ts:703-723`). Without the check after the await, a real offline Submit could incorrectly say Not saved, or queue its answer under an older principal. diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 00077ecfc0..4d49c005ae 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -73,7 +73,7 @@ next to it. `@schlessera/brain-backend-claude` at `^0.3.241` (`"@anthropic-ai/claude-agent-sdk"`, `packages/ui-backend-claude/package.json:49`), resolved by this repo's - lockfile (`"@anthropic-ai/claude-agent-sdk": [`, `bun.lock:505`): 0.3.278 when + lockfile (`"@anthropic-ai/claude-agent-sdk": [`, `bun.lock:504`): 0.3.278 when this record was written, 0.3.280 from 0.37.0, 0.3.283 from 0.38.0. The binary at `CLAUDE_CODE_PATH` is whatever the host put there. @@ -87,13 +87,13 @@ than recalled: (`node_modules/@anthropic-ai/claude-agent-sdk/sdk.d.ts:1887-1889`). - The built-in executable is a real Claude Code release, shipped as per-platform optional dependencies pinned to the SDK's exact version - (`optionalDependencies`, `bun.lock:505`, eight + (`optionalDependencies`, `bun.lock:504`, eight `claude-agent-sdk--[-musl]@0.3.278` entries), each with an integrity hash in the lockfile - (`"@anthropic-ai/claude-agent-sdk/@anthropic-ai/claude-agent-sdk-linux-x64": [`, - `bun.lock:2589`). The public SDK's platform package is nested because the - private development-only hygiene research alias retains its original292 pair; - the public backend still resolves293. The SDK carries a manifest naming the release and a checksum + (`"@anthropic-ai/claude-agent-sdk-linux-x64": [`, + `bun.lock:514`). The platform packages are hoisted again now that the + development-only hygiene research alias and its 0.3.292 pair are gone + (#2509). The SDK carries a manifest naming the release and a checksum per platform (`node_modules/@anthropic-ai/claude-agent-sdk/manifest.json`: `"version": "2.1.278"`, `linux-x64` checksum `5c47359…`). - It is byte-identical to the standalone release. `sha256sum` of the SDK's diff --git a/docs/decisions/design-kit/sessions-and-drafts.md b/docs/decisions/design-kit/sessions-and-drafts.md index 247b54e042..d8250a7c3f 100644 --- a/docs/decisions/design-kit/sessions-and-drafts.md +++ b/docs/decisions/design-kit/sessions-and-drafts.md @@ -22,11 +22,20 @@ of the [six-part #943 design](https://github.com/schlessera/brain-kit/issues/943 (2026-10-04) with its four residual answers, R1–R4 (2026-10-05). Where those later rulings do not replace it, the supplied navigation and parallel-session designs still bind; §8 lists what carries over. The measured input is -[`docs/plans/navigation-recovery.md`](../../plans/navigation-recovery.md) +[`docs/plans/navigation-recovery.md`](https://github.com/schlessera/brain-kit/blob/5a0ce18fdcecf0a6c5b83487c865a3f73806d5d0/docs/plans/navigation-recovery.md) (#942). The row's adopted geometry is the [shared-row design](https://github.com/schlessera/brain-kit/issues/929#issuecomment-5998113323), which amends the #943 strip. +> **2026-11-02 — The measured input left `docs/plans/` ([#2511](https://github.com/schlessera/brain-kit/issues/2511)).** +> #942, #943, #964, #965, #910, #951 and #979 are closed, and the Sessions +> destination, host-backed drafts and latest-turn recovery are in source +> (`const destinations`, `packages/ui-react/src/components/layout/desktop-routes.ts`; +> `packages/ui-server/src/drafts/`). The report held measurements and +> follow-up ownership, not rulings; every ruling it fed is in this entry. Read +> it unchanged at the pinned link above. Its probes stay in the tree at +> `scripts/probes/navigation-recovery/`. + **What this amends.** D37 §1's destinations and New chat placement; D22's ≥1280 list pane and the space between transcript and composer; and the drawing of #93's New chat disc. It replaces the supplied tracker rules diff --git a/docs/decisions/design-kit/storage.md b/docs/decisions/design-kit/storage.md index f1fa704115..80952101f2 100644 --- a/docs/decisions/design-kit/storage.md +++ b/docs/decisions/design-kit/storage.md @@ -11,14 +11,28 @@ approval; it is a design, not evidence of a shipped pane or removal operation. The screenshots in the original brief illustrate the proposal; the rulings and layouts here control where the proposal differs. -The [accounting model](../../plans/storage-accounting.md) supplies ownership, -object identity, capacity scopes and coverage. The [lifecycle model](../../plans/storage-lifecycle.md) +The [accounting model](https://github.com/schlessera/brain-kit/blob/5a0ce18fdcecf0a6c5b83487c865a3f73806d5d0/docs/plans/storage-accounting.md) supplies ownership, +object identity, capacity scopes and coverage. The [lifecycle model](https://github.com/schlessera/brain-kit/blob/5a0ce18fdcecf0a6c5b83487c865a3f73806d5d0/docs/plans/storage-lifecycle.md) supplies action eligibility and recovery. Read both with the later [native storage decision](../native-brain-storage.md): immutable native checkpoints, writable output staging, turn temp and retained recovery objects have distinct owners and capacity. A lower-only deletion does not release writable-upper headroom. Neither discovery authorizes a new retention policy. +> **2026-11-02 — Both discoveries left `docs/plans/` ([#2511](https://github.com/schlessera/brain-kit/issues/2511)).** +> #1779, #1780, #1781 and #2013 are closed, and the inventory, owner +> maintenance and recoverable removal they informed are built (#2009 in #2017, +> #2010–#2013 in #2172). Their recommendations and constraints that +> still bind are in this entry, chiefly under +> [Maintenance and ongoing management](#maintenance-and-ongoing-management) and +> [Implementation boundaries and deferred capabilities](#implementation-boundaries-and-deferred-capabilities); +> the shipped command and HTTP shapes are in the integration contract +> (`docs/integration-contract/cli.md`, `docs/integration-contract/http.md`). +> Read the discoveries unchanged at the pinned links above. The accounting +> experiment moved to the +> [measurement archive](../measurement-archive.md#storage-design-experiments-2511); +> the lifecycle experiment is still `experiments/storage-lifecycle.ts`. + ### Placement and alternatives Storage is the eighth Settings pane, in **This brain**, immediately after diff --git a/docs/decisions/measurement-archive.md b/docs/decisions/measurement-archive.md index a46dc1e86d..2f75a2df46 100644 --- a/docs/decisions/measurement-archive.md +++ b/docs/decisions/measurement-archive.md @@ -192,6 +192,34 @@ a date. - **Measured source:** not recorded. **Introduced by:** `e8f94c6c1f1f`. - **Files:** [probe.py](https://github.com/schlessera/brain-kit/blob/48227b09076b350d70d9d20b8492ffcfb5b95771/scripts/policy-boundary-spike/probe.py), [worker.ts](https://github.com/schlessera/brain-kit/blob/48227b09076b350d70d9d20b8492ffcfb5b95771/scripts/policy-boundary-spike/worker.ts) +### Archived later + +> **2026-11-02 — Files removed from `main` after the original archive commit.** +> Each was added to `archive/measurements` as a new commit on top of the +> branch, at its original path, byte for byte. The 94-file count above and the +> branch's top-level `manifest.json` and `SHA256SUMS` describe only the original +> commit; each later bundle carries its own manifest and checksums. + +#### Unreferenced CI selection replays (#2512) + +- **Path:** `docs/process/evidence/independent-test-replay.json`, `docs/process/evidence/browser-input-closure-replay.json` +- **Role:** historical output (100-PR replays of independent Bun test-leaf selection and of browser proof input discovery, both at the 2026-10-16 cutoff). +- **Consumers before removal:** none. No document, test, script or CI step named either file; one note inside `docs/process/evidence/test-wait-review-partition.json` mentions `independent-test-replay.json` in passing, which is a pointer, not a consumer. +- **Disposition:** archived in commit [`c24a848238724b797386fdd9e9dbdbf2bb254d59`](https://github.com/schlessera/brain-kit/tree/c24a848238724b797386fdd9e9dbdbf2bb254d59/scripts/measurements/retired-docs-2542-2026-11-02), copied from main commit `5a0ce18fdcecf0a6c5b83487c865a3f73806d5d0`. +- **Measured source:** `626a03af4a9db064751230a84732755b8afa961e` (browser-input-closure-replay.json sourceBase); not recorded for independent-test-replay.json. **Introduced by:** `d6b527290fe2` (#2147), `b6d7391de6ba` (#2152). +- **SHA-256:** `4b5cd6bd74882b34893b958cca88ff90c5d1c3e60a28115712e5966062b1a496` (independent-test-replay.json), `6cf33fd312f82c3a0b4ec43274a2d714b45995720a40363beae62e662b35adaf` (browser-input-closure-replay.json). +- **Files:** [independent-test-replay.json](https://github.com/schlessera/brain-kit/blob/c24a848238724b797386fdd9e9dbdbf2bb254d59/docs/process/evidence/independent-test-replay.json), [browser-input-closure-replay.json](https://github.com/schlessera/brain-kit/blob/c24a848238724b797386fdd9e9dbdbf2bb254d59/docs/process/evidence/browser-input-closure-replay.json) + +#### Storage design experiments (#2511) + +- **Path:** `docs/plans/storage-accounting-experiment.py`, `docs/plans/storage-growth-experiment.ts` +- **Role:** finished experiments (the #1780 fixture inventory prototype and the #2014 offline rule-qualification traces). +- **Consumers before removal:** run only from `docs/plans/storage-accounting.md` and `docs/plans/storage-growth.md`, which were retired in the same change. No test, script or CI step runs either file, and neither sits under a TypeScript or lint root. The shipped storage code carries its own tests. +- **Disposition:** archived in commit [`c24a848238724b797386fdd9e9dbdbf2bb254d59`](https://github.com/schlessera/brain-kit/tree/c24a848238724b797386fdd9e9dbdbf2bb254d59/scripts/measurements/retired-docs-2542-2026-11-02), copied from main commit `5a0ce18fdcecf0a6c5b83487c865a3f73806d5d0`. The plans that record their conditions and results stay readable at that main commit. +- **Measured source:** not recorded. **Introduced by:** `1ed6e3d431fa` (#1785), `65ed23dc942e` (#2020). +- **SHA-256:** `e614e2887bbc470df39830d8432414ffced2d8559ad9b21b781be799b8b48bdf` (storage-accounting-experiment.py), `409624b52f10098f110f8d8e047679099dc9cfe2c9e4effa3cb1abe0007e0050` (storage-growth-experiment.ts). +- **Files:** [storage-accounting-experiment.py](https://github.com/schlessera/brain-kit/blob/c24a848238724b797386fdd9e9dbdbf2bb254d59/docs/plans/storage-accounting-experiment.py), [storage-growth-experiment.ts](https://github.com/schlessera/brain-kit/blob/c24a848238724b797386fdd9e9dbdbf2bb254d59/docs/plans/storage-growth-experiment.ts) + ### Retained in place (241 files) > **2026-10-10 — #838 spike harnesses removed.** The maintainer ruled the @@ -275,6 +303,21 @@ lists 240 of them, and the triage answers file under suggestions documents and one to the site-model spike's README. It links them at the pinned commit `c577320cb4b9e3224a84a374e975ef5910db1edd`, which still contains them, so those links stay valid and were not changed. +- Three root scripts lost their last consumer once their driving issues closed, + and were removed from `main` by + [#2510](https://github.com/schlessera/brain-kit/issues/2510). They are + harnesses, not measurement output, so they were not added to the archive + branch. Main commit `a62db8f27a22fd2df744308e9b1ee12bc50f3da2` is the last + to contain all four files; read them there: + - `scripts/measure-graph-routes.ts` timed graph reads for + [#1030](https://github.com/schlessera/brain-kit/issues/1030), after #697 + moved them onto `./queries`. + - `scripts/replay-ci-consumers.ts` replayed root-proof consumer selection + for #2149 (closing #2123). It read a 100-PR snapshot that was never + committed. + - `scripts/generated-inputs.ts` and its test `tests/generated-inputs.test.ts` + came from #2178 (refs #2126 and #2190). It was library code with no + production caller, so only its own test ran it. ## Pointers moved to the archive @@ -298,6 +341,12 @@ git restore --source 48227b09076b350d70d9d20b8492ffcfb5b95771 -- Each record keeps its measurements, failures and limits. Only the location of the evidence changed. +> **2026-11-02 — `docs/plans/policy-write-boundary.md` retired ([#2511](https://github.com/schlessera/brain-kit/issues/2511)).** +> The plan left `main` once its work shipped. Read it, with its links to this +> archive, at main commit +> [`5a0ce18f`](https://github.com/schlessera/brain-kit/blob/5a0ce18fdcecf0a6c5b83487c865a3f73806d5d0/docs/plans/policy-write-boundary.md); +> [the all-writer decision](policy-write-boundary.md) links it there. + ## Keeping new output out `.gitignore` ignores the archived paths and their dated siblings: diff --git a/docs/decisions/policy-write-boundary.md b/docs/decisions/policy-write-boundary.md index 37a558ead8..a4b02992fa 100644 --- a/docs/decisions/policy-write-boundary.md +++ b/docs/decisions/policy-write-boundary.md @@ -9,11 +9,21 @@ The maintainer's three 2026-10-02 rulings on These choices bind implementation. They do not establish production containment, enable autonomous execution or make a release commitment. The -[finite investigation](../plans/policy-write-boundary.md) remains evidence about +[finite investigation](https://github.com/schlessera/brain-kit/blob/5a0ce18fdcecf0a6c5b83487c865a3f73806d5d0/docs/plans/policy-write-boundary.md) remains evidence about its measured fixture. The [async collaboration decision](async-collaboration.md) and [voice decision](voice-permission.md#containment-shared-with-51-deliberately-not-identical) continue to bind authority and tool membership. +> **2026-11-02 — The investigation left `docs/plans/` ([#2511](https://github.com/schlessera/brain-kit/issues/2511)).** +> #672, #674 and #676 are closed, and the workers and validated application +> route this record selects are built, so the investigation is no longer a +> plan. Every ruling it asked for is recorded below, and its six measured +> escapes are retained as proof obligations in +> [Evidence the implementation still owes](#evidence-the-implementation-still-owes). +> Its measurements, mutation receipt and recorded environment are unchanged at +> the pinned link above; the spike it ran is on the +> [measurement archive](measurement-archive.md#policy-write-boundary-spike-750). + ## Every writer enters through the boundary Both first-party runtimes run in isolated workers, confined **before** SDK, diff --git a/docs/decisions/storage-guidance.md b/docs/decisions/storage-guidance.md index 9dc3799359..23ab3c0cf0 100644 --- a/docs/decisions/storage-guidance.md +++ b/docs/decisions/storage-guidance.md @@ -4,9 +4,17 @@ The maintainer approved the [reconciled bundle](https://github.com/schlessera/brain-kit/issues/2014#issuecomment-6212070681) after comparing the layered proposal in #2044 with the concurrent policy review. -The [design](../plans/storage-growth.md) specifies its encoding, qualification, +The [design](https://github.com/schlessera/brain-kit/blob/5a0ce18fdcecf0a6c5b83487c865a3f73806d5d0/docs/plans/storage-growth.md) specifies its encoding, qualification, recovery and delivery rules. This decision records policy, not runtime delivery. +> **2026-11-02 — The design left `docs/plans/` ([#2511](https://github.com/schlessera/brain-kit/issues/2511)).** +> #2058 and #2059 delivered it in #2172. The shipped history and guidance +> shapes are in the integration contract +> ([Storage history and pressure guidance](../integration-contract/http.md#storage-history-and-pressure-guidance-additive-2058)); +> the policy stays here. Read the design unchanged at the pinned link above. +> Its offline trace experiment moved to the +> [measurement archive](measurement-archive.md#storage-design-experiments-2511). + Keep 64 six-hour, 90 daily and 32 weekly endpoints: 186 records, four capacity scopes and a 256 KiB serialized history ceiling. The same observations update all three tiers without extra scans or catch-up work. Actual timestamps, gaps and diff --git a/docs/plans/README.md b/docs/plans/README.md index 0088f6700a..60fdd7ae24 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -10,21 +10,16 @@ judge any part of it. Once it ships, the plan stops being a plan: the durable half moves to [`../decisions/`](../decisions/README.md) and the rest is deleted, because the code has become the better answer to "what does this do". -| Plan | Design | -| --- | --- | -| [async-collaboration.md](async-collaboration.md) | The cross-package containment and collaboration design. | -| [async-collaboration-requirements.md](async-collaboration-requirements.md) | The requirements it came from. | -| [policy-write-boundary.md](policy-write-boundary.md) | U10's measured filesystem boundaries, escape cases and worker/effect-route ruling required before implementation. | -| [index-query-api.md](index-query-api.md) | Consumer migration using supported query results, approved optional-peer/root-bound context boundaries, reader inventory and safe SQL retirement. | -| [navigation-recovery.md](navigation-recovery.md) | Measured navigation reach, cold-session evidence and draft races informing the tracker design. | -| [storage-accounting.md](storage-accounting.md) | Proposed local storage ownership, deduplicated capacity and bounded measurement model, with synthetic evidence. | -| [voice-conversation.md](voice-conversation.md) | Proposed turn-taking, screen and interruption model; requirements for the later speech-architecture ruling. | -| [eleven-realtime-evaluation.md](eleven-realtime-evaluation.md) | Documentation-stage evaluation of Eleven Realtime v1 Max as a third live-conversation engine, the API choice, the unresolved nonblocking-result question and the prepared live probe. | -| [storage-growth.md](storage-growth.md) | Proposed bounded aggregate history, comparable growth and capacity-specific guidance, with explicit policy choices. | -| [storage-lifecycle.md](storage-lifecycle.md) | Storage cleanup eligibility, recovery boundaries and synthetic byte-lifecycle evidence for the storage design. | -| [host-owned-web-search.md](host-owned-web-search.md) | Pinned MCP/full-extension comparison, offline worker prototypes and authority boundaries for executor selection. | -| [module-renderers.md](module-renderers.md) | The content-renderer seam, Mermaid on it, the diagram spec, computed geometry, the brain-kit skin, surface and print matrix, ordering, and the upstream sync procedure. | -| [chat-history-deletion.md](chat-history-deletion.md) | Approved local deletion policy with unbuilt lifecycle design, retained-record boundaries and proof obligations. | +| Plan | Design | Open work | +| --- | --- | --- | +| [async-collaboration.md](async-collaboration.md) | The cross-package containment and collaboration design. | [#51](https://github.com/schlessera/brain-kit/issues/51) | +| [async-collaboration-requirements.md](async-collaboration-requirements.md) | The requirements it came from. | [#51](https://github.com/schlessera/brain-kit/issues/51) | +| [index-query-api.md](index-query-api.md) | Consumer migration using supported query results, approved optional-peer/root-bound context boundaries, reader inventory and safe SQL retirement. | [#701](https://github.com/schlessera/brain-kit/issues/701) | +| [voice-conversation.md](voice-conversation.md) | Proposed turn-taking, screen and interruption model; requirements for the later speech-architecture ruling. | [#54](https://github.com/schlessera/brain-kit/issues/54) | +| [eleven-realtime-evaluation.md](eleven-realtime-evaluation.md) | Documentation-stage evaluation of Eleven Realtime v1 Max as a third live-conversation engine, the API choice, the unresolved nonblocking-result question and the prepared live probe. | [#3100](https://github.com/schlessera/brain-kit/issues/3100) | +| [host-owned-web-search.md](host-owned-web-search.md) | Pinned MCP/full-extension comparison, offline worker prototypes and authority boundaries for executor selection. | [#1863](https://github.com/schlessera/brain-kit/issues/1863) | +| [module-renderers.md](module-renderers.md) | The content-renderer seam, Mermaid on it, the diagram spec, computed geometry, the brain-kit skin, surface and print matrix, ordering, and the upstream sync procedure. | [#2079](https://github.com/schlessera/brain-kit/issues/2079) | +| [chat-history-deletion.md](chat-history-deletion.md) | Approved local deletion policy with unbuilt lifecycle design, retained-record boundaries and proof obligations. | [#3234](https://github.com/schlessera/brain-kit/issues/3234) | ## What does not live here diff --git a/docs/plans/navigation-recovery.md b/docs/plans/navigation-recovery.md deleted file mode 100644 index 92ce84b935..0000000000 --- a/docs/plans/navigation-recovery.md +++ /dev/null @@ -1,416 +0,0 @@ -# Navigation and background-session recovery evidence - -Discovery for [#942](https://github.com/schlessera/brain-kit/issues/942), supplying -[#943](https://github.com/schlessera/brain-kit/issues/943) under -[#929](https://github.com/schlessera/brain-kit/issues/929). This is measured input -to the design, not a navigation amendment or an implemented recovery contract. -The [navigation ruling](https://github.com/schlessera/brain-kit/issues/929#issuecomment-5973564827) -and later [parallel-session ruling](https://github.com/schlessera/brain-kit/issues/929#issuecomment-5973572791) -provide the projected placements. The latter takes precedence. The later -maintainer decisions in [#929](https://github.com/schlessera/brain-kit/issues/929) -select authoritative host recovery A and per-session host-backed draft storage C. -They supersede the earlier discard-confirm proposal; the measurements below -describe incumbent behavior, and the selected contracts still require implementation. -The adopted design built on this evidence is -[D52 in the design-kit record](../decisions/design-kit/sessions-and-drafts.md#2026-10-06--d52-sessions-is-a-destination-work-left-running-is-tracked-until-seen-and-every-session-keeps-its-own-draft-943). - -## Evidence boundary and reproduction - -Package source measured: `94c3719608d68a7ccbe99d8ca6a7b0028b5c357d`. -The checked-in probes under `scripts/probes/navigation-recovery/` use public -package exports, built styles, the shared Odysseus raft fixture and the real -`createApp`/WebSocket/SQLite paths with a scripted `AgentBackend`. No model, -provider credential, private application, deployed host or usage telemetry is -involved. Sync and briefing endpoints return fixture SSE rather than performing -repository sync or paid generation. Search, stats and session/history/activity -routes use the real disposable fixture host. Opening Add is measured; submitting -it is not part of this probe. - -The consumer composition mounts ChatPage, ActivityPage or GraphPage according -to `activeView`, inside AppShell/BrainUiProvider. It deliberately holds a root -connection lease across those mounts. Consequently, composer unmount observations -apply to this composition; AppShell accepts children and does not prescribe a -consumer's page-retention policy. Files and Settings are currently owned by -ChatPage. Visiting them from Actions/Graph needs a Chat activation in this -composition; changing a store flag alone is not proof of a visible destination. - -Run from an installed checkout with built packages and real Chromium: - -```sh -bun run build -bun scripts/probes/navigation-recovery/store.ts /tmp/brain-navigation-recovery -bun scripts/probes/navigation-recovery/navigation.ts /tmp/brain-navigation-recovery -bun scripts/probes/navigation-recovery/paths.ts /tmp/brain-navigation-recovery -bun scripts/probes/navigation-recovery/live.ts /tmp/brain-navigation-recovery -bun scripts/probes/navigation-recovery/away.ts /tmp/brain-navigation-recovery -bun scripts/probes/navigation-recovery/terminal.ts /tmp/brain-navigation-recovery -bun scripts/probes/navigation-recovery/races.ts /tmp/brain-navigation-recovery -``` - -The optional last argument is the output directory. Each phase writes its own -JSON receipt; navigation also writes screenshots. Output records the checkout -SHA and browser version. The browser permits only its loopback fixture origin; -external attempts are counted and blocked. No remote fonts are loaded. Viewports -are CSS pixels with a viewport meta tag, height 900, reduced motion, fine versus -coarse pointer, and dark versus light theme. The six widths are 320, 390, 480, -900, 1280 and 1440. Keyboard injection into a coarse-pointer context proves the -registered keyboard route, not a physical phone keyboard or operating-system -soft-keyboard geometry. - -Receipts: 24 layout cases, 84 act paths plus 60 destination paths, 37 handler/store -scenarios, 17 draft paths, 20 live-host observations, two offline-completion -observations, two terminal/pruning observations and four delayed-frame races. -Inputs include nonempty streams, one pending approval, all four pending question -kinds, real 64×64 image attachments and nonempty draft text. Chromium 140.0.7339.127 reported no page errors or attempted external requests. A zero-message or zero-question input is not used as proof of retention. -The handler-only matrix calls the actual root/demux but is not a browser or host -restart. JSON observations are evidence, not a new application wire format. - -Existing controls: 20 tests/65 assertions across session-demux and root-isolation; -85 tests/379 assertions across parallel sessions, history, failure replay, -approval persistence, list/rank/form, revocation and multi-backend session routes; -33 tests/169 assertions across turn correlation, Activity routes and boot sweep. -The last group verifies pruned rollup resolution, unknown-run 404 and orphan -interruption. These are existing behavioral tests, not new implementation guards; -no fix or failing-first mutation is claimed by this documentation spike. - -## Destinations, acts and frequency provenance - -S means session-level, D daily, O occasional. These classes come from the -maintainer's supplied preferences, not observed counts. Search's S is provisional; -Graph's O includes the explicit preference that it is never used. No quantitative -frequency distribution was collected or inferred. - -| Destination | Current rail / phone | Projected rail / phone | Availability and effect | Class | -| --- | --- | --- | --- | --- | -| Chat | slot 1 / slot 1 | slot 1 / slot 1 | Local view change; no turn dispatch | S preference | -| Sessions | palette / More | slot 2 / slot 2 | Opens session selection; history reads on selection; no turn dispatch | S preference | -| Actions | slot 2 / slot 2 | slot 3 / slot 3 | Activity/decision destination; its own actions retain their authority checks | No measured class | -| Files | slot 3 / slot 3 | slot 4 / slot 4 | Opens file browser; reads are distinct from edits | O preference | -| Graph | slot 4 / slot 4 | palette / More | Opens graph; graph edits are separate actions | O preference | -| Settings | slot 5 / More | slot 5 / More | Opens settings; saving configuration is separate | No measured class | - -Sessions is currently one of the palette's seven acts, and becomes a destination -in the ruling. This is one command with two inventory roles, not an eighth act. - -| Act | Current visible homes | Projected homes | Availability and actual effect | Class | -| --- | --- | --- | --- | --- | -| New chat | occupied Chat disc, Sessions New conversation, desktop palette | occupied Chat below 1280; Sessions pane at ≥1280; palette/selection | Local transcript selection resets; no cancel/send. Current local composer is retained | S preference | -| Sessions | desktop palette; phone More | destination; wide pane | Opens history list; selecting replays history, does not restart the agent | S preference | -| Search | empty welcome, slash, desktop palette | both rails; occupied phone disc; welcome | Opening remains allowed during streaming/socket loss. REST search still requires a reachable authorized host. No model dispatch or write | S provisional preference | -| Add a note | slash, desktop palette | both rails; welcome; phone More | Opening has no write, including during streaming/socket loss. Submit writes/indexes and retains its own errors/authority | D preference | -| Daily briefing | welcome, slash, More, desktop palette | expanded rail; welcome; More; palette on collapsed rail | Handler requires connected/quiet active buffer; opening starts its streaming job. Paid-generation possibility must keep `spends` visible | D preference | -| Sync | slash, More, desktop palette | More and palette | Handler requires connected/quiet active buffer; opening starts repository sync. Keep `sync` visible when unavailable | O preference | -| Brain statistics | welcome, slash, More, desktop palette | More/palette | Quiet active buffer; REST data plus local software identity, no inference. Adds a local exchange and can persist it to the host; no Markdown write | O preference | - -The expanded rail currently contains no dedicated act rows. The desktop palette -has 12 commands: five destinations and seven acts in Jump to / Ask / Run groups. -The five slash commands are sync/search/whatsup/add/stats; slash provides neither -New chat nor Sessions. Current More has Settings/Sessions/Sync/briefing/stats, -without Search/Add. Current welcome has briefing/Search/stats, without Add. - -Opening a Search/Add panel is not evidence of executing its operation. Conversely, -Sync/briefing opening starts a job; the harness substitutes those two job responses -and therefore makes no claim about real job success or cost. - -## Browser reach and activation counts - -A count is an activation of a control, including opening the palette or More; -setup/reset and typing a slash query are excluded. Slash paths therefore include -an explicit typing prerequisite and are not equivalent to one visible tap. -Each counted route was executed without forced clicks. Panel dismissal counts. - -| CSS width | Visible primary controls | Observed target dimensions | ⌘K cap click/tap | Keyboard palette | -| --- | --- | --- | --- | --- | -| 320, 390 | Chat/Actions/Files/Graph/More | Tabs: 48.06–59.16 wide, 50.5 high | No cap | Hidden, including after modifier-K | -| 480 | Collapsed five-destination rail | Every destination 43×36 | 0 palette openings | 12 commands | -| 900, 1280, 1440 | Expanded five-destination rail | Every destination 183×36 | 0 palette openings | 12 commands | - -Both themes and pointer modes gave the same control geometry. Fine pointers -print chords; coarse pointers omit printed destination chords but the injected -keyboard still opens the desktop palette. The passive cap's glyph box is -23.40625×17.5, not a button. Its position is x=17.796875 at 480, x=12 at expanded -widths, y=866.5. The occupied New chat target is 44×44 at x=`width−60`, y=11 at all -six widths. Welcome Search opened the Search panel in every layout case. -The More dialog wrapper has zero height because its docked sheet child is -absolutely positioned; measuring the child/rows proves visibility. Treating the -wrapper's `isVisible()` as proof that the sheet failed to open was a harness -error, corrected before recording the matrix. - -Current observed act paths at 390 (coarse), from the six entry states: - -| Entry | New chat | Sessions | Search | Add | Briefing | Sync | Stats | -| --- | --- | --- | --- | --- | --- | --- | --- | -| Empty Chat | 3: More → Sessions → New conversation | 2 | 1: welcome | 1 + slash typing | 2 via More | 2 | 2 | -| Occupied Chat | 1: disc | 2 | 1 + slash typing | 1 + slash typing | 2 | 2 | 2 | -| Actions | 2: Chat → disc | 2 | 2 + slash typing | 2 + slash typing | 2 | 2 | 2 | -| Files open over Chat | 2: close → disc | 3 | 2 + slash typing | 2 + slash typing | 3 | 3 | 3 | -| Graph | 2: Chat → disc | 2 | 2 + slash typing | 2 + slash typing | 2 | 2 | 2 | -| Settings open over Chat | 2: close → disc | 3 | 2 + slash typing | 2 + slash typing | 3 | 3 | 3 | - -At 900, modifier-K plus the act row takes two activations from all six states; -`inChat` closes the other panels through the UI view setter. The occupied Chat -disc separately takes one. These keyboard measurements do not establish a -pointer-only desktop route: clicking the cap never opens anything. Welcome or -slash alternatives require Chat/composer access. Sync/briefing/stats cannot -execute merely because a visually present row was clicked when the handler's -availability guard refuses it. - -Current destination paths at 390: Chat/Actions/Graph take one activation from -uncovered pages; Files takes one from Chat and two from Actions/Graph in this -composition; Settings takes More plus its row, with an extra Chat activation -from Actions/Graph. Dismissing an open Files/Settings drawer adds one. At 900, -rail Chat/Actions/Graph takes one; Files/Settings takes one over Chat, or Chat -then the destination from Actions/Graph. These distinctions are recorded in -`paths.json`, including the resulting UI state, not inferred from labels. - -Projected counts below are source/ruling projections, not runtime measurements: - -| Width/view | Search | Add | Briefing | Sessions | New chat | Rare commands | -| --- | --- | --- | --- | --- | --- | --- | -| 320/390 occupied Chat | 1 disc | 2 via More | 2 via More | 1 destination | 1 disc | 2 via More | -| 320/390 empty Chat | 1 welcome | 1 welcome | 1 welcome | 1 destination | Selection → New conversation; a reset of an already empty view needs no act | 2 via More | -| 320/390 Actions/Graph | Chat → Search, 2 | More → Add, 2 | More → briefing, 2 | 1 destination | Chat → disc or Sessions → New conversation, 2 | 2 via More | -| 480 collapsed rail | 1 rail | 1 rail | 2 visible palette | 1 destination | 1 occupied Chat; selection needed from other views | 2 visible palette | -| 900 expanded rail | 1 rail | 1 rail | 1 rail | 1 destination | 1 occupied Chat; selection needed from other views | 2 visible palette | -| 1280/1440 Chat | 1 rail | 1 rail | 1 rail | Visible Sessions pane | 1 pane action | 2 visible palette | - -Open-panel dismissal, already active Sessions behavior, New chat from other -views at ≥1280 and focus/selection outcomes need the exact table in #943. -The report does not assume that a hidden or covered control fulfills reach. -The later ruling's two-activation phone daily acts and collapsed briefing are -settled exceptions, not grounds for adding unspecified controls. - -## Session and run recovery matrix - -The 36 primary store cases cross running, queued, approval, question, list, -rank, form, success and failure with A→B, New chat, twelve idle buffers and a -fresh root. The 37th verifies nonempty background A completion leaves B untouched. - -| Transition | Actual evidence | Consequence | -| --- | --- | --- | -| A→B / New chat | Running A and all pending cards remain in its in-memory buffer; terminal success/failure remain too. Live backend-start count does not change | Navigation does not abort or redispatch work | -| Twelve idle buffers | Six real live sessions, including approval and all four ask kinds, survive; idle buffers evict down to eight. Handler-only queued/terminal A can evict while queued runStates remains | Buffer presence and badge presence are different facts; MAX_BUFFERS is not a tracker retention policy | -| Fresh root without a connection | Stored selected ID survives with a stable prefix; transcripts/runStates/cards do not | Local storage currently holds resume identity, not history or a pending-card snapshot | -| Same-root reconnect, six open turns | Host retains and resends all pending kinds; existing question buffers retain cards | Warm reconnect is stronger than cold reload, but history replacement can overwrite live content | -| Fresh root / reload, six open turns | Only selected running session history materializes; other pending frames leave run badges but no cards because their buffers do not exist | Multiple-open-turn reconnect does not reconstruct every background transcript | -| Background session_resume | History materializes without changing selected running transcript; backend starts remain 6 before/after. It does not resend interactive requests | Replaying history is not restarting work, nor complete pending-request recovery | -| Reconnect after background histories | Question/list/rank/form cards return. Approval still does not appear when replay ends in a user-only message | Approval rendering needs an assistant target; it cannot rely on a later delta existing | -| Success/failure reload | Finished selected session replays two nonempty history messages; no new turn starts | Successful replay does not by itself correlate every historical message to its original turn | -| A succeeds/B fails while socket is closed, C still running | Activity records success/error; warm client can retain stale A/B running badges. Explicit background replay clears their run state without selecting them or starting a turn | Missed terminal frames require authoritative per-turn reconciliation | -| Cancel pending approval | Host Activity run ends cancelled, distinctly from error; client badges can remain stale after interactive cleanup | A badge is not terminal proof; cancelled must not be guessed to mean succeeded/failed | -| Missing backend history | Scoped SESSION_LOAD_ERROR; selected transcript preserved | Show unavailable/unknown with recovery action; do not fabricate empty successful history | -| Pruned Activity detail | Actual fixture REST returns 200, detailPruned=true and terminal rollup; never-existing run returns 404 | Pruning is not deletion or an unknown outcome | - -The scripted backend's partial running history deliberately ends in a user row. -This is a valid `getHistory` result and exposes the approval target dependency; -it is not a claim that a particular live provider always persists that shape. -All four question kinds were nonempty before transition. The existing -[#910](https://github.com/schlessera/brain-kit/issues/910) already owns question -identity/deduplication, post-resume redelivery and honest submitted-answer -recovery. Its approved policies are not reopened here. Tool approval recovery is -outside its scope and needs separate scoping with the tracker prerequisites. - -The browser fixture uses ambient loopback authorization, not a browser login -claim. The host's real revocation tests establish authorization leases, pending -reply refusal after revocation and no history emission after async revocation. -The API auth guard covers session and Activity routes. Session IDs and turn IDs -are correlation, never grants. session_resume rechecks connection authorization -after asynchronous history/replay waits. Rehydration must remain read-only and -must not reply to questions/approvals, create a turn or restore revoked authority. - -A root recreation is not a host process restart. Host pending interactions and -queued follow-ups live in coordinator maps. Boot-sweep tests prove that persisted -orphan Activity roots become interrupted after reopening the database, not that -pending backend execution or interactive prompts resume. No host restart or -browser reload should claim to resurrect those maps. - -## Terminal and seen-turn proof - -The real host probe observes a turn's session_info `turnId` equal to Activity's -`runId`. The same ID progresses from live (outcome/endedAt null) to terminal -success. A second request updates catalog lastActiveAt and creates a different -live run with null outcome/endedAt while the old success remains in history. -A queued follow-up also leaves the earlier live Activity root in place while the -client session badge becomes queued. Queue acceptance is not terminal success, -and its requestId is not yet a new executing turnId. - -Thus `lastActiveAt > leftAt`, a missing runStates entry, history existence, -replay-generated message IDs and lastTouched cannot prove latest-turn completion -or visibility. Both catalog stub and result persistence update lastActiveAt. -Activity already provides terminal identity/outcome/end time for a known run, -including after detail pruning. It does not prove which accepted queued request -is latest, that successful history contains that turn, or that it was on screen. - -Recommended minimal truthful strategy: - -1. Persist root-scoped tracker identity and known request/turn IDs, never - credentials, transcripts or a global unpartitioned `brain-trackers` key. - A default root gets a random prefix; an embedder needs an explicit stable - prefix for reload continuity. Changing principal must remove replay authority. -2. Use a current authorized pending request for **needs you**; a current queue - entry for **queued**; a live matching Activity turn for **running**. Use a - matching terminal rollup for **done** or **failed**, with its actual endedAt. - A known old success cannot hide a newer queued/running/unknown request. -3. Preserve **unknown/unavailable** when the latest accepted identity, authorized - pending state or replay linkage is unproved. Missing Activity support is - unknown, not done. Existing failure taxonomy includes error/timeout/interrupted; - cancelled and denied are user dispositions. Revocation is an authority event, - not an additional Activity terminal outcome: work can continue after it. -4. Clear a tracker only after the recovered latest turn is rendered at the - adopted foreground/viewport position. Guard that observation with the exact - identity so a newer request cannot be erased by an older visibility callback. - Merely selecting a session or reaching the bottom of an unrelated replay - does not establish this proof. - -For full cold latest-turn semantics, selected recovery A requires executable -identity proof while retaining honest unknown states when evidence is absent. -#943 supplies the exact design and durable amendment; #964 implements the selected read-only -`GET /api/sessions/:id/recovery` envelope with: - -```ts -{ - sessionId: string; - backendId: string | null; - revision: number; // host-owned per-session accepted-work ordering - latest: { - requestId: string | null; - turnId: string | null; // absent/null before queued work dispatches - state: "queued" | "running" | "terminal" | "unknown"; - outcome: ActivitySpanOutcome | null; - startedAt: number | null; - endedAt: number | null; - }; - pending: Array<{ - kind: "approval" | "ask_user" | "ask_user_list" | "ask_user_rank" | "ask_user_form"; - requestId: string; - turnId: string; - }>; -} -``` - -This is selected future scope under recovery A, not an existing endpoint. Latest/revision provenance must be -host acceptance plus the coordinator and durable catalog/Activity records; -backend mtime is insufficient. Unknown remains explicit after lost queue state -or uncorrelated imported history. Successful `session_history` messages need an -optional host-proven `turnId` (or an equivalent replay boundary) before a cold -viewport can claim that turn seen. Do not manufacture linkage from message count, -content equality or timestamp ordering. Missing evidence omits linkage. - -Authorization must cover the whole envelope and every pending identity; denial -must not disclose protected work. Recheck leases after asynchronous reads and -retain interactive principal/session/turn binding. The endpoint grants no action. -A compatible host advertises optional recovery support; unsupported peers keep -unknown state. New endpoint/optional history fields/capability require the SDK -schemas, HTTP reference, same-commit integration contract, CONTRACT: commit and -minor changeset. No such machine surface changes in this evidence PR. - -## Draft measurements and design input - -The ordinary draft cases run at 390/coarse and 900/fine; each starts with `Unsent raft plan` and one valid image. - -| Path | Text / image after navigation | Transcript result | -| --- | --- | --- | -| New chat disc | Preserved / 1 | Active session null | -| Sessions New conversation | Preserved / 1 | Active session null | -| Palette New chat | Preserved / 1 | Active session null | -| Drawer A→B selection, including background row | Preserved / 1 | B selected and history replayed | -| Files or Settings and back | Preserved / 1 | A remains selected | -| Actions or Graph and back | Empty / 0 | A's store survives; this composition remounts Composer | - -The store's clearMessages does not clear Composer's useState input/images and -does not clear pendingDraftId. Current New chat therefore does not discard an -ordinary unsent local draft, while session selection can carry its text into B. -The later maintainer choice replaces discard confirmation with a separate draft -per session: New chat saves A and opens empty; returning to A restores its text -and attachments. #943 supplies exact restore/delete/focus behavior, #951 owns -composer/send correlation, and #979 owns selected authenticated host storage C -with revision/idempotency, durable attachment bytes and cross-device conflict handling. -Preserved content must not be labelled lost or described as saved before acceptance. - -The delayed-frame probe holds actual host frames after a first Composer send: - -| Race | Observed result | -| --- | --- | -| Edit a newer draft before acceptance | Newer text remains; submitted image is removed; matching session announcement binds the first turn | -| New chat before acceptance | Newer text remains, old submitted image is consumed on receipt; new view remains unbound but pendingDraftId remains stale | -| New chat, then local stats creates a draft | Old matching announcement adopts the recreated stats draft and selects the old session, undoing New chat; newer text remains | -| Attempt another send while acknowledgement is held | Pending-send guard prevents a second dispatch; it is not evidence of two simultaneous first sends | - -The selected per-session draft lifecycle must coordinate local input lifetime, -accepted versus unconfirmed send ownership, correlation invalidation and receipt consumption. Preserve an -unknown send for review rather than silently resending it. A background result -cannot own a new draft. Explicit draft removal and accepted-send consumption must target the matching -identity/revision, retaining newer unsent edits and another session's attachments. -No discard confirmation for preserved drafts or streaming-only backend cancel -is selected by the later ruling. - -## Source anchors - -The ranges below describe the measured package snapshot, not an inferred future -implementation. Any PR moving these lines owns their citation repairs. - -- Palette commands: [`const jumpTo: PaletteItem[] = [`](https://github.com/schlessera/brain-kit/blob/18d5ddee154b5dbebb3dbd6c487bc8ea1fc036db/packages/ui-react/src/components/layout/desktop-palette.tsx#L84-L117), before #946 moved the destinations into `desktop-routes.ts`. - -- Palette opening: [`function onKey(e: KeyboardEvent) {`](https://github.com/schlessera/brain-kit/blob/18d5ddee154b5dbebb3dbd6c487bc8ea1fc036db/packages/ui-react/src/components/layout/desktop-palette.tsx#L52-L59), before #946 moved the open state into the root's UI store. - -- Phone destinations/More: (`const items: TabItem[] = [`, `packages/ui-react/src/components/layout/mobile-tab-bar.tsx:93-150`). - -- Command availability/effects: (`export function useChatCommands(): (command: string) => void {`, `packages/ui-react/src/components/chat/use-chat-commands.ts:18-56`). - -- Stats local exchange: (`export async function runStats(root: BrainUiRoot, sessionId: string | null): Promise {`, `packages/ui-react/src/components/chat/use-chat-commands.ts:70-156`). - -- Welcome alternatives: (`label="Start with"`, `packages/ui-react/src/components/chat/welcome-state.tsx:46-55`). - -- Session selection: (`const handleSessionResume = useCallback(`, `packages/ui-react/src/components/chat/chat-page.tsx:497-504`). - -- New chat: (`{hasMessages && !wide && (`, `packages/ui-react/src/components/chat/chat-page.tsx:702-709`). - -- Buffer eviction: (`function evictStale(`, `packages/ui-react/src/stores/chat-state.ts:1116-1132`). - -- Root namespace: (`const prefix = options.storagePrefix ??`, `packages/ui-react/src/root.ts:182-237`). - -- Clear transcript selection: (`clearMessages: () => {`, `packages/ui-react/src/stores/chat-state.ts:2202-2211`). - -- Composer draft/acknowledgement: [`const [input, setInput] = useState("");`](https://github.com/schlessera/brain-kit/blob/7bfdc71074f4ff6243e0d7133e83dbb36eb2a971/packages/ui-react/src/components/chat/composer.tsx#L62-L85), before #951 moved the draft into the root's draft store (`stores/draft-state.ts`). - -- Receipt consumption: [`if (!receipt || !pendingSend) return;`](https://github.com/schlessera/brain-kit/blob/7bfdc71074f4ff6243e0d7133e83dbb36eb2a971/packages/ui-react/src/components/chat/composer.tsx#L161-L176), before #951 moved send settlement into the draft client (`lib/draft-client.ts`). - -- Draft announcement correlation: (`function isOurDraftAnnouncement(`, `packages/ui-react/src/connection.ts:95-106`). - -- Demux: (`const frameSessionId = (msg as { sessionId?: string }).sessionId;`, `packages/ui-react/src/connection.ts:500-574`). - -- History replay: (`session_history: (msg, context) => {`, `packages/ui-react/src/hooks/websocket-handlers/chat.ts:444-455`). - -- Single background drawer row: [`const backgroundSessionId =`](https://github.com/schlessera/brain-kit/blob/ea8506b0eb511a3e16dba685d250d34e5340afa4/packages/ui-react/src/components/chat/session-drawer.tsx#L59-L60), before #950 replaced it with the Working group. - -- Host reconnect: (`const runningTurns = [...coordinator.running].filter((t) => t.sessionId);`, `packages/ui-server/src/ws/connection.ts:130-195`). - -- Host resume: (`case "session_resume": {`, `packages/ui-server/src/ws/dispatch.ts:649-720`). - -- Catalog activity: (`persistSessionStub(sessionId, promptText, providerId, backendId) {`, `packages/ui-server/src/ws/session-catalog.ts:486-493`). - -- Session summary shape: (`export interface ChatSession {`, `packages/ui-sdk/src/protocol.ts:1610-1626`). - -- Run identity: (`const runId = turn.turnId;`, `packages/ui-server/src/activity/recorder.ts:155-156`). - -- Outcome vocabulary: (`export type ActivitySpanOutcome =`, `packages/ui-sdk/src/protocol.ts:3081-3104`). - -- Activity resolution: (`.get("/activity/runs", (c) => {`, `packages/ui-server/src/routes/activity.ts:145-283`). - -- API authorization: (`app.use("/api/*", authGuard(authMode, auth, db));`, `packages/ui-server/src/app.ts:944`). - -- Queued acceptance: (`// Queue it as the session's next turn; report queued immediately.`, `packages/ui-server/src/ws/run-session.ts:1112-1157`). - -- Approval target: (`function mutateLastAssistant(`, `packages/ui-react/src/stores/chat-state.ts:1263-1293`). - -## Bounded follow-up ownership - -[#964](https://github.com/schlessera/brain-kit/issues/964) implements the selected -latest-turn/replay proof and pending-approval recovery after #943 supplies its exact design. -[#910](https://github.com/schlessera/brain-kit/issues/910) retains the four ask -recovery paths; #951 retains New chat draft/receipt coordination. -[#965](https://github.com/schlessera/brain-kit/issues/965) records the currently -unnamed Files drawer close button found while measuring dismissal. These scopes -consume the later recovery A and draft-storage C rulings in #929. This report -implements neither contract and does not waive their separate design, compatibility -or runtime proof requirements. diff --git a/docs/plans/policy-write-boundary.md b/docs/plans/policy-write-boundary.md deleted file mode 100644 index f2a644a558..0000000000 --- a/docs/plans/policy-write-boundary.md +++ /dev/null @@ -1,197 +0,0 @@ -# Policy-write boundary investigation - -R35 requires every agent runtime, including ordinary interactive turns, to be -unable to write `context/policies/**`. V1 also reads no policies for authority -(R33). This investigation for [#672](https://github.com/schlessera/brain-kit/issues/672) -preserves [the full autonomous scope](../decisions/async-collaboration.md) and -[the voice rule](../decisions/voice-permission.md#containment-shared-with-51-deliberately-not-identical): -one tool-enforcement mechanism with different named voice/unattended memberships. - -**Result:** no measured boundary meets R35 in the current server/adapter -architecture while retaining ordinary direct brain writes. A Linux whole-worker -experiment protects policy bytes, including aliases and inherited-descriptor -attempts, by mounting the entire brain read-only and giving the worker a separate -scratch filesystem. Applying that shape requires a ruling on worker isolation -and how interactive edits reach the authoritative brain. This is a recommendation, -not that ruling, a shipping guard, or production containment evidence. - -**2026-10-02 ruling:** [The durable decision](../decisions/policy-write-boundary.md) -records the subsequently approved worker architecture, editing/application policy -and Linux-first host/refusal scope. The result above and the recommendation below -describe the experiment before those rulings; their measurements and proof limits -remain unchanged. Approval is not production containment evidence. - -## Why a tool hook or child-only wrapper is insufficient - -Claude assembles the ordinary SDK turn, project settings and in-process bridge -tools (`createClaudeSdkTurn`, `packages/ui-backend-claude/src/sdk-options.ts:110-499`). -The installed SDK exposes `spawnClaudeCodeProcess`; at the investigation baseline, -the adapter wrapped the child with piped stdio -([historical `createWrappedSpawn`](https://github.com/schlessera/brain-kit/blob/ca1facc1e7086bd2119c260150e9f091e16817f1/packages/ui-backend-claude/src/spawn-wrapper.ts)). -#1037 subsequently made worker execution unconditional, and #1808 retired the -unused adapter. This paragraph preserves the earlier child-only boundary analysis. -Parent-side MCP/bridge -handlers are outside a boundary around that child. Their effects must be audited -and validated separately; this report does not claim they currently write policies. - -At the investigation baseline, pi created sessions directly in the server. -The same SDK construction is now worker-local (`async newSession`, -`packages/ui-backend-pi/src/native-session-runtime.ts:41-72`). Its resource loader -initializes extensions (`createSessionResources`, -`packages/ui-backend-pi/src/session-resources.ts:29-116`). The permission extension -registers a tool-call handler (`createPermissionGate`, -`packages/ui-backend-pi/src/permission-gate.ts:99-123`); it cannot interpose arbitrary -filesystem calls during extension initialization or execution. The experiment -loads a real pi inline extension and observes its parent-side initialization -changing the policy. Sandboxing only its spawned shell cannot repair that. - -Upstream [pi's security policy](https://github.com/earendil-works/pi/security) -places extensions inside the local user's trust boundary. Claude's -[Bash sandbox documentation](https://code.claude.com/docs/en/sandboxing#scope) -distinguishes shell/descendant confinement from built-in file tools and other -execution paths. A Bash sandbox plus path predicates therefore does not establish -the requested all-writer boundary. The repository's Bash classifier documents -indirection as accepted write-lock exposure (`A Bash command the classifier misses`, -`packages/ui-backend-claude/src/tool-policy.ts:226-231`), rather than containment. - -## Executable evidence - -The private experiment is [probe.py](https://github.com/schlessera/brain-kit/blob/48227b09076b350d70d9d20b8492ffcfb5b95771/scripts/policy-boundary-spike/probe.py) -with [worker.ts](https://github.com/schlessera/brain-kit/blob/48227b09076b350d70d9d20b8492ffcfb5b95771/scripts/policy-boundary-spike/worker.ts). It creates and -destroys its own fictional Odysseus files; it never opens a content repository, -uses provider credentials, or makes an inference request. Both files now live -on the [measurement archive](https://github.com/schlessera/brain-kit/tree/48227b09076b350d70d9d20b8492ffcfb5b95771/scripts/policy-boundary-spike) -([#1385](https://github.com/schlessera/brain-kit/issues/1385)); the archive's -README records the historical runtime. `worker.ts` imports repository source, -so a checkout of `9adc62e70b4f5eac9b5e3ef779552cd1858a6bd2`, the last main -commit that contains them, is the faithful setting. To try them on another -checkout, restore them at their original path, then run from the repository -root after a frozen dependency install: - -```sh -git fetch origin 48227b09076b350d70d9d20b8492ffcfb5b95771 -git restore --source 48227b09076b350d70d9d20b8492ffcfb5b95771 -- scripts/policy-boundary-spike -set -o pipefail -python3 scripts/policy-boundary-spike/probe.py 2>&1 | tee /tmp/policy-boundary-proof.log -python3 scripts/policy-boundary-spike/probe.py --mutation 2>&1 | tee /tmp/policy-boundary-mutation.log -python3 scripts/policy-boundary-spike/probe.py 2>&1 | tee /tmp/policy-boundary-restored.log -``` - -The mutation is expected to exit 1. It replaces the brain's read-only binding with -a writable binding. The installed pi Write executor succeeds, scratch writing -still succeeds, and the controller's `POLICY_BYTES_UNCHANGED failed: write under -mutation` assertion fails. This is an observed byte-integrity failure after the -writer executes, rather than a module-load failure. Restoring the normal profile -passes again. - -Measured on 2026-10-01: Linux x86_64, kernel -`6.18.33.2-microsoft-standard-WSL2`, Bun `1.3.14`, Python `3.12.3`, bubblewrap -`0.9.0`, Landlock ABI `7`, installed pi coding-agent `0.99.2`, and installed Claude -Agent SDK `0.3.283`. Versions come from the running tools and installed manifests. -The Claude adapter's real spawn function executes a fixture Bun program; the -experiment does **not** run a Claude model turn or its built-in Write/Edit/ -NotebookEdit implementations. Notebook serialization and nested subagent-like -processes are fixtures. Installed pi Write/Edit/Bash and extension loading/custom -executors run directly without replacing their filesystem operations. This -distinction limits the proof to the measured boundary and named writers. - -The protected profile uses bubblewrap namespaces, a read-only root and brain, -fresh `/proc` and `/dev`, a separate scratch tmpfs, dropped capabilities and a -cleared environment. The launcher closes inherited descriptors above 2. Protocol -stdout/stderr must be pipes; no policy-backed stdio is admitted. No -agent code runs before confinement. This is a reproducible filesystem experiment, -not an R28 network/credential/configuration sandbox: it has no inference egress, -still exposes readable host files, and does not measure hostile Unix sockets, -resource exhaustion or kernel exploits. - -The controller checks nonempty original bytes and directory membership from -outside the sandbox, independently of tool return values. Sixteen protected -attempts cover installed Write/Edit, notebook serialization, an indirect Bash -script, nested execution, the Claude spawn adapter, relative traversal, symlink -and preexisting hardlink aliases, creation of a scratch hardlink, new policy -creation, unlink, directory rename, extension initialization/custom execution, -and a descriptor closed before entry. None changes policy bytes or directory -membership. New scratch hardlinks fail across filesystems. Six permitted probes -use the same Write/Bash/nested/Claude-spawn/extension executors in scratch and -read back the expected nonempty payload; they prove the writers were functional. - -Six deliberately insufficient configurations produce actual policy changes: - -| Configuration | Observed escape | Consequence | -| --- | --- | --- | -| Writable brain with only the policy directory mounted read-only | Installed Write follows a preexisting hardlink in `notes/` to the policy inode | Protecting a pathname does not protect every writable alias. | -| Read-only brain plus a writable host scratch directory | A preexisting policy hardlink in scratch remains writable | Use an isolated scratch filesystem; merely choosing a fresh path is an assumption about its contents and other writers. | -| Whole-worker mounts with an inherited writable descriptor 3 | `write(3, ...)` changes the original file | Explicit closure belongs in the launcher; bubblewrap is not a descriptor sanitizer. | -| Whole-worker mounts with policy-backed stdout | `write(1, ...)` changes the original file | Validate protocol descriptors, including stdio, rather than closing only descriptors above 2. | -| Pi extension initialized in the unsandboxed parent | Installed loader runs the extension factory's filesystem write | Confining a child shell leaves the in-process writer privileged. | -| Landlock applied after a policy descriptor is opened | New policy opens are denied, scratch writes work, but the old descriptor writes | Enter before loading untrusted code and close inherited authority. | - -The [Landlock kernel interface](https://www.kernel.org/doc/html/latest/userspace-api/landlock.html#filesystem-flags) -documents the preopened-descriptor limitation. The native x86_64 probe requires -ABI >=3, restricts write/create/remove/refer/truncate rights to scratch, observes -a denied new open, and then writes through the old descriptor. Applying Landlock -late to a live server also cannot split JavaScript closures into different trust -domains or undo earlier opens/mappings. This investigation does not endorse that -as an in-process pi solution. - -## Architecture ruling required for implementation - -**2026-10-02 correction:** the three choices requested by this historical section -are now recorded in [the decision](../decisions/policy-write-boundary.md). Its -approved read-only workers and validated application route bind implementation; -the unproved direct-write alternative below remains rejected. GitHub owns -implementation dependencies and completion evidence. - -Recommend a concrete worker boundary shared by both adapters, managed inside the -existing server lifecycle. Pi SDK sessions and extension initialization/execution -would live inside workers; the Claude process and any runtime-owned local MCP -executors would also live inside them. No new daemon or extension seam is proposed. -Every worker receives a read-only authoritative brain view and a separate writable -attempt filesystem, pipe-only protocol descriptors and no inherited file/socket -authority. Workers cannot request privileged filesystem handles through the bridge. - -The ruling must choose how ordinary interactive effects reach Markdown: - -1. **Recommend server-validated effects:** existing curated brain operations run - through a narrow server-owned path, with explicit operation/path/principal - authority, descriptor-based race/alias protection, policy and ancestor denial, - and preserved locking/indexing. Shell/custom-extension edits happen in a - disposable view and require a bounded validated application step. This changes - ordinary shell behavior and must be expressly approved; this proof has no - broker, merge algorithm or ordinary-turn integration to claim ready. -2. **Direct-write alternative:** choose a real separately privileged worker - identity, policy inode/ancestor ownership and stable mount topology that still - permits other authoritative brain writes. Prove hardlinks, rename/replacement, - `/proc`, inherited descriptors, supplementary groups/capabilities and privileged - bridge effects on the chosen platform. Changing only the numeric UID inside a - user namespace is not proof of a different host filesystem identity. No such - layout was implemented or proved here. - -Approve the worker model, effect route, supported platforms and refusal behavior -before #674 becomes ready. The measured candidate is Linux/WSL2 with namespaces -and bubblewrap available. macOS and native Windows have no measured result here; -upstream support for a Bash sandbox is not support for this all-writer design. -An implementation must visibly refuse an unsupported mode before SDK/extension -initialization, with no automatic unsandboxed fallback. Preserve one shared tool -availability/enforced-membership mechanism for voice and unattended execution; -the filesystem boundary applies independently to every agent turn. - -## Concrete implementation and verification obligations - -#674 must incorporate the selected ruling and isolate all runtime initialization -before dispatch. Use the existing AgentBackend interface and server lifecycle for -internal worker communication, retain cancellation/session history and ordinary -turn semantics explicitly, and audit parent-side bridge effects. Assess SDK/wire/ -CLI/MCP/HTTP contract impact rather than presuming the worker implementation needs -no contract change. Changed package behavior needs changesets; breaking semantics -need their explicit ruling and same-commit contract documentation. - -Its proof must enter through both installed adapters' actual ordinary-turn paths, -using a keyless fixture inference transport, and cover allowed authoritative edits -under the selected effect route. Run all the measured escapes plus mappings, -descriptor/socket transfer, `/proc`/parent process access, topology races and -extension startup before any tool event. Observe original policy bytes and -unrelated permitted results, mutate the integrated guard, and verify unsupported -runtime/platform refusal before code initialization. #676 separately proves the -complete R28/R29/R31 credentials, ambient configuration and egress envelope. -Neither task may treat this finite fixture experiment as autonomous enablement. diff --git a/docs/plans/storage-accounting-experiment.py b/docs/plans/storage-accounting-experiment.py deleted file mode 100644 index 42bfce38a4..0000000000 --- a/docs/plans/storage-accounting-experiment.py +++ /dev/null @@ -1,202 +0,0 @@ -"""Fixture-only storage experiment for #1780; accepts no external scan roots. - -Run with python3 -B docs/plans/storage-accounting-experiment.py. All writes, -including Git setup/packing and permission changes, stay in fresh temporary -Odysseus trees. Measurement reads metadata, not attachment contents. This -single-process prototype does not establish race-safe production traversal. -""" -import json -import os -from pathlib import Path -import stat -import subprocess -import tempfile -import time - - -def command(args, env=None): - return subprocess.run(args, env=env, check=True, text=True, - capture_output=True, timeout=10).stdout.strip() - - -def inventory(roots, limit=10000, seconds=2, cancelled=lambda: False): - started = time.monotonic() - objects, errors, visited = {}, [], 0 - stack = list(reversed(roots)) - while stack: - if cancelled() or visited >= limit or time.monotonic() - started >= seconds: - errors.append("budget_or_cancel") - break - path = stack.pop() - visited += 1 - try: - info = path.lstat() - key = (info.st_dev, info.st_ino) - if key in objects: - continue - objects[key] = (info.st_size, info.st_blocks * 512, info.st_mode, - info.st_mtime_ns, info.st_ctime_ns, info.st_nlink) - if stat.S_ISDIR(info.st_mode): - with os.scandir(path) as entries: - # Incremental read avoids materializing an unbounded directory. - for entry in entries: - if len(stack) + visited >= limit: - errors.append("entry_budget") - break - stack.append(Path(entry.path)) - except OSError as error: - errors.append(error.__class__.__name__) - return {"logical": sum(v[0] for v in objects.values() if not stat.S_ISDIR(v[2])), - "directory_stat_bytes": sum(v[0] for v in objects.values() if stat.S_ISDIR(v[2])), - "allocated": sum(v[1] for v in objects.values()), - "entries": len(objects), "errors": errors, - "elapsed_ms": round((time.monotonic() - started) * 1000, 3)}, objects - - -def capacity(path): - fs = os.statvfs(path) - return {"identity": path.stat().st_dev, - "total": fs.f_blocks * fs.f_frsize, - "used": (fs.f_blocks - fs.f_bfree) * fs.f_frsize, - "available": fs.f_bavail * fs.f_frsize} - - -def run(): - with tempfile.TemporaryDirectory(prefix="odysseus-storage-") as temporary: - root = Path(temporary) - home, brain, state = (root / name for name in ("home", "brain", "state")) - for path in (home, brain, state): - path.mkdir() - env = {"PATH": os.environ["PATH"], "HOME": str(home), - "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": "/dev/null", - "GIT_OPTIONAL_LOCKS": "0", "LC_ALL": "C"} - git = lambda *args: command(["git", "-C", str(brain), *args], env) - git("init", "-q", "-b", "main") - git("config", "user.name", "Odysseus") - git("config", "user.email", "odysseus@example.invalid") - (brain / "voyage.md").write_text("# Voyage\nSail from Ithaca.\n") - (brain / ".gitignore").write_text("ignored.pdf\nworkspaces/\n.brain/\n") - git("add", "voyage.md", ".gitignore") - git("commit", "-qm", "Voyage") - (brain / "voyage.md").write_text("# Voyage\nConsult Athena.\n") - git("commit", "-qam", "Consult Athena") - loose = git("count-objects", "-v") - git("repack", "-ad") # Setup only: never part of the observation pass. - packed = git("count-objects", "-v") - worktree = root / "worktree" - git("worktree", "add", "-q", "-b", "athena", str(worktree)) - common = command(["git", "-C", str(worktree), "rev-parse", - "--path-format=absolute", "--git-common-dir"], env) - assert Path(common) == brain / ".git", "worktree shares Git common directory" - separate = root / "separate" - separate.mkdir() - command(["git", "init", "-q", "--separate-git-dir", str(root / "git-store"), - str(separate)], env) - assert (separate / ".git").is_file(), "alternate Git directory is a gitfile" - for name, size in (("map.pdf", 6000000), ("boundary.pdf", 5000000), - ("binary-boundary.PDF", 5242880), ("ignored.pdf", 7000000)): - with (brain / name).open("wb") as file: - file.truncate(size) - file.seek(0) - file.write(b"%PDF-Odysseus\n") - workspace = brain / "workspaces" - workspace.mkdir() - (workspace / "raft.txt").write_text("Raft plans\n") - (brain / ".brain").mkdir() - (brain / ".brain" / "scratch").mkdir() - (state / "brain-ui.db").write_bytes(b"synthetic operational bytes") - os.link(brain / "map.pdf", state / "map-alias.pdf") - (brain / "loop").symlink_to(brain, target_is_directory=True) - (brain / "external").symlink_to(state, target_is_directory=True) - many = brain / "crew" - many.mkdir() - for index in range(2000): - (many / f"oar-{index}.txt").write_text("row\n") - - before, baseline = inventory([root]) - overlap, _ = inventory([root, brain, workspace, state, worktree]) - assert overlap["allocated"] == before["allocated"], "overlapping roots counted once" - assert overlap["logical"] == before["logical"], "hard links counted once" - du_alloc = int(command(["du", "-s", "-B1", str(root)]).split()[0]) - du_logical = int(command(["du", "-s", "--apparent-size", "-B1", str(root)]).split()[0]) - assert before["allocated"] == du_alloc, "allocated aggregate agrees with du" - assert before["logical"] == du_logical, f"logical aggregate agrees with du: metadata={before['logical']} du={du_logical}; directory bytes={sum(v[0] for v in baseline.values() if stat.S_ISDIR(v[2]))}" - sparse = (brain / "map.pdf").stat() - assert sparse.st_blocks * 512 < sparse.st_size, "sparse logical differs from allocation" - pdfs = [p for p in brain.iterdir() if p.suffix.lower() == ".pdf" - and p.lstat().st_size > 5000000] - assert len(pdfs) == 3, "PDF > 5 MB includes ignored and uppercase, excludes exact boundary" - assert sum(p.stat().st_size for p in pdfs) == 18242880, "PDF logical total" - assert git("check-ignore", "ignored.pdf", "workspaces/raft.txt").splitlines() == [ - "ignored.pdf", "workspaces/raft.txt"], "ignored files remain inventory candidates" - short, _ = inventory([root], limit=10) - assert short["errors"], "entry budget reports partial" - cancelled, _ = inventory([root], cancelled=lambda: True) - assert cancelled["errors"] and cancelled["entries"] == 0, "cancellation is visible" - timed, _ = inventory([root], seconds=0) - assert timed["errors"], "time budget reports partial" - denied = root / "denied" - denied.mkdir() - (denied / "secret.txt").write_text("Odysseus fixture\n") - denied.chmod(0) - try: - refused, _ = inventory([denied]) - # A root run cannot demonstrate ordinary permission denial. - assert "PermissionError" in refused["errors"], "real EACCES must be visible (run unprivileged)" - finally: - denied.chmod(0o700) - (denied / "secret.txt").unlink() - denied.rmdir() - # Root directory timestamps changed during the separate denial probe; - # every descendant measured in the observation pass must be unchanged. - after, observed = inventory([root]) - root_key = (root.stat().st_dev, root.stat().st_ino) - assert {k: v for k, v in baseline.items() if k != root_key} == { - k: v for k, v in observed.items() if k != root_key}, "measurement did not mutate fixture" - changing = state / "changing.txt" - changing.write_text("Athena\n") - first = changing.stat() - changing.write_text("Consult Athena before sailing.\n") - last = changing.stat() - assert (first.st_size, first.st_mtime_ns, first.st_ctime_ns) != ( - last.st_size, last.st_mtime_ns, last.st_ctime_ns), "changing metadata invalidates a stable observation" - changing.unlink() - filesystem = capacity(brain) - df_values = command(["df", "-B1", "--output=size,used,avail", str(brain)]).splitlines()[-1].split() - df_capacity = dict(zip(("total", "used", "available"), map(int, df_values))) - assert df_capacity["total"] == filesystem["total"], "capacity total agrees with df" - df_delta = {k: df_capacity[k] - filesystem[k] for k in df_capacity} - assert capacity(state)["identity"] == filesystem["identity"], "colocated capacity deduplicates" - second = None - if Path("/dev/shm").is_dir(): - with tempfile.TemporaryDirectory(prefix="odysseus-storage-", dir="/dev/shm") as other: - other_root = Path(other) - (other_root / "raft.txt").write_text("Raft\n") - second = capacity(other_root) - assert second["identity"] != filesystem["identity"], "two real capacity identities" - (brain / "other-volume").symlink_to(other_root, target_is_directory=True) - local, _ = inventory([brain]) - combined, _ = inventory([brain, other_root]) - assert combined["logical"] > local["logical"], "cross-volume symlink not traversed" - (brain / "other-volume").unlink() - packs = list((brain / ".git" / "objects" / "pack").glob("*.pack")) - pack_logical = sum(p.stat().st_size for p in packs) - packed_fields = dict(line.split(": ", 1) for line in packed.splitlines()) - pack_disk = sum(p.stat().st_blocks * 512 for p in (brain / ".git" / "objects" / "pack").iterdir() - if p.suffix in (".pack", ".idx")) - pack_git_bytes = int(packed_fields["size-pack"]) * 1024 - print(json.dumps({"versions": {"python": command(["python3", "--version"]), - "git": command(["git", "--version"]), - "du": command(["du", "--version"]).splitlines()[0]}, - "inventory": before, "overlap": overlap, "du_allocated": du_alloc, - "du_logical": du_logical, "sparse": {"logical": sparse.st_size, - "allocated": sparse.st_blocks * 512}, "pdf_count": len(pdfs), - "pdf_logical": 18242880, "loose_git": loose, "packed_git": packed, - "pack_logical": pack_logical, "pack_and_index_allocated": pack_disk, "git_pack_report_bytes": pack_git_bytes, - "capacity": filesystem, "df_delta_bytes": df_delta, "second_capacity": second, - "denied": refused, "budget": short, "cancelled": cancelled, - "timed": timed, "readonly_descendants": True}, indent=2)) - - -if __name__ == "__main__": - run() diff --git a/docs/plans/storage-accounting.md b/docs/plans/storage-accounting.md deleted file mode 100644 index 93f9895850..0000000000 --- a/docs/plans/storage-accounting.md +++ /dev/null @@ -1,391 +0,0 @@ -# Storage ownership and capacity accounting - -Discovery for [#1780](https://github.com/schlessera/brain-kit/issues/1780), -informing [#1779](https://github.com/schlessera/brain-kit/issues/1779) and the -design in [#1782](https://github.com/schlessera/brain-kit/issues/1782). -Source reviewed at `f2c98da6093c9e1731f061625ba7302f51bf7340`. -This is a proposed model, with a fixture experiment, not a shipped collector, -retention decision or cleanup authorization. Existing stats and MCP meanings -remain unchanged. Cleanup/recovery policy is the separate #1781 discovery. - -## Recommendation - -Use one inventory of permitted storage objects, with separate **ownership -views**, **capacity scopes**, and **measurement evidence**. Brain and deployment -are views over that inventory, not two quantities to add. Keep filesystem -allocation estimates separate from logical file sizes and actual volume usage. -Start with local metadata and configured application stores; leave remote -storage, quotas and host runtime stores unknown unless explicitly observable. - -Core owns deterministic content/Git measurement through a later supported CLI -JSON operation. ui-server resolves its effective configuration, adds its stores, -merges duplicate identities and serves authenticated inventory. It must not -import core internals or put operational state into `brain.db`. Backends retain -their transcript layout and lifetime ownership. No storage-provider seam, -privileged host browser or worker-accessible inventory is proposed. - -The binding constraints are [the roadmap](../../ROADMAP.md#what-binds-future-work), -[governed writable workers](../decisions/governed-writable-workers.md), -[worker writable areas](../decisions/worker-writable-areas.md), -[the recovery guide](../inbox-recovery.md), and the existing -[machine contract](../integration-contract.md). Navigation and presentation -remain for #1782 under [navigation](../decisions/design-kit/navigation.md) and -[sessions and drafts](../decisions/design-kit/sessions-and-drafts.md). - -## Current stores and source owners - -In the matrix, `B` is the effective canonical brain root; `D` is the effective -UI database path. `C(path)` is a resolved capacity identity, not a path string. -Every location is configuration-derived or an explicitly permitted root; -environment defaults are resolved by the existing owner, not reconstructed by -the collector. Each row uses the anchors below. Lifetime describes current -ownership, not permission to delete. - -| Category / source | Owner and location resolution | Persistence / authority | Measurement and capacity identity | Existing API / maintenance and limitations | -| --- | --- | --- | --- | --- | -| Tracked, untracked and ignored notes, attachments, configuration / A | Core; `B` from context | Markdown/files are authoritative; Git tracking is an independent facet | `lstat` per entry; logical `size`, allocation `blocks`; `C(B)` or approved nested mount | `brain stats`, read/tree, capture/update/archive; stats is a filtered corpus, not all files. Index/type/reference metadata may be absent or stale. | -| Git objects, packs, indexes, refs, reflogs, administrative files / B | Core; Git resolves per-worktree git-dir, common-dir, object directories and alternates | History/refs/reflogs have separate recoverability; not disposable index data | Inventory distinct resolved directories; `count-objects -v` supplemental counts; capacity for each physical store | `brain doctor` storage check and `brain maintain` packing; never expire reflogs/delete refs. Pack bytes cannot be apportioned exactly to current files. External alternates need explicit permission. | -| Derived content index and SQLite sidecars / A | Core; context `dbPath`, ordinarily `B/brain.db`; `-wal`, `-shm`, `-journal` | Regenerated by force indexing | Metadata for existing files once; their actual `C(path)` | `brain index --force`; current stats includes main DB and WAL bytes, not a complete deployment total. Tables/vector slots are counts, not additive bytes. | -| Corpus stats history / C | Core; canonical `B/.stats-history.jsonl` | Historical observations, not content/index authority | File metadata, `C(B)` | `brain stats --record/--history`; no server state belongs here. Daily/weekly thinning has no lifetime byte cap. | -| UI operational DB, sidecars and associated quarantine / D | ui-server; effective `D`, including explicit app override; sibling `brain-ui-quarantine` | Sessions, drafts including image bytes, principals, settings, budgets, inbox and schedules are authoritative operational state | DB/sidecar/quarantine file metadata; `C(D)`; in-memory DB has no disk file | Whole-store operational export/restore, not core index rebuild. DB page/table approximations must not be added to file bytes; quarantine evidence is not automatically disposable. | -| Claude native transcripts and compressed archives / E | Claude backend; resolved config directory, encoded canonical brain project; live `projects`, cold `transcript-archive` | Native transcripts and archive manifests retain conversation authority across turns | On-disk compressed bytes for archives; live metadata; each root's capacity | Existing list/history/idle archival. Count live, committed archive and conflict/pending files as separate physical objects; archived logical uncompressed length is a different metric. Never scan the entire home/config directory. | -| Pi native transcripts / F | Pi backend; explicit session directory or canonical brain hash under its state default | Persistent conversation state | Only resolved session store metadata, `C(store)` | Existing list/history; Pi archival remains #1637. Production resolver rejects brain/ancestor aliases; fixture session-factory fallback is not a production location contract. Credential files must not become inventory details. | -| Share/upload staging / G | ui-server; `B/.brain-ui/inbox`, including partial publications | Staged bytes may be required for durable inbox settlement/recovery | Metadata of allowed staging subtree; `C(B)` | Share staging/prune and inbox cleanup; live/settlement guards apply. Files physically in `B` can be server-owned. Inline uploads saved in drafts/DB are counted there; finalized attachments count at their final location. | -| Persistent scratch and workspaces / H | Core policies and ui-server pin coordinator; `B/.brain/scratch`, `B/workspaces` | Scratch has bounded lifetime/pins; workspace files can be intentional user work and nested repositories | Metadata including hidden/nested Git data; dedupe hard links/shared object stores; `C(path)` | `brain scratch prune`, pin-aware server timer, maintain. Index exclusion does not imply storage absence or permission to remove workspaces. | -| Turn temp, runtime state, startup/output staging and maintenance temp / I | ui-sdk launcher/host ledger, backend workers; resolved private per-turn roots and tmpfs mounts | Temporary working bytes, bounded admissions; some state is promoted/persisted by its owner | Live host-observed mount/counter evidence where available; tmpfs capacity and ledger reservations separate from allocated bytes | Existing admission/status/teardown, not a recursive scan of host `/tmp`. A configured allowance is a limit, a reservation is not usage; discarded home overlays may be unobservable. | -| Journal and revert objects / J | ui-server; sibling `${basename(D)}.journal`, and the journal metadata database `${D}.journal.db` with its sidecars (#2789); temporary root for ephemeral DB | Before/after/revert bytes support review and recovery; not the disposable content index | Object/temporary metadata plus existing accounting evidence, `C(root)`; hash dedup is within this store | Journal/revert routes and guarded object accounting. Operational backup scope does not automatically include this external directory. No inventory-triggered reaping. | -| Backups / K | Generated host/operator; explicitly selected artifact root(s), Git backups independently | Retained recovery points, additional physical copies | Artifact metadata only; distinct capacity or remote evidence; count copies even when content is identical | `brain-ui-inbox export/restore`; whole DB plus checksummed required staging. Does not back up external transcripts/journal by implication. No reading/decompressing artifacts for size. | -| Runtime caches, logs, images and layers / I | Generated host/runtime, outside package authority; only expressly configured roots | Host-selected persistent or disposable state | Ordinary readable app-owned files if declared; runtime shared layers/provider quotas unknown | No general prune, Docker socket, privileged host inventory or guessed layer attribution. Stdout logs and runtime-host stores may be outside the app mount namespace. | - -Source anchors, checked against the reviewed commit: - -- A: root and index resolution (`initContext`, `packages/core/src/lib/context.ts:36-50`); - existing corpus exclusions (`corpusSize`, `packages/core/src/lib/stats.ts:164-215`), - available capacity (`freeSpaceBytes`, `packages/core/src/lib/stats.ts:219-230`). -- B: loose report (`looseObjects`, `packages/core/src/lib/git-storage.ts:68-77`) - and safe packing (`packRepository`, `packages/core/src/lib/git-storage.ts:115-121`). - The completed #94 and #398 provide existing stats/maintenance foundations. -- C: snapshot fields (`snapshotOf`, `packages/core/src/lib/stats-history.ts:132-172`), - thinning (`thin`, `packages/core/src/lib/stats-history.ts:232-244`). -- D: effective path/journal resolution (`createApp`, `packages/ui-server/src/app.ts:310-346`), - WAL store (`createUiDb`, `packages/ui-server/src/db/client.ts:27-44`), and - private locations (`statePaths`, `packages/ui-server/src/brain/operational-state.ts:113-119`). -- E: live/archive paths (`transcriptPaths`, `packages/ui-backend-claude/src/transcript-archive.ts:31-40`). -- F: session location (`piSessionDirectory`, `packages/ui-backend-pi/src/session-storage.ts:10-30`). -- G: staging location (`shareStagingRoot`, `packages/ui-server/src/share/staging.ts:149-151`) - and settlement-aware cleanup (`function claim`, `packages/ui-server/src/inbox/lifecycle-writes.ts:42-61`). - [#807](https://github.com/schlessera/brain-kit/issues/807) supplies live-work - and settlement protection for staging cleanup. -- H: scratch defaults (`SCRATCH_DIR`, `packages/core/src/lib/scratch.ts:56-65`), - scheduled prune (`startScratchPrune`, `packages/ui-server/src/cron/scratch-prune.ts:41-49`), - and the [writable-area decision](../decisions/worker-writable-areas.md). - [#1656](https://github.com/schlessera/brain-kit/issues/1656) supplies retained - scratch conversation pins. -- I: [server configuration](../../packages/ui-server/README.md) and worker-area/governed-worker - decisions distinguish the independent configured limits and mounts. Delivered - #1703 adds scoped turn-temp usage/purge and promotion protection; those - measurements do not include the separate runtime-state tmpfs. -- J: private object store (`createJournalObjects`, `packages/ui-server/src/brain/journal-objects.ts:35-50`) - and D's path resolution. Existing journal/revert accounting owns reservations. -- K: consistent export (`exportInboxSnapshot`, `packages/ui-server/src/inbox/snapshot.ts:295-312`) - and [operational recovery](../inbox-recovery.md); delivered #686 and its - [generated-host counterpart](https://github.com/schlessera/brain-hosting-template/issues/9). - -## Three identities and honest units - -An **entry identity** represents a visible name within a permitted root. Use an -opaque stable root ID plus normalized relative path; rename/replacement needs a -new revision or explicit continuity evidence. Do not publish inode numbers or -absolute private paths as stable public IDs. An **object identity** deduplicates -the bytes: on tested Linux local filesystems, `(device, inode)` for the scan -epoch, validated again when reopening. Inode reuse, remounts and remote/overlay -filesystems limit cross-scan stability. A **capacity identity** represents one -allocation/quota pool in the process mount namespace, with provenance. - -Canonical paths deduplicate nested roots and aliases, but are insufficient for -hard links or bind mounts. Use mount information plus device/filesystem evidence; -bind mounts of the same filesystem normally share capacity even when mount IDs -or root strings differ. Separate quota domains need separate quota identities. -Unknown equivalence must remain unknown, not cause guessed capacity addition. -An overlay's backing-store relation is not inferred from its device number. -Nested repositories/worktrees have their own ownership boundaries, and may share -a Git common directory or alternate object store: resolve those via -[Git path operations](https://git-scm.com/docs/git-rev-parse), never by assuming -`.git` is a directory. Do not follow alternates outside approved roots. - -For regular files, logical bytes are `st_size`; on Linux allocated bytes are -`512 * st_blocks`, not `st_blksize * st_blocks`. Directory allocation and link -objects belong in a metadata bucket. Directory `st_size` is not user content. -Sparse files can have large logical size with tiny allocation. Compression, -reflinks, snapshots and shared extents prevent inode-based sums from proving -exclusive physical usage or reclaimable space. Report the allocation basis and -its limits. No content hash read or per-blob history analysis is necessary. -See [Linux stat fields](https://man7.org/linux/man-pages/man3/stat.3type.html). - -For a supported filesystem observation, using its reported allocation unit `b`: - -```text -total = blocks * b -used = (blocks - bfree) * b -free = bfree * b -available_to_caller = bavail * b -reserved_or_unavailable_free = free - available_to_caller (if meaningful) -``` - -`used + available` need not equal `total`. Keep quota used/limit/remaining as -separate nullable measurements; do not infer quotas from `bavail`, or substitute -a worker admission budget. Tmpfs has its own finite mount capacity and may -consume memory/swap; it is not extra persistent disk. Remote repository usage, -remote limits, and local Git bytes remain different scopes. A provider may -report repository logical storage rather than physical allocation; unsupported -remote measurement is unknown, without issuing a network request. Capacity -semantics follow [Linux statfs](https://man7.org/linux/man-pages/man2/statfs.2.html). - -## Worked accounting - -These numbers illustrate the model in MiB; they are not installation evidence. -Assume ordinary non-shared allocation for these examples. - -One volume V: content 100, Git 40, index 10, scratch 5, staging 8, UI DB 12, -transcripts 20, journal 15, backups 30. The resolved object union totals 240. - -```text -V capacity: total 1000; used 600; free 400; available 350; reserved free 50 -app inventory allocated: 240 - brain ownership: content 100 + Git 40 + index 10 + scratch 5 = 155 - server ownership: staging 8 + DB 12 + transcripts 20 + journal 15 = 55 - operator backups: 30 -volume used outside attributed inventory: 360 (only under these assumptions) -``` - -Staging is physically under the brain root. A whole-root physical view is -163, while server ownership is 55. Adding them with backups gives 248 and -duplicates staging. Likewise, including scratch in a deployment view and in -the brain view duplicates scratch. The inventory union is 240, and available -capacity is shown once as 350, not once per store. A 6 MiB file hard-linked into -scratch remains one object: its two entry rows show the alias relationship; -physical rollups allocate it to one primary bucket or a shared bucket, never -two parents. Content-path logical filter totals can still count both visible -names, explicitly labeled as file entries rather than unique objects. - -Separate volumes: move brain/scratch/staging to V1, DB/transcripts/journal/backups -to V2, and turn temp to tmpfs T: - -```text -V1: inventory 163; total 500; used 300; free 200; available 180 -V2: inventory 77; total 800; used 400; free 400; available 350 -T: inventory 4; total 64; used 4; free/available 60 -persistent attributed union = 163 + 77 = 240 -``` - -An upload to V1 has 180 available, not `180 + 350 + 60`. A journal write to -V2 uses its 350; a turn additionally meets T's limit and the host ledger's -admission rules. A bind alias of V1 adds no capacity. A separately mounted Git -object store adds its own permitted store/capacity row, not imaginary space -under V1. Shared extents or uncertain mount equivalence make sums estimated; -do not show a negative residual or call it exact host-wide attribution. - -## Inventory needed by the treemap and file workflow - -Proposed fields, to review before naming any CLI command or HTTP route: - -| Field group | Meaning | -| --- | --- | -| Identity | Inventory/scan ID, stable root ID, opaque entry ID, parent ID, revision, scan-local object ID, aliases/shared-accounting bucket, capacity ID or unknown | -| Ownership | Core/server/backend/operator owner, category, persistence/authority, permitted operation capability supplied by owner; no deletion inferred from category | -| Hierarchy | Permitted relative path, display name, parent/children or paginated continuation, explicit nested-store boundary; ancestors hold aggregates, not additional bytes | -| Classification | Regular/directory/link/special; normalized extension and its provenance; MIME only if already recorded; tracking facet tracked/untracked/ignored/unknown; indexing facet indexed/excluded/unindexed/unknown with reason | -| Values | Decimal integer byte strings for safe JSON precision; logical bytes, allocated bytes nullable; entry count and unique object count; subtree totals with a declared metric/basis; no mixture of compressed/uncompressed or logical/allocated values | -| Evidence | Method/source, exact/estimated/unknown accuracy, complete/partial coverage, observation start/end, owner revision where available, observed-at, cached-at, stale-after, errors/reasons and omitted entry count when knowable | -| Capacity | Total/used/free/available, quota identity/values nullable, tmpfs limits, remote scope/provider capability if observable; units and identity confidence | - -Use logical **regular-file entry** size for `PDF > 5 MB`: MB means 1,000,000 -bytes, comparison is strictly `> 5,000,000`, and MiB is a separate choice -(`> 5,242,880`). Case-insensitive extension classification is explicitly -filename-based, not verified MIME. Do not read attachment contents for size or -type sniffing. Exact-boundary files fail the strict filter. Show matching entry -count and logical total, plus unique objects/allocated estimate when known; -symlinks are link rows, not PDF targets. Filtering partial inventory shows a -known subtotal with a visible incomplete warning, not a complete result count. - -Ignored/unindexed PDFs appear in this inventory without changing indexing -policy. Existing indexed IDs/types/references may enrich results, with their -index freshness; absent references are unknown, not proof of no incoming links. -No comparison between stale metadata and a current file authorizes cleanup. -The treemap switches a single size basis at a time and represents unknown/ -unattributed storage outside proportional known tiles. It must not render an -unknown zero-sized tile as though nothing occupies space. #1782 owns visual -design; #1781 owns inspection/consequence/operation rules. - -## Bounded read-only collection - -Resolve an allowlist from existing owner configuration. Never accept a request -path as a scan root. Do not scan home, `/tmp`, runtime-host storage, credentials -or unknown mounts to fill a gap. Explicitly approved root aliases are resolved -once; descendants use descriptor-relative no-follow directory traversal and -inode/device checks before reading metadata. No FIFO/device opens, symlink -target traversal, implicit automount exploration or filesystem-crossing recursion. -Same-device bind mounts need mount-boundary checks as well as device checks. -An approved nested mounted store gets a separate root and is merged by identity. - -Production proposal: one scan per app, two metadata workers maximum, 100,000 -visited/queued entries, 30 seconds elapsed, bounded page/error buffers, maximum -depth 64, and cancellation at directory iteration and before each I/O/process -operation. Budgets are candidate defaults to qualify, not established runtime -promises. Kill/reap any bounded Git subprocess on timeout/cancel; a blocking -filesystem call may need a separately cancellable child process, because an -AbortSignal alone cannot interrupt kernel I/O. Git observations disable optional -locks, run with controlled config/environment/hooks authority, and never invoke -maintenance. No writes, checkpointing, index rebuild, packing or creation of -missing store directories happen during measurement. - -Writes continue during observation. Validate metadata when opening directories -and before emitting inspected files; detect disappearance/replacement and record -changing evidence, not a snapshot guarantee. A coherent point-in-time DB byte -inventory is not obtained by copying the live main file; opening a new writable -SQLite handle could create sidecars. Read filesystem metadata only, and use -existing owner counters if read-only. Cache successful/partial scans with scan -IDs and a proposed 60-second freshness window; bound cache entries/bytes and -coalesce refresh requests. Low-space checks can refresh capacity alone. - -Accuracy and completeness are independent: - -| Observation | Required report | -| --- | --- | -| Stable regular file on supported local FS | Exact observed logical bytes; filesystem-reported allocation, estimated exclusive physical attribution | -| Sparse/compressed/reflink file | Logical exact at observation; reported allocation with basis; reclaimable space unknown | -| EACCES directory | Partial parent subtree, known bytes lower bound, inaccessible child count unknown; no zero-size claim | -| File changed/disappeared during scan | Partial/changing with interval/reason; bounded retry optional, no silent omission | -| Time/entry/depth/cancellation limit | Partial with continuation only if safely resumable; never call cached subtotal complete | -| Capacity permission failure or unsupported identity | Unknown capacity/identity; preserve known store bytes without invented available space | -| Quota unavailable | Unknown quota; known `bavail` remains filesystem availability, not quota headroom | -| Packed Git | Exact observed pack/index file sizes, coarse Git KiB report, unknown exact per-file/history attribution | -| Remote provider unimplemented/unavailable | Unknown remote usage/limit, no local substitute or default zero | -| Root absent vs unreadable | Absent may be exact empty only after successful parent resolution; permission errors remain unknown | - -## Growth and low-space evidence - -The later [growth proposal](storage-growth.md) specifies candidate fields, bounds, -cadence, guidance and synthetic decisions without approving production policy. - -Reuse concepts from core stats history (nullable values, date/version provenance, -UTC buckets and thinning), not its schema/file or core authority. That file stores -corpus/index figures and lacks capacity IDs, coverage/basis and server ownership; -blindly reusing it would change the existing stats contract. Recommend a server -owned aggregate history, initially capped at 128 samples / 256 KiB, recording -per-category and per-capacity values with scan IDs, interval, basis, partial -reasons and metric version. No per-file histories, private paths or complete -inventory snapshots in history. Its own bytes count in server storage. - -Only comparable scopes/bases produce growth rates. Unknown or partial samples -break the rate rather than contribute zero; deleting/adding a root or changing -capacity identity also breaks comparability. Capacity-only observations and -reservations remain distinct. Refresh after an owner-reported completed mutation -and on explicit request, with coalescing; a rate-based exhaustion estimate is -estimated and unavailable with insufficient comparable evidence. Low-space -signals name the affected write target's capacity/quota, freshness and margin. -Alert thresholds, cadence and persistence require later design; this spike does -not authorize automatic cleanup or a new retention policy. - -## Synthetic experiment and evidence - -Run `python3 -B docs/plans/storage-accounting-experiment.py` as an unprivileged -Linux user. The script accepts no external roots and creates only temporary -Odysseus fixtures. Git initialization, commits, packing, linked worktree, separate -Git directory, hard links, permissions and attachment writes are **fixture -setup**, not collection. Measurements use metadata and bounded local subprocesses; -no provider/network, attachment reads or real deployment corpus is involved. - -Observed with Python 3.15.0, Git 2.55.0, GNU du 9.11, Bun 1.4.2: - -- 2,103 distinct entries including 2,000 small crew files: 23,309,497 logical - bytes and 8,478,720 allocated bytes; baseline 18.919 ms, overlapping-root - scan 19.155 ms. Both exactly matched independent `du -s --apparent-size -B1` - and `du -s -B1`. Root/path-dependent Git fixture sizes and timings may vary. -- Initial naive inclusion of directory `st_size` overcounted apparent bytes by - 43,460. Excluding directory logical sizes restored agreement; directory - allocation remains in the allocation total. This mismatch is why the model - distinguishes directory metadata from content. -- The 6,000,000-byte sparse PDF occupied 4,096 allocated bytes. The strict - decimal PDF filter returned three entries / 18,242,880 logical bytes, - including ignored and uppercase-extension files, excluding exactly 5 MB. - A hard-linked server alias did not duplicate union allocation/logical bytes. -- Seven loose Git objects became seven packed objects in one pack during setup. - `count-objects -v` then reported `size-pack: 1` KiB (1,024 bytes), while - pack plus index allocated 8,192 bytes; the pack file alone had 593 logical - bytes. This deliberate mismatch disproves treating Git's coarse report as - full allocated Git-directory usage. See [Git's report units](https://git-scm.com/docs/git-count-objects). -- Actual linked worktree resolution shared the main Git common directory; - separate-git-dir produced a `.git` file. Shared/overlapping roots measured - once. Symlink loops/external targets were not traversed. `/dev/shm` permitted - a second real capacity identity, and its file was counted only when its - temporary root was explicitly included. No mounts were created. -- `statvfs` total/used/available agreed with independent - `df -B1 --output=size,used,avail` (all three deltas zero in this receipt). - Live host writes can change used/available between calls; the experiment - records deltas rather than demanding a stable whole-filesystem snapshot. - A separately changed fixture file invalidated size/mtime/ctime continuity. -- Real mode-000 directory enumeration returned `PermissionError`, preserving - partial semantics; entry/time limits and cancellation were visibly partial. - Before/after descendant metadata (identity, size, blocks, mode, mtime, ctime, - link count) agreed across the observation pass. Atime is intentionally not - a read-only invariant. The separate permission probe changes only its own - temporary fixture; root timestamps are excluded from that comparison. - -Three restored mutations demonstrated live assertions: replacing inode identity -with path identity failed `allocated aggregate agrees with du`; changing `>` -to `>=` failed the strict PDF count/boundary assertion; ignoring cancellation -failed `cancellation is visible`. The restored script passed. These qualify the -fixture observations, not a shipped production guard. - -The script is a single-process prototype: it does not qualify descriptor races, -mount/bind traversal, exclusive extent accounting, real quotas, compression, -remote providers, live DB coherence, hostile directory renames, process-kill -cancellation, long blocking I/O or production-scale performance. It uses -scan-epoch Linux device IDs as its capacity proxy; that is not the complete -production capacity resolver. Other platforms and a root execution require -separate qualification (root cannot demonstrate ordinary EACCES). - -## Alternatives, open decisions and implementation boundaries - -An index-only report is cheap but misses unindexed/ignored attachments and -server state. Summing `du` per store is simple but double-counts aliases and -capacity and cannot express authority. Host-wide/runtime API scanning offers -more coverage but exceeds ordinary app access and requires a separately approved -host contract. Detailed historical Git attribution is expensive, often inexact -with deltas/shared objects, and unnecessary for the first honest overview. - -Recommend the local permitted-object model above. Remaining choices for later -review are metric defaults in the treemap, snapshot/refresh/alert cadence, -history byte/sample caps, large-corpus pagination and resumability, platform -support and allocation terminology, capacity identity on overlays/quotas, and -whether remote-provider or runtime-host metrics are worth a separate scope. -These do not block this discovery deliverable; they must not be silently decided -by a future implementation. - -Proposed implementation slices, not commitments or status: - -1. Core local content/Git metadata inventory and bounded traversal, preserving - stats; additive CLI JSON contract plus fixture/mutation proof for aliases, - budgets, unknowns and Git path resolution. -2. ui-server owner-root registration and backend-owned transcript resolution, - object/capacity merge and authenticated cached transport. No new public SDK - seam; inventory access needs host/operator authorization reviewed separately - from ordinary content read permission. Public health remains minimal - (`createStatusRoutes`, `packages/ui-server/src/routes/health.ts:60-82`). -3. Server-owned bounded aggregate history/capacity refresh and low-space signals, - after cadence/threshold design; no persistence in core `brain.db`. -4. The #1782 treemap/list/filter/inspection design, followed by separately scoped - implementation with real browser/accessibility proof. Cleanup uses #1781's - reviewed owner operations and independent confirmation/recovery rules. - -Each new supported command/JSON/HTTP/config surface requires same-commit contract -documentation, appropriate `CONTRACT:` changes and consumer changesets when it -ships; none is introduced here. Names and schemas are intentionally unselected. - -No concrete generated-host change is established: current configured stores and -ordinary `stat`/Git access are enough for this first model. The existing hosting -template #9 already owns backup scheduling/storage policy. If later discovery -requires mounted metric files, declared host capacity identity or a runtime -collector, file a bounded `brain-hosting-template` counterpart then; no Docker -socket or privileged inventory is implied by this document. diff --git a/docs/plans/storage-growth-experiment.ts b/docs/plans/storage-growth-experiment.ts deleted file mode 100644 index 99ffc913c9..0000000000 --- a/docs/plans/storage-growth-experiment.ts +++ /dev/null @@ -1,198 +0,0 @@ -/** Offline synthetic design qualification for #2014. No production imports, collection or delivery. */ -import { strict as assert } from "node:assert"; - -const hour = 3_600_000, day = 24 * hour; -const start = Date.parse("2026-07-12T00:00:00Z"); -type Sample = { total?: number; gap?: boolean; at: number; scope: string; basis: number; complete: boolean; bytes: number | null; available: number | null }; -function rate(samples: Sample[]): number | null { - const last = samples.at(-1); - if (!last?.complete || last.gap || last.bytes === null) return null; - const window: Sample[] = [last]; - for (let i = samples.length - 2; i >= 0; i--) { - const value = samples[i], next = window[0]; - if (!value.complete || value.gap || value.bytes === null || value.scope !== last.scope || value.basis !== last.basis || next.at <= value.at || next.at - value.at > 12 * hour || last.at - value.at > 7 * day) break; - window.unshift(value); - } - const first = window[0], span = last.at - first.at; - return window.length >= 5 && span >= 2 * day ? (last.bytes - first.bytes!) / (span / day) : null; -} -const trace = (value: (i: number) => number): Sample[] => Array.from({ length: 13 }, (_, i) => ({ at: start + i * 6 * hour, scope: "ithaca", basis: 1, complete: true, bytes: value(i), available: 8_000_000_000 })); -const steady = trace(i => 1_000_000_000 + i * 30_000_000); -const burst = trace(i => 1_000_000_000 + (i >= 4 ? 600_000_000 : 0)); -const reclaim = trace(i => 1_000_000_000 - i * 10_000_000); -const changed = steady.map((s, i) => ({ ...s, scope: i >= 8 ? "new-ithaca" : s.scope })); -const partial = steady.map((s, i) => ({ ...s, complete: i !== 8 })); -const unknown = steady.map((s, i) => ({ ...s, bytes: i === 8 ? null : s.bytes })); -const concurrent = trace(() => 1_000_000_000).map((s, i) => ({ ...s, available: 8_000_000_000 - i * 100_000_000 })); -assert.equal(rate(steady), 120_000_000); -assert.equal(rate(burst), 200_000_000); -assert.equal(rate(reclaim), -40_000_000); -assert.equal(rate(steady.map((sample, i) => ({ ...sample, at: i === 10 ? start + 80 * hour : sample.at }))), null); -assert.equal(rate(steady.map((sample, i) => ({ ...sample, gap: i === 8 }))), null); -assert.equal(rate(changed), null); assert.equal(rate(partial), null); assert.equal(rate(unknown), null); -assert.equal(rate(concurrent), 0); assert.equal(concurrent[0].available! - concurrent.at(-1)!.available!, 1_200_000_000); - -type Severity = "observed" | "low" | "critical"; -function episode(values: { at: number; available: number | null; fresh: boolean; refused?: boolean }[]): Severity[] { - let state: Severity = "observed", qualifying: number | null = null; - return values.map(sample => { - const ratio = sample.available === null ? null : sample.available / 100; - if (sample.refused || (sample.fresh && ratio !== null && ratio <= 0.05)) { state = "critical"; qualifying = null; } - else if (sample.fresh && ratio !== null) { - if (state === "observed" && ratio <= 0.10) state = "low"; - const clears = state === "critical" ? ratio > 0.07 : state === "low" ? ratio > 0.12 : false; - if (!clears) qualifying = null; - else if (qualifying === null) qualifying = sample.at; - else if (sample.at - qualifying >= 60_000) { state = state === "critical" ? "low" : "observed"; qualifying = null; } - } else qualifying = null; - return state; - }); -} -const oscillation = [9, 11, 9, 13, 13, 4, null, 8, 8].map((available, i) => ({ at: start + i * 60_000, available, fresh: true })); -const states = episode(oscillation); -assert.deepEqual(states, ["low", "low", "low", "low", "observed", "critical", "critical", "critical", "low"]); -assert.deepEqual(episode([{ at: start, available: null, fresh: true, refused: true }]), ["critical"]); -assert.deepEqual(episode([{ at: start, available: 4, fresh: true }, { at: start + hour, available: 90, fresh: false }]), ["critical", "critical"]); - -const max = Number.MAX_SAFE_INTEGER; -// At most 12 nullable byte fields per capacity, all at their longest representation. -const capacity = [743, max, max, max, max, 2, max, max, max, max, max, max, max, max]; -const worst = [1, 2, 1, max, max, 2, 185, 2, 5, Array.from({ length: 4 }, () => capacity)]; -const sampleBytes = Buffer.byteLength(JSON.stringify(worst)); -assert.ok(sampleBytes <= 1152, `sample ${sampleBytes} exceeds 1152 bytes`); -const payloadBound = 186 * 1152 + 40960 + 187; -assert.ok(payloadBound <= 256 * 1024); -type Tier = "recent" | "daily" | "weekly"; -type Point = Sample & { tier: Tier; gap: boolean }; -const widths = { recent: 6 * hour, daily: day, weekly: 7 * day }; -const limits = { recent: 64, daily: 90, weekly: 32 }; -const epoch = Date.parse("1970-01-05T00:00:00Z"); // Monday -const bucket = (at: number, tier: Tier) => Math.floor((at - epoch) / widths[tier]); -const history = new Map>( - (["recent", "daily", "weekly"] as Tier[]).map(tier => [tier, new Map()]), -); -let last: Sample | null = null; -function retain(sample: Sample): boolean { - if (last && sample.at < last.at) return false; - for (const [tier, points] of history) { - const key = bucket(sample.at, tier), previous = points.get(key); - // Closing a bucket with no observation in its final six-hour interval is a gap. - for (const [oldKey, point] of points) { - if (oldKey < key && bucket(point.at, "recent") < (oldKey + 1) * widths[tier] / widths.recent - 1) point.gap = true; - if (oldKey < key - limits[tier] + 1) points.delete(oldKey); - } - const missed = previous - ? bucket(sample.at, "recent") - bucket(previous.at, "recent") > 1 - : bucket(sample.at, "recent") > key * widths[tier] / widths.recent; - const changed = !!last && (last.scope !== sample.scope || last.basis !== sample.basis); - const gap = !!previous?.gap || missed || changed || !sample.complete || sample.bytes === null; - // A failed refresh preserves complete evidence, but never erases its gap. - points.set(key, { ...(previous?.complete && !sample.complete ? previous : sample), tier, gap }); - assert.ok(points.size <= limits[tier]); - } - last = sample; - return true; -} -for (let i = 0; i < 365 * 4; i++) retain({ ...steady[0], at: start + i * 6 * hour }); -assert.deepEqual([...history.values()].map(points => points.size), [64, 90, 32]); -const weekly = [...history.get("weekly")!.values()]; -assert.ok(weekly.at(-1)!.at - weekly[0].at >= 210 * day); -const beforeReverse = JSON.stringify([...history.values()].map(points => [...points])); -assert.equal(retain(steady[0]), false); -assert.equal(JSON.stringify([...history.values()].map(points => [...points])), beforeReverse); -// Three missed intervals within the next UTC day remain visible after a good endpoint. -const nextDay = start + 365 * day; -retain({ ...steady[0], at: nextDay }); -retain({ ...steady[0], at: nextDay + 18 * hour }); -assert.equal(history.get("daily")!.get(bucket(nextDay, "daily"))!.gap, true); -retain({ ...steady[0], at: nextDay + 19 * hour }); -assert.equal(history.get("daily")!.get(bucket(nextDay, "daily"))!.gap, true); -const afterOutage = nextDay + 400 * day; -retain({ ...steady[0], at: afterOutage }); -assert.deepEqual([...history.values()].map(points => points.size), [1, 1, 1]); - -// Distinct available-capacity endpoint windows; no production implementation is imported. -type Forecast = { kind: "depleting"; days: number } | { kind: "non-depleting" } | { kind: "unavailable" }; -function forecast(samples: Sample[], now: number, long = false): Forecast { - const latest = samples.at(-1), points: Sample[] = []; - if (!latest || latest.at > now || now - latest.at > 6 * hour) return { kind: "unavailable" }; - for (let i = samples.length - 1; i >= 0; i--) { - const point = samples[i], next = points[0]; - if (!point.complete || point.gap || point.available === null || point.scope !== latest.scope || point.basis !== latest.basis || point.total !== latest.total - || latest.at - point.at > (long ? 30 : 7) * day || (next && (next.at <= point.at || next.at - point.at > (long ? 48 : 12) * hour))) break; - points.unshift(point); - } - if (points.length < (long ? 15 : 5) || latest.at - points[0].at < (long ? 14 : 2) * day) return { kind: "unavailable" }; - const changes = points.slice(1).map((point, i) => points[i].available! - point.available!); - const net = points[0].available! - latest.available!; - if (net === 0) return { kind: changes.every(value => value === 0) ? "non-depleting" : "unavailable" }; - if (changes.filter(value => value * Math.sign(net) >= 0).length / changes.length < 2 / 3 - || Math.max(...changes.map(Math.abs)) > Math.abs(net) / 2) return { kind: "unavailable" }; - if (net < 0) return { kind: "non-depleting" }; - const days = latest.available! / (net / ((latest.at - points[0].at) / day)); - return Number.isFinite(days) ? { kind: "depleting", days } : { kind: "unavailable" }; -} -const capacityTrace = (count: number, spacing: number, available: (i: number) => number) => Array.from({ length: count }, (_, i) => ({ ...steady[0], at: start + i * spacing, available: available(i), total: 10_000_000_000 })); -const short = capacityTrace(13, 6 * hour, i => 3_000_000_000 - i * 25_000_000).map(p => ({ ...p, at: p.at + 18 * day })); -const long = capacityTrace(22, day, i => 3_750_000_000 - i * 50_000_000); -const shortResult = forecast(short, short.at(-1)!.at), longResult = forecast(long, long.at(-1)!.at, true); -assert.deepEqual(shortResult, { kind: "depleting", days: 27 }); -assert.deepEqual(longResult, { kind: "depleting", days: 54 }); -// The approved 30-day window includes the early change 29 days ago, while -// excluding the preceding 31-day-old endpoint. A 28-day window loses it. -const month = capacityTrace(32, day, i => 4_000_000_000 - Math.min(i, 2) * 100_000_000 - Math.max(0, i - 2) * 50_000_000); -assert.deepEqual(forecast(month, month.at(-1)!.at, true), { kind: "depleting", days: 2_350_000_000 / (1_550_000_000 / 30) }, "STORAGE_DESIGN_USES_30_DAY_POLICY"); -assert.equal(forecast(short.map((p, i) => ({ ...p, total: i === 8 ? p.total + 1 : p.total })), short.at(-1)!.at).kind, "unavailable"); -assert.equal(forecast(short, short.at(-1)!.at + 7 * hour).kind, "unavailable"); -assert.equal(forecast(short, short.at(-1)!.at - 1).kind, "unavailable"); -assert.equal(forecast(short.map((p, i) => ({ ...p, gap: i === 8 })), short.at(-1)!.at).kind, "unavailable"); -assert.equal(forecast(short.map((p, i) => ({ ...p, scope: i === 8 ? "troy" : p.scope })), short.at(-1)!.at).kind, "unavailable"); -assert.equal(forecast(capacityTrace(13, 6 * hour, i => 3e9 - (i >= 4 ? 1e9 : 0)), start + 3 * day).kind, "unavailable"); -assert.equal(forecast(capacityTrace(13, 6 * hour, i => 3e9 + i * 1e7), start + 3 * day).kind, "non-depleting"); -assert.equal(forecast(capacityTrace(13, 6 * hour, () => 3e9), start + 3 * day).kind, "non-depleting"); -assert.equal(forecast(capacityTrace(13, 6 * hour, i => 3e9 + (i % 2 ? 1e9 : 0)), start + 3 * day).kind, "unavailable"); -assert.equal(forecast(long.slice(0, 14), long[13].at, true).kind, "unavailable"); -assert.equal(forecast(long.map((p, i) => ({ ...p, complete: i !== 17 })), long.at(-1)!.at, true).kind, "unavailable"); -const unknownForecast: Forecast = { kind: "unavailable" }; -const depletion = (days: number): Forecast => ({ kind: "depleting", days }); -const within = (f: Forecast, days: number) => f.kind === "depleting" && f.days <= days; -const beyond = (f: Forecast, days: number) => f.kind === "non-depleting" || f.kind === "depleting" && f.days > days; -function severity(ratio: number | null, a: Forecast, b: Forecast, refused = false): Severity { - if (refused || ratio !== null && ratio <= .05 || within(a, 7) && within(b, 7)) return "critical"; - if (ratio !== null && ratio <= .10 || within(a, 30) || within(b, 30)) return "low"; - return "observed"; -} -assert.equal(severity(.5, depletion(6), unknownForecast), "low"); -assert.equal(severity(.5, depletion(6), depletion(7)), "critical"); -assert.equal(severity(.04, unknownForecast, unknownForecast), "critical"); -assert.equal(severity(null, unknownForecast, unknownForecast, true), "critical"); -assert.equal(severity(.5, shortResult, longResult), "low"); -const recoverForecast = (state: "low" | "critical", a: Forecast, b: Forecast) => state === "critical" ? beyond(a, 10) || beyond(b, 10) : beyond(a, 45) && beyond(b, 45); -assert.equal(recoverForecast("critical", unknownForecast, depletion(9)), false); -assert.equal(recoverForecast("critical", unknownForecast, depletion(11)), true); -assert.equal(recoverForecast("low", unknownForecast, depletion(100)), false); -assert.equal(recoverForecast("low", { kind: "non-depleting" }, depletion(46)), true); -// Every active cause must recover. Missing refusal evidence never disappears in a good scan. -const clears = (ratio: number | null, forecastRecovered: boolean, refused: boolean, matchingSuccess: boolean) => ratio !== null && ratio > .07 && forecastRecovered && (!refused || matchingSuccess); -assert.equal(clears(.9, true, true, false), false); -assert.equal(clears(.9, false, false, true), false); -assert.equal(clears(null, true, true, true), false); -assert.equal(clears(.08, true, true, true), true); - -// Model durable notification intent/receipt, with no transport or network call. -type Delivery = { phase: "pending" | "sending" | "accepted" | "unknown" | "rejected"; attempts: number }; -function deliver(row: Delivery, input: { owner: boolean; active: boolean; fresh: boolean; hour: number | null; outcome: "accepted" | "unknown" | "rejected" }): boolean { - if (!input.owner || !input.active || !input.fresh || input.hour === null || input.hour >= 22 || input.hour < 8 || row.attempts >= 3 || ["sending", "accepted", "unknown"].includes(row.phase)) return false; - row.phase = "sending"; row.attempts++; row.phase = input.outcome; return true; -} -const eligible = { owner: true, active: true, fresh: true, hour: 12, outcome: "accepted" as const }; -const receipt: Delivery = { phase: "pending", attempts: 0 }; -for (const input of [{ ...eligible, owner: false }, { ...eligible, active: false }, { ...eligible, fresh: false }, { ...eligible, hour: 22 }, { ...eligible, hour: 7 }, { ...eligible, hour: null }]) assert.equal(deliver(receipt, input), false); -assert.equal(deliver(receipt, { ...eligible, hour: 8 }), true); -assert.equal(deliver(JSON.parse(JSON.stringify(receipt)), eligible), false); // restart -assert.equal(deliver({ phase: "unknown", attempts: 1 }, eligible), false); -assert.equal(deliver({ phase: "sending", attempts: 1 }, eligible), false); // crash after intent -const retries: Delivery = { phase: "pending", attempts: 0 }; -for (let i = 0; i < 3; i++) assert.equal(deliver(retries, { ...eligible, outcome: "rejected" }), true); -assert.equal(deliver(retries, eligible), false); -console.log(JSON.stringify({ fixture: "Odysseus, 2026-07-12", sampleBytes, payloadBound, tierLimits: limits, weeklySpanDays: (weekly.at(-1)!.at - weekly[0].at) / day, scenarios: { shortResult, longResult }, states, delivery: "offline model only; no notifications sent" }, null, 2)); diff --git a/docs/plans/storage-growth.md b/docs/plans/storage-growth.md deleted file mode 100644 index de637db92c..0000000000 --- a/docs/plans/storage-growth.md +++ /dev/null @@ -1,443 +0,0 @@ -# Storage growth and low-space guidance - -This design implements the maintainer's [reconciled ruling](https://github.com/schlessera/brain-kit/issues/2014#issuecomment-6212070681), -recorded durably in [Storage guidance](../decisions/storage-guidance.md). -It specifies a later extension; it does not activate runtime collection or -notifications. The [initial Storage design](../decisions/design-kit/storage.md) -keeps its complete inspect/select/review/remove/result journey and does not wait -for history. No cleanup or retention policy is changed by a pressure warning. - -## Boundaries and ownership - -The UI server owns aggregate observation history in its existing operational -state, under the same human-owner boundary as Storage inventory. Agents and -ordinary content readers receive neither history nor capacity targets. No -new core database, `.stats-history.jsonl` fields or filesystem-provider seam. -Operational backup/restore includes the new server table through its existing -versioned migration/export machinery; restoring history never restores files. - -Core corpus history is intentionally different (`snapshotOf`, -`packages/core/src/lib/stats-history.ts:132-172`) records filtered corpus and -health fields; thinning (`thin`, `packages/core/src/lib/stats-history.ts:232-244`) retains -recent days and older weekly observations. Neither contract supplies server -capacity identity or a lifetime byte bound. Caller availability alone -(`freeSpaceBytes`, `packages/core/src/lib/stats.ts:219-230`) is not quota headroom. -[Accounting discovery](storage-accounting.md) and -[native brain storage](../decisions/native-brain-storage.md) bind all quantities. - -## Bounded record and encoding - -Schema `storage_history_v1` retains **186 aggregate samples** globally, with at -most four capacities per sample. Its canonical UTF-8 JSON payload uses compact -tuples, capped at **1,152 bytes per sample**, plus at most **40,960 bytes** for a -shared descriptor dictionary and singleton warning/scheduler state. Including -array framing (187 bytes), the maximum is **255,419 bytes**, below **256 KiB**. -Notification delivery receipts have their own bounded operational table; they -are not smuggled into this history-payload claim. Their physical charge is part -of the operational DB inventory, as are SQLite pages and WAL. - -The conceptual fields are preserved by this exact tuple schema (no rounding, -lossy packing or silently dropped values): - -```ts -type Quantity = number | null; // safe, nonnegative byte integer; null is unknown -type Capacity = [ - descriptor: number, // integer 0..743; dictionary holds identity and root scope - total: Quantity, used: Quantity, free: Quantity, available: Quantity, - coverage: 0 | 1 | 2, // complete, partial, unknown - brainLogical: Quantity, brainAllocated: Quantity, - appLogical: Quantity, appAllocated: Quantity, - operatorLogical: Quantity, operatorAllocated: Quantity, - unionLogical: Quantity, unionAllocated: Quantity, -]; -type Sample = [ - version: 1, tier: 0 | 1 | 2, gap: 0 | 1, - at: number, start: number, // actual UTC epoch milliseconds; safe nonnegative - source: 0 | 1 | 2, // scheduled, refresh, operation - descriptor: number, // integer 0..185: collector, global scope and basis - coverage: 0 | 1 | 2, - reason: 0 | 1 | 2 | 3 | 4 | 5, // none, partial, capacity, scope-limit, budget, changed - capacities: Capacity[], // at most four -]; -``` - -Dictionary entries are fixed tuples. A sample descriptor holds package version -(at most 32 ASCII characters), 32-character scope hash and basis version 1. -A capacity descriptor holds a 32-character identity hash and 32-character root -scope hash. The combined serialized dictionary and singleton must fit 40,960 -bytes; do not reserve an independent budget per dictionary kind. Descriptor IDs -are local immutable references while used by retained samples, never reused -under an existing sample. Garbage-collect unreferenced descriptors in the same -transaction as tier replacement. If churn exhausts this budget, pause history -and expose the reason while preserving the previous valid set. The maximum -field-length experiment separately qualifies four capacities and 186 samples; -it does not pretend worst-case unique scope churn fits the dictionary forever. -No per-file names, paths or content are retained. Public JSON uses named fields -and documented versioning; compact tuples are private persistence encoding. - -`owners` are attribution views, not additive physical partitions. `union` is -computed once from object identities; never sum overlapping owners. Shared -extents remain qualified charges. Capacity fields retain native provenance and -unknown semantics in the schema/basis version; unsupported overlay/quota -identities cannot become comparable capacities. There is no per-file/path -history, reservation estimate, transcript content, filename, provider key or -host pathname. The server maps opaque IDs to current authorized display names. - -At most four capacities have retained history. Select their stable order once -per scope epoch, rather than rotating capacities. Additional capacities remain -visible in inventory with “History not recorded for this capacity.” Global -coverage becomes partial with `scope-limit`; individually complete retained -scopes can still be compared. Reconfiguration starts a new epoch. - -SQLite page/index/WAL overhead is **outside the serialized-payload bound**; -it is not claimed to fit in 256 KiB. The operational DB already appears once in -App storage, including history. Do not add payload bytes to measured DB bytes. -Report the payload charge separately as explanation. Insufficient operational -headroom preserves the previous valid tiers and reports “History paused.” Never -force vacuum, truncate WAL, expire journal objects or delete backups to fit -history. Sampling failure must not destroy recovery. - -## Cadence, replacement and cost - -Sample **once per six-hour UTC bucket**, at the first eligible opportunity while -the server runs. No catch-up scans after restart/sleep. No startup admission or -worker hot-path scans. A cross-process owner lease coalesces scheduled, explicit -refresh and operation requests into one collection; callers share its result. -It does not exclude file writers; operations keep their existing mutation locks. - -A successful Refresh or completed operation may replace the current bucket. -Persist at most one history transaction per minute; requests during that minute -retain only the newest pending aggregate. A crash loses that pending observation, -not content. A partial observation may be retained only if no complete sample -exists in the bucket; otherwise expose the failure without erasing good evidence. - -Retain three overlapping UTC tiers, with **186 total slots**, including current -buckets: - -| Tier | Bucket width | Slots | Nominal retained horizon | -| --- | --- | --- | --- | -| Recent | Six hours | 64 | 16 days | -| Daily | One UTC day | 90 | 90 days | -| Weekly | Seven days, Monday 00:00 UTC | 32 | 224 days (about seven months) | - -Each collected observation updates the current bucket in all three tiers in -**one transaction**. Each tier retains the latest actual observation in its -bucket, with its original timestamp and values; these are endpoints, not sums, -averages or peaks. The same observation may occupy three slots. Overlap is -intentional and included in the 186-slot bound, not added to the horizon. -No scans run for compaction, and no raw history is retained behind these tiers. -Updating three bounded records replaces the old single-record write while the -scan cadence and transaction rate remain unchanged. - -Expire buckets by UTC age as well as slot count: retain bucket indexes from -current index minus (slots minus one) through current index. On restart, prune -old records during the next eligible transaction without backfilling empty -buckets. Thus a long outage cannot turn 32 weekly slots into an unbounded age -claim. Current buckets are labelled provisional; actual endpoint timestamps -remain visible. Clock reversal pauses persistence until the last accepted time -is reached, rather than overwriting a newer bucket with an older measurement. - -`gap` is sticky within each bucket. Set it when an observation is partial, -unknown, has a changed scope/basis, or a scheduled six-hour bucket is missing. -For a bucket first observed after its first six-hour interval, set it immediately. -When closing a bucket, a missing final interval also sets it. Retaining a prior -complete endpoint after a failed refresh does not clear this flag. A whole -missing day/week has no invented record. Reconfiguration never combines values -across identities; retain the newest endpoint but mark the affected bucket. -This conservative flag applies to all capacity series in that sample. - -The table labels Recent/Daily/Weekly and the actual observation time. Older -history uses discrete points, without interpolating daily or weekly endpoints -or implying that peaks between them were retained. Missing buckets and flagged -buckets are visibly incomplete. Observed recent rates use only Recent samples with `gap: false`. Forecasts use -the separately qualified windows below. A coarse point cannot fill a recent gap -or count as an extra recent observation; weekly history is inspection-only. - -The bounded dictionary/singleton records schema, last attempted bucket, last persisted -time and current episode states for four scopes. Tier indexes derive from -sample timestamps, and gap flags live in the capped samples. No unbounded event -log or separate rollup staging buffer. - -A full sample reuses inventory budgets: one scan/app, at most two metadata -workers, finite entries/depth/time/output/errors. No Git maintenance, attachment -hashes, unapproved stores or writable content DB. Capacity-only refresh can update -current guidance but is not an aggregate-history sample: it cannot repeat an old -store total under a new timestamp. - -Maximum scheduled cost is four bounded scans and four small transactions per -running day. A tick coalesces with an active scan and never queues a backlog. -Explicit refresh retains owner-coordinator rate limits. This is a cost -ceiling, not proof that large-corpus scanning is cheap. Implementation needs -real runtime/cancellation evidence and no-stall proof for concurrent turns. - -## Comparability and growth - -Compare only equal capacity identity, root-set scope, basis version, complete -coverage, no gap flag and available fields. A collector patch is comparable only when its -measurement semantics are unchanged; a basis change starts a new epoch. Unknown -allocation, unsupported identity, overflow, root changes and partial samples -create labelled gaps. Never interpolate across them. Reflink allocation is a -qualified charge, not exclusive physical usage or reclaimable space. - -The observed rate is **observed endpoint change divided by elapsed -time** across the latest contiguous comparable Recent window, at most seven days. -Require five complete samples spanning at least 48 hours and no gap over -12 hours. Display signed decimal bytes/day, basis and interval: -“App allocation +120 MB/day observed over 3 days.” Negative values say decreased; -a flat observed window can show zero. Insufficient evidence cannot. - -Capacity availability is a separate series. Other writers, retained objects, -filesystem overhead and delayed reclamation can change it independently of the -known-store union. Never label all capacity loss as App growth or all observed -post-operation gain as reclaimed by that operation. - -### Qualified exhaustion scenarios - -Compute depletion from **available capacity**, independently of the known-store -union. A capacity's total, identity, permitted-root scope and basis must match -throughout a window. Never use logical/allocated App growth to forecast capacity. - -| Window | Evidence | -| --- | --- | -| Short | Recent points within seven days; at least five distinct endpoints spanning 48 hours; no interval over 12 hours. | -| Long | Completed Daily endpoints within 30 days plus the latest Recent endpoint; at least 15 distinct endpoints spanning 14 days; no interval over 48 hours. | - -Deduplicate identical timestamps. The latest point must be the current complete -capacity observation and at most six hours old, with no future timestamp. Walk -back only through a contiguous compatible suffix: partial, unknown, gap, changed -identity/total/basis, invalid ordering or excess interval breaks the window. -Coarse gap flags reject incomplete daily buckets; weekly points never qualify. -The current day's provisional daily point supplies no extra evidence. - -For each qualified window, observed depletion/day is `(first.available - -last.available) / elapsedDays`. Require at least two-thirds of intervals to -move in the net direction (flat intervals qualify), and no single interval's -absolute change to exceed half the absolute net change. This rejects a lone -burst/cleanup and inconsistent reversals; it does not establish statistical -accuracy. A perfectly flat window qualifies as non-depleting. A mixed window -with zero net change is unavailable. A smoothly replenishing qualified window -also reports **No depletion observed**, without a numeric exhaustion horizon. - -For positive depletion, horizon is `latest.available / depletionPerDay` in days, -with finite arithmetic. Keep exact values for severity comparisons; round only -copy. Zero available bytes can yield zero days. Qualified non-depleting evidence -is distinct from missing/incompatible evidence and may satisfy forecast recovery; -it never says unlimited space or guarantees a write will fit. - -Show both labelled window scenarios and their actual intervals. If both finite -estimates differ, show their min–max range with “If these observed rates continue.” -If one is unavailable, show the other with the missing window's reason; a sole -projection can trigger Low, never forecast-driven Critical. If one is -non-depleting and the other positive, show the finite scenario and “No depletion -observed in the other window,” not a numeric range to infinity. Rapid acceleration -may remain underpredicted: capacity thresholds and owner refusals remain independent. -No probabilistic confidence, countdown promise or causal cleanup-savings claim. - -## Low-space states and hysteresis - -Evaluate each resolved capacity independently. Fresh means a complete trustworthy -observation no older than six hours. Unknown capacity has no inferred percentage, -zero meter or healthy verdict. Preserve warning age when evidence goes stale. - -| State | Entry | Copy/action | -| --- | --- | --- | -| Unknown | Missing trustworthy total/available/identity | “Capacity unavailable. Refresh or inspect host capacity.” | -| Observed | No active cause | “Capacity observed … ago.” No promise an operation fits. | -| Low | Available at or below 10%, or either qualified finite scenario at or below 30 days | “Low space. Review capacity and observed trends.” | -| Critical | Available at or below 5%, both finite scenarios at or below seven days, or an owner-confirmed no-space refusal | “Very low space. Some writes may be refused.” | -| Stale | Current evidence older than six hours | “Refresh before planning maintenance.” Preserve active warnings. | - -Track causes separately within a capacity episode; never clear one cause using -another cause's unrelated evidence. Worsening takes one qualifying observation. -Recovery takes two successive qualifying fresh observations at least 60 seconds -apart; intervening failure, incompatible evidence or reversal resets that pair. -Critical drops to Low first; two additional observations are needed to clear Low. - -- Capacity recovery: above 7% to leave Critical; above 12% to leave Low. -- Forecast recovery: to leave Critical, at least one qualified scenario beyond - ten days (or qualified non-depletion) breaks the two-scenario Critical condition. - To leave Low, both must be qualified beyond 45 days or non-depleting. Missing - evidence cannot be the recovering scenario. -- Refusal recovery: require a subsequent owner-reported successful write in the - same affected target and resource class, after the last refusal, plus the two - fresh above-7% observations. No synthetic write probe, empty-file test or - disappearance of the failing operation establishes recovery. Unresolved quota, - inode or unknown-target refusals stay explicit until the owning operation can - provide matching recovery evidence. After downgrade, the capacity Low rule - still applies. A new refusal resets recovery. - -Every active cause must satisfy its own exit rule before severity falls. -Clock reversal, unknown/partial/stale data and scope changes cannot clear an -old episode. A changed scope is Unknown; retain the unresolved prior episode -as requiring inspection, without transferring its measurements into the new scope. -Explicit Refresh can provide the recovery pair without extra background scans. - -## Indicator and Critical Web Push - -Storage shows capacity-specific evidence; a persistent app indicator shows the -highest active severity and opens Storage. Neither adds a main destination or -shortcut. Unknown/stale state is labelled, never silently green. Storage and the -indicator remain usable without push permission. Repeated scans update the same -state without repeated assertive announcements; explicit Refresh announces its -completion once politely. Critical text is associated with the capacity heading. - -Use only existing authenticated, opt-in **owner** Web Push subscriptions, with -revocation rechecked at dispatch. Ordinary content readers and agents must not -receive operational information. Send at most one successful transport submission -per Critical episode/subscription; no daily reminders initially. An episode starts -on entry to Critical and ends only after confirmed downgrade. A later re-entry is -a new episode. Persist episode and destination receipt identities across restarts. -Bound episode state to the four tracked capacities; purge retired episodes after -all pending delivery is terminal, retaining active and latest resolved identity -per capacity. Destination rows cannot outlive their existing subscription. - -Use a unique durable `(episode, subscription)` intent before transport. Cap all -attempts at three per pair, with retry delays of one and five minutes only for -known non-delivery/rejection. An ambiguous timeout or crash after dispatch is -**unknown**, not a reason to resend; expose that delivery state in Storage. -No exactly-once device-display claim: push transport acceptance is not delivery. -A browser notification tag derived from the opaque episode coalesces replacement -at the destination, but is not used to justify duplicate server submissions. - -All attempts respect device-local **[22:00, 08:00)** quiet hours, without refusal -exceptions. Use authenticated timezone reporting; an absent/invalid zone keeps -delivery pending without guessing. Recompute eligibility after timezone/clock -changes. When eligible, revalidate current owner access, subscription, active -Critical state and fresh supporting evidence. A stale/unknown warning stays -visible but sends no push until refreshed; confirmed recovery suppresses pending -notices. Coalesce multiple eligible capacities into one generic notification, -recording every included episode's receipt. No backlog replay or new scans solely -for delivery. Contents say only “Storage needs attention. Open Storage for details.” -Do not expose capacity IDs, amounts, paths or filenames on a lock screen. - -A status never authorizes writes. Packing, index rebuild/compaction, pin refresh, -retained binary removal/Undo and backups may need headroom. Label those actions -“Needs headroom.” Owner preflight remains final; refusal and manual capacity -provision are legitimate. Never discard history, pins, sessions or backups as an -automatic cure. Scratch/staging cleanup uses existing policies. Retained-only -pressure must be able to say “No eligible cleanup found.” - -## Layouts and accessible copy - -At 320px (296px content), cards stack with wrapping text/actions and 44px targets. -Units are decimal with exact-byte details. Labels/icons/text convey states in -dark, paper and grey; colour is supplementary. - -```text -Storage -Capacity · Brain volume -! Low space -1.80 GB available of 20.0 GB -Observed 4 minutes ago -Writes: Brain files, Git, -retained file history -[Refresh] - -Growth · On disk -App: +120 MB/day observed -Over 3 days · 13 samples -Shared extents may overlap -Capacity scenarios: 18–42 days -If observed rates continue -[View observations] - -Review cleanup -[Prune eligible scratch] -Pinned answers stay -[Pack Git objects] -Needs headroom -No eligible cleanup found? -Add capacity through your host. -``` - -Desktop keeps capacity-specific cards above the existing treemap/list. Do not -combine capacities. Expand details inline without losing filters, selection or -focus; alerts never displace a selected-file review. - -```text -Storage [Refresh] Observed 4 minutes ago -+----------------------------------+----------------------------------+ -| ! Low space · Brain volume | App volume · Capacity observed | -| 1.80 GB available / 20.0 GB | 8.00 GB available / 40.0 GB | -| Writes: files, Git, retained | Writes: sessions, inbox, UI DB | -| history | | -+----------------------------------+----------------------------------+ -Growth · On disk App +120 MB/day over 3 days · 13 samples -[View observations] Shared extents may overlap · Capacity scenarios 18–42 days -If observed rates continue · Short 3 days / long 21 days -Treemap / equivalent table Existing inspect/remove flow -Maintenance: [Prune eligible scratch] [Pack Git objects · Needs headroom] -``` - -Unknown and retained-only pressure have complete phone states: - -```text -Capacity · Brain volume -? Capacity unavailable -Last observation: 8 hours ago -Writes: Brain files, Git, -retained file history -[Refresh] -Growth unavailable -Need comparable observations - -! Very low space · App volume -Owner refused a write -Available bytes unknown -Retained data uses this store -No eligible cleanup found -Add capacity through your host. -[Refresh] [View retained usage] -``` - -An observation table supplies time/age, scope, basis, coverage and nullable values -as an equivalent to any sparkline. Missing points are gaps, not zeros. Keyboard -users reach all actions and return from details; refresh never moves focus. -At 200% zoom the layout stacks without clipping. Reduced motion disables chart -animation. Runtime/browser/accessibility proof belongs to implementation. - -## Synthetic decision examples - -The companion [trace experiment](storage-growth-experiment.ts) evaluates these -rules offline using Odysseus observations anchored to 2026-07-12. It is -not production history, implemented runtime or a benchmark. - -| Trace | Required interpretation | -| --- | --- | -| Steady growth, 13 samples over three days | Signed rate; no long-window scenario until its evidence minimum is met. | -| Burst then steady size | Signed rate; burst-dominated depletion window yields no projection. | -| Reclamation | Negative observed change; no causal savings claim. | -| Capacity/root change | New epoch; old observations cannot supply a rate. | -| Partial/unknown midpoint | Break the window; too little new evidence means no rate. | -| Retained-only pressure | Low/Critical plus no eligible cleanup; capacity provision is legitimate. | -| Concurrent unowned writer | Capacity falls while store usage is flat; do not attribute loss to App. | -| Year of six-hour observations | At most 64/90/32 slots; weekly history reaches approximately seven months without extra scans. | -| Missing interval inside a daily/weekly bucket | Sticky gap survives replacement by a later complete endpoint. | -| Long outage | Empty periods remain empty; age-expired buckets disappear without catch-up scans. | -| Threshold oscillation | Worsen immediately; clear only with two qualifying observations 60 seconds apart. | - -The experiment checks maximum-width numeric tuple encoding for four capacities, -the 186-record payload ceiling, all tier caps and seven-month weekly reach. It -also checks forecast windows, burst/reclamation rejection, divergent scenarios, -missing evidence, direct warnings, cause-specific recovery, refusal evidence and -restart/deduplication/quiet-hours suppression with a deterministic local model. -These traces qualify rules, not real-world forecast error bounds or transport -reliability. Implementation issues require genuine runtime/browser/migration proof -and physical SQLite/WAL measurements. No fixture sends a notification. - -## Implementation boundaries - -Server history/state/delivery and UI guidance are separate native children of -#1779, after this design spike. The server issue owns migration, bounded payload -and receipts, authoritative owner checks, shared scan coalescing, timers, -cancellation, recovery and versioned HTTP/config contracts. The UI issue owns -history tables/charts, labelled scenarios, persistent indicator, accessible -capacity guidance and notification navigation. Initial pane delivery is #2013; -these additions must not introduce an incomplete public pane before it. - -Remote/provider usage needs an authenticated provider-specific scope/quota -contract. Host/container stores need explicit owner-approved roots and safe -measurement evidence. Per-file Git attribution needs a bounded meaningful model. -Derivative grouping needs provenance. Workspace cleanup needs its own lifecycle -and use-case ruling. New journal/history/backup expiry needs an explicit loss -and recovery ruling. Pressure does not authorize any of them. diff --git a/docs/plans/storage-lifecycle.md b/docs/plans/storage-lifecycle.md deleted file mode 100644 index c6b9bf19ea..0000000000 --- a/docs/plans/storage-lifecycle.md +++ /dev/null @@ -1,331 +0,0 @@ -# Storage cleanup and retention discovery - -Recommendation for [#1781](https://github.com/schlessera/brain-kit/issues/1781), -under [#1779](https://github.com/schlessera/brain-kit/issues/1779). This is design -input for [#1782](https://github.com/schlessera/brain-kit/issues/1782), coordinated -with the accounting discovery in [#1780](https://github.com/schlessera/brain-kit/issues/1780). -It approves no deletion policy, new retention default or runtime API. - -Source inspected at `f2c98da6093c9e1731f061625ba7302f51bf7340`. -Final lifecycle review also includes `2ea27697850dfffe956f2aa8471a720ea738f2bb`: -[#1778](https://github.com/schlessera/brain-kit/issues/1778)'s delivered correction -separates immutable startup inputs from bounded copy-on-write output staging. -The synthetic measurement below retains its original source/conditions. -The [governed-worker decision](../decisions/governed-writable-workers.md), -[writable-area decision](../decisions/worker-writable-areas.md), and -[all-writer boundary](../decisions/policy-write-boundary.md) bind execution. -The governed record supersedes older read-only defaults and HOME overlays. - -## Recommendation - -Build storage inspection first, then expose existing bounded housekeeping -through its owners. Offer selected canonical attachment removal only after a -dedicated, stale-safe, journaled application operation exists. The current -file routes read files; they have no deletion endpoint. The curated application -route accepts ordinary Markdown, not arbitrary binaries -(`function validatePath`, `packages/ui-server/src/brain/application.ts:37-55`). -Document archive changes visibility/relevance and may move Markdown; it does -not remove an attachment or reclaim its history. Do not present it as Delete. - -Use maintenance workers for repository code, the CLI and Git. Host routes may -perform narrowly validated descriptor operations, as the journal/revert do; -they must not evaluate brain configuration, hooks, filters or executables. -The existing brain client supplies boundary execution -(`async function execBrain`, `packages/ui-server/src/brain/client.ts:302-357`). -Do not turn the new surface into a host command runner or an extension seam. - -Reuse existing authorization. A requested reversible, fully journaled edit -needs no extra approval solely because it appears under Storage. An unjournaled -delete is irreversible under the governing ruling and cannot masquerade as -that edit. Outward sync retains G5 policy/approval; command rules still apply -to shell actions. Protected policy paths retain R35. UI execution is bound to -the authenticated principal, exact selection and operation; revocation and -profile authority are checked again at execution. Restricted autonomous work -and voice gain no new tools from this recommendation. - -## Operation matrix - -Logical bytes, allocated bytes and available volume capacity are separate -measurements. Every row requires fresh after-state even when the operation -fails. A removed-byte count is not a volume-reclamation receipt. Temporary -space entries below are requirements to assess, not reservations implemented -by this spike. - -| Operation / owner / primitive | Data and eligibility | Protection, revalidation and authority | Recovery / temporary space | Expected effect and after-measurement | -| --- | --- | --- | --- | --- | -| Selected content removal; core deterministic content semantics + ui-server application/journal; **proposed binary operation** | Canonical tracked/untracked attachments, individually selected. Ignored, unindexed and external-link cases need explicit classification. | Recheck exact root/parent/file identity, bytes/hash, permissions, protected paths, references and live ownership under the applicable gate/lock. Authenticated requested edit; no arbitrary host Git. | Retained, verified before-version required for reversible removal; current journal exclusions can make a file ineligible. CAS capture may copy its entire bytes and uses charged temporary capacity. | Current file count/bytes decrease; references can break. Measure working-tree bytes/status, retained journal bytes, local Git and per-volume availability separately. History/remotes can remain unchanged. | -| Attachment sidecars; core conversion/export owners + same application boundary; **proposed grouped selection** | Derived previews/OCR/Markdown/metadata only where provenance demonstrates the relationship. A filename suffix alone is insufficient. | Preview siblings and references; recheck each selected version. Never delete an independently edited or shared derivative automatically. Same authority as each selected content edit. | Each non-rebuildable selected file needs recovery bytes. Rebuildable sidecars still need a declared generator and resource/cost implications. | Report each removed, kept or conflicted sibling and actual aggregate delta. Regeneration can consume disk/CPU or paid services; no automatic paid rebuild. | -| Git packing; core `packRepository`, #398 | Local objects and refs, valid Git worktree. | Existing Git maintenance lock; worker boundary and existing Git locks. No ref deletion, reflog expiry, history rewrite or configuration mutation. | No history restoration needed because reachable content remains. Packs and old loose data coexist during packing; disk headroom and maintenance tmpfs admission are both required. | Loose count often drops; packs can grow before duplicate loose copies disappear. Measure loose+pack bytes, refs and availability after both passes; savings are workload-dependent. | -| Derived index refresh/rebuild/compaction; core index machinery, existing maintain/index entry points | `brain.db` and its owned sidecars only; content remains authority. | Run supported command in maintenance worker; use its locking and indexing configuration. Never infer that `ui.sqlite` or its sidecars are disposable. | Rebuild from Markdown; semantic data may require provider calls. Rebuild, WAL and vector compaction need headroom and can initially grow. | Index correctness/health is the goal, not guaranteed space savings. Report actual DB/sidecar bytes and failures, keeping existing stats contracts. | -| Eligible persistent scratch prune; core `pruneScratch`, server timer/pin bridge; #1656/#1691 | `.brain/scratch`; existing seven-day / 1 GiB policy for unpinned candidates. | Managed pins must be complete/readable; reread pins before each removal. Linked retained answers survive age and cap. Current writers pin their outputs for their own post-write pass. Use existing CLI boundary. | Unlinked scratch is ephemeral; no general Undo promise. Explicit `scratch clean` bypasses pin protection and must **not** back an ordinary safe-prune button. Pin refresh itself can need disk. | Existing report includes removals, failures, remaining/pinned bytes and overage. Show suspension/overage, never release pins merely to make the meter smaller. Re-measure allocated bytes/capacity independently. | -| Settled share staging cleanup; ui-server `createInboxCleanup`, #807/#686 | Server intake staging and partial directories associated with durable cleanup work. | Recovery gate, Queue/Action status, attempts, waits, lease/version and actual originating lifetime/settlement. Age or a terminal Queue row alone is insufficient. | Durable lease acknowledged after idempotent filesystem removal; restart resumes claimed work after recovery. Database writes still need headroom. | Existing sweep counts completed cleanup items, not exact bytes. Measure staged bytes after settlement; preserve attributable item outcomes instead of claiming everything in the directory was discarded. | -| Claude idle compression; backend `archiveIdleSessions`, #1621 | Native session trees idle strictly more than 30 days; at most daily. | Active IDs read after asynchronous metadata; checksum/source comparison before deleting live bytes. Private roots outside brain. Existing backend housekeeping, no session deletion implied. | Durable gzip/manifest/index precede source removal; restore before read/resume, conflicts keep newer live files. Full source and compressed copy coexist; code reads full individual files in memory. Not an emergency no-space operation. | Conversations remain listed. Measure combined live+archive+pending/conflict bytes; later restore can expand usage again. Compression is not guaranteed to save much for already compressed data. | -| Pi idle compression; backend #1637, **unavailable** at inspected source | Native Pi SessionManager trees. | #1637 owns same active-session/30-day/crash-safe policy; this spike does not implement it. | No shipped equivalent archive primitive verified. | Show unavailable, link existing work; do not promise Pi savings or create a duplicate task. | -| Workspace cleanup; ui-server journal + SDK writable areas, **proposed selective operation** | `workspaces/` may contain clones, uncommitted work, ignored build outputs and nested repositories. Index exclusion is not disposability. | Recheck running processes/jobs/locks, Git worktree/common-dir relationships, outside links/mounts, dirty/untracked state and journal coverage. No universal lease exists proving all arbitrary commands are idle. Unknown ownership is ineligible for unattended cleanup. | A recreatable clone still may contain unique work; copy/export guarantees must cover it before removal. Large directory copies are not admitted implicitly. | Report exact selected scope and excluded live/unknown work. Nested Git common storage must not be counted or removed as private to this workspace. No blanket age-based `rm -rf`. | -| Journal collection; ui-server `createTurnJournal` / accounting | Private CAS, journal-owned SQLite pages, manifests, reservations and quarantine/revert evidence. Existing 10 GiB cap / completed-detail retention. | Existing owner collects completed detail oldest-first under cap; active windows, shared refs and reader reservations protect objects. Do not offer a manual “cache clear” that circumvents ownership. | Detail expiry loses Undo; summaries can remain, and no pre-expiry deletion receipt extends retention. Existing cap collection is already approved; **new expiry rules are unresolved**. WAL/checkpoint needs safe headroom and can refuse reader contention. | Measure CAS and owned DB/WAL allocation, not just deleted rows. SQLite free pages may remain allocated. Label expired detail and remaining recovery window honestly. | -| Operational backups; ui-server export/restore + generated host scheduling/retention, #686 and hosting-template #9 | Full operational DB image and matching staging bytes; separate Git content backup. | Capture consistency checks; restore requires stopped writers, empty targets and matching checksum/recovery marker. Backup retention must preserve an operator-tested compatible recovery point. | At least 24-hour successful capture objective; replacement export has private temporary bytes. Retention policy and remote/provider deletion belong to host configuration, not a package default. | List known age/completeness/size; unknown remote or older artifacts stay unknown. Never delete recovery material to make an export fit. Report local and remote outcomes separately. | -| Runtime maintenance; SDK owned turn temp vs externally managed logs/images/layers | `turn_temp` only reaches the current worker's private `/tmp`; runtime state is excluded. Host/container caches and other users' data are outside ordinary app authority. | Existing scoped tool skips output-linked paths; named force may override, all+force refused; no-follow/device checks. No approval for this already-authorized scoped tool. No Docker socket or global prune. | Turn temp expires at exit; linked files promote via held descriptor. Purge is not Undo; runtime transcripts/settings/memory are not its targets. | Tool measures tmpfs usage/limit/actual delta and records governance; persistent storage reclamation is a separate metric. Host logs/images/volumes show externally managed/unavailable and generic operator guidance only. | -| Immutable native inputs and output staging; ui-sdk, #1790 | Short-lived read-only Btrfs checkpoints and separately bounded writable output. These are neither canonical content nor agent turn temp. | Durable owner leases and live references protect inputs and publication material. No storage-UI sweep of host temporary paths or deletion by guessed prefix. | Checkpoints consume the operator-configured hard managed-volume capacity. Recovery releases owned stages before their lower checkpoints; unknown ownership remains retained. Writable upper bytes/metadata use the existing staging allowance. | Measure managed-volume reclamation, writable upper allocation and canonical post-publication state separately. Removing a lower-only input does not free upper write capacity; whiteout metadata can consume it. No promise that canonical deletion fixes a staging-capacity refusal. | - -Source foundations for the matrix: - -- Packing runs two passes and deletes only loose duplicates already held in - packs (`export function packRepository`, `packages/core/src/lib/git-storage.ts:115-121`). - The upstream [maintenance manual](https://git-scm.com/docs/git-maintenance) - explains these tasks; broad `gc` has different expiry behavior. -- Staging eligibility, removal and acknowledgment are separate - (`export function createInboxCleanup`, `packages/ui-server/src/inbox/cleanup.ts:15-72`). -- Scratch pin loading and per-entry revalidation sit inside pruning - (`export function pruneScratch`, `packages/core/src/lib/scratch.ts:645-726`); - explicit clean is different - (`export function cleanScratch`, `packages/core/src/lib/scratch.ts:729-747`). - Server refresh refuses incomplete enumeration and confirms missing histories - before releasing links (`function openScratchPins`, `packages/ui-server/src/cron/scratch-pins.ts:72-195`). -- Claude publishes and verifies cold copies before deleting the live source - (`export async function archiveIdleSessions`, `packages/ui-backend-claude/src/transcript-archive.ts:261-321`). -- Journal collection requires no refs/reservations and only expires ended - turns (`function collectObjects`, `packages/ui-server/src/brain/turn-journal.ts:308-361`). - Retention is applied at admission - (`begin(turnId: string`, `packages/ui-server/src/brain/turn-journal.ts:463-510`). - Object copies reserve temporary bytes before writing - (`async putFileAsync`, `packages/ui-server/src/brain/journal-objects.ts:95-150`). -- Turn-temp purge has its own scope and measured result - (`export function purgeTurnTemp`, `packages/ui-sdk/src/server/worker-turn-temp.ts:451-534`), - and tool validation/recording - (`export function handleTurnTemp`, `packages/ui-sdk/src/server/bridge-tools/turn-temp.ts:19-41`). - [Operational recovery](../inbox-recovery.md) specifies backup consistency and - restart behavior; it is not an index rebuild. -- Startup input ownership is separate from writable staging - (`export async function prepareNativeWorkerStartupView`, `packages/ui-sdk/src/server/worker-startup-view.ts:108-160`). - The [native storage decision](../decisions/native-brain-storage.md) supersedes - complete user-space startup copies and defines checkpoint recovery ownership. - The staged-write limit states the separation - (`export function outputStagingLimit`, `packages/ui-sdk/src/server/worker-state-limits.ts:144-150`). - -## PDF larger than 5 MB: review and execution - -Use decimal MB explicitly: strict `sizeBytes > 5_000_000`. Offer MiB separately -as 1,048,576 bytes. File count and total logical bytes belong to the current -filtered inventory. The accounting discovery owns physical identity, overlap, -volume scopes, partialness and freshness; cleanup consumes that model rather -than summing content and deployment totals. - -1. Inspect authenticated file metadata/preview using the existing file reader. - Display tracked/untracked/ignored status and reference evidence with its - timestamp/completeness. Query indexed links, but also inspect bounded - Markdown references and report unindexed/unsupported sources as unknown. - A zero from the index is not proof of no attachments referenced in Markdown, - retained conversations, external consumers or another workspace. Do not - read every PDF's contents just to filter sizes. -2. Select exact files, then review references, related derivatives, current - Git state and available recovery coverage. For a referenced PDF, offer Keep - or an explicit removal selection with the broken-link consequence shown; - editing the referencing note is a separately selected, version-bound effect. - Do not silently rewrite references or cascade delete sidecars. Unknown - dependencies remain disclosed and can make automated removal ineligible. -3. The proposed server operation uses principal/session/operation-bound - idempotency and a durable selected-version manifest. Under the writer gate - and appropriate content locks, recheck parent descriptors/device identity, - existence/type/mode/link count, content hash, protected paths, active work, - reference/provenance changes and journal eligibility. A changed file or - changed consequence is a conflict requiring refreshed review; never widen - the set after selection. Do not follow aliases or nested mounts. -4. Retain verified before bytes and record intent before unlink. Use the - journal's own charged CAS/reader ownership; do not bypass retention to promise - permanent Undo. Ignored files only listed by name/size, incomplete snapshots - and unretained versions cannot qualify as reversible. Report refusal rather - than upgrading authority. A new binary route must define this integration; - the existing Markdown route cannot be reused by passing a `.pdf` path. -5. Unlink the exact eligible entry; reconcile observations and per-item durable - status. Queue supported index refresh through its maintenance boundary. - Worker/maintenance coordination must prevent a concurrent writer replacing - the selected entry between validation and unlink. Existing shared gate - admission alone is **not** an exclusive cleanup lock. -6. Report removed/conflicted/protected/failed/not-started separately, references - left broken, sidecars kept, recovery receipt and expiry/partialness. Offer - existing journal/revert only where eligible and version-verified. A restart - reads the original operation receipt; it never blindly reissues deletion. - Current content deletion and index refresh are distinct outcomes. -7. Git status initially shows deletion; supported sync may later commit and - push through its credentialed maintenance boundary and G5 authority. A failed - sync does not undo successful local removal. Report local, committed and - remote-sync state independently. Previous commits still reach the PDF blob; - a normal deletion commit is not historical/remote erasure. Git's - [object traversal](https://git-scm.com/docs/git-rev-list) and - [GC documentation](https://git-scm.com/docs/git-gc) distinguish reachability - from storage optimization. Remote provider reclamation is not observed here. - -## Pressure, cancellation and recovery - -Before execution, classify headroom on **each actual capacity scope**: content, -private journal, operational DB, Git storage, maintenance tmpfs and backup -destination can differ. Logical admission is not proof that disk allocation -will succeed. Preflight cannot eliminate ENOSPC races, quotas or concurrent -writes. Use bounded batches, item/byte/time budgets and cancellation between -items; no recursive unbounded copy or “delete whatever is oldest” fallback. - -Include immutable startup-copy disk headroom separately from the bounded -copy-on-write output upper. #1778 corrects the former accidental charging of -the whole input tree to output staging. A lower-only deletion can reduce a -published canonical tree without releasing upper write capacity, so candidate -file bytes cannot predict staging-limit relief. Input copy, staged writes, -turn temp and runtime state keep their own owners and capacity evidence. - -At low space, prefer known eligible existing scratch/staging/turn-temp work -where its owner can safely record the outcome. Packing, archive compression, -index rebuilding and backup export need temporary space and must not be offered -as guaranteed immediate rescue. Deleting a journaled PDF may initially use -more storage if its before-version was not already retained. - -At zero allocatable space, a new recovery manifest or CAS object can fail. -Refuse new reversible removals that cannot establish durable intent/recovery. -Do not purge journal objects, leases, WAL, authentication state, unsettled staging -or the last complete backup to make the operation succeed. Existing compensation -may remove already authorized eligible bytes but an acknowledgment can fail; -its durable original lease, not a success toast, governs restart. If safe -owned housekeeping cannot progress, show the refused store and required -headroom, and direct the operator to add capacity or manage externally owned -storage. This is an honest manual boundary, not a new privilege grant. - -A proposed cleanup receipt must distinguish pre-unlink failure, successful -unlink awaiting reconciliation, complete local mutation awaiting indexing/sync, -and ambiguous result. After a crash, compare the selected before-version and -current entry under the same gate: an absent entry can complete reconciliation; -a replacement never gets deleted on retry. Reconcile intent against the actual -journal and source identity before reporting success. A mixed selection keeps -successful outcomes and does not roll them back automatically; retry only -unstarted eligible items. Cancellation stops admission of more items, finishes -the current critical reconciliation, and keeps completed receipts. Lost responses -read the original receipt. Undo is a fresh stale-safe operation, not a blind copy -over a newer file. Such a receipt protocol is proposed, not implemented here. - -The writer gate is cross-process and tracks process identity, not age -(`export function gateProcedures`, `packages/ui-server/src/brain/writer-gate.ts:198-289`). -Use that primitive alongside lifecycle ownership; do not interpret stale leases -as proof an actually running backend is dead. Locks, retained readers and backups -can deliberately prevent immediate reclamation. - -## Synthetic evidence - -Run from a dependency-installed checkout: - -```sh -bun experiments/storage-lifecycle.ts -bun run test packages/core/tests/scratch-pins.test.ts packages/ui-server/tests/inbox-unwind.test.ts packages/ui-backend-claude/tests/transcript-archive.test.ts packages/ui-server/tests/turn-journal.test.ts packages/ui-server/tests/journal-accounting.test.ts packages/ui-sdk/tests/turn-temp-tool.test.ts -``` - -The manual experiment mutates only a newly created temporary Odysseus brain, -bare local remote and operational store, then removes them. It uses the real -packing and journal primitives, local-only Git subprocesses, fixed synthetic -`2026-07-12` content/commit dates and deterministic PDF-shaped bytes. These are -binary lifecycle fixtures, not valid PDF-rendering proof. No service/network, -real corpus, cleanup API or retention change is exercised. - -Observed with Bun 1.4.2, Git 2.55.0 on the local filesystem: - -| Measurement | Before | After removal + other PDF edit + local commit | After existing Git packing | -| --- | ---: | ---: | ---: | -| Current PDF count | 2 | 1 | 1 | -| Current logical PDF bytes | 12,000,000 | 6,000,027 | 6,000,027 | -| Attachment allocated bytes | 12,001,280 | 6,000,640 | 6,000,640 | -| Local `.git` allocated bytes | 6,447,104 | 12,787,712 | 6,447,104 | -| Journal object allocated bytes | 6,012,928 | 12,001,280 | 12,001,280 | -| Local bare-remote allocated bytes | 6,430,720 | 6,430,720 | 6,430,720 | -| Loose object count | 5 | 9 | 0 | -| Objects in packs | 0 | 0 | 9 | - -Both initial PDFs share identical bytes, so Git and journal deduplicate them. -The second gains 27 bytes after preview. Its hash differs, proving stale -selection evidence; the script observes that conflict but does not implement -the future executor. The first loses its working-tree entry while its referenced -Markdown link remains. A retained journal before-version matches all 6,000,000 -original bytes. `rev-list --objects --all` still includes its blob and -`cat-file -s` returns 6,000,000 before and after packing, locally and in the -bare remote. Ref identities are unchanged by packing. There is no remote push. - -The three selected local category deltas after removal sum to a **growth of -6,328,320 allocated bytes**: attachment -6,000,640, Git +6,340,608, journal -+5,988,352. Packing later saves 6,340,608 Git allocated bytes; that is neither -historical deletion nor guaranteed volume recovery. These figures exclude DB, -WAL, other files and filesystem metadata. They are `st_blocks * 512` category -observations on a quiescent fixture, not exact exclusive physical attribution -on CoW/compressed/shared storage, nor a free-volume or remote-quota measurement. -They must not be generalized into a savings estimator. - -The existing six focused test files execute 66 passing cases / 439 assertions. -They demonstrate: ten-day pinned scratch survives while its unlinked peer expires; -missing/corrupt pins suspend deletion; active Claude sessions are excluded after -async metadata; archive/index/restore interruptions preserve session bytes; -a real gated backend after denial keeps staging until unwind/settlement; -SIGKILL recovery settles cost before one cleanup; journal capacity refuses an -initial snapshot and labels later missing observations partial; interrupted CAS -publication remains charged and recovered; and actual turn-temp purge refuses -runtime-state mounts. These are current primitive receipts, not proof of the -proposed storage UI or binary removal endpoint. They do not simulate a physically -full disk for all operations; no-space execution semantics above require future -ENOSPC/crash injection and actual constrained-volume verification. - -Mutation receipt: replacing the archive's post-metadata active-session set with -an empty set makes `running sessions are checked after asynchronous SDK metadata -arrives` fail on `expect(listArchivedSessions(options)).toEqual([])` (one running -session was archived). The original source was restored; the same named test -then passed with both archive-empty and live-source assertions. No runtime -source change is part of this discovery. - -## Design inputs, alternatives and unresolved decisions - -Recommend the first operation set as inspection, existing non-destructive Git -packing, eligible pin-aware scratch prune and lifecycle-owned staging cleanup. -Backend compression remains existing transparent upkeep, with unavailable Pi -support owned by #1637. Runtime `turn_temp` remains scoped to its own admitted -worker. Generic scratch clean, session deletion, workspace sweeping, backup -purge, ref/reflog expiry, history rewriting/force push and broad container prune -are excluded from initial storage actions. - -Prefer an explicit bounded binary content application over assembling shell -commands from user-selected paths: it can bind versions, consequences, journal -coverage and per-file recovery. Ordinary governed agent requests remain available -within their existing policy; this recommendation does not replace that flow or -claim arbitrary shell deletion is a storage API. A trash directory alone is not -a complete alternative: it still retains bytes, needs its own expiry/authority, -and can double storage across filesystems. A plain unlink without a retained -before-version cannot promise Undo. - -Longer-term growth handling should reuse #1780's bounded snapshots and capacity -scopes: show which category is growing and which safe owned action can affect it. -Keep snapshot/receipt storage itself bounded. No alert threshold, polling cadence, -new retention duration, session eviction or backup expiry is selected here. -Packing/compression reduce representation costs; attachments, journal evidence -and backups may continue growing. Capacity provisioning remains a legitimate -outcome when protected content accounts for the usage. - -Maintainer decisions remain explicit for any permanent loss of history, refs, -reflogs, journal detail beyond existing policy, session data or backup evidence. -Such proposals must specify affected copies/remotes, recovery loss, active/read -protections, rollback feasibility and required authority. Changing a retention -default is not approved by accepting this discovery. #1782 owns visible placement, -interaction, responsive/accessibility design and the final reviewed initial scope. - -Proposed implementation slices, for #1782 to turn into scoped tracker work after -review (not a status checklist): - -- **Accounting-to-review handoff:** consume #1780 identities, units, hierarchy, - freshness, known/partial/unknown metrics and distinct volume deltas; add an - operation eligibility/consequence view without changing existing stats. -- **Existing upkeep orchestration:** server-owned authenticated dispatch and - attributable bounded results through current worker/pin/staging owners; - prove live work, revocation, overlap, partial failure and zero-space refusals. -- **Canonical binary removal:** core-supported deterministic selection semantics - and server application/journal receipt integration; exact-version locks, - sidecar/reference policy, retained binary before-version, crash/restart, - mixed-success and stale-safe Undo proof. Stable CLI/JSON/API additions need - their own contract review, changeset and acceptance tests before shipping. -- **Growth and capacity guidance:** bounded history/refresh/cost model from - #1780, honest unavailable/manual operations, no unreviewed retention defaults. - #1637 continues independently; #686 and hosting-template #9 retain recovery - ownership. No concrete additional generated-host change is established by - this discovery, so no speculative hosting issue is filed. - -These slices depend on the existing sibling design issue, rather than creating -parallel deletion policy or archive projects. Closing #1781 supplies evidence -and recommendations; it does not complete #1779 or authorize those slices. diff --git a/docs/process/evidence/browser-input-closure-replay.json b/docs/process/evidence/browser-input-closure-replay.json deleted file mode 100644 index 1dc1646ff4..0000000000 --- a/docs/process/evidence/browser-input-closure-replay.json +++ /dev/null @@ -1,2179 +0,0 @@ -{ - "version": 1, - "sourceBase": "626a03af4a9db064751230a84732755b8afa961e", - "snapshotSha256": "ac31b09adf903d3c9483d5c9be55188010577a113d087d90fd2cea90c404dbbd", - "window": { - "cutoff": "2026-10-16T10:49:55Z", - "order": "number descending, first 100 merged PRs at cutoff", - "oldest": 1741, - "newest": 2071 - }, - "sourceSha256": { - "scripts/browser-input-closure.ts": "01b950bfa3b3174da2f81b9776c5786e4a2009102eef41c4bf19913583d1a1ba", - "scripts/replay-browser-selection.ts": "cb7559c20c678f4a4364e756904f000c6a63b63e49d2b972c80e6c4afc4c108f", - "scripts/ci-plan.ts": "0c1d4b717cc833d5425a12a048f2fb6fdc8f0818dd8ed0e45df157cd46f59e1b", - "scripts/check-pr.ts": "91ed2ac967d2e8241eca2513f07129b7af2e89f10c13d708ef30111bba360001", - "packages/ui-kit/tests/proof-inputs.json": "70253abfa88198b9262e3b8310ebf3c7360e65cc1375a77690fc50b2e7a5190e", - "scripts/captures/proof-inputs.json": "858ae956418048a354e7e18fcc3c15fe29779c5871340de6659f8acfecb073e1" - }, - "fullDiagnosticSha256": "12367004e3eeb7bec15326d17e5ce458bd7d07812f2f5ae0612943b51891c41a", - "browserBefore": 85, - "browserAfter": 85, - "noLongerBrowser": [], - "limits": [ - "Current planner over immutable historical changed paths, not historical-source execution or elapsed speedup.", - "Closure hashes describe graph structure and diagnostics, not source byte identity or passing-proof fingerprints.", - "Actual configured dispatch fixture reaches every current server route.", - "Unresolved runtime config/module/backend dependencies preserve the broad category.", - "Exhaustive actual-merged-SHA browser-domain proof remains required before issue closure." - ], - "domains": { - "browser": { - "files": 1239, - "directories": 16, - "unresolved": 721, - "closureSha256": "faac35cb6a39499adedb1fa0ac40ae801e534c40eb0ebeca3086eb0171af342d", - "runtimeVariableExamples": [ - "Computed import packages/core/src/lib/config.ts: import(tsPath)", - "Computed import packages/core/src/lib/module-loader.ts: import(specifier.startsWith(\"/\") ? specifier : Bun.resolveSync(specifier, root))", - "Computed import packages/ui-server/src/agent/backend.ts: import(specifier)" - ] - }, - "layout": { - "files": 1108, - "directories": 16, - "unresolved": 715, - "closureSha256": "daa333bd7c3e4820ac05c572f2053e88180adee19fc7735b9493406f5acc030d", - "runtimeVariableExamples": [ - "Computed import packages/core/src/lib/config.ts: import(tsPath)", - "Computed import packages/core/src/lib/module-loader.ts: import(specifier.startsWith(\"/\") ? specifier : Bun.resolveSync(specifier, root))", - "Computed import packages/ui-react/tests/browser/error-boundaries.layout.tsx: import(/* @vite-ignore */ `${location.origin}/__missing-chunk-${Math.random().toString(36).slice(2)}__.js`)", - "Computed import packages/ui-server/src/agent/backend.ts: import(specifier)" - ] - }, - "endurance": { - "files": 883, - "directories": 16, - "unresolved": 713, - "closureSha256": "b910ea8787757faa190f2a5b6a565357c295708c677f1c492fd10fbc77d6b4e8", - "runtimeVariableExamples": [ - "Computed import packages/core/src/lib/config.ts: import(tsPath)", - "Computed import packages/core/src/lib/module-loader.ts: import(specifier.startsWith(\"/\") ? specifier : Bun.resolveSync(specifier, root))", - "Computed import packages/ui-server/src/agent/backend.ts: import(specifier)" - ] - }, - "captures": { - "files": 1020, - "directories": 40, - "unresolved": 720, - "closureSha256": "2977e46ba3b13060331fe248dd648eb53452eade51bea0bde72ed10f69972bac", - "runtimeVariableExamples": [ - "Computed import packages/core/src/lib/config.ts: import(tsPath)", - "Computed import packages/core/src/lib/module-loader.ts: import(specifier.startsWith(\"/\") ? specifier : Bun.resolveSync(specifier, root))", - "Computed import packages/ui-server/src/agent/backend.ts: import(specifier)" - ] - } - }, - "plans": [ - { - "number": 2071, - "mergeCommit": "53258a203d37ab32ae211c5f645cb32e2b3898d1", - "changedSha256": "e989d0e8ac7f40a330b537843fe6ac95f808ce08cf95565b78868786af0a50ed", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 2060, - "mergeCommit": "fec9a379da878c59d2e7577c6c940dc6ee5d4a03", - "changedSha256": "00a2f4b118adeddaf751426478d9ad4f7779cc146ff21ea1c65421640d6be68b", - "before": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - }, - "after": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - } - }, - { - "number": 2057, - "mergeCommit": "44a8ab0be7e48a73f61bc794e65ea3f8e84e4289", - "changedSha256": "f18072450df46facc9b08ea91f5dca2653bf8702829767d43ae351249b3a8a0d", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 2044, - "mergeCommit": "b8be3819e93fa3bd60f7dd990030775716c5bdce", - "changedSha256": "8436533a26c91ffa556f2d44a4e7ace43e905fd0b844844f21a366b73c16a5d6", - "before": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - }, - "after": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - } - }, - { - "number": 2043, - "mergeCommit": "d194625395eb200f68d1ec05bc27f262ba75579c", - "changedSha256": "51f22f4207cc5f45fc339a1ea1ebb4a83b6581763b5cecebe118bf549a124d5a", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 2020, - "mergeCommit": "65ed23dc942ecaccbe86ae1beb4af6eeb3ad3eb5", - "changedSha256": "fba20c723e25304f0068feee8e1c457e7787a6ab974280e80b9c21d3074cd0e9", - "before": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - }, - "after": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - } - }, - { - "number": 2019, - "mergeCommit": "abe5086df48883bc270a36edb127b05519398332", - "changedSha256": "6d76bb31f46f8645eb6ebfe413387779629050ea74332b6e843ac28c12985606", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 2018, - "mergeCommit": "ed6b0c5f09ada1b6f899bf245f3f1b176352bf77", - "changedSha256": "a493ded98aeb9b6667d143438872ea3724c05afb5f201b42437851e4171a7cbd", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 2017, - "mergeCommit": "493127587508f305db86e1a1db2d042fa666845b", - "changedSha256": "635d6d5e55eb2cd896f6de1acea89980203f9fa810f2fd1206a32a4f29bdc622", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 2015, - "mergeCommit": "9fc02d5fc5a7f62f13063c04ce68b3cbe12948c9", - "changedSha256": "636d60de9212826acddf905eedab11bfd36ae6001d2d5a8edd37f1e6ab9eb270", - "before": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - }, - "after": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - } - }, - { - "number": 2008, - "mergeCommit": "11655e165474578801b7a2425f0f4a070419157c", - "changedSha256": "f3214057139552383870e77f77a20a2f13f047d47f6ab7998bdfa80c3702404c", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 2007, - "mergeCommit": "04ef3552190d8f56eab09dd6c3580101b6385ba4", - "changedSha256": "44a184a6c6ca2101669da04b92fca4d3522c65e4b1d121ab0c0c44d8a6a2f24d", - "before": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - }, - "after": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - } - }, - { - "number": 2006, - "mergeCommit": "5e9854b2e53ab7cfb4364008cf9cd2065b369404", - "changedSha256": "0f94e198ae00f929befbe13d43042483a88486f81fcd9038457691e3724a9a31", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 2005, - "mergeCommit": "ab0e9fb77a236cefbe5a0b19424836acf9205bde", - "changedSha256": "af6b3222ad189f0a4a7eee22f0cf4a519844aca3a3f89c9daa7e9979e523fff3", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 2002, - "mergeCommit": "4e4a663f98054d86f2dc90154b42ffbe8f8b7692", - "changedSha256": "56cf24fb32062e4ff19270ccafa67bbbfbcba8dd077e982a283acffb23ff6e61", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 2001, - "mergeCommit": "9cf4aa5f37a33d40f53f783ecd0e8344f920f9ec", - "changedSha256": "cf5001238a3596c6b824ffecc8100bdf656921a96bb8480014b434f8f7a216c4", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 2000, - "mergeCommit": "45908608df63b07ee3d10d84ac608d132aa21caa", - "changedSha256": "e6fa3a4a3730fee65387aa66b37842f2739479237258c36636d4d31cab424f6e", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1998, - "mergeCommit": "6863804ef9095cc0b984fed8d8e0ba4c3c9e93c1", - "changedSha256": "f40e25b26ea597cd88dadab03644a30942f272900a74b5405be6f60dff6d09dc", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1995, - "mergeCommit": "61399d103bd59445c6d4dfa183173ba12bbf0f4e", - "changedSha256": "d23a1f3a0d6b2e19e361840d04a370e443416e6adda639bcbfbf51433a952ee4", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1994, - "mergeCommit": "d9ac37b82700d7b45406ba47c0850ae46251fa9b", - "changedSha256": "cf4a0ad080e8b83f67390aa6656deb9697fda4bdc8bcb67ed97864d3ec8aaf9d", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1992, - "mergeCommit": "090c8a5463effe6811742259bc27af2b5ff6e66c", - "changedSha256": "91c73d73da9281b69997f40c6a16f2db666629610c51ee51dacfdc43e6229321", - "before": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - }, - "after": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - } - }, - { - "number": 1991, - "mergeCommit": "74d48eaafc1921032f8027efc082a0e3319408b4", - "changedSha256": "14e88cbf81dbe04b32bc6dea886632a7374b83cafefb2b56634812513ab6135d", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1986, - "mergeCommit": "b4609b961084268309287fff807b1dbd2687d607", - "changedSha256": "06e9e20b1fd6798e6d7b4974e970b8276493080e7a06ceafe9d457a338ce62ab", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1985, - "mergeCommit": "9274b8a06db43932e17b5d401fcfb900306e97cd", - "changedSha256": "8374e1e353cd81a3982e66aee8fee8318b777b20dc04313f901de40c25fe3cab", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1984, - "mergeCommit": "131f3a7d70c829bd27a3fa8ddac9fda0261918b9", - "changedSha256": "a7765712ca24e832b6c8f5177667e6357a084794593f059d1147869474c8d598", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1983, - "mergeCommit": "c857a5db365b7725df24f0c00be8dd082fb68794", - "changedSha256": "af6b3222ad189f0a4a7eee22f0cf4a519844aca3a3f89c9daa7e9979e523fff3", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1981, - "mergeCommit": "e75f9af2ee058b3e43059d92daf78064db467fe2", - "changedSha256": "1a96294a6c41161b5c46b8327a3afc2b68b30dbc43bfc1ccc98dad2b8af37f5a", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1979, - "mergeCommit": "cbf2bb87f8eee79f971099aa4858262888f087ae", - "changedSha256": "013163e724ddc1a1bdd493ddea5d39de01fcced0fa4644d5f5161a703e33f61e", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1977, - "mergeCommit": "82c1f211ee2ebabf44ed819e4a6bae47c93fca51", - "changedSha256": "78d43f852ccf8946c7e4b76ab223043d4d24f18f8a49f2d746a5af3413cadcaf", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1972, - "mergeCommit": "9355d1bd6ec91915e07aff184080bd48bb85fc2c", - "changedSha256": "40a32fb17a8bd96c2dbf96927e2a84f49f275809a27652d753faa26c598514a1", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1968, - "mergeCommit": "66c370b54e65151c6b56a0466347b609b31571b1", - "changedSha256": "a441049cf9a005ca65c07d3ee1095cc6b392efff0828a56c136832ae9ba3521a", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1966, - "mergeCommit": "f2e0fcee7de537c26e218bbc0b7c508c54da76b6", - "changedSha256": "c720f7e2ffb3a7c3a1115ec8b4849a10b89b2bffaeb647b207ad5954d841f708", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1965, - "mergeCommit": "7139f116d1994cac9d47a4c59356c9f220c61f47", - "changedSha256": "cba6a12cdd6b9b33ed79578f1b10075e9b2bd98e1277d785a40a50f302aee2a3", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1964, - "mergeCommit": "3100afa2b8efa25ea31114cdee1f2a89a48dd013", - "changedSha256": "097395eb907d8fe7294cec46e5d0092924cf6c3ec52d4f2284b9ce0d27877a04", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1963, - "mergeCommit": "838f05d2ff611c72bdea8405c46f2504dccb6f24", - "changedSha256": "7394bd61d837089a868af71a79188376613e74f551c3393a331a2063bc03c9c8", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1962, - "mergeCommit": "9bebef7bfed47139792ccaf1d22d4ac7f5f093e9", - "changedSha256": "1bca5bab89e6b4817ced0ee882b6a5e9acf2f2d6ab3fd206192ced648490883c", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1961, - "mergeCommit": "1cc1b34a802f0894391b9bb445fed39fed610230", - "changedSha256": "955a65aa243d01b4c670e90c02a1135660075a1f774b5dad41c3ff1003791f97", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1960, - "mergeCommit": "c95223333a83fd3049749a2e68fb0c07963b7ba5", - "changedSha256": "cf3e5b0cb6adcd95fe5b12fbf586ee40642f95dcde23e02ac07834f14dbdc800", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1959, - "mergeCommit": "1b2a2e816effe05f4e4c69bb0df94afc2f648061", - "changedSha256": "5d31fc44944b55ddeb4695164b4218a6aa20193d58283695e0fbfffefd79e410", - "before": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - }, - "after": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - } - }, - { - "number": 1958, - "mergeCommit": "6090132d964c8ccde4ee43fc5e85382f7ac40640", - "changedSha256": "eef391e71aaaf9f49d6decd26ef6ac3d3a4ddddd91d47e41428f87584b455320", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1957, - "mergeCommit": "95b951aa122424f7d171d16ca16b3cc94f8c8545", - "changedSha256": "f40dd8c8b500805a9eec2aa2b4ee64e8c31e190c30fc3bbcbb7ca675bc8415dc", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1955, - "mergeCommit": "bb4578a71953ed8130c9d6a8a929e75f1530d4fd", - "changedSha256": "f53837c7796d2627dad4c3a09d2fa795ef4b89d93e784d54e09254e8327d2f0d", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1954, - "mergeCommit": "5c453d865d55993c86861da3f428d324405bf506", - "changedSha256": "bcc15e9a6bcc21a6080590302fc5ed779914d26feb9d6bb414ce903bd423e8b3", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1953, - "mergeCommit": "085d8ccf4a76f58b48640800ee9e86cb573aa2be", - "changedSha256": "70a49820709611210f26de5c9081563b563b03a416c0142bfff453fc26cb0635", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1952, - "mergeCommit": "0c68c2b2c9c06e3f0bdc6a52577d3ce66710f49c", - "changedSha256": "9e9e8392b948811dd9788e4e16057afc39db9d8d1671d0de4e87698fb3cbd66e", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1951, - "mergeCommit": "4db852bb7482877d2e72eb3d23078bdd591023cf", - "changedSha256": "e2754efa5ba393a898627340d4324b86f915a507d0005fc3317ab4b13a2b3b63", - "before": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - }, - "after": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - } - }, - { - "number": 1949, - "mergeCommit": "c40200d920353a3a158c9a577bdfbce26751bf68", - "changedSha256": "e037618c2b70b6275cb8ec8e16ad7167e3e6a430fbfca7c786b76a982c8ccee6", - "before": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - }, - "after": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - } - }, - { - "number": 1941, - "mergeCommit": "400c50ed231f33eeca875ec9223b24ad535b2b22", - "changedSha256": "eb5642fb7aa190d0f46d1019d4cec8cb474d1224e55e1ad42b3293a21434d84e", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1934, - "mergeCommit": "cc3fa3a209e0f7f6d9a0ac33778e514fcff69f07", - "changedSha256": "6c8e12ca63f24e2f23bb829b99fad3f0bd9a62902fa9f014d731ed75465cc423", - "before": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - }, - "after": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - } - }, - { - "number": 1932, - "mergeCommit": "f691c5b62a0ffcca67bedfee0be6557631d0930d", - "changedSha256": "448cff054b0b23ede4d56deac65a5607766aa8504fce3ca7f8e7b6933f78cee9", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1930, - "mergeCommit": "615b97f50e7a22a011b31839f04e17c6ccd20f10", - "changedSha256": "0f8a8e2c98645a18af60b8da4c0b391e3af1eb3d1de8fb003c05170ea14c3476", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1928, - "mergeCommit": "155dffdd8237a1543da3109f3de0b659cfac5c93", - "changedSha256": "7804baf77791a1cf2965d7ad926f165255fdaa93c6c93dd97cbcb3a4707c384f", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1927, - "mergeCommit": "21b1527b9eb235d3f5c82ec8d1a945fb36d57cdf", - "changedSha256": "fc3be35721726cf451d2967e1237576221fd4a3ef7c267049e841fb89dd4bb94", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1926, - "mergeCommit": "43c6b9a96fe230504ae4adb6c33eb72283778ec7", - "changedSha256": "9c7c1e53fe0a53bc354e2cec724acd13451152cba27da49b30910d26c9196a31", - "before": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - }, - "after": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - } - }, - { - "number": 1924, - "mergeCommit": "26d972ad066d5ecde72222942e8ffe5d28e647d7", - "changedSha256": "a27efbcf7a695f860d78ca6744a7433f67c5be6ef7b08d44a00ce60db1c39a51", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1923, - "mergeCommit": "d83e4381a2f9a84245b7bf176e3f09d065301937", - "changedSha256": "b75393d0be603898d97af29834d14a3133d47b36ce12d5fa6f9df5a2a35ba9a3", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1920, - "mergeCommit": "009e45714701844a632101a181be2d5e8d66afbb", - "changedSha256": "80a1a47b0dc2f19ba630f9278ded33249b313c0de0e8cd09b67d20e65ebcf262", - "before": { - "fullTests": true, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": true - } - }, - { - "number": 1916, - "mergeCommit": "5fd5c24810dd5fdecea1bc378bfed7155b9cd911", - "changedSha256": "7470e8ec939281988e9c47722e73ede27ac2df869765ff702837c4c635e7b811", - "before": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - }, - "after": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - } - }, - { - "number": 1914, - "mergeCommit": "cf18e810c5c60a1b10f67ba0ee28f7e0cbf0502b", - "changedSha256": "e119957872105155d208d50cecc0fe1cbe3f15d0938f200931aebfb520d4040a", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1911, - "mergeCommit": "58f572c4d2f86fe55d76ff053fb315b83e549158", - "changedSha256": "052d270db26065c391854342ecde4bad4ae23935f1ae60bdd73025107f6d66c2", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1909, - "mergeCommit": "200efc8d4e5e2ef6bd7c5385440a9289bd14c774", - "changedSha256": "9e1d8162380b17ebdf344b671f790f247d3502daab94a598a3a430bbe2b49f5e", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1908, - "mergeCommit": "932d2b3066a34f725531b70ef108cc6c05a0b5ae", - "changedSha256": "77608a2bbed39dd0fd246f350d152c781120a676df593d32393a6637ac5927e2", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1907, - "mergeCommit": "603a754b9e229f9b96c1aaf2b18917374b6483b0", - "changedSha256": "1d1a85f8b619a2168d7522330e37e6c601e7ccaee1585de57623d82ce18e4039", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1906, - "mergeCommit": "5d1580e74c991941397c46bacb60d2cfe8cfb2f3", - "changedSha256": "fc738f4292af0cf7b4b7bc14d6146c2c5634eca7bec062628adcfcf92dd80577", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1905, - "mergeCommit": "52f85a1721910ca560fce38cf47eb3096ae97562", - "changedSha256": "32a2f7f370622e4c2f5a13dbacc226952f8a5fc4bd7818006811b60c72d7e2f4", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1900, - "mergeCommit": "4bcfb45135e4191dfd8a009a48805f319ffb6822", - "changedSha256": "4e5bc589fe8b0e0bdbf1f38fd807a8e381827507d3283dc77ddec0c63e0e30da", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1899, - "mergeCommit": "fb219e069a8afd7fbc5eac6524b7a77ec08a7560", - "changedSha256": "f02f194cb5524840cd8653f8a5bb8090f1d7013380a4f08fa682e98d15b5359a", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1896, - "mergeCommit": "d2b4cf941498d1276deee8acf42f411b7d1c8090", - "changedSha256": "ad758479cb0dec8343492da236e2019f2958a16acc2c04311be717806b2ea544", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1893, - "mergeCommit": "fd8f030f5e90f5cd3d3ab4aaa40f25fb64f328f8", - "changedSha256": "871634cc945a458bf8501d59b11adec4a0df428a2f2f6a99dbd282625ee7dcf2", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1892, - "mergeCommit": "f48c83d613ca63400f5e384373fdd81992b33de8", - "changedSha256": "45a1ddb5cdb14d4e302f33a29c2909940ebb685ea6e635a63e4e9f6eafe99cc1", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1891, - "mergeCommit": "d08bbf8be72f4143aaa28e9a22d53524968d50f2", - "changedSha256": "ac6928c934fd068493737ec2233c4454c0f98846d3f11938ad780290059d7e09", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1888, - "mergeCommit": "f6f5c713b2c52b400a5d34fc1d04120d3ea54107", - "changedSha256": "455f6e410e87fa19660a8fa3839fd1fe0b9762ea96e9344e97b9ad2aaa22c1d2", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1886, - "mergeCommit": "d6ad60a26119978e70a5ad1f1dbcb8fbbf3a9fae", - "changedSha256": "7c121326430307bcec00f177b2a27ad513bdccac8bfc15a17c579c263bdca887", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1882, - "mergeCommit": "25899b1e5829b9d7593ed56e2ae3f6fe271b72f0", - "changedSha256": "5032c1b3cb2afbc6b45932a5e1065094d61e63c59928fa5ca38e1030225faa99", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1881, - "mergeCommit": "04a659593379a0c8da9c049fa649124d6fd54f70", - "changedSha256": "3c733e80d84f90906b3a6cd52e533a39c3efed2979a4ee19886122ade149d64e", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1880, - "mergeCommit": "a754ad02273beb2625d5bce528149028243528cf", - "changedSha256": "5ef56b1555f466f462b2b9186da71a27060b86da0e28b09565e8d3846910a935", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1879, - "mergeCommit": "210b35c52259454952a060644980aabd83c64e7a", - "changedSha256": "ea2aef27aa99ac99c43f983e7b2fd047854c6b3ca9119b94811fd6f47548b24d", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1878, - "mergeCommit": "c68bd6965e381c2a35478e555882b84894a84985", - "changedSha256": "c26bb5a59788325a2338bcfc0d6bbea61fb71a0351d80cc0a27089e7bc0948fd", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1876, - "mergeCommit": "08b4f15fc494749349c94c8352b9c6ae824faa89", - "changedSha256": "772e845be50549f741177714ad2e446789b87fd75c4247f54baa5a37209f8383", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1875, - "mergeCommit": "1a217d72295c66edd7c2b759f2c6a761f8c0a8da", - "changedSha256": "3a74add63094d95606bddf2c4da002f4e6d3d0b9a60881cea59fd884c8b189ce", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1874, - "mergeCommit": "27a368b6ed7c8e80b33613da0c33af6776d74f75", - "changedSha256": "049963ce4d25a3c98db179ea62a2c46f1c1bcf5e2ab7912d07e7354ccb72a956", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1864, - "mergeCommit": "ca1facc1e7086bd2119c260150e9f091e16817f1", - "changedSha256": "16c931daf9b32e247d107f921cabb49ea76c538ce0e767c87a69b70c9286699a", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1862, - "mergeCommit": "5af94530672aec0999c571b3f8774a71f4f97729", - "changedSha256": "76023b6364be16775a70e78c5331f7b64bc7d8a651ed27f230dd73f28de3665b", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1861, - "mergeCommit": "2f244e2c2e31b4ce9cc489601430a3dd94f9088b", - "changedSha256": "af0d9bf2843fa785541922ed3cf289f9231aaa7c3c86863baa5d19032d465efa", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1860, - "mergeCommit": "4317fab88eeb550d4c12248ac4ebcc3d087f53e1", - "changedSha256": "149bfa207911c91ed7b6a5755f8da5d3c9ebadb5a4728882f33023581b6c0fba", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1848, - "mergeCommit": "5869996f186dd730b4dc56e8bea60664a04aa232", - "changedSha256": "dd24bbc0a5a3108a7145d39de74b084b46164fca09a68f3eeb2f0f15eb3bcc06", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1839, - "mergeCommit": "5dc2595ca07042f2e2024c95bbc361f31637559f", - "changedSha256": "3df892bb2e10d70913afb8f417a52b70c6d0ca034f736003e8c0fbadf6e2ed7d", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1832, - "mergeCommit": "5cf1d548f7bd3a314eb36394dc5db0268db97da6", - "changedSha256": "d0c05b100253fcbe49962a159c54fdb3b2e6b4630eb1375921172955e6f1fde3", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1793, - "mergeCommit": "4af7b2f20a43d23260c2ee5e3bac3896aee971bd", - "changedSha256": "b0d30f9eb2724539f556d35defcc08f79c01589b880034bb9658e6e4251a4460", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1789, - "mergeCommit": "79d54278f1b2f35e929f4c6f182089360ab7759f", - "changedSha256": "19fccb02e86d9a7f3cf42b5085ac101eee73ab5b712e0d89950b532fd70838f9", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1786, - "mergeCommit": "2ea27697850dfffe956f2aa8471a720ea738f2bb", - "changedSha256": "e8c7157618d5c970b8fa547fe8c03a200ad90d38da45f7058a7f586a4d534215", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1785, - "mergeCommit": "1ed6e3d431fac8fa28c217d695a8ab412dd22fe4", - "changedSha256": "8403797dca35ff0a177a0bb3401bc17910bbdc584c31574d5a9e7ca60e2c9e12", - "before": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - }, - "after": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - } - }, - { - "number": 1784, - "mergeCommit": "42cfc0eaa24464d3c165ca62a800a45a3e16b6ce", - "changedSha256": "79cb6b1ad4a580f177f4a5aca462636068dd3a868528de7d43c1b1ed03b812b4", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1776, - "mergeCommit": "665bf5e4e7dca4fcaba5e9cf6b341fbef95c9f4c", - "changedSha256": "e474496fdf7ca5f9076f45886d4125fa1635ff3a00eba7bebf5654a7b352af75", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1769, - "mergeCommit": "f2c98da6093c9e1731f061625ba7302f51bf7340", - "changedSha256": "452f2e4e597621bdc3b69b3a4bfcdad45e19895a6e41183bdea23f6dc0049c56", - "before": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - }, - "after": { - "fullTests": false, - "browser": false, - "layout": false, - "captures": false, - "endurance": false, - "runtime": false - } - }, - { - "number": 1761, - "mergeCommit": "7bb7e0ccb0fd660bbdd6019773951ad54d205b38", - "changedSha256": "026f93c01f16c8e89b5f1e5bd349f6f53e715e260b9acd8eef739a63a681389a", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1753, - "mergeCommit": "857ab01d1f9cb591f928755f5be516ab7f73338e", - "changedSha256": "ba6245dcc114827820f35eab507c93a5e3baea87696f42f8a44c3451014e35ed", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1748, - "mergeCommit": "f5433b33e5ed5f8b280049909e3577783cc72953", - "changedSha256": "837403a6cefd787d1d3eaf06110e3f94b0f01bcb3fae682d34efcd68e4da0f8b", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1747, - "mergeCommit": "52cbd1db182b618706cd7edca72159ba62768a63", - "changedSha256": "96809deb0cdc0bc5242523f792fa87461ea6eeed79f566abf6078510fd82b004", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - }, - { - "number": 1741, - "mergeCommit": "185803c4a67e1074a06007c88402cd3fdcfee0c2", - "changedSha256": "ab69a14408b95fec6c78791d7d7cfe2fd8769b7364a891c78ba5be6de7e0e45e", - "before": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - }, - "after": { - "fullTests": true, - "browser": true, - "layout": true, - "captures": true, - "endurance": true, - "runtime": true - } - } - ] -} diff --git a/docs/process/evidence/independent-test-replay.json b/docs/process/evidence/independent-test-replay.json deleted file mode 100644 index c22d0fc330..0000000000 --- a/docs/process/evidence/independent-test-replay.json +++ /dev/null @@ -1,1375 +0,0 @@ -{ - "cutoff": "2026-10-16T10:49:55Z", - "ordering": "descending PR number among merged-at-cutoff,100", - "inputNumbers": [ - 2071, - 2060, - 2057, - 2044, - 2043, - 2020, - 2019, - 2018, - 2017, - 2015, - 2008, - 2007, - 2006, - 2005, - 2002, - 2001, - 2000, - 1998, - 1995, - 1994, - 1992, - 1991, - 1986, - 1985, - 1984, - 1983, - 1981, - 1979, - 1977, - 1972, - 1968, - 1966, - 1965, - 1964, - 1963, - 1962, - 1961, - 1960, - 1959, - 1958, - 1957, - 1955, - 1954, - 1953, - 1952, - 1951, - 1949, - 1941, - 1934, - 1932, - 1930, - 1928, - 1927, - 1926, - 1924, - 1923, - 1920, - 1916, - 1914, - 1911, - 1909, - 1908, - 1907, - 1906, - 1905, - 1900, - 1899, - 1896, - 1893, - 1892, - 1891, - 1888, - 1886, - 1882, - 1881, - 1880, - 1879, - 1878, - 1876, - 1875, - 1874, - 1864, - 1862, - 1861, - 1860, - 1848, - 1839, - 1832, - 1793, - 1789, - 1786, - 1785, - 1784, - 1776, - 1769, - 1761, - 1753, - 1748, - 1747, - 1741 - ], - "scope": "Historical merged source replay; planning results are not runtime speedup measurements.", - "results": [ - { - "number": 2071, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 8 - } - ] - }, - { - "number": 2060, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 1 - } - ] - }, - { - "number": 2057, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 2 - } - ] - }, - { - "number": 2044, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 1 - } - ] - }, - { - "number": 2043, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 2 - } - ] - }, - { - "number": 2020, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 1 - } - ] - }, - { - "number": 2019, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 8 - } - ] - }, - { - "number": 2018, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 4 - } - ] - }, - { - "number": 2017, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 9 - } - ] - }, - { - "number": 2015, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "prose only", - "inputCount": 0 - } - ] - }, - { - "number": 2008, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 1 - } - ] - }, - { - "number": 2007, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "prose only", - "inputCount": 0 - } - ] - }, - { - "number": 2006, - "briefCandidate": true, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputs": [ - "docs/process/evidence/test-wait-renderer-phase-clock.json", - "packages/ui-render-puppeteer/tests/phase-budgets.test.ts" - ] - } - ] - }, - { - "number": 2005, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 2 - } - ] - }, - { - "number": 2002, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 1 - } - ] - }, - { - "number": 2001, - "briefCandidate": false, - "qualifies": true, - "merge": "9cf4aa5f37a33d40f53f783ecd0e8344f920f9ec", - "unitTests": [ - "tests/browser-shards.test.ts", - "tests/candidate-proof.test.ts", - "tests/changeset-gate.test.ts", - "tests/ci-pack.test.ts", - "tests/ci-plan.test.ts", - "tests/ci-runner.test.ts", - "tests/ci-workflows.test.ts", - "tests/contract-gate.test.ts", - "tests/decision-citations.test.ts", - "tests/dependency-edges.test.ts", - "tests/export-native-rejection-runtime.test.ts", - "tests/frontmatter-parse-gate.test.ts", - "tests/hosted-proof.test.ts", - "tests/local-checks.test.ts", - "tests/lockfile.test.ts", - "tests/measurement-fixture-lifetime.test.ts", - "tests/proof-inventory.test.ts", - "tests/proof-reuse.test.ts", - "tests/release-manifest.test.ts" - ], - "categories": { - "fullTests": true, - "browser": false, - "layout": false, - "captures": false, - "runtime": false, - "endurance": false - }, - "reasons": [] - }, - { - "number": 2000, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 3 - } - ] - }, - { - "number": 1998, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 3 - } - ] - }, - { - "number": 1995, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 3 - } - ] - }, - { - "number": 1994, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 3 - } - ] - }, - { - "number": 1992, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "prose only", - "inputCount": 0 - } - ] - }, - { - "number": 1991, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 4 - } - ] - }, - { - "number": 1986, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 1 - } - ] - }, - { - "number": 1985, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 7 - } - ] - }, - { - "number": 1984, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 1 - } - ] - }, - { - "number": 1983, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 2 - } - ] - }, - { - "number": 1981, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 5 - } - ] - }, - { - "number": 1979, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 3 - } - ] - }, - { - "number": 1977, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 6 - } - ] - }, - { - "number": 1972, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 2 - } - ] - }, - { - "number": 1968, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 11 - } - ] - }, - { - "number": 1966, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 3 - } - ] - }, - { - "number": 1965, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 2 - } - ] - }, - { - "number": 1964, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 29 - } - ] - }, - { - "number": 1963, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 3 - } - ] - }, - { - "number": 1962, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 3 - } - ] - }, - { - "number": 1961, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 7 - } - ] - }, - { - "number": 1960, - "briefCandidate": true, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputs": [ - "docs/process/evidence/test-wait-html-download-completion.json", - "packages/ui-react/tests/html-preview-runtime.test.ts" - ] - } - ] - }, - { - "number": 1959, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 1 - } - ] - }, - { - "number": 1958, - "briefCandidate": true, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputs": [ - "docs/process/evidence/test-wait-browser-pacing-completion.json", - "docs/process/evidence/test-wait-browser-robots-completion.json", - "docs/process/evidence/test-wait-search-deadlines.json", - "packages/core/tests/search-reliability.test.ts", - "packages/scrape/tests/browser-politeness.test.ts" - ] - } - ] - }, - { - "number": 1957, - "briefCandidate": true, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputs": [ - "docs/process/evidence/test-wait-html-form-boundaries.json", - "docs/process/evidence/test-wait-html-popup-boundaries.json", - "docs/process/evidence/test-wait-html-top-boundary.json", - "packages/ui-react/tests/html-preview-runtime.test.ts" - ] - } - ] - }, - { - "number": 1955, - "briefCandidate": true, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputs": [ - "docs/process/evidence/test-wait-html-navigation-boundaries.json", - "packages/ui-react/tests/html-preview-runtime.test.ts" - ] - } - ] - }, - { - "number": 1954, - "briefCandidate": true, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputs": [ - "docs/process/evidence/test-wait-agent-runner-observations.json", - "docs/process/evidence/test-wait-consumed-draft-completion.json", - "docs/process/evidence/test-wait-consumed-draft-observations.json", - "docs/process/evidence/test-wait-index-observations.json", - "docs/process/evidence/test-wait-maintenance-gates.json", - "docs/process/evidence/test-wait-politeness-boundaries.json", - "packages/ui-react/tests/draft-client.test.ts", - "packages/ui-react/tests/draft-runtime.test.ts" - ] - } - ] - }, - { - "number": 1953, - "briefCandidate": true, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputs": [ - "docs/process/evidence/test-wait-native-child-observations.json", - "packages/ui-react/tests/html-preview-runtime.test.ts" - ] - } - ] - }, - { - "number": 1952, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 45 - } - ] - }, - { - "number": 1951, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 2 - } - ] - }, - { - "number": 1949, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 3 - } - ] - }, - { - "number": 1941, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 47 - } - ] - }, - { - "number": 1934, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 1 - } - ] - }, - { - "number": 1932, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 20 - } - ] - }, - { - "number": 1930, - "briefCandidate": true, - "qualifies": false, - "merge": "615b97f50e7a22a011b31839f04e17c6ccd20f10", - "reasons": [ - { - "file": "packages/ui-kit/tests/ghost-text.test.tsx", - "reason": "tracked basename references", - "references": [ - "docs/decisions/design-kit/loading.md", - "docs/process/evidence/test-wait-native-observations.json", - "docs/process/evidence/test-wait-operational-basis.json", - "docs/process/evidence/test-wait-sites.tsv", - "docs/process/test-waits.md", - "packages/ui-kit/src/tokens.css", - "scripts/test-shard-costs.json", - "scripts/unit-shard-observation.json", - "tests/dom-global-restoration.test.ts" - ] - }, - { - "file": "tests/dom-global-restoration.test.ts", - "reason": "tracked basename references", - "references": [ - "scripts/test-shard-costs.json", - "scripts/unit-shard-observation.json" - ] - } - ] - }, - { - "number": 1928, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 2 - } - ] - }, - { - "number": 1927, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 2 - } - ] - }, - { - "number": 1926, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 2 - } - ] - }, - { - "number": 1924, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 2 - } - ] - }, - { - "number": 1923, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 35 - } - ] - }, - { - "number": 1920, - "briefCandidate": true, - "qualifies": false, - "merge": "009e45714701844a632101a181be2d5e8d66afbb", - "reasons": [ - { - "file": "packages/scrape/tests/client.test.ts", - "reason": "tracked basename references", - "references": [ - "docs/decisions/experiment-tier.md", - "docs/decisions/runtime-requirements.md", - "docs/http-api-coverage.md", - "docs/process/evidence/test-wait-sites.tsv", - "docs/process/test-waits.md", - "scripts/test-shard-costs.json", - "scripts/unit-shard-observation.json" - ] - } - ] - }, - { - "number": 1916, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 2 - } - ] - }, - { - "number": 1914, - "briefCandidate": true, - "qualifies": false, - "merge": "cf18e810c5c60a1b10f67ba0ee28f7e0cbf0502b", - "reasons": [ - { - "file": "packages/ui-react/tests/association-signout-runtime.test.ts", - "reason": "tracked basename references", - "references": [ - "docs/process/evidence/test-wait-observations.json", - "docs/process/evidence/test-wait-sites.tsv", - "docs/process/test-waits.md", - "docs/process/theme-parity.md", - "scripts/test-shard-costs.json", - "scripts/unit-shard-observation.json" - ] - }, - { - "file": "packages/ui-react/tests/turn-journal-runtime.test.ts", - "reason": "tracked basename references", - "references": [ - "docs/http-api-coverage.md", - "docs/process/evidence/test-wait-observations.json", - "docs/process/evidence/test-wait-sites.tsv", - "docs/process/theme-parity.md" - ] - } - ] - }, - { - "number": 1911, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 1 - } - ] - }, - { - "number": 1909, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 3 - } - ] - }, - { - "number": 1908, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 95 - } - ] - }, - { - "number": 1907, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 42 - } - ] - }, - { - "number": 1906, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 3 - } - ] - }, - { - "number": 1905, - "briefCandidate": true, - "qualifies": false, - "merge": "52f85a1721910ca560fce38cf47eb3096ae97562", - "reasons": [ - { - "file": "packages/ui-react/tests/connection-continuity-runtime.test.ts", - "reason": "tracked basename references", - "references": [ - "docs/process/evidence/test-wait-sites.tsv", - "docs/process/test-waits.md", - "docs/process/theme-parity.md", - "packages/ui-react/tests/reconnect-reattach.test.ts", - "scripts/test-shard-costs.json", - "scripts/unit-shard-observation.json" - ] - } - ] - }, - { - "number": 1900, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 5 - } - ] - }, - { - "number": 1899, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 17 - } - ] - }, - { - "number": 1896, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 6 - } - ] - }, - { - "number": 1893, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 6 - } - ] - }, - { - "number": 1892, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 21 - } - ] - }, - { - "number": 1891, - "briefCandidate": true, - "qualifies": false, - "merge": "d08bbf8be72f4143aaa28e9a22d53524968d50f2", - "reasons": [ - { - "file": "packages/ui-react/tests/draft-client.test.ts", - "reason": "tracked basename references", - "references": [ - "scripts/test-shard-costs.json", - "scripts/unit-shard-observation.json" - ] - } - ] - }, - { - "number": 1888, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 13 - } - ] - }, - { - "number": 1886, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 3 - } - ] - }, - { - "number": 1882, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 3 - } - ] - }, - { - "number": 1881, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 45 - } - ] - }, - { - "number": 1880, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 3 - } - ] - }, - { - "number": 1879, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 5 - } - ] - }, - { - "number": 1878, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 2 - } - ] - }, - { - "number": 1876, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 2 - } - ] - }, - { - "number": 1875, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 4 - } - ] - }, - { - "number": 1874, - "briefCandidate": true, - "qualifies": false, - "merge": "27a368b6ed7c8e80b33613da0c33af6776d74f75", - "reasons": [ - { - "file": "packages/ui-react/tests/tracker-runtime.test.ts", - "reason": "tracked basename references", - "references": [ - "scripts/test-shard-costs.json", - "scripts/unit-shard-observation.json" - ] - } - ] - }, - { - "number": 1864, - "briefCandidate": true, - "qualifies": false, - "merge": "ca1facc1e7086bd2119c260150e9f091e16817f1", - "reasons": [ - { - "file": "packages/ui-server/tests/inbox-snapshot.test.ts", - "reason": "export token" - }, - { - "file": "packages/ui-server/tests/inbox-snapshot.test.ts", - "reason": "tracked basename references", - "references": [ - "docs/plans/async-collaboration.md", - "scripts/test-shard-costs.json", - "scripts/unit-shard-observation.json" - ] - } - ] - }, - { - "number": 1862, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 24 - } - ] - }, - { - "number": 1861, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 7 - } - ] - }, - { - "number": 1860, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 4 - } - ] - }, - { - "number": 1848, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 25 - } - ] - }, - { - "number": 1839, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 22 - } - ] - }, - { - "number": 1832, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 3 - } - ] - }, - { - "number": 1793, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 70 - } - ] - }, - { - "number": 1789, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 20 - } - ] - }, - { - "number": 1786, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 14 - } - ] - }, - { - "number": 1785, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 1 - } - ] - }, - { - "number": 1784, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 1 - } - ] - }, - { - "number": 1776, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 100 - } - ] - }, - { - "number": 1769, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "prose only", - "inputCount": 0 - } - ] - }, - { - "number": 1761, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 28 - } - ] - }, - { - "number": 1753, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 53 - } - ] - }, - { - "number": 1748, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 53 - } - ] - }, - { - "number": 1747, - "briefCandidate": false, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputCount": 62 - } - ] - }, - { - "number": 1741, - "briefCandidate": true, - "qualifies": false, - "reasons": [ - { - "reason": "non-test changed inputs or root test inputs", - "inputs": [ - "bun.lock", - "packages/common/package.json", - "packages/common/src/governance-policy.ts", - "packages/common/src/protected-paths.ts", - "packages/core/src/cli/brain.ts", - "packages/core/src/cli/commands/index.ts", - "packages/core/src/cli/commands/policy.ts", - "packages/core/src/cli/core-command-names.ts", - "packages/core/src/internal.ts", - "packages/core/src/lib/config.ts", - "packages/core/src/lib/governance-policy.ts", - "packages/core/src/lib/scratch.ts", - "packages/core/tests/governance-policy.test.ts", - "packages/core/tests/policy-cli.test.ts", - "packages/ui-sdk/src/server/protected-paths.ts", - "packages/ui-sdk/src/server/worker-protection.ts", - "packages/ui-server/migrations/041_turn_governance_policy.sql", - "packages/ui-server/src/app.ts", - "packages/ui-server/src/brain/application.ts", - "packages/ui-server/src/brain/governance-policy.ts", - "packages/ui-server/src/brain/governed-turn.ts", - "packages/ui-server/src/brain/mask-application.ts", - "packages/ui-server/src/brain/protected-target.ts", - "packages/ui-server/src/ws/bridge.ts", - "packages/ui-server/src/ws/run-session.ts", - "packages/ui-server/tests/governance-policy-application.test.ts", - "packages/ui-server/tests/governance-policy.test.ts", - "scripts/check-ui-server-query-package.ts", - "scripts/ci-pack.ts", - "tests/allowed-edges.ts" - ] - } - ] - } - ] -} diff --git a/docs/process/test-waits.md b/docs/process/test-waits.md index 66ace596e5..aa001f33bc 100644 --- a/docs/process/test-waits.md +++ b/docs/process/test-waits.md @@ -1735,8 +1735,8 @@ intact. Extra same-stack registrations fail the ownership assertion; numeric matching or callback text is insufficient (`installReceiptWatchdogObserver`, `packages/ui-react/tests/fixtures/receipt-watchdog-observer.ts:2-88`). The actual manager arms after send and later probes liveness before asking for the same -submission (`send`, `packages/ui-react/src/lib/answer-delivery/manager.ts:327-342`; -`armWatchdog`, `packages/ui-react/src/lib/answer-delivery/manager.ts:250-260`). +submission (`send`, `packages/ui-react/src/lib/answer-delivery/manager.ts:325-340`; +`armWatchdog`, `packages/ui-react/src/lib/answer-delivery/manager.ts:248-258`). The candidate checks the independently required 5000 ms registration before pausing at its actual deadline minus one millisecond. It observes no callback, diff --git a/experiments/fixtures/runtime-placement-probe.ts b/experiments/fixtures/runtime-placement-probe.ts index c168e34bd0..6e1890aa15 100644 --- a/experiments/fixtures/runtime-placement-probe.ts +++ b/experiments/fixtures/runtime-placement-probe.ts @@ -2,7 +2,8 @@ import assert from "node:assert/strict"; import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { dirname, join, resolve } from "node:path"; +import { createRequire } from "node:module"; +import { join, resolve } from "node:path"; import { captureSurface } from "../../scripts/capture-turn-surface.js"; import { observedSkills } from "../../scripts/turn-surface-skills.js"; @@ -11,8 +12,11 @@ assert.deepEqual(networkInterfaces, ["lo"], "OWNED_CLAUDE_REQUIRES_OFFLINE_NAMES const root = resolve(import.meta.dir, "../../tmp"); mkdirSync(root, { recursive: true }); const outside = mkdtempSync(join(root, "odysseus-cli-placement-")); const inside = mkdtempSync(join(tmpdir(), "odysseus-cli-placement-")); -const sdk = dirname(Bun.resolveSync("@anthropic-ai/claude-agent-sdk", join(import.meta.dir, "../../packages/ui-backend-claude/src"))); -const installed = join(sdk, `node_modules/@anthropic-ai/claude-agent-sdk-linux-${process.arch}/claude`); +// Resolve the platform binary from the SDK entry, as the SDK itself does, so +// nested and hoisted layouts both find the package the SDK would launch. +const sdkRequire = createRequire(Bun.resolveSync("@anthropic-ai/claude-agent-sdk", join(import.meta.dir, "../../packages/ui-backend-claude/src"))); +const installed = sdkRequire.resolve(`@anthropic-ai/claude-agent-sdk-linux-${process.arch}/claude`); +const manifest = JSON.parse(readFileSync(sdkRequire.resolve("./manifest.json"), "utf8")); try { const paths = [outside, inside].map(root => { writeFileSync(join(root, "package.json"), '{"name":"odysseus-owned-cli-control"}\n'); @@ -20,6 +24,7 @@ try { }); const digest = (path: string) => new Bun.CryptoHasher("sha256").update(readFileSync(path)).digest("hex"); const installedDigest = digest(installed), runtimeDigests = paths.map(digest); + assert.equal(installedDigest, manifest.platforms[`linux-${process.arch}`].checksum, "OWNED_CLAUDE_NATIVE_MATCHES_SDK_MANIFEST"); assert.deepEqual(runtimeDigests, [installedDigest, installedDigest], "OWNED_CLAUDE_NATIVE_BYTES_MATCH"); const results = []; for (const path of paths) { diff --git a/package.json b/package.json index be1299e4e2..f19cb6edd9 100644 --- a/package.json +++ b/package.json @@ -39,7 +39,6 @@ "@modelcontextprotocol/sdk": "^1.29.0", "@types/bun": "^1.4.2", "axe-core": "^4.13.0", - "claude-agent-sdk-research-292": "npm:@anthropic-ai/claude-agent-sdk@0.3.292", "github-slugger": "^2.0.0", "mdast-util-to-string": "^4.0.0", "oxlint": "^1.79.0", diff --git a/packages/ui-kit/src/blocks/MapView.tsx b/packages/ui-kit/src/blocks/MapView.tsx index 045be6f9fb..14a3fb0ab0 100644 --- a/packages/ui-kit/src/blocks/MapView.tsx +++ b/packages/ui-kit/src/blocks/MapView.tsx @@ -382,7 +382,7 @@ export function mapViewBounds( /** `A`…`Z`, then `AA`, `AB`…: a letter per merge, never a number that could * be mistaken for a pin's own. */ -export function clusterLetter(index: number): string { +function clusterLetter(index: number): string { let out = ""; let i = index; do { diff --git a/packages/ui-kit/src/blocks/TrackerPillList.tsx b/packages/ui-kit/src/blocks/TrackerPillList.tsx index c550ee83ed..4363345b40 100644 --- a/packages/ui-kit/src/blocks/TrackerPillList.tsx +++ b/packages/ui-kit/src/blocks/TrackerPillList.tsx @@ -79,7 +79,7 @@ export interface TrackerPillListProps { } /** What the kit read from an accepted address. */ -export interface TrackerItem { +interface TrackerItem { ok: true; href: string; /** ASCII (`xn--`) host with any non-default port, as `classifyLink` gives it. */ @@ -89,11 +89,11 @@ export interface TrackerItem { } /** A list longer than this collapses. */ -export const TRACKER_COLLAPSE_AFTER = 6; +const TRACKER_COLLAPSE_AFTER = 6; /** How many events a collapsed list shows. */ -export const TRACKER_COLLAPSED_VISIBLE = 5; +const TRACKER_COLLAPSED_VISIBLE = 5; /** The longest qualifier drawn whole; the accessible name always has all of it. */ -export const TRACKER_QUALIFIER_MAX = 16; +const TRACKER_QUALIFIER_MAX = 16; /** GitHub owners are alphanumerics and single hyphens; repositories add `.` and `_`. */ const GITHUB_ITEM = /^\/([A-Za-z0-9](?:[A-Za-z0-9-]{0,38}))\/([A-Za-z0-9._-]{1,100})\/(issues|pull)\/([1-9][0-9]{0,9})(?:[/?#]|$)/; @@ -147,7 +147,7 @@ export function shortQualifier(qualifier: string): string { } /** The pill's accessible name, built only from what the kit derived plus the action. */ -export function trackerPillName(item: TrackerItem, event: Pick): string { +function trackerPillName(item: TrackerItem, event: Pick): string { const what = event.qualifier?.trim() ? `${event.action}, ${event.qualifier.trim()}` : event.action; if (!item.github) return `Open ${item.host}, ${what}`; const kind = item.github.type === "pull" ? "pull request" : "issue"; @@ -155,14 +155,14 @@ export function trackerPillName(item: TrackerItem, event: Pick = { }; /** `HH:MM` on a 24-hour clock in the reader's zone, the design's `ended 09:41`. */ -export function defaultWorkingClock(ms: number): string { +function defaultWorkingClock(ms: number): string { return new Date(ms).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit", hourCycle: "h23" }); } diff --git a/packages/ui-kit/src/decisions/AskUserListCard.tsx b/packages/ui-kit/src/decisions/AskUserListCard.tsx index 90b6125ce4..6144ec78b6 100644 --- a/packages/ui-kit/src/decisions/AskUserListCard.tsx +++ b/packages/ui-kit/src/decisions/AskUserListCard.tsx @@ -116,17 +116,17 @@ export interface AskUserListCardProps { } /** Above this many items the answered record collapses its groups. */ -export const ASK_LIST_COLLAPSE_AT = 12; +const ASK_LIST_COLLAPSE_AT = 12; /** How many chips sit in one grid row at a narrow card, for `n` options. */ -export function narrowColumns(n: number): number { +function narrowColumns(n: number): number { if (n <= 4) return n; if (n <= 6) return 3; return 4; } /** The Submit label for the state the card is in. */ -export function submitLabel(answered: number, total: number, allowSkip: boolean): string { +function submitLabel(answered: number, total: number, allowSkip: boolean): string { const open = total - answered; if (open === 0) return `Submit ${total}`; if (!allowSkip) return `${open} left to answer`; @@ -138,7 +138,7 @@ export function submitLabel(answered: number, total: number, allowSkip: boolean) * the one rule that matters — never overwrite a choice — is testable without * a DOM. */ -export function fillOpen( +function fillOpen( items: readonly Pick[], answers: Readonly>, label: string @@ -150,7 +150,7 @@ export function fillOpen( /** The answered record's groups: one per option that got answers, in scale * order, then the skipped items. */ -export function groupAnswers( +function groupAnswers( scale: readonly AskUserListOption[], items: readonly AskUserListItem[], answers: Readonly> diff --git a/packages/ui-kit/src/decisions/AskUserRankCard.tsx b/packages/ui-kit/src/decisions/AskUserRankCard.tsx index cf6a49e853..0419e0853e 100644 --- a/packages/ui-kit/src/decisions/AskUserRankCard.tsx +++ b/packages/ui-kit/src/decisions/AskUserRankCard.tsx @@ -31,7 +31,7 @@ export interface AskUserRankCardProps { onAskAgain?: () => void; } -export function moveRankItem(order: readonly string[], id: string, position: number): string[] { +function moveRankItem(order: readonly string[], id: string, position: number): string[] { const next = order.filter((item) => item !== id); next.splice(Math.max(0, Math.min(position, next.length)), 0, id); return next; diff --git a/packages/ui-kit/src/internal/cue.tsx b/packages/ui-kit/src/internal/cue.tsx index e1b43b8af3..2ff8e7cd95 100644 --- a/packages/ui-kit/src/internal/cue.tsx +++ b/packages/ui-kit/src/internal/cue.tsx @@ -19,7 +19,7 @@ import { ICONS, type IconName } from "../primitives/Icon.js"; * Not `Icon`: that component owns the box and hands nothing through to the * SVG, and the two attributes above have to sit on the SVG itself. */ -export interface CueProps { +interface CueProps { icon: IconName; /** 11 in rows and cells, 12 in the trend pill, 13 in a tile. */ size: number; diff --git a/packages/ui-kit/src/internal/expansion.ts b/packages/ui-kit/src/internal/expansion.ts index a4b2b99776..f53613aee9 100644 --- a/packages/ui-kit/src/internal/expansion.ts +++ b/packages/ui-kit/src/internal/expansion.ts @@ -23,12 +23,12 @@ import { useId, useState, type KeyboardEvent } from "react"; * component is moving TO. It is the presence of both props, and only both, * that hands control to the parent. */ -export interface ExpansionOptions { +interface ExpansionOptions { open?: boolean; onOpenChange?: (open: boolean) => void; } -export interface Expansion { +interface Expansion { open: boolean; toggle: () => void; /** The id the body element must carry; `aria-controls` points at it. */ diff --git a/packages/ui-kit/src/internal/orbit-layout.ts b/packages/ui-kit/src/internal/orbit-layout.ts index 32c69121b1..5ef8346d33 100644 --- a/packages/ui-kit/src/internal/orbit-layout.ts +++ b/packages/ui-kit/src/internal/orbit-layout.ts @@ -1,14 +1,14 @@ import type { OrbitAgent } from "../agents/AgentOrbit.js"; export interface OrbitSize { width: number; height: number } -export interface OrbitPlacement extends OrbitSize { +interface OrbitPlacement extends OrbitSize { agent?: OrbitAgent; ring: 0 | 1 | 2; overflow: number; x: number; y: number; } -export function agentRing(agent: OrbitAgent): 0 | 1 | 2 { +function agentRing(agent: OrbitAgent): 0 | 1 | 2 { return agent.ring ?? (agent.state === "waiting" ? 0 : agent.state === "running" ? 1 : 2); } function overlaps(a: OrbitPlacement, b: OrbitPlacement, gap: number) { diff --git a/packages/ui-kit/src/internal/roving.ts b/packages/ui-kit/src/internal/roving.ts index b59c5d2da0..ee396f6681 100644 --- a/packages/ui-kit/src/internal/roving.ts +++ b/packages/ui-kit/src/internal/roving.ts @@ -34,7 +34,7 @@ import { useState } from "react"; * the group belongs to its caller. Its answer is a `tabStop` prop, driven by * {@link AskUserCard}, and it is documented on the component. */ -export interface Roving { +interface Roving { /** `0` for the group's one tab stop, `-1` for every other eligible item. */ tabIndexFor: (index: number) => 0 | -1; /** Wire to each item's `onFocus` so the stop follows the caret. */ diff --git a/packages/ui-kit/src/internal/sheet-dialog.tsx b/packages/ui-kit/src/internal/sheet-dialog.tsx index ef1fb70038..3427b5b046 100644 --- a/packages/ui-kit/src/internal/sheet-dialog.tsx +++ b/packages/ui-kit/src/internal/sheet-dialog.tsx @@ -5,7 +5,7 @@ import { BottomSheet } from "../chrome/BottomSheet.js"; import { Overlay } from "../chrome/Overlay.js"; /** The Working and Pending follow-up sheet adapter; Overlay owns modality. */ -export interface SheetDialogProps { +interface SheetDialogProps { /** The dialog's accessible name and the sheet's title. */ title: string; subtitle?: string; diff --git a/packages/ui-kit/src/primitives/BrandMark.tsx b/packages/ui-kit/src/primitives/BrandMark.tsx index 11b25db5c6..c731733be7 100644 --- a/packages/ui-kit/src/primitives/BrandMark.tsx +++ b/packages/ui-kit/src/primitives/BrandMark.tsx @@ -31,7 +31,7 @@ export interface BrandMarkProps { } /** Below this height the mark uses the small-size master. */ -export const BRAND_MARK_SMALL_BELOW = 24; +const BRAND_MARK_SMALL_BELOW = 24; /** `mark-on-*.svg`, viewBox 0 0 64 64. */ const MARK = { diff --git a/packages/ui-kit/src/primitives/DiffBlock.tsx b/packages/ui-kit/src/primitives/DiffBlock.tsx index 9171e38cb4..44b7af11bd 100644 --- a/packages/ui-kit/src/primitives/DiffBlock.tsx +++ b/packages/ui-kit/src/primitives/DiffBlock.tsx @@ -48,7 +48,7 @@ const TINT: Record = { /** The rows `tinted` draws, split on newline and signed by first character. * Exported for tests; a consumer wanting the same split gets the same rows. */ -export function diffRows(text: string): { sign: Sign; text: string }[] { +function diffRows(text: string): { sign: Sign; text: string }[] { return text.split("\n").map((line) => { const sign: Sign = line[0] === "-" || line[0] === "+" ? (line[0] as Sign) : " "; // A unified diff spells a context line as a blank sign and a separator, diff --git a/packages/ui-react/src/components/activity/activity-report.tsx b/packages/ui-react/src/components/activity/activity-report.tsx index 6b8652cf87..6bfa85b38c 100644 --- a/packages/ui-react/src/components/activity/activity-report.tsx +++ b/packages/ui-react/src/components/activity/activity-report.tsx @@ -26,7 +26,7 @@ import { DiagnosticReview, type ReviewCopy } from "../report/diagnostic-review.j * record from this server without payloads. The run is never changed. */ -export const ACTIVITY_REVIEW_COPY: ReviewCopy = { +const ACTIVITY_REVIEW_COPY: ReviewCopy = { reportSubtitle: "Opening the issue sends this text to GitHub before you submit it. The issue will be public at github.com/schlessera/brain-kit.", copySubtitle: "Review and edit this text. Copy places it on your clipboard only when you choose Copy.", footnote: ( @@ -63,7 +63,7 @@ function isOffline(wsStatus: string): boolean { return wsStatus !== "connected" || (typeof navigator !== "undefined" && navigator.onLine === false); } -export const OFFLINE_NOTE = "You appear to be offline. Copy works now; the GitHub link needs a connection."; +const OFFLINE_NOTE = "You appear to be offline. Copy works now; the GitHub link needs a connection."; /** One report request: the run, and its record when the opener already holds it. */ export interface ActivityReportRequest { diff --git a/packages/ui-react/src/components/activity/activity-views.tsx b/packages/ui-react/src/components/activity/activity-views.tsx index f566590e4a..3fc081bf2d 100644 --- a/packages/ui-react/src/components/activity/activity-views.tsx +++ b/packages/ui-react/src/components/activity/activity-views.tsx @@ -19,7 +19,7 @@ export function toolState(outcome: ActivitySpanOutcome | undefined | null): RunT return isFailureOutcome(outcome) ? "failed" : "idle"; } -export interface LiveRunCardProps { +interface LiveRunCardProps { name: string; /** The step in flight, if the run has steps at all (a plain cron job has none). */ current: string | null; @@ -57,7 +57,7 @@ export function LiveRunCard(p: LiveRunCardProps) { ); } -export interface HistoryRowProps { +interface HistoryRowProps { name: string; cron: boolean; /** The run's outcome, or null while unknown. */ @@ -87,7 +87,7 @@ export function HistoryRow(p: HistoryRowProps) { ); } -export interface IntentCardProps { +interface IntentCardProps { intent: ActivityIntent; /** When it was raised, already formatted. */ when: string; @@ -120,7 +120,7 @@ export function IntentCard(p: IntentCardProps) { ); } -export interface RunRollupReceiptProps { +interface RunRollupReceiptProps { origin: string; outcome: ActivitySpanOutcome | null; when: string; diff --git a/packages/ui-react/src/components/activity/approval-card.tsx b/packages/ui-react/src/components/activity/approval-card.tsx index 8dba877a90..e85bf00575 100644 --- a/packages/ui-react/src/components/activity/approval-card.tsx +++ b/packages/ui-react/src/components/activity/approval-card.tsx @@ -26,7 +26,7 @@ import { useFinePointer } from "../../hooks/use-fine-pointer.js"; */ const ALLOW_MOUNT = { flex: "1 1 auto", minWidth: 0, width: "auto" } as const; const DENY_MOUNT = { flex: "0 0 auto", minWidth: 96, minHeight: 44, width: "auto" } as const; -export interface ApprovalCardProps { +interface ApprovalCardProps { tool: ToolCall; /** Where it came from, for the foot line. */ origin: string; @@ -34,7 +34,7 @@ export interface ApprovalCardProps { onDecide: (approved: boolean, always?: boolean) => void; } -export const APPROVAL_CARD = "[data-approval-card]"; +const APPROVAL_CARD = "[data-approval-card]"; /** * What a decision on an Actions card prints and sends. The receipt follows diff --git a/packages/ui-react/src/components/activity/digest-summary.tsx b/packages/ui-react/src/components/activity/digest-summary.tsx index 2042fd5d37..0970931d64 100644 --- a/packages/ui-react/src/components/activity/digest-summary.tsx +++ b/packages/ui-react/src/components/activity/digest-summary.tsx @@ -13,7 +13,7 @@ import type { ActionDigestSummary, ActivityDigest } from "../../lib/api-client.j * last summary are the groups that need you. Either half may be absent: an * activity window with no runs, or no new Actions for this client. */ -export interface DigestSummaryProps { +interface DigestSummaryProps { digest: ActivityDigest | null; /** This client's newest Actions/FYI contribution, when it has new entries. */ actions?: ActionDigestSummary | null; diff --git a/packages/ui-react/src/components/activity/durable-actions.tsx b/packages/ui-react/src/components/activity/durable-actions.tsx index 1ecf454a3b..58731af40f 100644 --- a/packages/ui-react/src/components/activity/durable-actions.tsx +++ b/packages/ui-react/src/components/activity/durable-actions.tsx @@ -65,7 +65,7 @@ function provenance(thread: InboxThread | undefined): string | undefined { } /** Send one decision frame and record it, or do nothing at all. */ -export function useSendDecision() { +function useSendDecision() { const root = useBrainUiRoot(); return (item: InboxActionItem, decision: Omit): boolean => { const inbox = root.stores.inbox.getState(); diff --git a/packages/ui-react/src/components/activity/inbox-model.ts b/packages/ui-react/src/components/activity/inbox-model.ts index ba77e5c6ba..efa705838a 100644 --- a/packages/ui-react/src/components/activity/inbox-model.ts +++ b/packages/ui-react/src/components/activity/inbox-model.ts @@ -42,7 +42,7 @@ export function priorityTerms(thread: InboxThread | undefined, item: InboxAction return `stakes ${stakes} · ${urgency} · age ${days}d`; } -export interface DecisionGroup { +interface DecisionGroup { thread: InboxThread | undefined; threadId: string; items: InboxActionItem[]; @@ -75,7 +75,7 @@ export function groupDecisions(items: readonly InboxActionItem[], threads: Recor } /** One stored option, classified for display. */ -export type OptionView = +type OptionView = | { role: "commit"; option: InboxOption; effect: EffectPreviewProps; target: string; tool?: string } | { role: "dismiss"; option: InboxOption } | { role: "later"; option: InboxOption } @@ -83,7 +83,7 @@ export type OptionView = | { role: "malformed"; option: InboxOption; effect: EffectPreviewProps }; /** Escaped, indented JSON as text. Never markup. */ -export function rawText(value: unknown): string { +function rawText(value: unknown): string { try { return JSON.stringify(value, null, 2) ?? String(value); } catch { @@ -97,7 +97,7 @@ export function rawText(value: unknown): string { * schema would not accept, so anything that fails it is shown raw, as text, * with its commit disabled. */ -export function viewOption(option: InboxOption, blockedSubject: string | null): OptionView { +function viewOption(option: InboxOption, blockedSubject: string | null): OptionView { const parsed = inboxOptionSchema.safeParse(option); if (!parsed.success) { return { diff --git a/packages/ui-react/src/components/activity/push-switch.tsx b/packages/ui-react/src/components/activity/push-switch.tsx index 3033e7aa95..3a909def33 100644 --- a/packages/ui-react/src/components/activity/push-switch.tsx +++ b/packages/ui-react/src/components/activity/push-switch.tsx @@ -20,7 +20,7 @@ import { BellOff } from "lucide-react"; */ export type PushState = "unsupported" | "not-asked" | "blocked" | "subscribed" | "unsubscribed"; -export interface PushSwitchProps { +interface PushSwitchProps { state: PushState; busy: boolean; onToggle: () => void; diff --git a/packages/ui-react/src/components/activity/span-bits.tsx b/packages/ui-react/src/components/activity/span-bits.tsx index f38a8c8ff2..bd6ca998a4 100644 --- a/packages/ui-react/src/components/activity/span-bits.tsx +++ b/packages/ui-react/src/components/activity/span-bits.tsx @@ -292,17 +292,3 @@ export function digestCostClause(digest: { return "free"; } -/** The "9+" unread-count bubble shared by the rail and the tab bar. Hidden at 0. */ -export function CountBadge({ count, className }: { count: number; className?: string }) { - if (count <= 0) return null; - return ( - - {count > 9 ? "9+" : count} - - ); -} diff --git a/packages/ui-react/src/components/chat/ask-user-card.tsx b/packages/ui-react/src/components/chat/ask-user-card.tsx index 5ad2d31055..ce987521b1 100644 --- a/packages/ui-react/src/components/chat/ask-user-card.tsx +++ b/packages/ui-react/src/components/chat/ask-user-card.tsx @@ -45,7 +45,7 @@ function defaultState(): PerQuestionState { /** The preview to show for a question: the focused option's, else the single * chosen one's. `preview` is "content rendered when an option is focused" * in the ask_user contract; selection is the fallback once focus has moved on. */ -export function previewFor( +function previewFor( question: AskUserQuestion, state: Pick ): string | undefined { @@ -58,7 +58,7 @@ export function previewFor( } /** The answer the exchange recorded for one question, as the card shows it. */ -export function recordedAnswer( +function recordedAnswer( question: AskUserQuestion, answers: Record | undefined ): string { @@ -90,7 +90,7 @@ export function answeredMeta(answeredAt: number | undefined, count = 1): string export const TYPED_META = "taken from your next message"; /** The typed answer is the user's own words, so the card quotes them. */ -export function quoted(text: string): string { +function quoted(text: string): string { return text ? `\u201C${text}\u201D` : ""; } diff --git a/packages/ui-react/src/components/chat/ask-user-list-card.tsx b/packages/ui-react/src/components/chat/ask-user-list-card.tsx index 7b8d3905e1..ed15463401 100644 --- a/packages/ui-react/src/components/chat/ask-user-list-card.tsx +++ b/packages/ui-react/src/components/chat/ask-user-list-card.tsx @@ -31,7 +31,7 @@ import { DISMISSED_NOTE } from "./ask-user-card.js"; import type { RecordHead } from "./answer-text.js"; /** "you answered 7 · 3m ago", or without the time when none is known. */ -export function listAnsweredMeta(count: number, total: number, answeredAt: number | undefined): string { +function listAnsweredMeta(count: number, total: number, answeredAt: number | undefined): string { const what = count === total ? `you answered ${count}` : `you answered ${count} of ${total}`; return answeredAt === undefined ? what : `${what} · ${formatRelativeTime(answeredAt)}`; } diff --git a/packages/ui-react/src/components/chat/brain-markdown-links.tsx b/packages/ui-react/src/components/chat/brain-markdown-links.tsx index a0cb391c0d..357198f70d 100644 --- a/packages/ui-react/src/components/chat/brain-markdown-links.tsx +++ b/packages/ui-react/src/components/chat/brain-markdown-links.tsx @@ -34,7 +34,7 @@ export function repoImageSrc(src: string, root: BrainUiRoot): string { * checked once per store; until the answer arrives, and whenever the check * cannot tell, the reference keeps its ordinary form. */ -export function useScratchExpired(path: string | undefined): boolean { +function useScratchExpired(path: string | undefined): boolean { const scratch = scratchPath(path); const status = useFileStore((s) => (scratch ? s.scratchFiles[scratch] : undefined)); const check = useFileStore((s) => s.checkScratchFile); @@ -56,7 +56,7 @@ const InsideExpiredLink = createContext(false); * only open an error. It keeps the link role, marked unavailable, so a screen * reader still meets it as the link it was, named with the label. */ -export function ExpiredFileLink({ path, children, style }: { path: string; children?: React.ReactNode; style?: React.CSSProperties }) { +function ExpiredFileLink({ path, children, style }: { path: string; children?: React.ReactNode; style?: React.CSSProperties }) { return ( @@ -73,7 +73,7 @@ export function ExpiredFileLink({ path, children, style }: { path: string; child * same muted "expired". It is a `span` because markdown images sit inside * paragraphs. */ -export function ExpiredImage({ alt }: { alt?: string }) { +function ExpiredImage({ alt }: { alt?: string }) { const words = alt?.trim(); return ( @@ -153,7 +153,7 @@ export function FileLink({ path, children, style }: { path: string; children?: R * slugs are looked up by basename. An `#anchor` suffix is stripped before * lookup. */ -export function resolveWikilinkTarget( +function resolveWikilinkTarget( raw: string, slugMap: Record ): string | null { diff --git a/packages/ui-react/src/components/chat/brain-markdown-share.ts b/packages/ui-react/src/components/chat/brain-markdown-share.ts index c172320484..0e98ec0648 100644 --- a/packages/ui-react/src/components/chat/brain-markdown-share.ts +++ b/packages/ui-react/src/components/chat/brain-markdown-share.ts @@ -2,7 +2,7 @@ import type { ShareBlockFormat } from "./share-block.js"; type ShareSegment = { kind: "share"; format: ShareBlockFormat; title?: string; body: string }; type TextSegment = { kind: "text"; text: string }; -export type Segment = TextSegment | ShareSegment; +type Segment = TextSegment | ShareSegment; const SHARE_BLOCK_RE = /]*)>([\s\S]*?)<\/share>/gi; const VALID_FORMATS: ReadonlySet = new Set([ @@ -47,6 +47,3 @@ export function shareBlockRanges(input: string): Array<{ segment: Segment; start } -export function splitShareBlocks(input: string): Segment[] { - return shareBlockRanges(input).map(({ segment }) => segment); -} diff --git a/packages/ui-react/src/components/chat/composer-view.tsx b/packages/ui-react/src/components/chat/composer-view.tsx index e3668be6c3..50188649c5 100644 --- a/packages/ui-react/src/components/chat/composer-view.tsx +++ b/packages/ui-react/src/components/chat/composer-view.tsx @@ -28,12 +28,12 @@ import { isThinkingLevel, type ThinkingLevel } from "@schlessera/brain-ui-sdk/pr * Paste-to-attach is caught here too: the kit's textarea has no paste * handler of its own, and the event bubbles to this frame with its files. */ -export interface ComposerAttachment { +interface ComposerAttachment { previewUrl: string; name: string; } -export interface ComposerProvider { +interface ComposerProvider { label: string; /** The model is fixed for this conversation; effort remains editable. */ locked: boolean; diff --git a/packages/ui-react/src/components/chat/renderers/apify-tools.tsx b/packages/ui-react/src/components/chat/renderers/apify-tools.tsx index 20fb88d34e..ca6fd3973a 100644 --- a/packages/ui-react/src/components/chat/renderers/apify-tools.tsx +++ b/packages/ui-react/src/components/chat/renderers/apify-tools.tsx @@ -59,7 +59,7 @@ function useApifyLimits(): { limits: ApifyLimitsRead | null; read: boolean } { } /** The exact run a person approves once (rev 1 §3): Actor, what is sent, who pays, cost and what is not covered. */ -export function ApifyRunReview({ tool }: { tool: ToolCallView }) { +function ApifyRunReview({ tool }: { tool: ToolCallView }) { const root = useBrainUiRoot(); const effective = useApifyLimits(); const review = tool.input ?? {}; diff --git a/packages/ui-react/src/components/chat/renderers/bind.tsx b/packages/ui-react/src/components/chat/renderers/bind.tsx index 4f0b1f6d52..f69493dfb6 100644 --- a/packages/ui-react/src/components/chat/renderers/bind.tsx +++ b/packages/ui-react/src/components/chat/renderers/bind.tsx @@ -37,7 +37,7 @@ export function boundToolNames(contract: ToolComponentContract): string[] { ]; } -export interface BindOptions { +interface BindOptions { icon?: ToolRenderer["icon"]; label?: string; /** Collapsed one-liner, from the parsed payload. */ diff --git a/packages/ui-react/src/components/chat/risk-hints.ts b/packages/ui-react/src/components/chat/risk-hints.ts index b5d84f6e52..71d35d95d0 100644 --- a/packages/ui-react/src/components/chat/risk-hints.ts +++ b/packages/ui-react/src/components/chat/risk-hints.ts @@ -35,7 +35,7 @@ function asString(v: unknown): string { } /** The extracted, plain-value meaning risk rules test against. */ -export type ResolvedSemantics = { +type ResolvedSemantics = { /** Shell command line the call executes, or "". */ command: string; /** Filesystem path the call writes, or "". */ @@ -67,7 +67,7 @@ function sniffSemantics(tool: ToolCall): ResolvedSemantics { } /** Evaluate a renderer's semantics accessors (each optional) for one call. */ -export function resolveSemantics( +function resolveSemantics( tool: ToolCall, semantics?: ToolSemantics ): ResolvedSemantics { @@ -84,12 +84,12 @@ export function resolveSemantics( }; } -export type RiskRule = { +type RiskRule = { test: (sem: ResolvedSemantics) => boolean; message: string; }; -export const RISK_RULES: RiskRule[] = [ +const RISK_RULES: RiskRule[] = [ { // Note: the Bash input view already badges this red, so this line is // secondary. Kept for consistency so the advisory row reflects every known diff --git a/packages/ui-react/src/components/chat/scope-cap-card.tsx b/packages/ui-react/src/components/chat/scope-cap-card.tsx index e167e71b42..ff66832eff 100644 --- a/packages/ui-react/src/components/chat/scope-cap-card.tsx +++ b/packages/ui-react/src/components/chat/scope-cap-card.tsx @@ -6,7 +6,7 @@ import { useBrainUiRoot } from "../../root-context.js"; import { useChatStore } from "../../stores/chat-store.js"; import { useConnectionStore } from "../../stores/connection-store.js"; -export const scopeLimitName: Record = { +const scopeLimitName: Record = { files_changed: "File limit", minutes: "Time limit", tool_calls: "Tool-call limit", turn_bytes: "Write allowance", free_space_floor: "Free-space floor", }; export function scopeNumber(dimension: ScopeCapReceipt["dimension"], value: number): string { diff --git a/packages/ui-react/src/components/chat/session-list.tsx b/packages/ui-react/src/components/chat/session-list.tsx index 4b99395f6e..feba388ed5 100644 --- a/packages/ui-react/src/components/chat/session-list.tsx +++ b/packages/ui-react/src/components/chat/session-list.tsx @@ -36,7 +36,7 @@ import { useMediaQuery } from "../../hooks/use-media-query.js"; * (Continue on another backend) is a stop only beside the row that holds the * list's stop, so Tab leaves the list in one or two steps however long it is. */ -export interface SessionRowData { +interface SessionRowData { id: string; title: string | null; /** Already formatted: "2h ago". */ @@ -71,7 +71,7 @@ export interface DraftRowData { current: boolean; } -export interface SessionGroupData { +interface SessionGroupData { label: string; sessions: SessionRowData[]; } diff --git a/packages/ui-react/src/components/chat/share-document.tsx b/packages/ui-react/src/components/chat/share-document.tsx index 36e915e397..9073252c39 100644 --- a/packages/ui-react/src/components/chat/share-document.tsx +++ b/packages/ui-react/src/components/chat/share-document.tsx @@ -22,7 +22,7 @@ import { usableBlocks } from "./markdown-content.js"; import { BlockCard } from "./tool-cards/block-card.js"; /** One piece of the shared answer, in the order the reader saw it. */ -export type ShareSegment = { kind: "markdown"; text: string } | { kind: "block"; block: Block }; +type ShareSegment = { kind: "markdown"; text: string } | { kind: "block"; block: Block }; /** * The answer as the transcript draws it: each text part, with the blocks the diff --git a/packages/ui-react/src/components/chat/tool-cards/image-mask-card.tsx b/packages/ui-react/src/components/chat/tool-cards/image-mask-card.tsx index fc1f7c9467..d92adb9266 100644 --- a/packages/ui-react/src/components/chat/tool-cards/image-mask-card.tsx +++ b/packages/ui-react/src/components/chat/tool-cards/image-mask-card.tsx @@ -32,7 +32,7 @@ import { useBrainUiRoot } from "../../../root-context.js"; import { ClampedPre } from "../tool-views.js"; /** A normalised rectangle over the source image: every value in 0..1. */ -export interface MaskRegion { +interface MaskRegion { x: number; y: number; w: number; @@ -55,7 +55,7 @@ function bytesLabel(bytes: number): string { } /** The mask file exists with content: the handler reports the PNG's byte length. */ -export function hasMaskBytes(payload: Pick): boolean { +function hasMaskBytes(payload: Pick): boolean { return typeof payload.bytes === "number" && payload.bytes > 0; } @@ -64,7 +64,7 @@ export function hasMaskBytes(payload: Pick): boolean * the mask image over both when `maskUrl` is given. Exported for the view * test; the bound card computes `maskUrl` from the payload. */ -export function MaskThumb({ +function MaskThumb({ region, label, maskUrl, diff --git a/packages/ui-react/src/components/chat/tool-cards/map-block.tsx b/packages/ui-react/src/components/chat/tool-cards/map-block.tsx index c88becec78..da2022aff9 100644 --- a/packages/ui-react/src/components/chat/tool-cards/map-block.tsx +++ b/packages/ui-react/src/components/chat/tool-cards/map-block.tsx @@ -36,7 +36,7 @@ type FrameGeometry = PlaceMapFrame["geometry"]; * width over this many pixels, and buckets 495 up to 660, which errs towards * streets rather than an empty map. */ -export const MAP_BLOCK_REQUEST_WIDTH = 495; +const MAP_BLOCK_REQUEST_WIDTH = 495; /** Below this viewport width the list starts collapsed past eight rows. */ const LIST_OPEN_FROM_PX = 480; diff --git a/packages/ui-react/src/components/chat/transcript-turn.tsx b/packages/ui-react/src/components/chat/transcript-turn.tsx index 31d2139de1..1cd2b3b4f9 100644 --- a/packages/ui-react/src/components/chat/transcript-turn.tsx +++ b/packages/ui-react/src/components/chat/transcript-turn.tsx @@ -17,7 +17,7 @@ import { cn } from "../../lib/utils.js"; * tokens"), controlled by the container so it can auto-collapse when the * stream ends. */ -export interface TurnHeaderProps { +interface TurnHeaderProps { who: string; /** Mono time, already formatted. Absent prints no time (a turn shell the host has not timed). */ when?: string; @@ -71,7 +71,7 @@ export function AttachmentCount({ count }: { count: number }) { return ; } -export interface ThinkingBlockProps { +interface ThinkingBlockProps { content: ReactNode; /** Roughly how much was thought; the collapsed summary's number. */ chars: number; diff --git a/packages/ui-react/src/components/chat/turn-notice.tsx b/packages/ui-react/src/components/chat/turn-notice.tsx index d3854babe3..482485a2c1 100644 --- a/packages/ui-react/src/components/chat/turn-notice.tsx +++ b/packages/ui-react/src/components/chat/turn-notice.tsx @@ -15,7 +15,7 @@ import { useBrainUiRoot } from "../../root-context.js"; import type { ChatMessage, TurnNotice as TurnNoticeValue } from "../../stores/chat-store.js"; import { useChatStore } from "../../stores/chat-store.js"; -export const TURN_NOTICE_COPY: Record = { +const TURN_NOTICE_COPY: Record = { timeout: { tag: "Turn timed out", body: "The host's time limit for one turn ran out, so this turn stopped.", diff --git a/packages/ui-react/src/components/chat/worker-host-notice.tsx b/packages/ui-react/src/components/chat/worker-host-notice.tsx index a211d51133..1afcdbf3b4 100644 --- a/packages/ui-react/src/components/chat/worker-host-notice.tsx +++ b/packages/ui-react/src/components/chat/worker-host-notice.tsx @@ -11,7 +11,7 @@ export const WORKER_HOST_DOCS_URL = export const ROOT_SERVER_DOCS_URL = "https://github.com/schlessera/brain-kit/blob/main/docs/hosting/agent-workers.md#running-the-server-as-root"; -export interface WorkerHostNoticeViewProps { +interface WorkerHostNoticeViewProps { /** The probe's named requirement, as a refused turn names it. */ requirement: string; checking: boolean; @@ -24,7 +24,7 @@ export interface WorkerHostNoticeViewProps { * a re-check. The composer stays usable: a turn sent anyway is refused by the * server with the same requirement. */ -export function WorkerHostNoticeView({ requirement, checking, onCheck }: WorkerHostNoticeViewProps) { +function WorkerHostNoticeView({ requirement, checking, onCheck }: WorkerHostNoticeViewProps) { return (
@@ -45,7 +45,7 @@ export function WorkerHostNoticeView({ requirement, checking, onCheck }: WorkerH * so it only says what an agent turn can reach and links the fix. There is * nothing to re-check: only restarting the server as another user clears it. */ -export function RootServerNoticeView() { +function RootServerNoticeView() { return (
diff --git a/packages/ui-react/src/components/connectivity/login-form.tsx b/packages/ui-react/src/components/connectivity/login-form.tsx index 97fcc0fd32..4ce0683c66 100644 --- a/packages/ui-react/src/components/connectivity/login-form.tsx +++ b/packages/ui-react/src/components/connectivity/login-form.tsx @@ -18,12 +18,12 @@ import type { FormEvent, ReactNode } from "react"; * Fail-open by design: `methods.password` defaults to true in the container, * so a failed probe still shows the one method that always works. */ -export interface LoginMethods { +interface LoginMethods { password: boolean; passkey: boolean; } -export interface LoginFormProps { +interface LoginFormProps { appName: string; title?: string; notice?: ReactNode; diff --git a/packages/ui-react/src/components/files/file-tree-view.tsx b/packages/ui-react/src/components/files/file-tree-view.tsx index d66d5c02aa..869a80f8db 100644 --- a/packages/ui-react/src/components/files/file-tree-view.tsx +++ b/packages/ui-react/src/components/files/file-tree-view.tsx @@ -27,7 +27,7 @@ export function fileKind(name: string, isDir: boolean, expanded: boolean): FileK return IMAGE_EXT.has(ext) ? "image" : "file"; } -export interface TreeRowProps { +interface TreeRowProps { name: string; kind: FileKind; depth: number; @@ -64,7 +64,7 @@ export interface TreeRowProps { } /** How long the reveal flash runs before the request is cleared. */ -export const HIGHLIGHT_MS = 1800; +const HIGHLIGHT_MS = 1800; export function TreeRow(p: TreeRowProps) { const ref = useRef(null); @@ -101,7 +101,7 @@ export function TreeRow(p: TreeRowProps) { ); } -export interface FileTreeViewProps { +interface FileTreeViewProps { /** The root listing: `loading` before it arrives, `error` when it failed, `ready` with rows. */ state: "loading" | "error" | "ready"; error?: string; diff --git a/packages/ui-react/src/components/files/file-viewer-frame.tsx b/packages/ui-react/src/components/files/file-viewer-frame.tsx index 8039aee032..2c8a18e61d 100644 --- a/packages/ui-react/src/components/files/file-viewer-frame.tsx +++ b/packages/ui-react/src/components/files/file-viewer-frame.tsx @@ -1,4 +1,4 @@ -import { Button, IconButton, Callout, EmptyState, FilterRow, Placeholder } from "@schlessera/brain-ui-kit"; +import { Button, IconButton, EmptyState, FilterRow, Placeholder } from "@schlessera/brain-ui-kit"; import { Check, Copy, ExternalLink, FolderOpen } from "lucide-react"; import type { ReactNode } from "react"; import type { FileLoadFailure } from "../../stores/file-state.js"; @@ -15,9 +15,9 @@ import type { FileLoadFailure } from "../../stores/file-state.js"; * The reveal and copy controls use the kit IconButton. The HTML "Open in * new tab" link stays native, and the share menu arrives rendered. */ -export type ViewMode = "preview" | "raw"; +type ViewMode = "preview" | "raw"; -export interface ViewerToolbarProps { +interface ViewerToolbarProps { fileName: string; fullPath: string; size?: number; @@ -115,14 +115,6 @@ export function ViewerFailure({ failure, onRetry }: { failure: FileLoadFailure;
; } -export function ViewerError({ message }: { message: string }) { - return ( -
- -
- ); -} - /** * A scratch file that has been cleared (#1657). Not an error: files made for * a conversation are kept for a while, so this is the expected end of one. diff --git a/packages/ui-react/src/components/files/file-viewer-html.tsx b/packages/ui-react/src/components/files/file-viewer-html.tsx index fb5b4c1f4a..b7d72382b2 100644 --- a/packages/ui-react/src/components/files/file-viewer-html.tsx +++ b/packages/ui-react/src/components/files/file-viewer-html.tsx @@ -13,7 +13,7 @@ * A press of Files (D52 N3) returns it to the top of the file by loading the * same `src` again (`data-html-preview`, `components/files/file-panel.tsx`). */ -export const HTML_PREVIEW_SANDBOX = "allow-scripts"; +const HTML_PREVIEW_SANDBOX = "allow-scripts"; export function FileViewerHtml({ src, onCheck }: { src: string; onCheck?: () => void }) { return ( diff --git a/packages/ui-react/src/components/files/frontmatter-chips.tsx b/packages/ui-react/src/components/files/frontmatter-chips.tsx index 64d5507277..1f5a1ab32b 100644 --- a/packages/ui-react/src/components/files/frontmatter-chips.tsx +++ b/packages/ui-react/src/components/files/frontmatter-chips.tsx @@ -11,7 +11,7 @@ import type { FrontmatterField } from "../../lib/frontmatter.js"; * A list-valued field is one chip per element, keyed by the field; an empty * value is an explicit em dash, because a blank chip reads as nothing. */ -export interface FrontmatterChipsProps { +interface FrontmatterChipsProps { fields: FrontmatterField[]; open: boolean; onOpenChange: (open: boolean) => void; diff --git a/packages/ui-react/src/components/files/untrusted-marks.tsx b/packages/ui-react/src/components/files/untrusted-marks.tsx index 809b1582ec..b9b6d5103b 100644 --- a/packages/ui-react/src/components/files/untrusted-marks.tsx +++ b/packages/ui-react/src/components/files/untrusted-marks.tsx @@ -14,11 +14,11 @@ import { ChevronLeft } from "lucide-react"; import type { BrainUiRoot } from "../../root.js"; import { useBrainUiRoot } from "../../root-context.js"; -export interface MarkedBy { label: string | null; you: boolean } -export type MarkDetail = +interface MarkedBy { label: string | null; you: boolean } +type MarkDetail = | { path: string; marked: false; canClear: boolean } | { path: string; marked: true; markedAt: number; missing: boolean; markedBy?: MarkedBy; canClear: boolean }; -export interface MarkRow { path: string; marked: true; markedAt: number; missing: boolean; markedBy?: MarkedBy } +interface MarkRow { path: string; marked: true; markedAt: number; missing: boolean; markedBy?: MarkedBy } /** What one host request came back as. `uncertain`: it may or may not have applied. */ type Failure = "unsupported" | "not-found" | "forbidden" | "owner-required" | "unreachable" | "uncertain" | "signed-out"; @@ -61,7 +61,7 @@ const sendClear = (root: BrainUiRoot, path: string) => call<{ status: "cleared" body => record(body) && (body.status === "cleared" || body.status === "already_cleared")); /** `12 Jul`: the design's mark date. */ -export function markDate(at: number): string { +function markDate(at: number): string { return new Date(at).toLocaleDateString("en-GB", { day: "numeric", month: "short" }); } /** Who marked, for the owner only: the host sends no `markedBy` to anyone else. */ @@ -145,12 +145,12 @@ export function UntrustedMarksScope({ children }: { children: ReactNode }) { // ── One path's mark: the toolbar control, cue and rail ───────────────────── -export type DetailState = +type DetailState = | { status: "checking" } | { status: "unsupported" } | { status: "unknown" } | { status: "absent" } | { status: "ready"; mark: MarkDetail }; /** The mark of the open file, read from the host whenever the path or the surface's revision changes. */ -export function useMarkDetail(path: string | null): [DetailState, () => void, (mark: MarkDetail) => void] { +function useMarkDetail(path: string | null): [DetailState, () => void, (mark: MarkDetail) => void] { const root = useBrainUiRoot(); const marks = useUntrustedMarks(); const [state, setState] = useState<{ path: string | null; detail: DetailState }>({ path, detail: { status: "checking" } }); @@ -174,7 +174,7 @@ export function useMarkDetail(path: string | null): [DetailState, () => void, (m } /** `◆ untrusted · marked 12 Jul` (+ ` by …` for the owner): glyph and word, never colour alone. */ -export function MarkCue({ mark }: { mark: Extract }) { +function MarkCue({ mark }: { mark: Extract }) { return (
@@ -198,7 +198,6 @@ const COPY = { stillUnknown: "Still couldn't check. Try again.", proxy: "On turns that run through the egress proxy, web access is limited to the untrusted allow-list and sites this chat already contacted. Your other web rules still apply.", } as const; -export const PROXY_BULLET = COPY.proxy; /** * Send one intent for one captured path, and settle it from the host. diff --git a/packages/ui-react/src/components/graph/graph-controls.tsx b/packages/ui-react/src/components/graph/graph-controls.tsx index cd50f9f918..bf919294e4 100644 --- a/packages/ui-react/src/components/graph/graph-controls.tsx +++ b/packages/ui-react/src/components/graph/graph-controls.tsx @@ -67,7 +67,7 @@ export function ControlsBody() { } /** The four colourings, in the design's order. */ -export const COLOUR_RULES: { value: DiscoveryColorBy; label: string }[] = [ +const COLOUR_RULES: { value: DiscoveryColorBy; label: string }[] = [ { value: "topic", label: "Topic" }, { value: "distance", label: "Distance" }, { value: "folder", label: "Folder" }, diff --git a/packages/ui-react/src/components/graph/node-card.tsx b/packages/ui-react/src/components/graph/node-card.tsx index ab31e28aad..c34b5946eb 100644 --- a/packages/ui-react/src/components/graph/node-card.tsx +++ b/packages/ui-react/src/components/graph/node-card.tsx @@ -8,7 +8,7 @@ import { useId, useRef } from "react"; * as chips, its path as a `PathRef`, its degrees as machine meta, and the * actions as kit `Button`s — "Open note" primary, the rest ghost. */ -export interface NodeCardProps { +interface NodeCardProps { kind: string; title: string; path: string; diff --git a/packages/ui-react/src/components/layout/desktop-routes.ts b/packages/ui-react/src/components/layout/desktop-routes.ts index a2d9d86d23..68cbe7c950 100644 --- a/packages/ui-react/src/components/layout/desktop-routes.ts +++ b/packages/ui-react/src/components/layout/desktop-routes.ts @@ -8,7 +8,7 @@ import { useChatCommands } from "../chat/use-chat-commands.js"; /** The palette's row tone, which the rail does not draw. */ type Tone = NonNullable; -export interface DesktopDestination { +interface DesktopDestination { icon: IconName; label: string; tone: Tone; diff --git a/packages/ui-react/src/components/layout/error-boundary.tsx b/packages/ui-react/src/components/layout/error-boundary.tsx index a4fa201dd6..4350d70279 100644 --- a/packages/ui-react/src/components/layout/error-boundary.tsx +++ b/packages/ui-react/src/components/layout/error-boundary.tsx @@ -9,7 +9,7 @@ export interface ErrorBoundaryFallback { reset: () => void; } -export interface ErrorBoundaryProps { +interface ErrorBoundaryProps { children: ReactNode; /** Any change (Object.is per element) clears the error and the failure count. */ resetKeys?: readonly unknown[]; diff --git a/packages/ui-react/src/components/layout/page-boundary.tsx b/packages/ui-react/src/components/layout/page-boundary.tsx index 1c4c82e543..966ca67f73 100644 --- a/packages/ui-react/src/components/layout/page-boundary.tsx +++ b/packages/ui-react/src/components/layout/page-boundary.tsx @@ -20,7 +20,7 @@ const PAGE_REVIEW_COPY: ReviewCopy = { footnote: "Left out by default: the error message, component names, file paths, hostnames, and anything from your notes or conversations. Redaction is best effort; read the text before you paste it anywhere.", }; -export interface PageBoundaryProps { +interface PageBoundaryProps { children: ReactNode; /** Test hook: observe a reload without navigating. */ reload?: () => void; diff --git a/packages/ui-react/src/components/layout/slide-panel.tsx b/packages/ui-react/src/components/layout/slide-panel.tsx index 22181c09db..ecb9c48aa8 100644 --- a/packages/ui-react/src/components/layout/slide-panel.tsx +++ b/packages/ui-react/src/components/layout/slide-panel.tsx @@ -3,9 +3,9 @@ import { openModal } from "../../lib/destination-start.js"; import { Overlay } from "@schlessera/brain-ui-kit"; /** Drawers use Overlay; panes are fixed regions beside the rail. */ -export type SlidePanelMode = "drawer" | "pane"; +type SlidePanelMode = "drawer" | "pane"; /** Native dialog dismissal vocabulary, implemented by Overlay. */ -export type SlidePanelClosedBy = "any" | "closerequest" | "none"; +type SlidePanelClosedBy = "any" | "closerequest" | "none"; export function SlidePanel({ open, diff --git a/packages/ui-react/src/components/quick-actions/add-form.tsx b/packages/ui-react/src/components/quick-actions/add-form.tsx index 4bbb3bddef..d13f72bce1 100644 --- a/packages/ui-react/src/components/quick-actions/add-form.tsx +++ b/packages/ui-react/src/components/quick-actions/add-form.tsx @@ -25,14 +25,14 @@ import { useFinePointer } from "../../hooks/use-fine-pointer.js"; */ export type AddState = "editing" | "saving" | "saved" | "error"; -export interface AddDraft { +interface AddDraft { content: string; title: string; type: string; tags: string; } -export interface AddFormProps { +interface AddFormProps { state: AddState; draft: AddDraft; /** Types already in the brain, offered as completions — a hint list, not a closed set. */ diff --git a/packages/ui-react/src/components/quick-actions/streaming-output.tsx b/packages/ui-react/src/components/quick-actions/streaming-output.tsx index 21e488cd2e..8073e32e11 100644 --- a/packages/ui-react/src/components/quick-actions/streaming-output.tsx +++ b/packages/ui-react/src/components/quick-actions/streaming-output.tsx @@ -25,7 +25,7 @@ const STATUS: Record cancelled: { tone: "red", pulse: false, text: "Cancelled" }, }; -export interface StreamingOutputProps { +interface StreamingOutputProps { state: StreamState; /** The job's lines so far, already turned into nodes by the container (paths linkified). */ lines: ReactNode[]; @@ -67,7 +67,7 @@ export function StreamingOutput(p: StreamingOutputProps) { * not know what it is made of. A failed or cancelled read says why and offers * Retry; a briefing with nothing in it says so instead of drawing a blank. */ -export interface BriefingOutputProps { +interface BriefingOutputProps { state: "loading" | "done" | "empty" | "error" | "cancelled"; content: ReactNode; /** Why the read failed; shown under the error. */ diff --git a/packages/ui-react/src/components/report/diagnostic-review.tsx b/packages/ui-react/src/components/report/diagnostic-review.tsx index eb69dba8b5..3cc2e50bd5 100644 --- a/packages/ui-react/src/components/report/diagnostic-review.tsx +++ b/packages/ui-react/src/components/report/diagnostic-review.tsx @@ -3,12 +3,12 @@ import { createPortal } from "react-dom"; import { Overlay, Button } from "@schlessera/brain-ui-kit"; /** The public tracker every report goes to (D51). */ -export const REPORT_ISSUE_URL = "https://github.com/schlessera/brain-kit/issues/new"; +const REPORT_ISSUE_URL = "https://github.com/schlessera/brain-kit/issues/new"; /** A prefilled issue link longer than this is refused, never truncated. */ -export const REPORT_URL_LIMIT = 8000; +const REPORT_URL_LIMIT = 8000; /** The exact link `Open issue on GitHub` opens: nothing is added at send time. */ -export function reportIssueUrl(title: string, body: string): string { +function reportIssueUrl(title: string, body: string): string { const url = new URL(REPORT_ISSUE_URL); url.searchParams.set("title", title); url.searchParams.set("body", body); @@ -19,7 +19,7 @@ export function reportIssueUrl(title: string, body: string): string { * Reviewed text appended at the end of the body on an explicit tap. `build` * returns null when the source is absent, and the button does not render. */ -export interface ReviewInclusion { +interface ReviewInclusion { id: string; label: string; build: () => string | null; @@ -50,7 +50,7 @@ export const CHAT_REVIEW_COPY: ReviewCopy = { copyFailed: "Couldn't copy. Select the reviewed text and copy it manually.", }; -export interface DiagnosticReviewProps { +interface DiagnosticReviewProps { mode: "copy" | "report"; /** * The generated body. While the reader has not edited the field, a new diff --git a/packages/ui-react/src/components/settings/apify-section.tsx b/packages/ui-react/src/components/settings/apify-section.tsx index 3289f26a5c..6555f83760 100644 --- a/packages/ui-react/src/components/settings/apify-section.tsx +++ b/packages/ui-react/src/components/settings/apify-section.tsx @@ -10,7 +10,7 @@ import { takeApifyFocus } from "../../lib/apify-focus.js"; import { ApifyView, type ApifyEdit, type ApifyFocusTarget } from "./apify-view.js"; /** How often an open section re-reads the host, so a change made on another device shows up. */ -export const APIFY_SETTINGS_REFRESH_MS = 30_000; +const APIFY_SETTINGS_REFRESH_MS = 30_000; /** * The Apify section's container (S6): the load, the owner/root lifetime diff --git a/packages/ui-react/src/components/settings/apify-view.tsx b/packages/ui-react/src/components/settings/apify-view.tsx index d74dd8e3a1..fdcff77087 100644 --- a/packages/ui-react/src/components/settings/apify-view.tsx +++ b/packages/ui-react/src/components/settings/apify-view.tsx @@ -17,7 +17,7 @@ export interface ApifyEdit { export type ApifyFocusTarget = "provider" | "discovery" | "actors" | "grants" | "limits" | "today"; -export interface ApifyViewProps { +interface ApifyViewProps { read: ApifySettingsRead; edit: ApifyEdit | null; /** The last outcome, announced politely. */ diff --git a/packages/ui-react/src/components/settings/models-list.tsx b/packages/ui-react/src/components/settings/models-list.tsx index 33dbd8c2db..793f936f00 100644 --- a/packages/ui-react/src/components/settings/models-list.tsx +++ b/packages/ui-react/src/components/settings/models-list.tsx @@ -19,7 +19,7 @@ import { useState, type ReactNode } from "react"; * §4, "no opacity de-emphasis"): it reads as hidden from its chip, at full * contrast. Refresh, Add and the section errors are the kit's. */ -export interface ModelsCatalogViewProps { +interface ModelsCatalogViewProps { catalog: ModelCatalogResponse | null; loading: boolean; refreshing: boolean; @@ -153,7 +153,7 @@ function DefaultModelSelect({ catalog, onChange }: { catalog: ModelCatalogRespon * change or redeploy. They appear in the roster above as ordinary profiles * (api-billed via OPENROUTER_API_KEY). The draft is the section's own. */ -export function OpenRouterSection({ models, onChange }: { models: string[]; onChange: (models: string[]) => void }) { +function OpenRouterSection({ models, onChange }: { models: string[]; onChange: (models: string[]) => void }) { const [draft, setDraft] = useState(""); function add() { diff --git a/packages/ui-react/src/components/settings/module-settings-fields.tsx b/packages/ui-react/src/components/settings/module-settings-fields.tsx index 88b6f4dd6a..95260bd274 100644 --- a/packages/ui-react/src/components/settings/module-settings-fields.tsx +++ b/packages/ui-react/src/components/settings/module-settings-fields.tsx @@ -15,7 +15,7 @@ function schemaAt(schema: Record, path: SettingsPath): Record, described: ModuleSettingsField[], value: unknown): ModuleSettingsField[] { +function settingsFields(schema: Record, described: ModuleSettingsField[], value: unknown): ModuleSettingsField[] { const result = [...described]; const covered = new Set(described.flatMap((f) => f.kind === "variant" ? f.variants?.flatMap((v) => v.fields.map((child) => child.key)) ?? [] : [f.key])); const properties = record(schema.properties) ? schema.properties : {}; diff --git a/packages/ui-react/src/components/settings/module-settings-state.ts b/packages/ui-react/src/components/settings/module-settings-state.ts index 750523f1f1..17b0e5a6cd 100644 --- a/packages/ui-react/src/components/settings/module-settings-state.ts +++ b/packages/ui-react/src/components/settings/module-settings-state.ts @@ -2,7 +2,7 @@ import { createStore } from "zustand/vanilla"; import type { ConfiguredModule, ModuleSettingsSnapshot, ModuleSettingsMigrationPreview } from "@schlessera/brain-ui-sdk"; export type SettingsPath = Array; -export interface VariantSelection { selected: string; original: string; keys: string[]; originallyPresent: string[] } +interface VariantSelection { selected: string; original: string; keys: string[]; originallyPresent: string[] } export interface ModuleSettingsSession { modules: ConfiguredModule[]; loading: boolean; diff --git a/packages/ui-react/src/components/settings/passkey-list.tsx b/packages/ui-react/src/components/settings/passkey-list.tsx index fc90935605..24b1e1248c 100644 --- a/packages/ui-react/src/components/settings/passkey-list.tsx +++ b/packages/ui-react/src/components/settings/passkey-list.tsx @@ -19,9 +19,9 @@ import { useState, type ReactNode } from "react"; * decorative. Rename state (which row is being * edited, the draft) is the row's own and never leaves the view. */ -export type PasskeyStatus = "loading" | "ready" | "unavailable"; +type PasskeyStatus = "loading" | "ready" | "unavailable"; -export interface PasskeyListProps { +interface PasskeyListProps { credentials: PasskeySummary[]; status: PasskeyStatus; /** A registration ceremony is in flight. */ diff --git a/packages/ui-react/src/components/settings/pi-accounts-list.tsx b/packages/ui-react/src/components/settings/pi-accounts-list.tsx index f362a2badf..ec2ff96563 100644 --- a/packages/ui-react/src/components/settings/pi-accounts-list.tsx +++ b/packages/ui-react/src/components/settings/pi-accounts-list.tsx @@ -14,7 +14,7 @@ import type { PiAuthProviderStatus, PiLoginFlow } from "../../lib/api-client.js" * a link is what it is — and the settled flow is a teal or red `Callout` * with a dismiss. */ -export interface AccountsListProps { +interface AccountsListProps { providers: PiAuthProviderStatus[]; /** The provider whose connect or disconnect is in flight. */ busy: string | null; diff --git a/packages/ui-react/src/components/settings/principal-list.tsx b/packages/ui-react/src/components/settings/principal-list.tsx index d6e64952fd..10dc3f7b81 100644 --- a/packages/ui-react/src/components/settings/principal-list.tsx +++ b/packages/ui-react/src/components/settings/principal-list.tsx @@ -15,7 +15,7 @@ import type { FormEvent, ReactNode } from "react"; * stay native; its submit is the kit `Button`, and ⏎ in a field submits the * form the same way. */ -export interface PrincipalRowData { +interface PrincipalRowData { id: string; label: string; kind: "owner" | "agent" | string; @@ -25,7 +25,7 @@ export interface PrincipalRowData { expires: string; } -export interface PrincipalListProps { +interface PrincipalListProps { children?: ReactNode; state: "loading" | "unavailable" | "error" | "ready"; principals: PrincipalRowData[]; diff --git a/packages/ui-react/src/components/settings/skills-list.tsx b/packages/ui-react/src/components/settings/skills-list.tsx index 1d0760afdc..2080b0e78a 100644 --- a/packages/ui-react/src/components/settings/skills-list.tsx +++ b/packages/ui-react/src/components/settings/skills-list.tsx @@ -19,7 +19,7 @@ import { cn } from "../../lib/utils.js"; * particular — the container passes the skill name it is working on, and * every row control is inert while any is running, as before. */ -export interface SkillsListProps { +interface SkillsListProps { skills: SkillEntry[]; /** The skill a mutation is running for, or null. */ busy: string | null; @@ -202,7 +202,7 @@ export function SkillsList(p: SkillsListProps) { ); } -export interface SkillEditorProps { +interface SkillEditorProps { name: string; content: string; isNew: boolean; diff --git a/packages/ui-react/src/components/settings/storage/use-storage.ts b/packages/ui-react/src/components/settings/storage/use-storage.ts index c6de418dc1..97a2ebc951 100644 --- a/packages/ui-react/src/components/settings/storage/use-storage.ts +++ b/packages/ui-react/src/components/settings/storage/use-storage.ts @@ -18,7 +18,7 @@ import { storageApi } from "../../../lib/storage-api.js"; import { canonicalPath, type StorageMetric } from "./storage-model.js"; export const running = (state: string | undefined) => state === "waiting" || state === "running"; -export interface InspectedFile { +interface InspectedFile { entry: StorageFileEntry; path: string | null; facts: StorageRemovalFile | null; diff --git a/packages/ui-react/src/components/settings/tool-permissions-list.tsx b/packages/ui-react/src/components/settings/tool-permissions-list.tsx index 981b230bf0..4df1e21c0d 100644 --- a/packages/ui-react/src/components/settings/tool-permissions-list.tsx +++ b/packages/ui-react/src/components/settings/tool-permissions-list.tsx @@ -9,7 +9,7 @@ import { Callout, Label, ListRow, Surface } from "@schlessera/brain-ui-kit"; * revokes, and the row dims while the revoke is in flight. * `ToolPermissionsSection` is the container that owns the request. */ -export interface ToolPermissionsListProps { +interface ToolPermissionsListProps { tools: string[]; /** The tool whose revoke is in flight. */ busy: string | null; diff --git a/packages/ui-react/src/components/settings/web-search-chain.tsx b/packages/ui-react/src/components/settings/web-search-chain.tsx index 937debefc5..24f3a0b64a 100644 --- a/packages/ui-react/src/components/settings/web-search-chain.tsx +++ b/packages/ui-react/src/components/settings/web-search-chain.tsx @@ -24,7 +24,7 @@ import type { WebSearchConfig, WebSearchProvider } from "../../lib/api-client.js * Key values never come back from the server; the view only ever learns "a * key is stored". */ -export interface WebSearchChainProps { +interface WebSearchChainProps { config: WebSearchConfig; busy: boolean; error: string | null; diff --git a/packages/ui-react/src/hooks/use-handoff-entry.ts b/packages/ui-react/src/hooks/use-handoff-entry.ts index 143cca1034..b0d2c4bba0 100644 --- a/packages/ui-react/src/hooks/use-handoff-entry.ts +++ b/packages/ui-react/src/hooks/use-handoff-entry.ts @@ -39,7 +39,7 @@ export function handoffWhy( return `${backends.map(name).join(", ")} ${reason}`; } -export interface HandoffEntry { +interface HandoffEntry { /** Whether the entry belongs here at all: a stored session with a settled turn. */ shown: boolean; /** Why it cannot run right now. Printed beside it, never a reason to hide it. */ diff --git a/packages/ui-react/src/hooks/use-vpn-status.ts b/packages/ui-react/src/hooks/use-vpn-status.ts index 6a9f5466a0..568bcc2672 100644 --- a/packages/ui-react/src/hooks/use-vpn-status.ts +++ b/packages/ui-react/src/hooks/use-vpn-status.ts @@ -1,4 +1,3 @@ -import { defaultRoot } from "../default-root.js"; import { useBrainUiRoot } from "../root-context.js"; import type { BrainUiRoot } from "../root.js"; import { useEffect, useRef, useState } from "react"; @@ -43,14 +42,6 @@ async function fetchVpnStatus(root: BrainUiRoot): Promise { } } -/** - * Ask the mounted connectivity poller for a fresh reading. The poller remains - * the only writer of vpnStatus and serializes this with its scheduled checks. - */ -export function recheckVpnStatus(): void { - defaultRoot.recheckVpn?.(); -} - export function useVpnStatus(localOnly = false) { const root = useBrainUiRoot(); const local = useRef(localOnly); diff --git a/packages/ui-react/src/hooks/use-websocket.ts b/packages/ui-react/src/hooks/use-websocket.ts index 381ac9b5b7..88577a5d70 100644 --- a/packages/ui-react/src/hooks/use-websocket.ts +++ b/packages/ui-react/src/hooks/use-websocket.ts @@ -1,15 +1,8 @@ import { useEffect, useCallback } from "react"; -import type { ClientMessage, ServerMessage } from "@schlessera/brain-ui-sdk/protocol"; -import { defaultRoot } from "../default-root.js"; +import type { ClientMessage } from "@schlessera/brain-ui-sdk/protocol"; import { useBrainUiRoot } from "../root-context.js"; export { runStateForFrame } from "./websocket-handlers/chat.js"; -/** Default-app entry points for callers outside React. */ -export function handleServerMessage(message: ServerMessage) { defaultRoot.connection.handleServerMessage(message); } -export function flushChatDeltas() { defaultRoot.connection.flushChatDeltas(); } -export function sendClientMessage(message: ClientMessage) { return defaultRoot.connection.send(message); } -export function reconnectWebSocketNow() { defaultRoot.connection.reconnectNow(); } - export function useWebSocket() { const root = useBrainUiRoot(); useEffect(() => root.connection.connect(), [root]); diff --git a/packages/ui-react/src/hooks/use-working-sessions.ts b/packages/ui-react/src/hooks/use-working-sessions.ts index e77f26ba3d..ca177e9eba 100644 --- a/packages/ui-react/src/hooks/use-working-sessions.ts +++ b/packages/ui-react/src/hooks/use-working-sessions.ts @@ -7,7 +7,7 @@ import type { ListedSession } from "../stores/session-list-state.js"; import type { TrackerView } from "../lib/trackers.js"; /** One tracker as the strip, its sheet, the drawer and the pane draw it. */ -export type WorkingSessionData = Omit; +type WorkingSessionData = Omit; /** * What a tracker is called (D52 §3): #1004's few-word label when the host @@ -33,7 +33,7 @@ const CANT_CHECK = { } as const; /** #948's view of one tracker, in the kit's vocabulary (`WorkingSession`). */ -export function workingSession(view: TrackerView, label: string): WorkingSessionData { +function workingSession(view: TrackerView, label: string): WorkingSessionData { const base = { id: view.sessionId, label, startedAt: view.startedAt, endedAt: view.endedAt }; switch (view.state) { case "needs_you": @@ -53,7 +53,7 @@ export function workingSession(view: TrackerView, label: string): WorkingSession } } -export interface WorkingSessions { +interface WorkingSessions { /** * The trackers to draw as Working rows and pills, in D52 §4's order: none * that is cleared, every live one, and at most 24 done or cancelled. diff --git a/packages/ui-react/src/lib/activity-report.ts b/packages/ui-react/src/lib/activity-report.ts index 2c722013ea..bade235b0c 100644 --- a/packages/ui-react/src/lib/activity-report.ts +++ b/packages/ui-react/src/lib/activity-report.ts @@ -16,7 +16,7 @@ import { INCLUDED_TEXT_CAP, providerMessageInclusion, redactProviderMessage } fr * Built-in tool names safe to print; any other tool is `other tool`. Claude's * built-ins, and the file and shell tools the pi backend registers. */ -export const BUILT_IN_TOOLS: ReadonlySet = new Set([ +const BUILT_IN_TOOLS: ReadonlySet = new Set([ "Read", "Write", "Edit", "Bash", "Grep", "Glob", "WebFetch", "WebSearch", "Agent", "read_file", "write_file", "edit_file", "grep", "bash", ]); @@ -37,7 +37,7 @@ export type ReportRecord = /** The read failed for a reason other than 404. */ | { state: "unloaded"; offline: boolean }; -export interface ReportContext { +interface ReportContext { /** The ui-react release bundled in this client. */ client: string | null; /** `/api/status`'s software identity, only when it was loaded and authorized. */ diff --git a/packages/ui-react/src/lib/answer-delivery/copy.ts b/packages/ui-react/src/lib/answer-delivery/copy.ts index 3d6bf23a41..cae35566e7 100644 --- a/packages/ui-react/src/lib/answer-delivery/copy.ts +++ b/packages/ui-react/src/lib/answer-delivery/copy.ts @@ -6,7 +6,7 @@ import { MAX_QUEUED_ANSWERS, type AnswerDelivery } from "./types.js"; export type DeliveryAction = "cancel" | "copy" | "sendAsMessage" | "edit" | "reload" | "tryAgain"; -export interface DeliveryCopy { +interface DeliveryCopy { tag: string; body?: string; meta?: string; @@ -25,13 +25,13 @@ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", " const pad = (n: number) => String(n).padStart(2, "0"); /** "09:41", in local time. */ -export function clockTime(at: number): string { +function clockTime(at: number): string { const d = new Date(at); return `${pad(d.getHours())}:${pad(d.getMinutes())}`; } /** "2 Oct 09:41", in local time. */ -export function dayAndTime(at: number): string { +function dayAndTime(at: number): string { const d = new Date(at); return `${d.getDate()} ${MONTHS[d.getMonth()]} ${clockTime(at)}`; } diff --git a/packages/ui-react/src/lib/answer-delivery/manager.ts b/packages/ui-react/src/lib/answer-delivery/manager.ts index bfa2d2fe28..803b122c47 100644 --- a/packages/ui-react/src/lib/answer-delivery/manager.ts +++ b/packages/ui-react/src/lib/answer-delivery/manager.ts @@ -38,7 +38,7 @@ import { } from "./types.js"; /** What the queue needs from the connection. */ -export interface DeliveryTransport { +interface DeliveryTransport { /** Send on the open socket; false when there is none. */ send(message: ClientMessage): boolean; /** Connected, and the host's hello (or its absence) is known. */ @@ -60,7 +60,7 @@ export interface SubmitAnswer { focus?: boolean; } -export interface AnswerDeliveryOptions { +interface AnswerDeliveryOptions { chat: StoreApi; /** null: this page cannot store answers, so it cannot queue them either. */ storage: AnswerStorage | null; @@ -87,8 +87,6 @@ interface Entry { cancelling?: boolean; } -export type AnswerDeliveryQueue = ReturnType; - export function createAnswerDelivery(options: AnswerDeliveryOptions) { const { chat, transport } = options; const now = options.now ?? Date.now; diff --git a/packages/ui-react/src/lib/answer-delivery/types.ts b/packages/ui-react/src/lib/answer-delivery/types.ts index f8f9a7191e..d6ed1d0b5e 100644 --- a/packages/ui-react/src/lib/answer-delivery/types.ts +++ b/packages/ui-react/src/lib/answer-delivery/types.ts @@ -15,8 +15,6 @@ import type { ServerAskAnswerReceipt, } from "@schlessera/brain-ui-sdk/protocol"; -export type AskKind = "ask_user" | "ask_user_list" | "ask_user_rank" | "ask_user_form"; - /** What the user submitted, in the shape of its kind. Immutable once queued. */ export type AnswerPayload = | { @@ -118,11 +116,6 @@ export interface AnswerDelivery { sentAsMessage?: boolean; } -/** States in which the answer may still reach the host. */ -export function isUnconfirmed(state: DeliveryState): boolean { - return state === "saving" || state === "queued" || state === "awaiting"; -} - /** States in which the card keeps its editable form, because nothing was admitted. */ export function isRefusedAdmission(state: DeliveryState): boolean { return state === "full" || state === "notSaved"; diff --git a/packages/ui-react/src/lib/answer-suggestions.ts b/packages/ui-react/src/lib/answer-suggestions.ts index b0e8853c87..62a6f74e4b 100644 --- a/packages/ui-react/src/lib/answer-suggestions.ts +++ b/packages/ui-react/src/lib/answer-suggestions.ts @@ -19,7 +19,7 @@ import type { VoiceMode } from "@schlessera/brain-ui-sdk/protocol"; import type { ChatMessage } from "../stores/chat-state.js"; import { isShowBlockTool } from "./tool-names.js"; -export type SuggestionsBlock = Extract; +type SuggestionsBlock = Extract; export type SuggestionsItem = SuggestionsBlock["items"][number]; /** The row label when the model gives none. */ @@ -92,7 +92,7 @@ export function endsWithQuestion(message: ChatMessage): boolean { } /** The facts the closing row depends on beyond the message itself. */ -export interface SuggestionsContext { +interface SuggestionsContext { /** Every message of the session, in order. */ messages: readonly ChatMessage[]; /** The session still has a turn running or queued. */ @@ -103,7 +103,7 @@ export interface SuggestionsContext { } /** The user message that started the turn `message` answers. */ -export function promptOf(message: ChatMessage, messages: readonly ChatMessage[]): ChatMessage | undefined { +function promptOf(message: ChatMessage, messages: readonly ChatMessage[]): ChatMessage | undefined { const index = messages.indexOf(message); for (let i = index - 1; i >= 0; i--) { if (messages[i]!.role === "user") return messages[i]; diff --git a/packages/ui-react/src/lib/apify-focus.ts b/packages/ui-react/src/lib/apify-focus.ts index 2fa0d27113..7d59113c91 100644 --- a/packages/ui-react/src/lib/apify-focus.ts +++ b/packages/ui-react/src/lib/apify-focus.ts @@ -6,7 +6,7 @@ */ import type { BrainUiRoot } from "../root.js"; -export type ApifySettingsTarget = "provider" | "discovery" | "actors" | "grants" | "limits" | "today"; +type ApifySettingsTarget = "provider" | "discovery" | "actors" | "grants" | "limits" | "today"; const requests = new WeakMap(); diff --git a/packages/ui-react/src/lib/apify.ts b/packages/ui-react/src/lib/apify.ts index 52146ff82a..46265cd52b 100644 --- a/packages/ui-react/src/lib/apify.ts +++ b/packages/ui-react/src/lib/apify.ts @@ -20,23 +20,23 @@ export function usd(value: number): string { return `$${value.toFixed(2)}`; } -export function shortTime(iso: string | null | undefined): string { +function shortTime(iso: string | null | undefined): string { if (!iso) return "an unknown time"; const date = new Date(iso); return Number.isFinite(date.getTime()) ? `${date.toISOString().slice(11, 16)} UTC` : "an unknown time"; } -export function shortDate(iso: string): string { +function shortDate(iso: string): string { const date = new Date(iso); return Number.isFinite(date.getTime()) ? date.toISOString().slice(0, 10) : iso; } /** The account as the owner knows it: name and the id's last four characters. */ -export function accountLabel(account: { id: string; username: string | null } | null): string { +function accountLabel(account: { id: string; username: string | null } | null): string { if (!account) return "an unknown account"; return `${account.username ?? "account"} (…${account.id.slice(-4)})`; } -export type ApifyProviderView = +type ApifyProviderView = | "off" | "policy_invalid" | "token_needed" | "token_removed" | "ready" | "unavailable" | "account_changed"; export interface ApifyProviderCard { @@ -138,7 +138,7 @@ export function receiptApify(receipt: TurnBudgetReceipt | undefined, scope: Budg } /** Machine refusal codes from the Apify envelope, mapped to owner copy that names the limiting fact. */ -export interface ApifyRefusal { title: string; text: string; setting: "provider" | "discovery" | "actors" | "grants" | "limits" | "today" | null } +interface ApifyRefusal { title: string; text: string; setting: "provider" | "discovery" | "actors" | "grants" | "limits" | "today" | null } export function refusalCopy(error: { code: string; reason?: string | null; message?: string }): ApifyRefusal { const reason = error.reason ?? ""; switch (error.code) { @@ -173,7 +173,7 @@ export function refusalCopy(error: { code: string; reason?: string | null; messa * reasons are the lower of the Apify limit and the overall budget less * inference, so the copy names both rather than guessing which one bound. */ -export function budgetName(reason: string): string { +function budgetName(reason: string): string { const names: Record = { run_usd: "the Apify per-run limit", turn_usd: "the lower of the Apify turn limit and this turn's overall budget", session_usd: "the lower of the Apify conversation limit and this conversation's overall budget", day_usd: "the Apify day limit for this account", diff --git a/packages/ui-react/src/lib/backend.ts b/packages/ui-react/src/lib/backend.ts index 9ad66d603c..891a6f932a 100644 --- a/packages/ui-react/src/lib/backend.ts +++ b/packages/ui-react/src/lib/backend.ts @@ -42,5 +42,3 @@ export function getBackendUrlFor(config: BrainUiConfig, path: string): string { // Existing consumers still address the default configuration. Root-owned // clients use the explicit helpers above, and keep their config in a closure. export function apiBase(): string { return apiBaseFor(uiConfig); } -export function getWsUrl(): string { return getWsUrlFor(uiConfig); } -export function getBackendUrl(path: string): string { return getBackendUrlFor(uiConfig, path); } diff --git a/packages/ui-react/src/lib/connection-issue.ts b/packages/ui-react/src/lib/connection-issue.ts index fedf758862..284b600a07 100644 --- a/packages/ui-react/src/lib/connection-issue.ts +++ b/packages/ui-react/src/lib/connection-issue.ts @@ -5,7 +5,7 @@ import type { VpnStatus } from "../stores/connection-store.js"; export const REFUSAL_ATTEMPTS = 3; /** ws/connection.ts closes with this when ClientSet.add refuses the socket. */ -export const CONNECTION_LIMIT_CLOSE_CODE = 4008; +const CONNECTION_LIMIT_CLOSE_CODE = 4008; export type ConnectionIssue = | "unauthorized" diff --git a/packages/ui-react/src/lib/content-fences.ts b/packages/ui-react/src/lib/content-fences.ts index 6b6ef25dfb..5d0ec92906 100644 --- a/packages/ui-react/src/lib/content-fences.ts +++ b/packages/ui-react/src/lib/content-fences.ts @@ -1,5 +1,5 @@ /** Closed CommonMark fences, including offsets needed to preserve surrounding source. */ -export interface ContentFence { +interface ContentFence { start: number; end: number; source: string; diff --git a/packages/ui-react/src/lib/diff.ts b/packages/ui-react/src/lib/diff.ts index 980b6d6bb1..6764214869 100644 --- a/packages/ui-react/src/lib/diff.ts +++ b/packages/ui-react/src/lib/diff.ts @@ -53,7 +53,7 @@ function diffSeq( } /** A rendered diff row. */ -export type DiffRow = { kind: "same" | "del" | "ins"; line: string }; +type DiffRow = { kind: "same" | "del" | "ins"; line: string }; /** * Merge `old_string`/`new_string` into a single diff: unchanged lines appear diff --git a/packages/ui-react/src/lib/discovery-expansion.ts b/packages/ui-react/src/lib/discovery-expansion.ts index 63faafdcfa..dcb4c099c9 100644 --- a/packages/ui-react/src/lib/discovery-expansion.ts +++ b/packages/ui-react/src/lib/discovery-expansion.ts @@ -1,9 +1,9 @@ import type { GraphNodePayload, GraphSubgraphResponse } from "@schlessera/brain-ui-sdk/protocol"; export const DISCOVERY_MAX_DEPTH = 8; -export interface DiscoveryIntent { id: number; path: string; distance: number; } +interface DiscoveryIntent { id: number; path: string; distance: number; } export interface DiscoveryEvidence { data: GraphSubgraphResponse; depth: number; } -export interface DiscoveryExpansionFailure { message: string; needsRefresh: boolean; } +interface DiscoveryExpansionFailure { message: string; needsRefresh: boolean; } export interface DiscoveryExpansionState { intents: readonly DiscoveryIntent[]; loading: readonly string[]; diff --git a/packages/ui-react/src/lib/discovery-layout.ts b/packages/ui-react/src/lib/discovery-layout.ts index 592fbdd67c..3ebb3f5d82 100644 --- a/packages/ui-react/src/lib/discovery-layout.ts +++ b/packages/ui-react/src/lib/discovery-layout.ts @@ -13,7 +13,7 @@ export const DISCOVERY_PACKING = { type Node = Pick & { community?: number | null; }; -export interface DiscoveryPoint { +interface DiscoveryPoint { x: number; y: number; angle: number; @@ -22,7 +22,7 @@ export interface DiscoveryPoint { branch: number | null; lane: number; } -export interface DiscoveryWedge { +interface DiscoveryWedge { id: number | null; start: number; end: number; diff --git a/packages/ui-react/src/lib/draft-api.ts b/packages/ui-react/src/lib/draft-api.ts index 588e53a04d..8e2051689d 100644 --- a/packages/ui-react/src/lib/draft-api.ts +++ b/packages/ui-react/src/lib/draft-api.ts @@ -8,7 +8,7 @@ import type { Draft, DraftErrorResponse, DraftListResponse, DraftSaveRequest, Dr * starts work or answers anything: these are data operations only. */ /** A failure body's fields, any of which a given `DraftErrorResponse` may carry. */ -export interface DraftFailureBody { +interface DraftFailureBody { error?: DraftErrorResponse["error"] | string; message?: string; current?: Draft; diff --git a/packages/ui-react/src/lib/draft-client.ts b/packages/ui-react/src/lib/draft-client.ts index 1df35e8e61..4adc296a7a 100644 --- a/packages/ui-react/src/lib/draft-client.ts +++ b/packages/ui-react/src/lib/draft-client.ts @@ -37,7 +37,7 @@ const RETRY_MS = [2_000, 4_000, 8_000, 16_000, 30_000, 60_000]; /** Errors the host sends for a frame it could not tie to a request, when they name none. */ const UNCORRELATED = ["RATE_LIMITED", "PARSE_ERROR", "INTERNAL_ERROR"]; -export interface DraftClientOptions { +interface DraftClientOptions { send: (msg: ClientMessage) => boolean; api?: DraftApi; } @@ -567,4 +567,3 @@ export function createDraftClient(root: BrainUiServices, options: DraftClientOpt }; } -export type DraftClient = ReturnType; diff --git a/packages/ui-react/src/lib/drafts.ts b/packages/ui-react/src/lib/drafts.ts index 920b5f22fa..02e4dc13a1 100644 --- a/packages/ui-react/src/lib/drafts.ts +++ b/packages/ui-react/src/lib/drafts.ts @@ -62,7 +62,7 @@ export function trackStateWord(t: Pick): str } /** The save state D52 §5 names, in its order of precedence. */ -export type DraftSaveView = +type DraftSaveView = | { state: "none" } | { state: "saving" | "saved" | "unsaved" | "conflict" | "unavailable" | "too_large" | "full"; copy: string; word: string }; @@ -124,7 +124,7 @@ export function unboundDrafts(drafts: Record): ComposerDr } /** One Sessions Draft entry: an unbound draft, its new chat's staged tracks, or both (#1112). */ -export interface DraftEntry { +interface DraftEntry { /** The draft id that opens it. */ id: string; draft: ComposerDraft | null; diff --git a/packages/ui-react/src/lib/graph-helpers.ts b/packages/ui-react/src/lib/graph-helpers.ts index bedc18328b..59d3ef3a5a 100644 --- a/packages/ui-react/src/lib/graph-helpers.ts +++ b/packages/ui-react/src/lib/graph-helpers.ts @@ -62,7 +62,7 @@ export function mergeSubgraphs( // --- Radial (discovery) layout ---------------------------------------------- -export interface RadialPoint { +interface RadialPoint { x: number; y: number; } @@ -194,7 +194,7 @@ export function assignFolderColors(paths: string[], palette: CanvasPalette): Map // --- Community legend grouping ---------------------------------------------- -export interface LegendGroups { +interface LegendGroups { /** Multi-note communities, size-descending — what the legend lists. */ major: T[]; /** Number of single-note communities folded out of the legend. */ @@ -213,7 +213,7 @@ export function groupCommunities( // --- Label policy ------------------------------------------------------------ -export interface LabelPolicyInput { +interface LabelPolicyInput { nodes: Pick[]; selectedId: number | null; hoveredId: number | null; @@ -300,7 +300,7 @@ export function matchScene( * neutral ink and is listed in the legend under its own name, because a * legend that hides a type is a legend that lies about a node. */ -export type EntityKind = "person" | "company" | "project"; +type EntityKind = "person" | "company" | "project"; export function entityKind(type: string): EntityKind | null { return type === "person" || type === "company" || type === "project" ? type : null; diff --git a/packages/ui-react/src/lib/image-optimize.ts b/packages/ui-react/src/lib/image-optimize.ts index b9e26462df..24de8956e9 100644 --- a/packages/ui-react/src/lib/image-optimize.ts +++ b/packages/ui-react/src/lib/image-optimize.ts @@ -12,7 +12,7 @@ */ /** What "optimized" means: long-edge ceiling and a byte target to land under. */ -export interface OptimizeTarget { +interface OptimizeTarget { maxEdge: number; maxBytes: number; } @@ -29,7 +29,7 @@ export const SHARE_OPTIMIZED: OptimizeTarget = { maxBytes: 1_048_576, }; -export interface OptimizeStep { +interface OptimizeStep { width: number; height: number; quality: number; @@ -124,7 +124,7 @@ function encode(canvas: HTMLCanvasElement, quality: number): Promise canvas.toBlob(resolve, "image/jpeg", quality)); } -export interface OptimizeResult { +interface OptimizeResult { blob: Blob; width: number; height: number; diff --git a/packages/ui-react/src/lib/light-dark.ts b/packages/ui-react/src/lib/light-dark.ts index 4875adc6c7..e22be25510 100644 --- a/packages/ui-react/src/lib/light-dark.ts +++ b/packages/ui-react/src/lib/light-dark.ts @@ -57,7 +57,7 @@ export function documentColorScheme(): ColorScheme { return prefersDark() ? "dark" : "light"; } -export function prefersDark(): boolean { +function prefersDark(): boolean { try { return ( typeof window !== "undefined" && diff --git a/packages/ui-react/src/lib/local-partitions.ts b/packages/ui-react/src/lib/local-partitions.ts index 89f976a6b4..6acaf2bdb3 100644 --- a/packages/ui-react/src/lib/local-partitions.ts +++ b/packages/ui-react/src/lib/local-partitions.ts @@ -43,7 +43,7 @@ export interface PartitionHandle { } /** What a partition holds, without any of its content. */ -export interface PartitionSize { +interface PartitionSize { partition: PartitionId; bytes: number; records: number; @@ -92,7 +92,7 @@ function request(req: IDBRequest): Promise { } /** An estimate of what a value occupies: UTF-8 for text, the byte length of binary data. */ -export function measure(value: unknown, seen = new Set()): number { +function measure(value: unknown, seen = new Set()): number { if (typeof value === "string") { let n = 0; for (let i = 0; i < value.length; i++) { @@ -115,7 +115,7 @@ export function measure(value: unknown, seen = new Set()): number { return n; } -export interface LocalPartitionOptions { +interface LocalPartitionOptions { /** The IndexedDB database: one per app origin, shared by every partition. */ name: string; /** The account key the client holds now; null while it holds none. */ diff --git a/packages/ui-react/src/lib/local-work.ts b/packages/ui-react/src/lib/local-work.ts index e179c6bdd2..b66312c25b 100644 --- a/packages/ui-react/src/lib/local-work.ts +++ b/packages/ui-react/src/lib/local-work.ts @@ -28,7 +28,7 @@ import { PartitionRefusedError, accountPartition, type LocalPartitions, type Par */ /** Where the reader was, beyond the drafts themselves. */ -export interface WorkContext { +interface WorkContext { sessionId: string | null; draftId: string; selectionStart: number | null; @@ -44,7 +44,7 @@ export interface WorkContext { } /** What a view reports at the moment a snapshot is taken. */ -export type WorkProbe = () => Partial>; +type WorkProbe = () => Partial>; /** What a restore hands back to the views, each consumed once. */ export interface WorkRestore { @@ -85,9 +85,9 @@ export interface LocalWork { } /** A pause after a change before it is written. */ -export const LOCAL_WRITE_DELAY_MS = 250; +const LOCAL_WRITE_DELAY_MS = 250; /** The longest a change waits while changes keep coming. */ -export const LOCAL_WRITE_MAX_DELAY_MS = 2_000; +const LOCAL_WRITE_MAX_DELAY_MS = 2_000; /** * What a transcript message says, in short: a replay rebuilds messages with @@ -102,7 +102,7 @@ export function messageFingerprint(m: { role: string; content: string }): string } /** The composer's field, by the attribute the kit gives it; else an element's own id. */ -export function stableFocusId(el: Element | null): string | null { +function stableFocusId(el: Element | null): string | null { if (!el || el === document.body) return null; if (el.matches("textarea[data-composer]")) return "composer"; const named = el.closest("[data-focus-id]")?.getAttribute("data-focus-id"); @@ -110,7 +110,7 @@ export function stableFocusId(el: Element | null): string | null { return el.id ? `id:${el.id}` : null; } -export function findByFocusId(id: string): HTMLElement | null { +function findByFocusId(id: string): HTMLElement | null { if (id === "composer") return document.querySelector("textarea[data-composer]"); if (id.startsWith("focus:")) return document.querySelector(`[data-focus-id="${CSS.escape(id.slice(6))}"]`); if (id.startsWith("id:")) return document.getElementById(id.slice(3)); @@ -118,7 +118,7 @@ export function findByFocusId(id: string): HTMLElement | null { } type StoredAttachment = { data: string; mediaType: string; bytes: number; name: string }; -export type StoredDraft = Omit & { v: 1; deviceRevision?: number; attachments: StoredAttachment[] }; +type StoredDraft = Omit & { v: 1; deviceRevision?: number; attachments: StoredAttachment[] }; const draftVersion = (value: unknown): number => (value as StoredDraft | undefined)?.deviceRevision ?? 0; function serializedDraft(value: unknown): string | undefined { if (value === undefined) return undefined; @@ -194,7 +194,7 @@ function sameEditableSnapshot(a: ComposerDraft | undefined, b: ComposerDraft | u return a === b || !!a && !!b && a.edit === b.edit && a.deviceEpoch === b.deviceEpoch && sameContent(storeDraft(a), storeDraft(b)); } -export interface LocalWorkOptions { +interface LocalWorkOptions { stores: BrainStores; partitions: LocalPartitions; /** This root's records, apart from another root's in the same partition. */ diff --git a/packages/ui-react/src/lib/mermaid.ts b/packages/ui-react/src/lib/mermaid.ts index 9821a179dd..7a588634e6 100644 --- a/packages/ui-react/src/lib/mermaid.ts +++ b/packages/ui-react/src/lib/mermaid.ts @@ -12,7 +12,6 @@ import { mermaidThemeVariables, type MermaidTheme } from "./mermaid-theme.js"; import { tokenizedMermaidSvg } from "./mermaid-svg.js"; -export type { MermaidTheme }; type MermaidApi = typeof import("mermaid").default; @@ -117,7 +116,7 @@ export async function renderMermaidSvg( } } -export interface MermaidFence { +interface MermaidFence { /** Offset of the opening fence line start. */ start: number; /** Offset just past the closing fence line (and its newline, if present). */ diff --git a/packages/ui-react/src/lib/recordings.ts b/packages/ui-react/src/lib/recordings.ts index 422763ee70..ad7f77aeca 100644 --- a/packages/ui-react/src/lib/recordings.ts +++ b/packages/ui-react/src/lib/recordings.ts @@ -7,7 +7,7 @@ import { registerUpdateHold } from "./update-holds.js"; /** Limits from #578's retention ruling; the budget and warning are tuning defaults. */ export const RECORDING_MAX_MS = 600_000; -export const RECORDING_WALL_BACKSTOP_MS = 660_000; +const RECORDING_WALL_BACKSTOP_MS = 660_000; const LIMIT_FLUSH_MARGIN_MS = 250; // Internal scheduler tolerance: modest callback jitter is not evidence of lost audio. const AUDIO_TIMER_LATENESS_MS = 1000; @@ -86,7 +86,7 @@ export interface RecordingStore { onEvent(listener: (event: RecordingEvent) => void): () => void; dispose(): void; } -export interface RecordingStoreOptions { +interface RecordingStoreOptions { partitions: LocalPartitions; heldAccountKey: () => string | null; root: BrainUiServices; diff --git a/packages/ui-react/src/lib/restored-approvals.ts b/packages/ui-react/src/lib/restored-approvals.ts index 1fa1948615..95b765aea6 100644 --- a/packages/ui-react/src/lib/restored-approvals.ts +++ b/packages/ui-react/src/lib/restored-approvals.ts @@ -24,7 +24,7 @@ import type { SessionChat, ToolCall } from "../stores/chat-state.js"; export type RestoredApprovalClosure = "answered" | "ended" | "revoked" | "unlisted"; /** D52 §4 R3's words, verbatim. `unlisted` has none. */ -export const RESTORED_APPROVAL_WORDS: Record, string> = { +const RESTORED_APPROVAL_WORDS: Record, string> = { answered: "answered on another device", ended: "ended with the turn", revoked: "no longer yours to answer", @@ -35,13 +35,13 @@ export function restoredApprovalWord(closure: RestoredApprovalClosure | undefine } /** A restored card that still takes a decision, with the turn that raised it. */ -export interface AwaitingRestoredCard { +interface AwaitingRestoredCard { toolUseId: string; turnId: string | null; } /** A restored card is open: pending here, and not closed, or closed only as `unlisted`. */ -export function isOpenRestored(tool: ToolCall): boolean { +function isOpenRestored(tool: ToolCall): boolean { return !!tool.restored && tool.status === "pending_approval" && (!tool.readOnly || tool.readOnly === "unlisted"); } diff --git a/packages/ui-react/src/lib/search-results.ts b/packages/ui-react/src/lib/search-results.ts index 04687d3923..64b8721126 100644 --- a/packages/ui-react/src/lib/search-results.ts +++ b/packages/ui-react/src/lib/search-results.ts @@ -6,7 +6,7 @@ export interface SearchHit { snippet?: string | null; score?: number | null; } -export interface SearchResults { results: SearchHit[]; warnings: string[] } +interface SearchResults { results: SearchHit[]; warnings: string[] } export function openableSearchPath(path: string): boolean { return Boolean(path) && !/^[\/\\]|^[a-z][a-z\d+.-]*:|[\u0000-\u001f\u007f\\?#]/i.test(path) diff --git a/packages/ui-react/src/lib/search-snippet.ts b/packages/ui-react/src/lib/search-snippet.ts index 45d0e8188b..b9a0681257 100644 --- a/packages/ui-react/src/lib/search-snippet.ts +++ b/packages/ui-react/src/lib/search-snippet.ts @@ -9,7 +9,7 @@ import { stripMarkdown } from "./strip-markdown.js"; * syntax stripped and the whitespace collapsed, so a result row is one legible * line with its hits highlighted. */ -export interface SnippetSegment { +interface SnippetSegment { text: string; hit: boolean; } diff --git a/packages/ui-react/src/lib/share-intake.ts b/packages/ui-react/src/lib/share-intake.ts index 72a11dad9b..1c052b5875 100644 --- a/packages/ui-react/src/lib/share-intake.ts +++ b/packages/ui-react/src/lib/share-intake.ts @@ -61,7 +61,7 @@ export function dropShareClaim(id: string): void { else storage()?.setItem(CLAIM_KEY, JSON.stringify(remaining)); } -export type ShareUploadOutcome = +type ShareUploadOutcome = | { ok: true; result: ShareIntakeResult } | { ok: false; error: string; status?: number; limit?: number }; diff --git a/packages/ui-react/src/lib/share-review.ts b/packages/ui-react/src/lib/share-review.ts index f18fb5aaba..33cbc92edb 100644 --- a/packages/ui-react/src/lib/share-review.ts +++ b/packages/ui-react/src/lib/share-review.ts @@ -5,7 +5,7 @@ import type { BrainUiRoot } from "../root.js"; import { accountPartition, type PartitionHandle } from "./local-partitions.js"; export const SHARE_REVIEW_PREFIX = "share:review:"; -export type ShareReview = { record: StoredShare; confirmed: boolean }; +type ShareReview = { record: StoredShare; confirmed: boolean }; /** Several mounted consumers may share one root; ownership belongs to the root. */ export type ShareReviewSession = { diff --git a/packages/ui-react/src/lib/share.ts b/packages/ui-react/src/lib/share.ts index e30c083ed9..5f0f7b6419 100644 --- a/packages/ui-react/src/lib/share.ts +++ b/packages/ui-react/src/lib/share.ts @@ -1,13 +1,11 @@ import type { BrainUiRoot } from "../root.js"; import type { RenderRequest } from "@schlessera/brain-ui-sdk/protocol"; -export type ShareKind = "file" | "text" | "richtext"; - /** * True when the browser supports navigator.share at all. Note this doesn't * guarantee that a specific payload is shareable — call canShareFiles too. */ -export function isShareSupported(): boolean { +function isShareSupported(): boolean { return typeof navigator !== "undefined" && typeof navigator.share === "function"; } diff --git a/packages/ui-react/src/lib/stats/compose-stats.ts b/packages/ui-react/src/lib/stats/compose-stats.ts index efc84799e3..f65e6ea86c 100644 --- a/packages/ui-react/src/lib/stats/compose-stats.ts +++ b/packages/ui-react/src/lib/stats/compose-stats.ts @@ -529,7 +529,7 @@ function unknownTone(unpriced: number, runs: number): { tone?: "dim" } { } /** A token count to three significant figures: `1.84 M`, `212 k`, `6.1 M`. */ -export function tokens(n: number): string { +function tokens(n: number): string { const scale = (value: number, unit: string) => `${Number(value.toPrecision(3))} ${unit}`; if (n >= 1_000_000_000) return scale(n / 1_000_000_000, "B"); if (n >= 1_000_000) return scale(n / 1_000_000, "M"); @@ -538,7 +538,7 @@ export function tokens(n: number): string { } /** The CLI's byte scale (`packages/core/src/cli/commands/stats.ts`, `bytes`). */ -export function bytes(n: number): string { +function bytes(n: number): string { const units = ["B", "KB", "MB", "GB", "TB"]; let value = n; let unit = 0; diff --git a/packages/ui-react/src/lib/stream-link-hold.ts b/packages/ui-react/src/lib/stream-link-hold.ts index 3c307c0ec7..645957e211 100644 --- a/packages/ui-react/src/lib/stream-link-hold.ts +++ b/packages/ui-react/src/lib/stream-link-hold.ts @@ -25,7 +25,7 @@ const ADDRESS_END = /[\s)\]>,;!?]$/; /** A bare address the autolinker would pick up, touching the end of the line. */ const BARE_ADDRESS = /(?:https?:\/\/|www\.|mailto:)\S*$|[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]*$/i; -export interface LinkHold { +interface LinkHold { /** The buffer up to the held tail: what is rendered. */ shown: string; /** What is held back, `""` when nothing is. */ diff --git a/packages/ui-react/src/lib/tool-names.ts b/packages/ui-react/src/lib/tool-names.ts index e5352531b5..ac334c1ee4 100644 --- a/packages/ui-react/src/lib/tool-names.ts +++ b/packages/ui-react/src/lib/tool-names.ts @@ -13,7 +13,7 @@ import { visibleToolName, } from "@schlessera/brain-ui-sdk/client"; -export const ASK_USER_TOOL_NAME = visibleToolName(ASK_USER_CONTRACT.name, "claude"); +const ASK_USER_TOOL_NAME = visibleToolName(ASK_USER_CONTRACT.name, "claude"); export const GET_LOCATION_TOOL_NAME = visibleToolName( GET_CURRENT_LOCATION_CONTRACT.name, "claude" diff --git a/packages/ui-react/src/lib/track-uploads.ts b/packages/ui-react/src/lib/track-uploads.ts index 7501c33ffc..fa1b38f523 100644 --- a/packages/ui-react/src/lib/track-uploads.ts +++ b/packages/ui-react/src/lib/track-uploads.ts @@ -4,7 +4,7 @@ import type { BrainUiRoot } from "../root.js"; // The parser's UTF-8 input cap is smaller than the generic share-file cap. export const TRACK_MAX_BYTES = TRACK_MAX_FILE_BYTES; -export type TrackUploadState = "picked" | "uploading" | "parsing" | "paused" | "failed" | "ready"; +type TrackUploadState = "picked" | "uploading" | "parsing" | "paused" | "failed" | "ready"; export interface PendingTrack { id: string; file: File; diff --git a/packages/ui-react/src/lib/tracker-announcer.ts b/packages/ui-react/src/lib/tracker-announcer.ts index ea59c0e982..4f99a229bc 100644 --- a/packages/ui-react/src/lib/tracker-announcer.ts +++ b/packages/ui-react/src/lib/tracker-announcer.ts @@ -2,7 +2,7 @@ import type { ActivitySpanOutcome } from "@schlessera/brain-ui-sdk/protocol"; import type { TrackerState, TrackerView } from "./trackers.js"; /** The three states a tracker announces when it changes into one (D52 §3). */ -export type AnnouncedState = Extract; +type AnnouncedState = Extract; const ANNOUNCED: ReadonlySet = new Set(["needs_you", "failed", "done"]); diff --git a/packages/ui-react/src/lib/trackers.ts b/packages/ui-react/src/lib/trackers.ts index 37d19d11e1..43052ecf07 100644 --- a/packages/ui-react/src/lib/trackers.ts +++ b/packages/ui-react/src/lib/trackers.ts @@ -40,7 +40,7 @@ export interface TrackerRecord { seen: TrackerSeen | null; } -export interface TrackerSeen { +interface TrackerSeen { turnId: string; revision: number; basis: "proof" | "acknowledged"; @@ -344,7 +344,7 @@ export function applyUnavailable(evidence: TrackerEvidence, reason: SessionRecov } /** States, in display order (D52 §4). */ -export const TRACKER_STATES = [ +const TRACKER_STATES = [ "needs_you", "failed", "unconfirmed", @@ -357,7 +357,7 @@ export const TRACKER_STATES = [ ] as const; export type TrackerState = (typeof TRACKER_STATES)[number]; -export type TrackerCantCheck = SessionRecoveryUnavailable; +type TrackerCantCheck = SessionRecoveryUnavailable; export interface TrackerView { sessionId: string; @@ -383,7 +383,7 @@ export interface TrackerView { settled: boolean; } -export interface TrackerContext { +interface TrackerContext { /** `server_hello.capabilities.sessionRecovery`; null before any hello. */ recoverySupported: boolean | null; /** A send in this session with no acceptance proof (D52 §5). */ diff --git a/packages/ui-react/src/stores/activity-state.ts b/packages/ui-react/src/stores/activity-state.ts index 6d05370a04..b5ff71003a 100644 --- a/packages/ui-react/src/stores/activity-state.ts +++ b/packages/ui-react/src/stores/activity-state.ts @@ -10,7 +10,6 @@ import { } from "./activity-store-helpers.js"; export { - EMPTY_EVENTS, childSpans, eventsFor, narrativeEventsFor, diff --git a/packages/ui-react/src/stores/activity-store-helpers.ts b/packages/ui-react/src/stores/activity-store-helpers.ts index cd940c857c..8ae5252516 100644 --- a/packages/ui-react/src/stores/activity-store-helpers.ts +++ b/packages/ui-react/src/stores/activity-store-helpers.ts @@ -84,7 +84,7 @@ export function subagentSpans(state: ActivityState, sessionId: string): Activity /** Stable empty result for `eventsFor` — a fresh `[]` per call would defeat * reference-equality checks in zustand selectors. */ -export const EMPTY_EVENTS: ActivitySpanEvent[] = Object.freeze( +const EMPTY_EVENTS: ActivitySpanEvent[] = Object.freeze( [] as ActivitySpanEvent[] ) as ActivitySpanEvent[]; diff --git a/packages/ui-react/src/stores/activity-store.ts b/packages/ui-react/src/stores/activity-store.ts index 456e823974..949e41e6db 100644 --- a/packages/ui-react/src/stores/activity-store.ts +++ b/packages/ui-react/src/stores/activity-store.ts @@ -9,6 +9,3 @@ export const useActivityStore = Object.assign( }, defaultRoot.stores.activity, ); - -export const loadSessionActivityHistory = defaultRoot.stores.activity.loadSessionActivityHistory; -export const loadSpanPayloads = defaultRoot.stores.activity.loadSpanPayloads; diff --git a/packages/ui-react/src/stores/draft-state.ts b/packages/ui-react/src/stores/draft-state.ts index 223de2047a..0607f6d3e9 100644 --- a/packages/ui-react/src/stores/draft-state.ts +++ b/packages/ui-react/src/stores/draft-state.ts @@ -28,7 +28,7 @@ import { attachmentFromDraft, mintDraftId } from "../lib/drafts.js"; * is the acknowledged one. */ -export type DraftSaveFailure = +type DraftSaveFailure = /** Dirty and unreachable, or a transient refusal: retried with backoff. */ | { kind: "unsaved" } /** 413: `limit` bytes (or images), named by `bound`. */ @@ -37,7 +37,7 @@ export type DraftSaveFailure = | { kind: "full"; limit: number; bound: string }; /** What the host acknowledged for a draft: its revision, and the local edit it holds. */ -export interface DraftHostCopy { +interface DraftHostCopy { revision: number; /** The `edit` generation this revision holds; -1 when it holds another device's. */ edit: number; @@ -80,7 +80,7 @@ export interface ComposerDraft { bind: { sessionId: string; requestId: string } | null; } -export type DraftSendState = "pending" | "accepted" | "refused" | "unconfirmed"; +type DraftSendState = "pending" | "accepted" | "refused" | "unconfirmed"; /** One send: an immutable snapshot of what left the composer (D52 §5). */ export interface DraftSend { @@ -254,7 +254,7 @@ export const hasContent = (d: Pick | unde Boolean(d && (d.text.length > 0 || d.attachments.length > 0)); /** The draft's content is the revision the host acknowledged. */ -export const isClean = (d: ComposerDraft): boolean => d.host !== null && d.host.edit === d.edit; +const isClean = (d: ComposerDraft): boolean => d.host !== null && d.host.edit === d.edit; function blank(draftId: string, sessionId: string | null, now: number): ComposerDraft { return { diff --git a/packages/ui-react/src/stores/file-state.ts b/packages/ui-react/src/stores/file-state.ts index 683822de68..54f41e6ee3 100644 --- a/packages/ui-react/src/stores/file-state.ts +++ b/packages/ui-react/src/stores/file-state.ts @@ -75,7 +75,7 @@ export interface FileState { reset: () => void; } -export type ViewMode = "preview" | "raw"; +type ViewMode = "preview" | "raw"; export interface FileLoadFailure { kind: "unreachable" | "unauthenticated" | "forbidden" | "not-found" | "too-large" | "unknown"; @@ -516,7 +516,7 @@ export function isInternalRepoDir(href: string | undefined): href is string { return DIR_REF_RE.test(href); } -export type RepoPathKind = "file" | "dir"; +type RepoPathKind = "file" | "dir"; export function classifyRepoPath( href: string | undefined @@ -544,7 +544,3 @@ export function scratchPath(href: string | undefined): string | null { return rel; } -/** Normalize a directory ref by trimming the trailing slash. */ -export function normalizeDirPath(path: string): string { - return path.replace(/\/+$/, ""); -} diff --git a/packages/ui-react/src/stores/follow-up-state.ts b/packages/ui-react/src/stores/follow-up-state.ts index 55c1e634f8..26ea1e139e 100644 --- a/packages/ui-react/src/stores/follow-up-state.ts +++ b/packages/ui-react/src/stores/follow-up-state.ts @@ -37,7 +37,7 @@ export interface PendingFollowUp { } /** What this client sent, kept to draw its message exactly when it starts. */ -export interface LocalFollowUp { +interface LocalFollowUp { requestId: string; text: string; source: MessageSource; @@ -50,7 +50,7 @@ export interface LocalFollowUp { } /** One polite announcement for the pending group (D52 §3). */ -export interface FollowUpAnnouncement { +interface FollowUpAnnouncement { sessionId: string; text: string; /** Bumped per announcement, so the same words announce twice. */ diff --git a/packages/ui-react/src/stores/graph-state.ts b/packages/ui-react/src/stores/graph-state.ts index c06a82522c..e64449eeff 100644 --- a/packages/ui-react/src/stores/graph-state.ts +++ b/packages/ui-react/src/stores/graph-state.ts @@ -23,7 +23,7 @@ export type LocalDirection = "in" | "out" | "both"; * (core unavailable / schema too old / not yet computed); "unsupported" means * the server predates the graph API entirely (404 on /graph/meta). */ -export type GraphErrorKind = "unavailable" | "unsupported" | "network"; +type GraphErrorKind = "unavailable" | "unsupported" | "network"; interface GraphError { kind: GraphErrorKind; @@ -36,25 +36,25 @@ class DiscoveryIntegrityFailure extends Error { } } -export interface LocalParams { +interface LocalParams { center: string | null; depth: 1 | 2 | 3; direction: LocalDirection; } -export interface DiscoveryParams { +interface DiscoveryParams { /** null = the precomputed default root (direction is fixed there). */ root: string | null; maxDepth: number; } -export interface ClustersParams { +interface ClustersParams { /** null = all communities. */ community: number | null; isolates: boolean; } -export interface MaintenanceParams { +interface MaintenanceParams { staleDays: number; } @@ -70,7 +70,7 @@ export type SizeBy = "degree" | "pagerank"; export type DiscoveryColorBy = "topic" | "distance" | "folder" | "entity"; /** Which finding sections are visible — a client-side filter, no refetch. */ -export interface MaintenanceFilters { +interface MaintenanceFilters { orphans: boolean; unreachable: boolean; broken: boolean; diff --git a/packages/ui-react/src/stores/handoff-state.ts b/packages/ui-react/src/stores/handoff-state.ts index c3b650b5cc..cfd0048fd2 100644 --- a/packages/ui-react/src/stores/handoff-state.ts +++ b/packages/ui-react/src/stores/handoff-state.ts @@ -11,7 +11,7 @@ import type { StoreEnvironment } from "./store-environment.js"; * user edits (text, references, destination) is the sheet's own state; this * holds what arrives over the socket, so a frame handler can reach it. */ -export interface HandoffSheetTarget { +interface HandoffSheetTarget { sourceSessionId: string; /** Minted per open: the idempotency key of everything this review sends. */ handoffId: string; @@ -22,7 +22,7 @@ export interface HandoffSheetTarget { } /** The model summary for the open sheet (R1: it runs when the sheet opens). */ -export interface HandoffDraftState { +interface HandoffDraftState { state: "idle" | "running" | "ready" | "failed" | "cancelled"; text?: string; message?: string; @@ -31,7 +31,7 @@ export interface HandoffDraftState { } /** Where `Start new chat` stands. */ -export type HandoffPhase = +type HandoffPhase = | { kind: "review" } | { kind: "creating" } | { kind: "checking" } @@ -39,7 +39,7 @@ export type HandoffPhase = | { kind: "uncertain" }; /** What the destination was sent, so its first message can be drawn before history. */ -export interface HandoffSend { +interface HandoffSend { handoffId: string; requestId: string; /** Echoed on `session_info`; never the chat draft's, so no draft adopts it. */ diff --git a/packages/ui-react/src/stores/inbox-state.ts b/packages/ui-react/src/stores/inbox-state.ts index 949efcca43..6078a4bf11 100644 --- a/packages/ui-react/src/stores/inbox-state.ts +++ b/packages/ui-react/src/stores/inbox-state.ts @@ -30,7 +30,7 @@ import type { * decision is ever re-sent automatically. */ -export type DecisionKind = "commit" | "later" | "dismiss"; +type DecisionKind = "commit" | "later" | "dismiss"; export interface InFlightDecision { kind: DecisionKind; @@ -74,7 +74,7 @@ export type InboxOutcome = | { kind: "not-applied" } | { kind: "gone"; status: "dropped" | "expired" | "removed" }; -export interface InboxChangeNotice { +interface InboxChangeNotice { fields: string[]; before: InboxActionItem; reviewed: boolean; diff --git a/packages/ui-react/src/stores/provider-state.ts b/packages/ui-react/src/stores/provider-state.ts index 8f42a1abd6..09daea18a8 100644 --- a/packages/ui-react/src/stores/provider-state.ts +++ b/packages/ui-react/src/stores/provider-state.ts @@ -97,14 +97,3 @@ export function createProviderStore(env: StoreEnvironment) { })); } -/** Resolve the backend metadata for an available provider profile. */ -export function selectBackendForProvider( - state: Pick, - providerId: string | null | undefined -): BackendInfo | null { - const backendId = state.available.find( - (provider) => provider.id === providerId - )?.backendId; - return backendId ? state.backends[backendId] ?? null : null; -} - diff --git a/packages/ui-react/src/stores/tracker-state.ts b/packages/ui-react/src/stores/tracker-state.ts index e4a50d881b..beea5898e4 100644 --- a/packages/ui-react/src/stores/tracker-state.ts +++ b/packages/ui-react/src/stores/tracker-state.ts @@ -22,7 +22,7 @@ import { } from "../lib/trackers.js"; import type { TrackerAnnouncement } from "../lib/tracker-announcer.js"; -export interface TrackerSeenObservation { +interface TrackerSeenObservation { sessionId: string; turnId: string; revision: number; diff --git a/packages/ui-react/src/voice/asr-deepgram.ts b/packages/ui-react/src/voice/asr-deepgram.ts index e4e0e59179..890d43d506 100644 --- a/packages/ui-react/src/voice/asr-deepgram.ts +++ b/packages/ui-react/src/voice/asr-deepgram.ts @@ -9,7 +9,7 @@ import { speechError } from "./dictation-failure.js"; import type { AsrClient } from "@schlessera/brain-ui-sdk/client"; import type { AsrEvent } from "@schlessera/brain-ui-sdk/protocol"; -export interface DeepgramClientOptions { +interface DeepgramClientOptions { /** Full Deepgram streaming WS URL (base params + keyterms), from the server. */ url: string; /** Short-lived Deepgram token, from the server. */ diff --git a/packages/ui-react/src/voice/asr-webspeech.ts b/packages/ui-react/src/voice/asr-webspeech.ts index bb880920c0..b500f7aa02 100644 --- a/packages/ui-react/src/voice/asr-webspeech.ts +++ b/packages/ui-react/src/voice/asr-webspeech.ts @@ -43,12 +43,7 @@ function getRecognitionCtor(): SpeechRecognitionCtor | null { return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null; } -/** True when this browser supports the Web Speech API. */ -export function isWebSpeechAvailable(): boolean { - return getRecognitionCtor() !== null; -} - -export interface WebSpeechClientOptions { +interface WebSpeechClientOptions { onEvent: (evt: AsrEvent) => void; onError?: (err: Error) => void; onEnd?: () => void; diff --git a/packages/ui-react/src/voice/local-capture.ts b/packages/ui-react/src/voice/local-capture.ts index 178dc0255f..8a9dd84fd7 100644 --- a/packages/ui-react/src/voice/local-capture.ts +++ b/packages/ui-react/src/voice/local-capture.ts @@ -19,7 +19,7 @@ export const LOCAL_CAPTURE_MIME_TYPES = ["audio/webm;codecs=opus", "audio/mp4"] export type LocalCaptureMimeType = (typeof LOCAL_CAPTURE_MIME_TYPES)[number]; /** The chunk interval MediaRecorder is asked for. Tuning only; never shown. */ -export const LOCAL_CAPTURE_TIMESLICE_MS = 1000; +const LOCAL_CAPTURE_TIMESLICE_MS = 1000; /** * Why a recording ended. `interrupted` is the browser ending it on its own: @@ -82,7 +82,7 @@ export interface StartLocalCaptureOptions extends LocalCaptureEnvironment { } /** The first container this browser's MediaRecorder records, or null. */ -export function pickLocalCaptureMimeType(Recorder: typeof MediaRecorder | undefined = globalThis.MediaRecorder): LocalCaptureMimeType | null { +function pickLocalCaptureMimeType(Recorder: typeof MediaRecorder | undefined = globalThis.MediaRecorder): LocalCaptureMimeType | null { if (typeof Recorder?.isTypeSupported !== "function") return null; return LOCAL_CAPTURE_MIME_TYPES.find((type) => Recorder.isTypeSupported(type)) ?? null; } diff --git a/packages/ui-react/src/voice/voice-state.ts b/packages/ui-react/src/voice/voice-state.ts index e224338388..e8d722dc9d 100644 --- a/packages/ui-react/src/voice/voice-state.ts +++ b/packages/ui-react/src/voice/voice-state.ts @@ -36,7 +36,7 @@ export interface VoiceState { } /** opening: waiting on the microphone; stopping: the final chunk is on its way. */ -export type LocalCapturePhase = "idle" | "opening" | "recording" | "stopping"; +type LocalCapturePhase = "idle" | "opening" | "recording" | "stopping"; export function createVoiceStore() { return createStore((set) => ({ diff --git a/packages/ui-react/tests/chat-store-approval-recovery.test.ts b/packages/ui-react/tests/chat-store-approval-recovery.test.ts index 13b85161cd..9b558fe7cc 100644 --- a/packages/ui-react/tests/chat-store-approval-recovery.test.ts +++ b/packages/ui-react/tests/chat-store-approval-recovery.test.ts @@ -1,7 +1,9 @@ import { beforeEach, describe, expect, test } from "bun:test"; import type { ServerMessage, SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; import { useChatStore } from "../src/stores/chat-store"; -import { flushChatDeltas, handleServerMessage } from "../src/hooks/use-websocket"; +import { defaultRoot } from "../src/default-root"; + +const { flushChatDeltas, handleServerMessage } = defaultRoot.connection; // Approval recovery in the client (#964, D52 §4): a pending approval the host // re-delivers after a replay lands on its own turn, as one card, marked diff --git a/packages/ui-react/tests/chat-store-ask-dedup.test.ts b/packages/ui-react/tests/chat-store-ask-dedup.test.ts index 12e4e82cef..619a634fa2 100644 --- a/packages/ui-react/tests/chat-store-ask-dedup.test.ts +++ b/packages/ui-react/tests/chat-store-ask-dedup.test.ts @@ -9,10 +9,12 @@ */ import { beforeEach, describe, expect, test } from "bun:test"; import type { ServerMessage, SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; -import { flushChatDeltas, handleServerMessage } from "../src/hooks/use-websocket"; +import { defaultRoot } from "../src/default-root"; import { useChatStore } from "../src/stores/chat-store"; import { matchAskExchanges } from "../src/components/chat/message-bubble"; +const { flushChatDeltas, handleServerMessage } = defaultRoot.connection; + type Kind = "ask_user" | "ask_user_list" | "ask_user_rank" | "ask_user_form"; const KINDS: Kind[] = ["ask_user", "ask_user_list", "ask_user_rank", "ask_user_form"]; diff --git a/packages/ui-react/tests/delta-batching.test.ts b/packages/ui-react/tests/delta-batching.test.ts index 8f5da7c576..dcc237d7a5 100644 --- a/packages/ui-react/tests/delta-batching.test.ts +++ b/packages/ui-react/tests/delta-batching.test.ts @@ -4,7 +4,9 @@ import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import type { ServerMessage } from "@schlessera/brain-ui-sdk/protocol"; import { useChatStore, activeChat } from "../src/stores/chat-store"; -import { handleServerMessage, flushChatDeltas } from "../src/hooks/use-websocket"; +import { defaultRoot } from "../src/default-root"; + +const { handleServerMessage, flushChatDeltas } = defaultRoot.connection; /** Frame callbacks the handler queued, run only when a test says to. */ let frames: FrameRequestCallback[] = []; diff --git a/packages/ui-react/tests/render/answer-delivery.test.tsx b/packages/ui-react/tests/render/answer-delivery.test.tsx index fd5f4f404a..3d78e53b85 100644 --- a/packages/ui-react/tests/render/answer-delivery.test.tsx +++ b/packages/ui-react/tests/render/answer-delivery.test.tsx @@ -7,12 +7,14 @@ import { unregisterAnswerDeliveryDom } from "./answer-delivery-dom.js"; import { afterAll, afterEach, beforeEach, describe, expect, test } from "bun:test"; import { cleanup, render } from "@testing-library/react"; import { MessageBubble } from "../../src/components/chat/message-bubble.js"; -import { flushChatDeltas, handleServerMessage } from "../../src/hooks/use-websocket.js"; +import { defaultRoot } from "../../src/default-root.js"; import { useChatStore } from "../../src/stores/chat-store.js"; import { useUIStore } from "../../src/stores/ui-store.js"; import type { AnswerDelivery, AnswerPayload, DeliveryState } from "../../src/lib/answer-delivery/types.js"; import type { SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; +const { flushChatDeltas, handleServerMessage } = defaultRoot.connection; + afterEach(cleanup); afterAll(unregisterAnswerDeliveryDom); beforeEach(() => { diff --git a/packages/ui-react/tests/render/ask-user-list.test.tsx b/packages/ui-react/tests/render/ask-user-list.test.tsx index 2071eb76c6..cc4ad9ded7 100644 --- a/packages/ui-react/tests/render/ask-user-list.test.tsx +++ b/packages/ui-react/tests/render/ask-user-list.test.tsx @@ -15,9 +15,11 @@ import { listReaskMessage, } from "../../src/components/chat/ask-user-list-card.js"; import { MessageBubble } from "../../src/components/chat/message-bubble.js"; -import { flushChatDeltas, handleServerMessage } from "../../src/hooks/use-websocket.js"; +import { defaultRoot } from "../../src/default-root.js"; import { useChatStore } from "../../src/stores/chat-store.js"; +const { flushChatDeltas, handleServerMessage } = defaultRoot.connection; + afterEach(cleanup); afterAll(unregisterAskUserListDom); diff --git a/packages/ui-react/tests/render/ask-user-rank.test.tsx b/packages/ui-react/tests/render/ask-user-rank.test.tsx index fb70d0833e..d4d9523836 100644 --- a/packages/ui-react/tests/render/ask-user-rank.test.tsx +++ b/packages/ui-react/tests/render/ask-user-rank.test.tsx @@ -3,11 +3,13 @@ import { afterAll, afterEach, beforeEach, describe, expect, test } from "bun:tes import { act, cleanup, fireEvent, render } from "@testing-library/react"; import { AskUserRankExchangeCard } from "../../src/components/chat/ask-user-rank-card.js"; import { MessageBubble } from "../../src/components/chat/message-bubble.js"; -import { flushChatDeltas, handleServerMessage } from "../../src/hooks/use-websocket.js"; +import { defaultRoot } from "../../src/default-root.js"; import { useChatStore } from "../../src/stores/chat-store.js"; import { useUIStore } from "../../src/stores/ui-store.js"; import type { AskUserRankSpec, SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; +const { flushChatDeltas, handleServerMessage } = defaultRoot.connection; + afterEach(cleanup); afterAll(unregisterAskUserRankDom); beforeEach(() => { diff --git a/packages/ui-react/tests/render/message-source.test.tsx b/packages/ui-react/tests/render/message-source.test.tsx index 9aa3512829..f1b56d0b0e 100644 --- a/packages/ui-react/tests/render/message-source.test.tsx +++ b/packages/ui-react/tests/render/message-source.test.tsx @@ -11,9 +11,11 @@ import { cleanup, render } from "@testing-library/react"; import type { SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; import { MessageBubble } from "../../src/components/chat/message-bubble.js"; -import { flushChatDeltas, handleServerMessage } from "../../src/hooks/use-websocket.js"; +import { defaultRoot } from "../../src/default-root.js"; import { useChatStore } from "../../src/stores/chat-store.js"; +const { flushChatDeltas, handleServerMessage } = defaultRoot.connection; + afterEach(cleanup); afterAll(unregisterMessageSourceDom); diff --git a/packages/ui-react/tests/render/streaming-bench.tsx b/packages/ui-react/tests/render/streaming-bench.tsx index 224e9b77a3..bd2b2a0922 100644 --- a/packages/ui-react/tests/render/streaming-bench.tsx +++ b/packages/ui-react/tests/render/streaming-bench.tsx @@ -59,7 +59,8 @@ const { render, cleanup, act } = await import("@testing-library/react"); const { ChatPage } = await import("../../src/components/chat/chat-page.js"); const { useChatStore } = await import("../../src/stores/chat-store.js"); const { useConnectionStore } = await import("../../src/stores/connection-store.js"); -const { handleServerMessage } = await import("../../src/hooks/use-websocket.js"); +const { defaultRoot } = await import("../../src/default-root.js"); +const { handleServerMessage } = defaultRoot.connection; import type { ServerMessage } from "@schlessera/brain-ui-sdk/protocol"; const BODY = `## Section heading diff --git a/packages/ui-react/tests/render/turn-failure.test.tsx b/packages/ui-react/tests/render/turn-failure.test.tsx index debba86866..f7ed13828f 100644 --- a/packages/ui-react/tests/render/turn-failure.test.tsx +++ b/packages/ui-react/tests/render/turn-failure.test.tsx @@ -16,10 +16,12 @@ import { import { useHandoffStore } from "../../src/stores/handoff-store.js"; import { MessageBubble } from "../../src/components/chat/message-bubble.js"; -import { flushChatDeltas, handleServerMessage } from "../../src/hooks/use-websocket.js"; +import { defaultRoot } from "../../src/default-root.js"; import { useChatStore } from "../../src/stores/chat-store.js"; import { failurePresentation } from "../../src/lib/turn-failure.js"; +const { flushChatDeltas, handleServerMessage } = defaultRoot.connection; + afterEach(cleanup); afterAll(unregisterTurnFailureDom); diff --git a/packages/ui-react/tests/session-demux.test.ts b/packages/ui-react/tests/session-demux.test.ts index 0057e2bebe..2eb10dd0e3 100644 --- a/packages/ui-react/tests/session-demux.test.ts +++ b/packages/ui-react/tests/session-demux.test.ts @@ -1,7 +1,10 @@ import { describe, test, expect, beforeEach } from "bun:test"; import type { ServerMessage } from "@schlessera/brain-ui-sdk/protocol"; import { useChatStore, activeChat } from "../src/stores/chat-store"; -import { runStateForFrame, handleServerMessage, flushChatDeltas } from "../src/hooks/use-websocket"; +import { runStateForFrame } from "../src/hooks/use-websocket"; +import { defaultRoot } from "../src/default-root"; + +const { handleServerMessage, flushChatDeltas } = defaultRoot.connection; function reset() { // Text deltas are coalesced into the next animation frame when one exists; diff --git a/packages/ui-server/src/activity/digest.ts b/packages/ui-server/src/activity/digest.ts index 182bd6b0b2..e68fd71201 100644 --- a/packages/ui-server/src/activity/digest.ts +++ b/packages/ui-server/src/activity/digest.ts @@ -17,12 +17,11 @@ import { isFailureOutcome, type ActivityDigest } from "@schlessera/brain-ui-sdk/ import { getSetting, setSetting } from "../db/settings.js"; import { rowToRunRollup, sumEffectiveCost } from "./store.js"; -export type { ActivityDigest } from "@schlessera/brain-ui-sdk/protocol"; -export const DIGEST_LATEST_KEY = "activity.digest.latest"; -export const DIGEST_COVERED_KEY = "activity.digest.coveredUntil"; -export const DIGEST_DISMISSED_KEY = "activity.digest.dismissedAt"; -export const DIGEST_JOB_NAME = "digest"; +const DIGEST_LATEST_KEY = "activity.digest.latest"; +const DIGEST_COVERED_KEY = "activity.digest.coveredUntil"; +const DIGEST_DISMISSED_KEY = "activity.digest.dismissedAt"; +const DIGEST_JOB_NAME = "digest"; /** First run ever: no covered-until marker — cap the window at 24h. */ const FIRST_WINDOW_MS = 24 * 60 * 60 * 1000; diff --git a/packages/ui-server/src/activity/notify.ts b/packages/ui-server/src/activity/notify.ts index 4ad5f7c0af..7f283925fb 100644 --- a/packages/ui-server/src/activity/notify.ts +++ b/packages/ui-server/src/activity/notify.ts @@ -31,9 +31,9 @@ import { getSetting, setSetting } from "../db/settings.js"; import { LABEL_RUN_NAME } from "../labels/labeller.js"; import type { AwaitableActivityStore, SpanRow } from "./store.js"; -export type IntentKind = "failure" | "completion" | "stuck"; +type IntentKind = "failure" | "completion" | "stuck"; -export interface NotificationIntent { +interface NotificationIntent { id: number; runId: string; spanId: string | null; @@ -46,7 +46,7 @@ export interface NotificationIntent { createdAt: number; } -export interface ActivityNotifierDeps { +interface ActivityNotifierDeps { db: Database; store: AwaitableActivityStore; /** Was anyone watching this run/session when the event was recorded? */ diff --git a/packages/ui-server/src/activity/push-sender.ts b/packages/ui-server/src/activity/push-sender.ts index 43c5ccd711..162e94cce5 100644 --- a/packages/ui-server/src/activity/push-sender.ts +++ b/packages/ui-server/src/activity/push-sender.ts @@ -27,7 +27,7 @@ import type { ActionAttempt, ActionAttemptOutcome } from "../inbox/notify.js"; import type { AwaitableActionNotifier } from "../inbox/notify-writes.js"; import type { StorageNotifier, StorageNoticeOutcome } from "../storage/notify.js"; -export interface PushSubscriptionRow { +interface PushSubscriptionRow { endpoint: string; p256dh: string; auth: string; @@ -69,7 +69,7 @@ export type AwaitablePushSender = Omit & { [K in LifecycleWrite]: (...args: Parameters) => ReturnType | Promise>; }; -export interface CreatePushSenderOptions { +interface CreatePushSenderOptions { /** Shared hosted write connection; absent for standalone synchronous callers. */ writer?: SqliteWriter; /** Injection seam for tests — the real webpush.sendNotification otherwise. */ diff --git a/packages/ui-server/src/activity/runtime-status.ts b/packages/ui-server/src/activity/runtime-status.ts index 6bdd7707c4..e4a5e2ec62 100644 --- a/packages/ui-server/src/activity/runtime-status.ts +++ b/packages/ui-server/src/activity/runtime-status.ts @@ -32,7 +32,7 @@ type RuntimeObserved = Extract; /** An auth failure as the status reports it: the runtime's text, with any credential redacted. */ -export type RecordedAuthFailure = Omit & { +type RecordedAuthFailure = Omit & { runId: string; at: string; /** diff --git a/packages/ui-server/src/activity/span-sink.ts b/packages/ui-server/src/activity/span-sink.ts index e649ef5e2f..c73f68489d 100644 --- a/packages/ui-server/src/activity/span-sink.ts +++ b/packages/ui-server/src/activity/span-sink.ts @@ -22,7 +22,7 @@ import { readFileSync } from "fs"; import { SPAN_OUTCOMES, type ActivityStore, type SpanOutcome, type SpanUsage } from "./store.js"; -export interface SpanSinkContext { +interface SpanSinkContext { /** The run every ingested span belongs to. */ runId: string; /** Parent for lines that name none — the cron root span. */ @@ -30,7 +30,7 @@ export interface SpanSinkContext { jobName?: string; } -export interface SpanSinkResult { +interface SpanSinkResult { /** Byte offset consumed so far — pass back on the next incremental call. */ offset: number; ingested: number; diff --git a/packages/ui-server/src/activity/sync-runtime.ts b/packages/ui-server/src/activity/sync-runtime.ts index 55e5539691..482eb6bf57 100644 --- a/packages/ui-server/src/activity/sync-runtime.ts +++ b/packages/ui-server/src/activity/sync-runtime.ts @@ -16,7 +16,7 @@ import type { Database } from "bun:sqlite"; import type { SpanOutcome } from "./store.js"; /** How the latest sync run stands on invoking an agent. */ -export type SyncAgentState = +type SyncAgentState = /** The run has not ended; nothing is recorded yet. */ | "pending" | "not-invoked" @@ -24,7 +24,7 @@ export type SyncAgentState = /** The run ended without a readable result: nothing is known. */ | "unknown"; -export interface SyncRunRuntime { +interface SyncRunRuntime { runId: string; startedAt: string; endedAt: string | null; diff --git a/packages/ui-server/src/activity/turn-lifecycle.ts b/packages/ui-server/src/activity/turn-lifecycle.ts index da044923ef..b05ff1fb19 100644 --- a/packages/ui-server/src/activity/turn-lifecycle.ts +++ b/packages/ui-server/src/activity/turn-lifecycle.ts @@ -9,7 +9,7 @@ import { orderedWrites } from "./store-writes.js"; */ export type PhaseTimer = (name: string) => () => void; -export type LifecycleMilestone = "dequeuedAt" | "governedStartedAt" | "governedAcquiredAt" | "budgetStartedAt" | "budgetAdmittedAt" | "journalStartedAt" | "journalBeganAt" | "backendInvokedAt" | "firstFrameAt" | "failureObservedAt"; +type LifecycleMilestone = "dequeuedAt" | "governedStartedAt" | "governedAcquiredAt" | "budgetStartedAt" | "budgetAdmittedAt" | "journalStartedAt" | "journalBeganAt" | "backendInvokedAt" | "firstFrameAt" | "failureObservedAt"; export function createTurnLifecycle(store: AwaitableActivityStore, turnId: string, sessionId: string | null, acceptedAt: number, onWrite: () => void, clock: () => number = Date.now) { diff --git a/packages/ui-server/src/agent/subscription.ts b/packages/ui-server/src/agent/subscription.ts index 2f34a73a1c..54bf651908 100644 --- a/packages/ui-server/src/agent/subscription.ts +++ b/packages/ui-server/src/agent/subscription.ts @@ -28,9 +28,9 @@ export const MINTED_AT_ENV = "BRAIN_UI_CLAUDE_TOKEN_MINTED_AT"; const DAY_MS = 24 * 60 * 60 * 1000; /** `claude setup-token`'s default lifetime, 31536000 s, as measured (#183). */ -export const TOKEN_LIFETIME_MS = 365 * DAY_MS; +const TOKEN_LIFETIME_MS = 365 * DAY_MS; /** How far ahead of expiry the warning starts. */ -export const EXPIRY_WARNING_MS = 30 * DAY_MS; +const EXPIRY_WARNING_MS = 30 * DAY_MS; /** At most one expiry warning per this interval while the server runs. */ const WARNING_INTERVAL_MS = DAY_MS; @@ -92,7 +92,7 @@ export interface SubscriptionStatus { | null; } -export interface SubscriptionMonitorOptions { +interface SubscriptionMonitorOptions { config: SubscriptionConfig; log: Logger; /** The app's database, where turns are recorded. */ @@ -107,7 +107,7 @@ export interface SubscriptionMonitorOptions { every?: (check: () => void, ms: number) => () => void; } -export interface SubscriptionMonitor { +interface SubscriptionMonitor { /** The hourly pass: keeps the last proof, and warns about expiry at most once a day. */ tick(): void; status(): Promise; diff --git a/packages/ui-server/src/apify/host.ts b/packages/ui-server/src/apify/host.ts index e2af5b3437..235ccf2c96 100644 --- a/packages/ui-server/src/apify/host.ts +++ b/packages/ui-server/src/apify/host.ts @@ -40,10 +40,9 @@ import type { ProviderExposure } from "../brain/governance-policy.js"; import { APIFY_PROVIDER_ROUTING } from "./routing.js"; import { coreSitePermission } from "./site-permission.js"; -export { APIFY_PROVIDER_ROUTING } from "./routing.js"; /** How often open runs are settled, timed out and cleaned up while the server runs. */ -export const APIFY_RECONCILE_INTERVAL_MS = 5 * 60_000; +const APIFY_RECONCILE_INTERVAL_MS = 5 * 60_000; /** The authenticated turn a call arrived on, as the host knows it. */ export interface ApifyHostTurn { @@ -57,7 +56,7 @@ export interface ApifyHostTurn { readonly signal: AbortSignal; } -export interface ApifyHostOptions { +interface ApifyHostOptions { brainPath: string; /** The shared ledger file, outside every brain. */ ledgerPath: string; diff --git a/packages/ui-server/src/apify/settings.ts b/packages/ui-server/src/apify/settings.ts index 465fb996b7..d2653ab029 100644 --- a/packages/ui-server/src/apify/settings.ts +++ b/packages/ui-server/src/apify/settings.ts @@ -61,7 +61,7 @@ export function parseApifyPolicyChange(raw: unknown): ApifyPolicyChange | null { const MODE_LABEL: Record = { deny: "Deny", ask: "Ask", allow: "Allow" }; /** The one-line rationale the review shows. Fixed words plus validated identifiers only. */ -export function apifyChangeRationale(change: ApifyPolicyChange): string { +function apifyChangeRationale(change: ApifyPolicyChange): string { if ("enabled" in change) return change.enabled ? "Settings: turn Apify on. This approves no search and no run." : "Settings: turn Apify off."; if ("discovery" in change) return `Settings: set Apify catalog search to ${MODE_LABEL[change.discovery]}.`; if ("actors" in change) return `Settings: set running Apify Actors to ${MODE_LABEL[change.actors]}.`; @@ -237,7 +237,7 @@ export interface ApifySettingsJournal { finish(turnId: string): Promise; } -export interface ApifyPolicyEditsOptions { +interface ApifyPolicyEditsOptions { root: string; proposals: PolicyProposals; journal: ApifySettingsJournal; diff --git a/packages/ui-server/src/apify/site-permission.ts b/packages/ui-server/src/apify/site-permission.ts index 4094fc5f38..a51254180a 100644 --- a/packages/ui-server/src/apify/site-permission.ts +++ b/packages/ui-server/src/apify/site-permission.ts @@ -18,7 +18,7 @@ interface CoreApify { createApifySitePermission(options?: { addressPolicy?: "any" | "public-only" }): ApifySitePermission; } -export interface CoreSitePermissionOptions { +interface CoreSitePermissionOptions { /** @internal Test seam: how core is loaded. Default: the optional peer. */ load?: () => Promise; /** @internal Test seam: passed to core's checker so an offline test can reach its loopback robots.txt server. */ diff --git a/packages/ui-server/src/bin/brain-ui-inbox.ts b/packages/ui-server/src/bin/brain-ui-inbox.ts index 7ff6a93112..74a1586763 100644 --- a/packages/ui-server/src/bin/brain-ui-inbox.ts +++ b/packages/ui-server/src/bin/brain-ui-inbox.ts @@ -4,7 +4,7 @@ import { Database } from "bun:sqlite"; import { readFile } from "node:fs/promises"; import { restoreInboxSnapshot, writeInboxSnapshot } from "../inbox/snapshot.js"; -export const USAGE = `usage: brain-ui-inbox export --db --brain-root --file [--json] +const USAGE = `usage: brain-ui-inbox export --db --brain-root --file [--json] brain-ui-inbox restore --db --brain-root --file [--json]`; const [command, ...args] = process.argv.slice(2), json = process.argv.slice(2).includes("--json"); diff --git a/packages/ui-server/src/brain/governed-manifest.ts b/packages/ui-server/src/brain/governed-manifest.ts index 1dfd771843..ee0c572746 100644 --- a/packages/ui-server/src/brain/governed-manifest.ts +++ b/packages/ui-server/src/brain/governed-manifest.ts @@ -29,7 +29,7 @@ import { procedureCaller, type SqliteWriter } from "../db/write-worker.js"; import { url as GOVERNED_TURN_WRITES, setup as governedTurnWriteSetup } from "./governed-turn-writes.js"; /** One protected path as it stood. `blocked`: an ancestor was not a real directory, named here. */ -export interface ManifestEntry { +interface ManifestEntry { path: string; exists: boolean; type?: "file" | "directory" | "symlink" | "other"; @@ -40,7 +40,7 @@ export interface ManifestEntry { blocked?: string; } -export interface TurnManifest { +interface TurnManifest { /** The protected list this turn ran under. */ protected: string[]; entries: ManifestEntry[]; diff --git a/packages/ui-server/src/brain/host-boundary.ts b/packages/ui-server/src/brain/host-boundary.ts index 3c085084f6..b56fd764ea 100644 --- a/packages/ui-server/src/brain/host-boundary.ts +++ b/packages/ui-server/src/brain/host-boundary.ts @@ -45,14 +45,13 @@ import { prepareMaintenanceGit } from "./maintenance-git.js"; import { createScratchIgnoreQuery } from "./scratch-mask-query.js"; /** Why `governed` cannot run on this server. */ -export type { GovernedUnavailableReason }; -export type GovernedAvailability = +type GovernedAvailability = | { available: true } | { available: false; reason: GovernedUnavailableReason; detail: string }; /** How a command meets the writer gate: not at all (a reader), shared, or exclusively. */ -export type GateUse = "none" | GateMode; +type GateUse = "none" | GateMode; /** One evaluation of the brain's own code: its working directory is the brain. */ export interface BrainExecution { @@ -116,7 +115,6 @@ export interface StreamingExecution { } /** Environment names a credential-free maintenance worker keeps: plain settings, never a key or a token. */ -export { CREDENTIAL_FREE_ENV }; /** * How each `brain` subcommand the server spawns meets the boundary. Every @@ -180,7 +178,7 @@ export const within = (dir: string, path: string) => isWithin(dir, path, { trail const real = (path: string) => { try { return realpathSync(path); } catch { return resolve(path); } }; /** Whether `governed` can run for this server and brain, and if not, why. */ -export function governedAvailability(input: OperationalStateLayout & { workerHost: () => { ok: true } | { ok: false; requirement: string } }): GovernedAvailability { +function governedAvailability(input: OperationalStateLayout & { workerHost: () => { ok: true } | { ok: false; requirement: string } }): GovernedAvailability { const brain = real(input.brainPath); const cwd = real(hostExecution.cwd()); if (within(brain, cwd)) { diff --git a/packages/ui-server/src/brain/index-batch.ts b/packages/ui-server/src/brain/index-batch.ts index 4cdfb2646e..b9a12402c8 100644 --- a/packages/ui-server/src/brain/index-batch.ts +++ b/packages/ui-server/src/brain/index-batch.ts @@ -12,7 +12,7 @@ */ /** What became of one application's queued paths. */ -export interface IndexOutcome { +interface IndexOutcome { /** The application's own committed paths. */ paths: readonly string[]; /** True only once an update that covered them completed. */ diff --git a/packages/ui-server/src/brain/index-directory.ts b/packages/ui-server/src/brain/index-directory.ts index 3d238dc61b..4d73a3b177 100644 --- a/packages/ui-server/src/brain/index-directory.ts +++ b/packages/ui-server/src/brain/index-directory.ts @@ -36,7 +36,7 @@ export function ensureIndexDirectory(brain: string): void { } /** Create `.brain-cache/` as {@link ensureIndexDirectory} creates `.brain-index/`. */ -export function ensureCacheDirectory(brain: string): void { +function ensureCacheDirectory(brain: string): void { ensureRetainedDirectory(brain, CACHE_DIR); } diff --git a/packages/ui-server/src/brain/journal-configuration-sets.ts b/packages/ui-server/src/brain/journal-configuration-sets.ts index 20a8ffdbe7..82045ed10c 100644 --- a/packages/ui-server/src/brain/journal-configuration-sets.ts +++ b/packages/ui-server/src/brain/journal-configuration-sets.ts @@ -6,7 +6,7 @@ import { createHash } from "node:crypto"; * sorted, de-duplicated path list as JSON, so the same set always has the same * hash, whichever turn observed it and in whatever order. */ -export interface ConfigurationSet { hash: string; paths: string[] } +interface ConfigurationSet { hash: string; paths: string[] } export function configurationSet(paths: Iterable): ConfigurationSet { const sorted = [...new Set(paths)].sort(); @@ -15,9 +15,9 @@ export function configurationSet(paths: Iterable): ConfigurationSet { } /** A turn row's view of its set: the referenced set, or a legacy per-turn array not moved yet. */ -export interface ConfigurationSetColumns { configuration_set: string | null; steering_inventory_missing: string } +interface ConfigurationSetColumns { configuration_set: string | null; steering_inventory_missing: string } -export type RecordedConfigurationSet = (ConfigurationSet & { recorded: true }) | { recorded: false; paths: [] }; +type RecordedConfigurationSet = (ConfigurationSet & { recorded: true }) | { recorded: false; paths: [] }; /** * What a turn recorded. A legacy empty array cannot tell "recorded nothing" diff --git a/packages/ui-server/src/brain/native-journal-observer.ts b/packages/ui-server/src/brain/native-journal-observer.ts index 1ea054353a..717483541c 100644 --- a/packages/ui-server/src/brain/native-journal-observer.ts +++ b/packages/ui-server/src/brain/native-journal-observer.ts @@ -26,7 +26,7 @@ export interface NativeJournalMetadata { path: string; kind: "directory" | "file" | "symlink" | "other"; mode: number; bytes: number; stamp: string; inode: string; target?: string; } -export interface NativeJournalChange { +interface NativeJournalChange { path: string; before: NativeJournalMetadata | null; after: NativeJournalMetadata | null; } export interface NativeJournalUnreadable { @@ -236,7 +236,7 @@ class RootMetadataReader { close(): Promise { return this.root?.close() ?? Promise.resolve(); } } -export interface NativeJournalObservation { +interface NativeJournalObservation { beforeRoot: NativeJournalCheckpoint; afterRoot: NativeJournalCheckpoint; changes: NativeJournalChange[]; stats: { readEntries: number; walkedDirectories: number }; @@ -501,4 +501,3 @@ export function createNativeJournalObserver(native: NativeJournalManager, worker }; } -export type NativeJournalObserver = ReturnType; diff --git a/packages/ui-server/src/brain/native-journal-read.ts b/packages/ui-server/src/brain/native-journal-read.ts index 5f80bd9807..3d71b6611b 100644 --- a/packages/ui-server/src/brain/native-journal-read.ts +++ b/packages/ui-server/src/brain/native-journal-read.ts @@ -14,7 +14,7 @@ export interface NativeJournalReadContext { export const nativeJournalPermissionDenied = (error: unknown): boolean => ["EACCES", "EPERM"].includes((error as NodeJS.ErrnoException)?.code ?? ""); -export async function openNativeJournalFile(root: string, path: string): Promise { +async function openNativeJournalFile(root: string, path: string): Promise { const parts = path.split("/"); if (!path || path.startsWith("/") || path.includes("\0") || parts.some(part => !part || part === "." || part === "..")) throw new Error("Invalid native journal path."); let directory = await open(root, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); diff --git a/packages/ui-server/src/brain/operational-state.ts b/packages/ui-server/src/brain/operational-state.ts index 78dcb46ccc..87ef84355d 100644 --- a/packages/ui-server/src/brain/operational-state.ts +++ b/packages/ui-server/src/brain/operational-state.ts @@ -131,7 +131,7 @@ export function operationalStateMasks(input: OperationalStateLayout): string[] { return [...masks]; } -export interface OperationalStateRefusal { +interface OperationalStateRefusal { available: false; reason: GovernedUnavailableReason; detail: string; diff --git a/packages/ui-server/src/brain/private-index-cache.ts b/packages/ui-server/src/brain/private-index-cache.ts index 216520fa42..8ac0ba3caf 100644 --- a/packages/ui-server/src/brain/private-index-cache.ts +++ b/packages/ui-server/src/brain/private-index-cache.ts @@ -42,9 +42,9 @@ import { INDEX_DIR } from "@schlessera/brain-common/internal/index-location"; import { CACHE_DIR } from "@schlessera/brain-common/internal/cache-location"; /** Distinct reusable bases kept at once; each holds one index copy and one retained checkpoint. */ -export const PRIVATE_INDEX_CACHE_ENTRIES = 2; +const PRIVATE_INDEX_CACHE_ENTRIES = 2; /** A base unused this long is dropped, releasing the checkpoint it pins. */ -export const PRIVATE_INDEX_CACHE_IDLE_MS = 30 * 60_000; +const PRIVATE_INDEX_CACHE_IDLE_MS = 30 * 60_000; /** Changes to what the masked build produces from the same inputs bump this. */ const BUILD_SEMANTICS = "brain-index-masked-v1"; const BASE_PREFIX = "brain-private-index-base-"; @@ -56,7 +56,7 @@ const ASSET_EXTENSIONS = [".jpg", ".jpeg", ".png", ".pdf"]; * index's scans skip hidden names), so the masked build sees them as empty, * and what turns write there cannot reach any build. */ -export const PRIVATE_INDEX_STATE_FOLDERS = [".brain", ".brain-ui"] as const; +const PRIVATE_INDEX_STATE_FOLDERS = [".brain", ".brain-ui"] as const; /** Everything the masked build's output depends on besides the view's content. */ export interface PrivateIndexIdentity { @@ -96,7 +96,7 @@ export type PrivateIndexDiffer = (from: WorkerStartupView, to: WorkerStartupView Promise<{ candidates: AsyncIterable; completed: Promise } | undefined>; /** The native send delta between two manager-acquired checkpoints. */ -export const nativePrivateIndexDiffer: PrivateIndexDiffer = async (from, to, signal) => { +const nativePrivateIndexDiffer: PrivateIndexDiffer = async (from, to, signal) => { if (!isManagedWorkerStartupView(from) || !isManagedWorkerStartupView(to)) return undefined; const before = nativeWorkerStartupInput(from), after = nativeWorkerStartupInput(to); if (before.manager !== after.manager || before.checkpoint.sourceUuid !== after.checkpoint.sourceUuid) return undefined; @@ -273,7 +273,7 @@ function sweepOrphans(parent: string): void { } /** Runs the masked build over another view into another directory; how a base advances off the turn path. */ -export type PrivateIndexRunner = (view: WorkerStartupView, index: string, signal: AbortSignal) => { +type PrivateIndexRunner = (view: WorkerStartupView, index: string, signal: AbortSignal) => { build(): Promise<{ ok: true } | { ok: false; detail: string }>; update(): Promise<{ ok: true; stdout: string } | { ok: false; detail: string }>; }; @@ -292,7 +292,7 @@ export type PrivateIndexOutcome = ( readonly ms?: Readonly>; }; -export interface PrivateIndexCache { +interface PrivateIndexCache { /** * Fill `index` (an empty turn-private directory) with an index of the * masked `startupView`, reusing the base for `identity` when it provably diff --git a/packages/ui-server/src/brain/provider-hardlinks.ts b/packages/ui-server/src/brain/provider-hardlinks.ts index 1fabe49cae..1ab420d5c4 100644 --- a/packages/ui-server/src/brain/provider-hardlinks.ts +++ b/packages/ui-server/src/brain/provider-hardlinks.ts @@ -7,7 +7,7 @@ import { lstatSync, readdirSync, type BigIntStats } from "node:fs"; import { INDEX_DIR } from "@schlessera/brain-common/internal/index-location"; -export interface ProviderHardlink { readonly path: string; readonly masked: string } +interface ProviderHardlink { readonly path: string; readonly masked: string } const SLASH = Buffer.from("/"); const vanished = (error: unknown) => (error as NodeJS.ErrnoException).code === "ENOENT"; diff --git a/packages/ui-server/src/brain/provider-mask-refusal.ts b/packages/ui-server/src/brain/provider-mask-refusal.ts index b06cc935f0..0aabf8c331 100644 --- a/packages/ui-server/src/brain/provider-mask-refusal.ts +++ b/packages/ui-server/src/brain/provider-mask-refusal.ts @@ -8,7 +8,7 @@ import type { EffectiveGovernancePolicy } from "@schlessera/brain-common/interna import { providerFolderRoots } from "./governance-policy.js"; /** The named refusal code an application result, or a thrown read, carries. */ -export const PROVIDER_MASKED = "provider_masked"; +const PROVIDER_MASKED = "provider_masked"; export interface ProviderMaskRefusal { /** The agent-facing tool name, as the governance event records it. */ diff --git a/packages/ui-server/src/brain/provider-types.ts b/packages/ui-server/src/brain/provider-types.ts index 96c5e7f9dd..70ca520aaa 100644 --- a/packages/ui-server/src/brain/provider-types.ts +++ b/packages/ui-server/src/brain/provider-types.ts @@ -26,7 +26,7 @@ import { providerFolderRoots, providerMaskedFolders, providerTypeSelectors, tran import { createPrivateIndexDirectory, removePrivateIndexDirectory, runMaskedBrainCli } from "./private-index.js"; /** How long admission waits for the taxonomy. */ -export const PROVIDER_TAXONOMY_MS = 30_000; +const PROVIDER_TAXONOMY_MS = 30_000; const TAXONOMY_BYTES = 1024 * 1024; /** The fields of `brain config check --json` a translation reads; the rest is ignored. */ @@ -92,7 +92,7 @@ const sameTaxonomy = (a: ProviderTaxonomy, b: ProviderTaxonomy) => { * Read the effective taxonomy in a worker that sees the brain through `folders` * masked and, with `visible`, sees only those paths of it. */ -export async function readProviderTaxonomy(options: { +async function readProviderTaxonomy(options: { brainPath: string; startupView: WorkerStartupView; folders: readonly string[]; index: string; maskPaths: readonly string[]; signal: AbortSignal; timeoutMs?: number; command?: readonly string[]; visible?: readonly string[]; }): Promise<{ ok: true; taxonomy: ProviderTaxonomy } | { ok: false; detail: string }> { diff --git a/packages/ui-server/src/brain/tool-observation.ts b/packages/ui-server/src/brain/tool-observation.ts index 8ac7c7efbc..835f99c766 100644 --- a/packages/ui-server/src/brain/tool-observation.ts +++ b/packages/ui-server/src/brain/tool-observation.ts @@ -15,7 +15,7 @@ export type ToolExecutionPath = Parameters target === dir || target.startsWith(`${dir}/`); let pending = (path.startsWith("/") ? path : `${brainPath}/${path}`).replace(/^\/proc\/(?:self|thread-self|[0-9]+)\/root(?=\/|$)/u, "").split("/"); let current: string[] = [], links = 0; diff --git a/packages/ui-server/src/brain/turn-egress.ts b/packages/ui-server/src/brain/turn-egress.ts index c8803c37a8..58bfae3cfc 100644 --- a/packages/ui-server/src/brain/turn-egress.ts +++ b/packages/ui-server/src/brain/turn-egress.ts @@ -14,8 +14,8 @@ const GITHUB_API_HOSTS = ["api.github.com", "uploads.github.com"] as const; * any host on these ports is outward; the hosts are HTTP mail-send APIs and * provider relays on alternate ports. `outward.hosts` adds the rest. */ -export const MAIL_SUBMISSION_PORTS = [25, 465, 587] as const; -export const MAIL_SUBMISSION_HOSTS = ["gmail.googleapis.com", "graph.microsoft.com", "outlook.office365.com", +const MAIL_SUBMISSION_PORTS = [25, 465, 587] as const; +const MAIL_SUBMISSION_HOSTS = ["gmail.googleapis.com", "graph.microsoft.com", "outlook.office365.com", "api.fastmail.com", "api.sendgrid.com", "smtp.sendgrid.net", "api.mailgun.net", "api.eu.mailgun.net", "smtp.mailgun.org", "smtp.eu.mailgun.org", "api.postmarkapp.com", "smtp.postmarkapp.com", "api.resend.com", "smtp.resend.com"] as const; diff --git a/packages/ui-server/src/brain/writer-gate.ts b/packages/ui-server/src/brain/writer-gate.ts index b8d73cbcf1..990d1cc44c 100644 --- a/packages/ui-server/src/brain/writer-gate.ts +++ b/packages/ui-server/src/brain/writer-gate.ts @@ -98,7 +98,7 @@ export interface WriterGate { } /** How often a waiting acquisition looks again. */ -export const GATE_POLL_MS = 200; +const GATE_POLL_MS = 200; /** * How long provider folder admission waits for a peer whose plan predates the @@ -107,7 +107,7 @@ export const GATE_POLL_MS = 200; * provider-policy turn, plan without them. The boot-time scratch prune is one; * on the native fixture it finishes within a second of the turn reaching it. */ -export const PEER_FOLDER_PLAN_WAIT_MS = 30_000; +const PEER_FOLDER_PLAN_WAIT_MS = 30_000; const UNRETAINED_PEER = "An active peer did not retain the requested provider folders; finish that peer and retry admission"; diff --git a/packages/ui-server/src/classification/blocks-store.ts b/packages/ui-server/src/classification/blocks-store.ts index 4d16474f09..e4669743e0 100644 --- a/packages/ui-server/src/classification/blocks-store.ts +++ b/packages/ui-server/src/classification/blocks-store.ts @@ -82,7 +82,7 @@ export function rewriteMessageBlockLinks( } /** The text parts of a history message, in order, as the client will number them. */ -export function textPartsOf(message: SessionHistoryMessage): string[] { +function textPartsOf(message: SessionHistoryMessage): string[] { if (message.parts) { return message.parts.filter((part) => part.kind === "text").map((part) => (part as { text: string }).text); } diff --git a/packages/ui-server/src/classification/classify-turn.ts b/packages/ui-server/src/classification/classify-turn.ts index 364c997fb6..1095d57dc0 100644 --- a/packages/ui-server/src/classification/classify-turn.ts +++ b/packages/ui-server/src/classification/classify-turn.ts @@ -68,9 +68,9 @@ export class TurnTextCollector { } } -export type PassOutcome = "skipped_no_candidates" | "swapped" | "kept" | JevOutcome; +type PassOutcome = "skipped_no_candidates" | "swapped" | "kept" | JevOutcome; -export interface ClassificationPassDeps { +interface ClassificationPassDeps { jev: JevClient; db: () => Database; log: Logger; @@ -79,7 +79,7 @@ export interface ClassificationPassDeps { writer?: SqliteWriter; } -export interface ClassificationPassRecord { +interface ClassificationPassRecord { outcome: PassOutcome; candidates: number; blocks: number; diff --git a/packages/ui-server/src/classification/confidence-store.ts b/packages/ui-server/src/classification/confidence-store.ts index e2a57998c8..0cc51c076a 100644 --- a/packages/ui-server/src/classification/confidence-store.ts +++ b/packages/ui-server/src/classification/confidence-store.ts @@ -30,20 +30,17 @@ import type { Database } from "bun:sqlite"; import type { QuestionObservation } from "@schlessera/brain-ui-sdk/internal"; /** How long a recorded confidence is kept. Long enough to tune on, bounded. */ -export const CONFIDENCE_RETENTION_MS = 30 * 24 * 60 * 60 * 1000; +const CONFIDENCE_RETENTION_MS = 30 * 24 * 60 * 60 * 1000; /** How many buckets the 0-1 range is cut into for the distribution. */ -export const CONFIDENCE_BUCKETS = 10; - -/** How wide one of those buckets is. */ -export const CONFIDENCE_BUCKET_WIDTH = 1 / CONFIDENCE_BUCKETS; +const CONFIDENCE_BUCKETS = 10; /** * One bucket of the distribution: how many answers to this question about * this candidate kind landed in it, how many cleared their threshold, and how * many belonged to a candidate that was drawn as a block. */ -export interface ConfidenceBucket { +interface ConfidenceBucket { candidateKind: string; question: string; /** The line these rows were compared against, or null when ungated. */ @@ -55,7 +52,7 @@ export interface ConfidenceBucket { swapped: number; } -export interface ConfidenceReadOptions { +interface ConfidenceReadOptions { /** Only rows recorded at or after this epoch-ms. Default: everything kept. */ since?: number; } diff --git a/packages/ui-server/src/classification/index.ts b/packages/ui-server/src/classification/index.ts index 470bb1f30d..b12c6858d8 100644 --- a/packages/ui-server/src/classification/index.ts +++ b/packages/ui-server/src/classification/index.ts @@ -1,37 +1,20 @@ export { - BREAKER_BASE_MS, - BREAKER_FAILURES, - BREAKER_MAX_MS, JEV_ENDPOINT, JEV_TIMEOUT_MS, createJevClient, - type FetchLike, type JevClient, - type JevClientOptions, - type JevOutcome, - type JevResult, } from "./jev-client.js"; export { - CONFIDENCE_BUCKETS, - CONFIDENCE_BUCKET_WIDTH, - CONFIDENCE_RETENTION_MS, confidenceDistribution, recordQuestionConfidence, - type ConfidenceBucket, - type ConfidenceReadOptions, } from "./confidence-store.js"; export { attachMessageBlocks, loadMessageBlocks, partHash, saveMessageBlocks, - textPartsOf, } from "./blocks-store.js"; export { TurnTextCollector, createTurnClassifier, - type ClassificationPassDeps, - type ClassificationPassRecord, - type PassOutcome, - type TurnClassifier, } from "./classify-turn.js"; diff --git a/packages/ui-server/src/classification/jev-client.ts b/packages/ui-server/src/classification/jev-client.ts index 356e018903..4bef436e7a 100644 --- a/packages/ui-server/src/classification/jev-client.ts +++ b/packages/ui-server/src/classification/jev-client.ts @@ -46,7 +46,7 @@ export const BREAKER_FAILURES = 3; /** First backoff once open; doubles per further failure. */ export const BREAKER_BASE_MS = 30_000; /** The backoff never grows past this. */ -export const BREAKER_MAX_MS = 30 * 60_000; +const BREAKER_MAX_MS = 30 * 60_000; export interface JevResult { outcome: JevOutcome; @@ -63,7 +63,7 @@ export interface JevResult { /** The slice of `fetch` the client uses, so a test can hand in one that never resolves. */ export type FetchLike = (url: string, init: RequestInit) => Promise; -export interface JevClientOptions { +interface JevClientOptions { apiKey: string | null; /** Injected so a test can hand in a fetch that never resolves. */ fetch?: FetchLike; diff --git a/packages/ui-server/src/cron/digest.ts b/packages/ui-server/src/cron/digest.ts index 91f9064c18..4da7d1ec99 100644 --- a/packages/ui-server/src/cron/digest.ts +++ b/packages/ui-server/src/cron/digest.ts @@ -6,13 +6,13 @@ interface TextSink { write(text: string): unknown; } -export interface DigestOptions { +interface DigestOptions { dbPath: string; stdout?: TextSink; stderr?: TextSink; } -export interface DigestDependencies { +interface DigestDependencies { createDb?: typeof createUiDb; generateDigest?: typeof generateActivityDigest; } diff --git a/packages/ui-server/src/cron/emit.ts b/packages/ui-server/src/cron/emit.ts index e6e45b6c8d..ba5d0065cb 100644 --- a/packages/ui-server/src/cron/emit.ts +++ b/packages/ui-server/src/cron/emit.ts @@ -5,14 +5,14 @@ import { } from "@schlessera/brain-ui-sdk/server"; /** One cron manifest entry in `brain module list --json`. */ -export interface BrainModuleListCronEntry { +interface BrainModuleListCronEntry { name: string; schedule: string; command: string; } /** One enabled module in the core CLI's module-list payload. */ -export interface BrainModuleListEnabledModule { +interface BrainModuleListEnabledModule { name: string; key: string; description: string | null; @@ -22,7 +22,7 @@ export interface BrainModuleListEnabledModule { } /** One disabled-but-available module in the core CLI's module-list payload. */ -export interface BrainModuleListAvailableModule { +interface BrainModuleListAvailableModule { key: string; description: string | null; enabled: false; diff --git a/packages/ui-server/src/cron/module-discovery.ts b/packages/ui-server/src/cron/module-discovery.ts index a91ed5d9bf..2a1f8afdcd 100644 --- a/packages/ui-server/src/cron/module-discovery.ts +++ b/packages/ui-server/src/cron/module-discovery.ts @@ -34,7 +34,7 @@ export const MODULE_DISCOVERY_JOB_NAME = "modules"; export const MODULE_DISCOVERY_RETRY_DELAYS_MS: readonly number[] = [5_000, 15_000]; /** The most of a failed `brain module list`'s stderr a cause carries. */ -export const DISCOVERY_STDERR_TAIL_CHARS = 500; +const DISCOVERY_STDERR_TAIL_CHARS = 500; /** One discovery attempt: the payload, or why there is none. */ export type DiscoveryAttempt = @@ -46,7 +46,7 @@ export type DiscoveryAttempt = retryable: boolean; }; -export interface DiscoveryOutcome { +interface DiscoveryOutcome { modules: BrainModuleListPayload | null; attempts: number; /** The last attempt's cause; absent when discovery succeeded. */ @@ -108,7 +108,7 @@ export async function readModuleList( return { modules: parsed as BrainModuleListPayload }; } -export interface DiscoverModulesOptions { +interface DiscoverModulesOptions { /** One whole attempt: qualify the host, read the list, release the host. */ attempt: () => Promise; /** Waits between attempts; its length plus one bounds the attempts. */ @@ -155,7 +155,7 @@ export async function discoverModules(options: DiscoverModulesOptions): Promise< * successful start clears the signal. Fail-open, as the cron wrapper's own * tracking is: the crontab is emitted whether or not this write lands. */ -export function recordModuleDiscovery(db: Database, outcome: DiscoveryOutcome): void { +function recordModuleDiscovery(db: Database, outcome: DiscoveryOutcome): void { const error = outcome.modules === null ? `module cron skipped: ${outcome.cause ?? "module discovery unavailable"}` : undefined; const run = recordCronRun(db, MODULE_DISCOVERY_JOB_NAME); const store = createActivityStore(db, { writer: `cron:${process.pid}` }); @@ -172,7 +172,7 @@ export function recordModuleDiscovery(db: Database, outcome: DiscoveryOutcome): store.rollupRun(runId); } -export interface PersistModuleDiscoveryOptions { +interface PersistModuleDiscoveryOptions { brainPath: string; dbPath: string | undefined; /** diff --git a/packages/ui-server/src/cron/run-job.ts b/packages/ui-server/src/cron/run-job.ts index 9523d4b284..98d1d58cff 100644 --- a/packages/ui-server/src/cron/run-job.ts +++ b/packages/ui-server/src/cron/run-job.ts @@ -26,24 +26,24 @@ export const OUTPUT_TAIL_CHARS = 8_000; * (#3380). The worker's host, homes and XDG state are read-only or per-run; * a bare `EROFS` from a module's own subprocess does not say so. */ -export const READ_ONLY_BOUNDARY_HINT = +const READ_ONLY_BOUNDARY_HINT = "the job wrote to a read-only path: it runs in a maintenance worker (the host execution boundary), where only the brain is writable and kept. " + "A module keeps durable state in .brain-ui/modules// (CommandContext.stateDir())."; /** A read-only write in the job's own stderr that nothing above it already explained. */ -export function readOnlyWithoutBoundary(stderr: string): boolean { +function readOnlyWithoutBoundary(stderr: string): boolean { return /\bEROFS\b|read-only file system/i.test(stderr) && !stderr.includes("host execution boundary"); } /** Heartbeat cadence, comfortably inside the activity store's stale threshold. */ -export const HEARTBEAT_MS = 30_000; +const HEARTBEAT_MS = 30_000; /** Child-visible path where span-sink JSONL may be appended. */ export const SPAN_SINK_ENV = "BRAIN_ACTIVITY_SPAN_SINK"; /** * The most stdout the `sync` job's result may hold. Past it the output is * passed through as it arrives and no result is read from it. */ -export const SYNC_RESULT_MAX_CHARS = 8_000_000; +const SYNC_RESULT_MAX_CHARS = 8_000_000; interface TextSink { write(text: string): unknown; @@ -64,7 +64,7 @@ interface RunRecorder { close(): void; } -export interface RunJobOptions { +interface RunJobOptions { jobName: string; command: string[]; dbPath: string; @@ -79,7 +79,7 @@ export interface RunJobOptions { stderr?: TextSink; } -export interface RunJobDependencies { +interface RunJobDependencies { spawn?: ( command: string[], options: { @@ -110,7 +110,7 @@ function writeLine(sink: TextSink, text: string): void { } /** Forward a stream verbatim while exposing decoded chunks for tail capture. */ -export async function teeStream( +async function teeStream( stream: ReadableStream, sink: TextSink, onText: (text: string) => void @@ -152,7 +152,7 @@ function holdStdout(sink: TextSink): TextSink & { release(): string | null } { } /** Keep the last `cap` characters, never the head. */ -export function appendTail(current: string, text: string, cap: number): string { +function appendTail(current: string, text: string, cap: number): string { return (current + text).slice(-cap); } diff --git a/packages/ui-server/src/cron/scheduler.ts b/packages/ui-server/src/cron/scheduler.ts index 12d3839c53..a2c268dcee 100644 --- a/packages/ui-server/src/cron/scheduler.ts +++ b/packages/ui-server/src/cron/scheduler.ts @@ -12,7 +12,7 @@ import { observeWrite } from "../activity/store-writes.js"; // Runs started by the crontab report themselves via recordCronRun below; // their stdout/stderr still goes to syslog. -export interface CronScheduler { +interface CronScheduler { getCronStatus(): Array<{ name: string; lastRunAt: number | null; @@ -30,7 +30,7 @@ interface CronJob { } /** One in-flight job run being recorded into `cron_runs`. */ -export interface CronRunRecord { +interface CronRunRecord { /** Mark the run finished: success without an argument, error with one. */ finish(error?: string): void; } diff --git a/packages/ui-server/src/drafts/store.ts b/packages/ui-server/src/drafts/store.ts index eb3e68569f..c0b00366f4 100644 --- a/packages/ui-server/src/drafts/store.ts +++ b/packages/ui-server/src/drafts/store.ts @@ -61,15 +61,15 @@ export class DraftAuthError extends Error { } /** A stored upload not named by any save is removed this long after upload. */ -export const PENDING_ATTACHMENT_TTL_MS = 60 * 60 * 1_000; +const PENDING_ATTACHMENT_TTL_MS = 60 * 60 * 1_000; /** Most stored attachments per draft, listed and not yet listed together. */ -export const MAX_STORED_ATTACHMENTS_PER_DRAFT = MAX_IMAGES_PER_MESSAGE * 2; +const MAX_STORED_ATTACHMENTS_PER_DRAFT = MAX_IMAGES_PER_MESSAGE * 2; /** Receipts kept per draft and operation; older keys are forgotten. */ const RECEIPTS_PER_DRAFT = 32; /** Accepted-send records kept per draft. */ const SENDS_PER_DRAFT = 8; -export interface SaveDraftInput { +interface SaveDraftInput { /** The `If-Match` revision; 0 creates the draft. */ ifMatch: number; idempotencyKey: string; @@ -78,14 +78,14 @@ export interface SaveDraftInput { attachmentIds: string[]; } -export interface UploadDraftAttachmentInput { +interface UploadDraftAttachmentInput { idempotencyKey: string; mime: DraftImageType; name: string | null; bytes: Uint8Array; } -export interface AcceptDraftInput { +interface AcceptDraftInput { draftRef: DraftRef; /** The session the accepted message runs in. */ sessionId: string; @@ -98,7 +98,7 @@ export interface AcceptDraftInput { } /** What an accepted chat message did to the draft it named. */ -export type DraftAcceptOutcome = "consumed" | "kept" | "unauthorized"; +type DraftAcceptOutcome = "consumed" | "kept" | "unauthorized"; export interface DraftStore { readonly limits: Readonly; diff --git a/packages/ui-server/src/files/walker.ts b/packages/ui-server/src/files/walker.ts index b9f5db630d..4408912c44 100644 --- a/packages/ui-server/src/files/walker.ts +++ b/packages/ui-server/src/files/walker.ts @@ -1,6 +1,6 @@ import { closeSync, constants, fstatSync, openSync, readSync, realpathSync } from "node:fs"; import { readdir, readFile, stat, realpath } from "node:fs/promises"; -import { join, relative, resolve, sep, posix, dirname } from "node:path"; +import { join, relative, resolve, sep, posix } from "node:path"; import ignore, { type Ignore } from "ignore"; import { isWithin, resolveContained, type ContainmentPolicy } from "@schlessera/brain-common/internal/safe-path"; import { BRAIN_SCRATCH_DIR, BRAIN_WORKSPACES_DIR } from "@schlessera/brain-common/internal/worker-areas"; @@ -341,7 +341,7 @@ const MIME_BY_EXT: Record = { ".webm": "video/webm", }; -export function mimeFor(name: string, kind: FileContentKind): string { +function mimeFor(name: string, kind: FileContentKind): string { const ext = extOf(name); if (MIME_BY_EXT[ext]) return MIME_BY_EXT[ext]; if (kind === "markdown") return "text/markdown; charset=utf-8"; @@ -350,7 +350,7 @@ export function mimeFor(name: string, kind: FileContentKind): string { return "application/octet-stream"; } -export interface FileContent { +interface FileContent { kind: FileContentKind; size: number; mtime: number; @@ -536,4 +536,3 @@ export async function resolveAncestors(rel: string, root: string): Promise<{ anc } // Re-export for callers -export { dirname }; diff --git a/packages/ui-server/src/governance/roadblocks.ts b/packages/ui-server/src/governance/roadblocks.ts index a841d9fb65..92536b21a7 100644 --- a/packages/ui-server/src/governance/roadblocks.ts +++ b/packages/ui-server/src/governance/roadblocks.ts @@ -30,8 +30,8 @@ import { * single unresolved failure followed by an eligible successful step. */ -export type RoadblockCategory = GovernanceEventPayload<"roadblock">["category"]; -export type RoadblockPayload = GovernanceEventPayload<"roadblock">; +type RoadblockCategory = GovernanceEventPayload<"roadblock">["category"]; +type RoadblockPayload = GovernanceEventPayload<"roadblock">; /** One tool call as the host observed it. */ export interface TracedCall { @@ -281,7 +281,7 @@ function statusProgram(command: string): string | null { * name only, so `/srv/brain/.brain/x.md` and `.brain/y.md` group together and * absolute roots never leak into the signature. */ -export function pathArea(path: string): string { +function pathArea(path: string): string { const parts = path.replace(/\\/g, "/").replace(/\/+$/, "").split("/").filter((p) => p && p !== "."); if (parts.length <= 1) return "*"; const dir = parts.at(-2)!; @@ -313,7 +313,7 @@ function urlKind(input: unknown): string | null { } /** The tool family a call belongs to; an episode only closes within it. */ -export function familyOf(tool: string, input: unknown): string { +function familyOf(tool: string, input: unknown): string { const { name, server } = bareTool(tool); const family = FAMILY_BY_TOOL[name.toLowerCase()]; if (family === "shell") { @@ -354,7 +354,7 @@ function deniedArea(output: string): string | null { } /** Why a finished call failed, or null when it did not. */ -export function failureCause(call: TracedCall): Cause | null { +function failureCause(call: TracedCall): Cause | null { if (call.denied) return { category: "permission_denied", detail: "denied" }; if (call.output === null) return null; const output = call.output; diff --git a/packages/ui-server/src/governance/session-taint.ts b/packages/ui-server/src/governance/session-taint.ts index 365a8258a9..97d95b6c9f 100644 --- a/packages/ui-server/src/governance/session-taint.ts +++ b/packages/ui-server/src/governance/session-taint.ts @@ -2,7 +2,7 @@ import type { Database } from "bun:sqlite"; import { insertGovernanceEvent, type GovernanceEventInput, type GovernanceEventPayload, type GovernanceEventRow } from "./events.js"; -export type TaintSource = GovernanceEventPayload<"taint">["source"]; +type TaintSource = GovernanceEventPayload<"taint">["source"]; export interface SessionTaint { eventId: number; source: TaintSource } const FIRST_TAINT = "SELECT id, payload FROM governance_events WHERE kind='taint' AND (turn_id=? OR (? IS NOT NULL AND session_id=?)) ORDER BY id LIMIT 1"; diff --git a/packages/ui-server/src/graph/reader.ts b/packages/ui-server/src/graph/reader.ts index 8e14660232..87bd8d154a 100644 --- a/packages/ui-server/src/graph/reader.ts +++ b/packages/ui-server/src/graph/reader.ts @@ -21,8 +21,8 @@ export const MAX_NEIGHBORHOOD_DEPTH = 3; export const MAX_DISCOVERY_DEPTH = 8; export const DEFAULT_STALE_DAYS = 180; -export type GraphDirection = "in" | "out" | "both"; -export type GraphUnavailableReason = "schema" | "not_computed"; +type GraphDirection = "in" | "out" | "both"; +type GraphUnavailableReason = "schema" | "not_computed"; /** No graph to read: the index is absent or predates the graph, or nothing computed one. */ export class GraphUnavailableError extends Error { @@ -60,30 +60,30 @@ export class GraphIndexError extends Error { } } -export interface GraphReadOptions { +interface GraphReadOptions { /** The brain repo to read — injected by the route layer from ServerConfig. */ brainPath: string; } -export interface ClustersOptions extends GraphReadOptions { +interface ClustersOptions extends GraphReadOptions { community?: number; includeIsolates?: boolean; } -export interface NeighborhoodOptions extends GraphReadOptions { +interface NeighborhoodOptions extends GraphReadOptions { center: string; depth?: number; direction?: GraphDirection; } -export interface DiscoveryOptions extends GraphReadOptions { +interface DiscoveryOptions extends GraphReadOptions { /** Omitted → the precomputed default root, virtual node included. */ root?: string; direction?: "out" | "both"; maxDepth?: number; } -export interface MaintenanceOptions extends GraphReadOptions { +interface MaintenanceOptions extends GraphReadOptions { staleDays?: number; } diff --git a/packages/ui-server/src/inbox/cleanup.ts b/packages/ui-server/src/inbox/cleanup.ts index 2cb2648272..5330fb1207 100644 --- a/packages/ui-server/src/inbox/cleanup.ts +++ b/packages/ui-server/src/inbox/cleanup.ts @@ -6,7 +6,7 @@ import { removeStagedArrival } from "../share/staging-fs.js"; import { assertInboxRecoveryReady } from "./recovery-gate.js"; import { reapInboxThreadLifetimes } from "./lifetime.js"; -export interface CleanupItemOutcome { id: string; state: "running" | "cleaned" | "failed"; reason: string | null } +interface CleanupItemOutcome { id: string; state: "running" | "cleaned" | "failed"; reason: string | null } export interface CleanupReport { cleaned: number; failed: number; deferred: number; cancelled: boolean; truncated: boolean; items: CleanupItemOutcome[] } export interface CleanupRequest { signal?: AbortSignal; assertAuthorized?: () => void; onItem?: (item: CleanupItemOutcome) => void | Promise } diff --git a/packages/ui-server/src/inbox/media-effects.ts b/packages/ui-server/src/inbox/media-effects.ts index ee7ee2bf5e..a5b581682c 100644 --- a/packages/ui-server/src/inbox/media-effects.ts +++ b/packages/ui-server/src/inbox/media-effects.ts @@ -47,7 +47,7 @@ const applyResultSchema = z.looseObject({ }); const keptSchema = z.looseObject({ status: z.string(), reason: z.string().nullable().optional() }); -export class MediaEffectUnavailable extends Error {} +class MediaEffectUnavailable extends Error {} /** The current version of a brain file as the journal records one, read without following links; null when absent. */ function currentVersion(brain: string, path: string): JournalVersion | null | "other" { diff --git a/packages/ui-server/src/inbox/notify.ts b/packages/ui-server/src/inbox/notify.ts index 87f0793f68..0b175c7b75 100644 --- a/packages/ui-server/src/inbox/notify.ts +++ b/packages/ui-server/src/inbox/notify.ts @@ -34,25 +34,25 @@ import { inboxItemSchema } from "@schlessera/brain-ui-sdk/schemas"; import { isUsablePrincipal, resolvePrincipal } from "../db/principals.js"; import { inboxPriority } from "./state.js"; -export type { ActionDigestState, ActionDigestSummary } from "@schlessera/brain-ui-sdk/protocol"; +export type { ActionDigestSummary } from "@schlessera/brain-ui-sdk/protocol"; /** Fixed batching window from the first eligible arrival. */ export const ACTION_NOTICE_WINDOW_MS = 60_000; /** Inclusive push cutoff on the existing priority score with zero attempts. */ -export const ACTION_PUSH_CUTOFF = 12; +const ACTION_PUSH_CUTOFF = 12; /** Strict local quiet interval [22:00, 08:00), retries included. */ -export const ACTION_QUIET_START_HOUR = 22; -export const ACTION_QUIET_END_HOUR = 8; +const ACTION_QUIET_START_HOUR = 22; +const ACTION_QUIET_END_HOUR = 8; /** Local in-app digest refresh slots. */ -export const ACTION_DIGEST_HOURS = [9, 17] as const; +const ACTION_DIGEST_HOURS = [9, 17] as const; /** The existing push retry discipline: three attempts, five-minute backoff. */ -export const ACTION_MAX_SEND_ATTEMPTS = 3; -export const ACTION_SEND_RETRY_BACKOFF_MS = 5 * 60 * 1000; +const ACTION_MAX_SEND_ATTEMPTS = 3; +const ACTION_SEND_RETRY_BACKOFF_MS = 5 * 60 * 1000; /** An in-flight attempt older than this is treated as an ambiguous outcome. */ -export const ACTION_IN_FLIGHT_STALE_MS = 60_000; +const ACTION_IN_FLIGHT_STALE_MS = 60_000; /** The Actions destination, the route the existing push contract uses. */ -export const ACTION_NOTICE_URL = "/#/activity"; -export const ACTION_NOTICE_TAG = "brain-actions"; +const ACTION_NOTICE_URL = "/#/activity"; +const ACTION_NOTICE_TAG = "brain-actions"; export type ActionAttemptOutcome = "success" | "failed" | "ambiguous" | "gone"; @@ -146,7 +146,7 @@ export function localHour(zone: string, at: number): number { return new Date(wallClock(zone, at)).getUTCHours(); } -export function inQuietHours(zone: string, at: number): boolean { +function inQuietHours(zone: string, at: number): boolean { const hour = localHour(zone, at); return hour >= ACTION_QUIET_START_HOUR || hour < ACTION_QUIET_END_HOUR; } @@ -181,7 +181,7 @@ export function noticeDestination(endpoint: string): string { return createHash("sha256").update(endpoint).digest("hex"); } -export function actionNoticePayload(count: number): ActionNoticePayload { +function actionNoticePayload(count: number): ActionNoticePayload { // Lock-screen minimization: a count and navigation, nothing from the thread. return { title: count === 1 ? "1 action waiting" : `${count} actions waiting`, diff --git a/packages/ui-server/src/inbox/provenance.ts b/packages/ui-server/src/inbox/provenance.ts index 2574fc5ce6..ab207d1e72 100644 --- a/packages/ui-server/src/inbox/provenance.ts +++ b/packages/ui-server/src/inbox/provenance.ts @@ -27,7 +27,7 @@ import { stagedArrival, stagedArrivalDigest, type StagedArrival } from "./arriva import { governancePolicyReaderFor } from "../brain/governance-policy.js"; import { ProviderThreadRefusedError } from "../brain/provider-mask-refusal.js"; -export type InboxSubject = { item: string } | { checkpoint: string }; +type InboxSubject = { item: string } | { checkpoint: string }; export type InboxProvenance = | { origin: "person"; evidence: string } | { origin: "server" } diff --git a/packages/ui-server/src/inbox/triage.ts b/packages/ui-server/src/inbox/triage.ts index 8e5cb31cb9..e3f25dd654 100644 --- a/packages/ui-server/src/inbox/triage.ts +++ b/packages/ui-server/src/inbox/triage.ts @@ -13,17 +13,16 @@ import { TRIAGE_RUBRIC } from "./triage-rubric.js"; import { stagedArrival, TRIAGE_ITEM_BYTES, type StagedArrival } from "./arrival.js"; import { recordInboxProvenance } from "./provenance.js"; -export { TRIAGE_ITEM_BYTES }; -export const TRIAGE_MODEL = "jev-1.13.0"; -export const TRIAGE_FLOOR = 0.4; -export const TRIAGE_BATCH_BYTES = 40_000; -export const TRIAGE_STATE_BYTES = 32_000; +const TRIAGE_MODEL = "jev-1.13.0"; +const TRIAGE_FLOOR = 0.4; +const TRIAGE_BATCH_BYTES = 40_000; +const TRIAGE_STATE_BYTES = 32_000; const ROUTES = ["drop", "rule", "needs_agent", "needs_user"] as const; type Route = typeof ROUTES[number]; type TriageItem = InboxQueueItem & { type: "triage" }; -export interface InboxEvidence { id: string; source: string; title: string; body: string; trust: string; incomplete: boolean; binary: boolean } -export interface TriageDecision { +interface InboxEvidence { id: string; source: string; title: string; body: string; trust: string; incomplete: boolean; binary: boolean } +interface TriageDecision { itemId: string; tier: "T0" | "T1"; route: Route; reason: "accepted" | "duplicate" | "empty" | "incomplete" | "binary" | "unknown" | "low-probability" | "transport" | "accounting"; proposedRoute: Route | null; diff --git a/packages/ui-server/src/labels/index.ts b/packages/ui-server/src/labels/index.ts index fb73dd1bbe..90a47beb6c 100644 --- a/packages/ui-server/src/labels/index.ts +++ b/packages/ui-server/src/labels/index.ts @@ -1,21 +1,11 @@ export { - LABEL_CACHE_ENTRIES, - LABEL_CONCURRENCY, - LABEL_MAX_WAITING, - LABEL_PROMPT_CHARS, LABEL_RUN_NAME, - LABEL_SYSTEM_PROMPT, - LABEL_TIMEOUT_MS, createLabeller, - labelSourceHash, - type CreateLabellerDeps, type LabelCompletion, type LabelCompletionProvider, type LabelCompletionRequest, type LabelCompletionUsage, - type LabelOutcome, type Labeller, type LabellerOptions, } from "./labeller.js"; -export { LABEL_MAX_CHARS, LABEL_MAX_WORDS, normaliseLabel } from "./normalise.js"; -export { createPillLabels, type PillLabels } from "./pill-labels.js"; +export { LABEL_MAX_CHARS, normaliseLabel } from "./normalise.js"; diff --git a/packages/ui-server/src/labels/labeller.ts b/packages/ui-server/src/labels/labeller.ts index 67e147e138..dca2a15a9b 100644 --- a/packages/ui-server/src/labels/labeller.ts +++ b/packages/ui-server/src/labels/labeller.ts @@ -88,22 +88,22 @@ export interface LabellerOptions { /** The Activity run name of one label call. */ export const LABEL_RUN_NAME = "pill label"; -export const LABEL_TIMEOUT_MS = 10_000; +const LABEL_TIMEOUT_MS = 10_000; /** Calls in flight at once; the rest wait their turn. */ -export const LABEL_CONCURRENCY = 2; +const LABEL_CONCURRENCY = 2; /** Texts waiting for a call; past this a new one keeps its fallback. */ -export const LABEL_MAX_WAITING = 100; +const LABEL_MAX_WAITING = 100; /** Distinct texts whose answer is kept in memory. */ -export const LABEL_CACHE_ENTRIES = 500; +const LABEL_CACHE_ENTRIES = 500; /** The most of a prompt the model is shown. */ -export const LABEL_PROMPT_CHARS = 2_000; +const LABEL_PROMPT_CHARS = 2_000; -export const LABEL_SYSTEM_PROMPT = +const LABEL_SYSTEM_PROMPT = "You label chat messages for a small pill in a user interface. " + "Reply with two to four plain words saying what the message is about. " + "No quotes, no trailing punctuation, no preamble, nothing else."; -export type LabelOutcome = "labelled" | "empty" | "timeout" | "error" | "skipped_busy"; +type LabelOutcome = "labelled" | "empty" | "timeout" | "error" | "skipped_busy"; export interface Labeller { /** False without a provider: every call answers null without work. */ diff --git a/packages/ui-server/src/labels/normalise.ts b/packages/ui-server/src/labels/normalise.ts index 5805fc7723..7a9d4df1ce 100644 --- a/packages/ui-server/src/labels/normalise.ts +++ b/packages/ui-server/src/labels/normalise.ts @@ -10,7 +10,7 @@ import { PILL_LABEL_MAX_CHARS } from "@schlessera/brain-ui-sdk/protocol"; /** The longest label a pill is given: the SDK's bound. */ export const LABEL_MAX_CHARS = PILL_LABEL_MAX_CHARS; /** The most words a label keeps; the model is asked for two to four. */ -export const LABEL_MAX_WORDS = 4; +const LABEL_MAX_WORDS = 4; // C0/C1 controls, zero-width and bidirectional formatting characters. const INVISIBLE = /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]/g; diff --git a/packages/ui-server/src/middleware/auth.ts b/packages/ui-server/src/middleware/auth.ts index 4e86e943db..8634ed4ad9 100644 --- a/packages/ui-server/src/middleware/auth.ts +++ b/packages/ui-server/src/middleware/auth.ts @@ -61,7 +61,7 @@ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/gu; const SESSION_REVOKED_CLOSE_CODE = 1008; const SESSION_REVOKED_CLOSE_REASON = "Sessions invalidated"; -export const LOGIN_RATE_LIMIT = 5; // failures per window, per client IP +const LOGIN_RATE_LIMIT = 5; // failures per window, per client IP const LOGIN_RATE_WINDOW_MS = 60_000; // per minute // A global cap in addition to the per-IP one: the per-IP key is derived from // X-Forwarded-For, which a client behind a trusted proxy can rotate to mint a @@ -78,7 +78,7 @@ const LOGIN_RATE_WINDOW_MS = 60_000; // per minute // admission path while each pool still has a process-wide ceiling. The failure // map and both reservation maps cap at 1,024 source keys, comfortably above // the global password-failure budget while bounding forged-IP memory growth. -export const GLOBAL_LOGIN_RATE_LIMIT = 100; // failures per window, all IPs combined +const GLOBAL_LOGIN_RATE_LIMIT = 100; // failures per window, all IPs combined export const PASSKEY_LOGIN_RATE_LIMIT = 5; const PASSWORD_VERIFY_IN_FLIGHT_PER_IP = 2; const PASSWORD_VERIFY_IN_FLIGHT_GLOBAL = 8; @@ -444,7 +444,7 @@ export function applyPrincipalRevocation( /** * Revoke every cookie-bearing principal and disconnect its attached clients. */ -export async function revokeAllSessions( +async function revokeAllSessions( db: Database, revoker: Pick ): Promise { diff --git a/packages/ui-server/src/middleware/body-limit.ts b/packages/ui-server/src/middleware/body-limit.ts index 9fd52a0ecd..8053288809 100644 --- a/packages/ui-server/src/middleware/body-limit.ts +++ b/packages/ui-server/src/middleware/body-limit.ts @@ -1,7 +1,7 @@ import type { Context } from "hono"; /** Ordinary JSON control-plane requests never need to be large. */ -export const JSON_BODY_LIMIT_BYTES = 256 * 1024; +const JSON_BODY_LIMIT_BYTES = 256 * 1024; /** Render requests may contain inlined images and SVG. */ export const RENDER_BODY_LIMIT_BYTES = 5_000_000; diff --git a/packages/ui-server/src/middleware/principals.ts b/packages/ui-server/src/middleware/principals.ts index 09e1669ed7..0643885b5b 100644 --- a/packages/ui-server/src/middleware/principals.ts +++ b/packages/ui-server/src/middleware/principals.ts @@ -40,7 +40,7 @@ const MAX_AGENT_TTL_DAYS = SESSION_TTL_SECONDS / SECONDS_PER_DAY; const MAX_LABEL_LENGTH = 64; const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/gu; -export interface PrincipalManagementContext { +interface PrincipalManagementContext { db: Database; revoker: Pick; log?: Logger; diff --git a/packages/ui-server/src/middleware/tailscale.ts b/packages/ui-server/src/middleware/tailscale.ts index 9cde4f7c1a..d5ee0eb7ae 100644 --- a/packages/ui-server/src/middleware/tailscale.ts +++ b/packages/ui-server/src/middleware/tailscale.ts @@ -10,7 +10,7 @@ import { getConnInfo } from "hono/bun"; * config says `trustProxy` (TRUST_PROXY=1) — set that ONLY when a trusted * reverse proxy in front of brain-ui sets the forwarding header. */ -export interface TailscaleGuardOptions { +interface TailscaleGuardOptions { /** Trust x-forwarded-for / x-real-ip. */ trustProxy: boolean; /** How many trusted proxies front the app (default 1). */ diff --git a/packages/ui-server/src/pricing/provider-pricing.ts b/packages/ui-server/src/pricing/provider-pricing.ts index af2be73de8..c6adea91c2 100644 --- a/packages/ui-server/src/pricing/provider-pricing.ts +++ b/packages/ui-server/src/pricing/provider-pricing.ts @@ -24,7 +24,7 @@ export const GEMINI_EMBEDDING_PRICES: Readonly; brainCliMinimum?: string; diff --git a/packages/ui-server/src/routes/files.ts b/packages/ui-server/src/routes/files.ts index 0f467a9122..98be2eee3e 100644 --- a/packages/ui-server/src/routes/files.ts +++ b/packages/ui-server/src/routes/files.ts @@ -168,7 +168,7 @@ function markView(mark: UntrustedMark, principal: Principal | undefined, missing }; } -export interface FilesRouteDeps { +interface FilesRouteDeps { brainRoot: string; log?: Logger; /** The untrusted-mark records (#2673) and the hosted write worker they commit on. Absent: the mark routes are not mounted. */ diff --git a/packages/ui-server/src/routes/geo.ts b/packages/ui-server/src/routes/geo.ts index 9a4c5fbf99..52fe871d12 100644 --- a/packages/ui-server/src/routes/geo.ts +++ b/packages/ui-server/src/routes/geo.ts @@ -69,7 +69,7 @@ const KEY_PRECISION = 3; * megabytes of geometry nobody can read at any render width. */ const MAX_SPAN_DEGREES = 5; -export interface GeoRouteDeps { +interface GeoRouteDeps { config: CoastlineConfig; log?: Logger; /** Injected in tests so no test ever reaches Overpass. */ diff --git a/packages/ui-server/src/routes/governance.ts b/packages/ui-server/src/routes/governance.ts index 937e4a7bd3..3593870cc7 100644 --- a/packages/ui-server/src/routes/governance.ts +++ b/packages/ui-server/src/routes/governance.ts @@ -5,8 +5,8 @@ import { queryRoadblockReport, ROADBLOCK_REPORT_QUERY } from "../governance/road import type { AppEnv } from "../app-env.js"; import { isGovernanceEventKind, queryGovernanceEvents, type GovernanceEventKind } from "../governance/events.js"; -export const GOVERNANCE_EVENTS_DEFAULT_LIMIT = 100; -export const GOVERNANCE_EVENTS_MAX_LIMIT = 500; +const GOVERNANCE_EVENTS_DEFAULT_LIMIT = 100; +const GOVERNANCE_EVENTS_MAX_LIMIT = 500; const ID_MAX = 200; /** diff --git a/packages/ui-server/src/routes/health.ts b/packages/ui-server/src/routes/health.ts index 8490110ba7..49cd4e6e60 100644 --- a/packages/ui-server/src/routes/health.ts +++ b/packages/ui-server/src/routes/health.ts @@ -37,7 +37,7 @@ export function createHealthRoutes(deps: { db: Database }): Hono { }); } -export interface StatusDeps { +interface StatusDeps { /** Trusted metadata from configured modules; absent with an older CLI. */ getContentRenderers?(signal?: AbortSignal): Promise; /** Git SHA baked at build time (SOURCE_COMMIT), "dev" when unset. */ diff --git a/packages/ui-server/src/routes/pi-auth.ts b/packages/ui-server/src/routes/pi-auth.ts index 49b2024b43..978176c15c 100644 --- a/packages/ui-server/src/routes/pi-auth.ts +++ b/packages/ui-server/src/routes/pi-auth.ts @@ -34,7 +34,7 @@ export interface PiLoginFlowView { } /** Structural mirror of the pi package's PiAuthProviderStatus. */ -export interface PiAuthProviderStatusView { +interface PiAuthProviderStatusView { providerId: string; name: string; configured: boolean; @@ -51,7 +51,7 @@ interface PiAuthMirror { logout(providerId: string): Promise; } -export interface PiAuthRoutesDeps { +interface PiAuthRoutesDeps { agent: AgentConfig; /** Test seam — forwarded to loadBackendModule. */ importer?: (specifier: string) => Promise; diff --git a/packages/ui-server/src/routes/share.ts b/packages/ui-server/src/routes/share.ts index 3aedddaa81..0a19ccdb22 100644 --- a/packages/ui-server/src/routes/share.ts +++ b/packages/ui-server/src/routes/share.ts @@ -93,7 +93,7 @@ function firstString(form: FormData, name: string): string | undefined { return typeof value === "string" && value.trim() ? value : undefined; } -export interface ShareRoutesDeps { +interface ShareRoutesDeps { brainRoot: string; /** ALLOWED_ORIGINS — the same-origin check's split-topology allowlist. */ allowedOrigins: string[]; diff --git a/packages/ui-server/src/routes/skills.ts b/packages/ui-server/src/routes/skills.ts index 534a7a44ce..910d3ac002 100644 --- a/packages/ui-server/src/routes/skills.ts +++ b/packages/ui-server/src/routes/skills.ts @@ -32,7 +32,7 @@ import { resolveGitHubToken } from "../config/env.js"; import { readJsonBody } from "../middleware/body-limit.js"; import { requireJson } from "../middleware/origin.js"; -export interface SkillRoutesDeps { +interface SkillRoutesDeps { brainPath: string; /** Runs `brain skills sync`; resolves with a human-readable summary. */ syncSkills: () => Promise; diff --git a/packages/ui-server/src/routes/transcriptions.ts b/packages/ui-server/src/routes/transcriptions.ts index d4ead0de83..b991a5ff38 100644 --- a/packages/ui-server/src/routes/transcriptions.ts +++ b/packages/ui-server/src/routes/transcriptions.ts @@ -18,7 +18,7 @@ const MEDIA = /^audio\/(?:webm|ogg|mp4)(?:\s*;\s*codecs\s*=\s*(?:opus|"opus"))?$ const PROVIDER_TIMEOUT_MS = 11 * 60 * 1000; /** An HTTP rejection is definitive. An error without that evidence is unknown. */ -export function transcriptionFailure(error: unknown): TranscriptionFailure { +function transcriptionFailure(error: unknown): TranscriptionFailure { if (!(error instanceof SpeechTranscriptionError)) return { reason: "outcome_unknown", retryable: false }; const status = error.providerStatus; const reasons = ["provider_error", "rate_limit", "provider_timeout", "media", "parameters", "validation", "authentication", "outcome_unknown"]; diff --git a/packages/ui-server/src/routes/voice.ts b/packages/ui-server/src/routes/voice.ts index 13111fe61a..413c12ad19 100644 --- a/packages/ui-server/src/routes/voice.ts +++ b/packages/ui-server/src/routes/voice.ts @@ -10,7 +10,7 @@ import { mintDeepgramToken } from "../voice/deepgram-token.js"; import { getKeyterms, type KeytermSettings } from "../voice/keyterm-builder.js"; import { pickSpeechProvider, speechCapabilities } from "../voice/speech-providers.js"; -export interface VoiceRoutesDeps { +interface VoiceRoutesDeps { voice: VoiceConfig; keyterms: KeytermSettings; speechProvider?: SpeechProvider; diff --git a/packages/ui-server/src/routes/web-search.ts b/packages/ui-server/src/routes/web-search.ts index b7b9a3a9e2..0e03392895 100644 --- a/packages/ui-server/src/routes/web-search.ts +++ b/packages/ui-server/src/routes/web-search.ts @@ -47,7 +47,7 @@ import { resolveWebSearchEnv } from "../config/env.js"; import { loadBackendDescriptor, loadBackendModule } from "../agent/backend.js"; /** One toggleable provider, as the Settings UI renders it. */ -export interface WebSearchProviderView { +interface WebSearchProviderView { id: string; label: string; /** In the active chain. */ @@ -66,7 +66,7 @@ export interface WebSearchProviderView { blurb: string; } -export interface WebSearchConfigView { +interface WebSearchConfigView { /** False when the pi backend is not configured — the client hides the card. */ configured: boolean; /** The active chain, in the order it is tried. Empty = the extension picks. */ @@ -86,7 +86,7 @@ export interface WebSearchConfigView { providers: WebSearchProviderView[]; } -export interface WebSearchRoutesDeps { +interface WebSearchRoutesDeps { agent: AgentConfig; /** Test seam — overrides the config file location. */ configPath?: string; diff --git a/packages/ui-server/src/schedules/admission.ts b/packages/ui-server/src/schedules/admission.ts index 167edeaeb2..0b9b0483fd 100644 --- a/packages/ui-server/src/schedules/admission.ts +++ b/packages/ui-server/src/schedules/admission.ts @@ -24,7 +24,7 @@ import { occurrenceId, OUTSTANDING_STATES, type ExecutionPolicy, type Occurrence import { SCHEDULE_FRESHNESS_MS } from "./time.js"; /** Result text kept on the occurrence: bounded, inert, never authority. */ -export const MAX_RESULT_BYTES = 4096; +const MAX_RESULT_BYTES = 4096; /** Tools whose repetition cannot repeat an effect, so a failed attempt may retry. */ const SAFE_READ_TOOLS = new Set(["brain_read"]); @@ -34,7 +34,7 @@ export interface AdmissionTimers { clearTimeout(timer: Timer): void; } -export interface ScheduleAdmissionDeps extends Pick { +interface ScheduleAdmissionDeps extends Pick { service: ScheduleService; /** The backend the approved execution policy names. */ backend: AgentBackend; @@ -473,4 +473,3 @@ export function createScheduleAdmission(db: Database, deps: ScheduleAdmissionDep }; } -export type ScheduleAdmission = ReturnType; diff --git a/packages/ui-server/src/schedules/definition.ts b/packages/ui-server/src/schedules/definition.ts index 55720c7245..0b786d3091 100644 --- a/packages/ui-server/src/schedules/definition.ts +++ b/packages/ui-server/src/schedules/definition.ts @@ -14,7 +14,7 @@ import { canonicalJson } from "./canonical.js"; import { canonicalTimeZone, isoInstant, parseCron, parseInstant, ScheduleTimeError } from "./time.js"; export const SCHEDULE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; -export const DEFAULT_LIMITS = Object.freeze({ attemptTimeoutMs: 600_000, maxOperations: 3 }); +const DEFAULT_LIMITS = Object.freeze({ attemptTimeoutMs: 600_000, maxOperations: 3 }); export const MAX_DEFINITION_FILE_BYTES = 32 * 1024; export const DEFINITIONS_DIR = "context/scheduled-tasks/definitions"; export const RETIRED_DIR = "context/scheduled-tasks/retired"; @@ -33,9 +33,9 @@ const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]); export class ScheduleValidationError extends Error {} -export type JsonScalar = null | boolean | string | number; -export type JsonValue = JsonScalar | JsonValue[] | { [key: string]: JsonValue }; -export type JsonObject = { [key: string]: JsonValue }; +type JsonScalar = null | boolean | string | number; +type JsonValue = JsonScalar | JsonValue[] | { [key: string]: JsonValue }; +type JsonObject = { [key: string]: JsonValue }; const jsonScalar = z.union([z.null(), z.boolean(), z.string(), z.number()]); const bound = z.discriminatedUnion("kind", [ @@ -54,7 +54,7 @@ const limitsSchema = z.strictObject({ attemptTimeoutMs: z.number().int().positive().max(DEFAULT_LIMITS.attemptTimeoutMs), maxOperations: z.number().int().positive().max(DEFAULT_LIMITS.maxOperations), }); -export const scheduleDefinitionInputSchema = z.strictObject({ +const scheduleDefinitionInputSchema = z.strictObject({ prompt: z.string(), when: z.discriminatedUnion("kind", [ z.strictObject({ kind: z.literal("at"), at: z.string(), timeZone: z.string().optional() }), @@ -65,10 +65,10 @@ export const scheduleDefinitionInputSchema = z.strictObject({ limits: limitsSchema.optional(), notifyOnSuccess: z.boolean().optional(), }); -export type ScheduleDefinitionInput = z.infer; -export type ScheduleScope = z.infer & { tools: { name: string; inputs: JsonObject }[] }; +type ScheduleDefinitionInput = z.infer; +type ScheduleScope = z.infer & { tools: { name: string; inputs: JsonObject }[] }; -export type ScheduleWhen = +type ScheduleWhen = | { kind: "at"; at: string; timeZone: string } | { kind: "cron"; cron: string; timeZone: string; endAt: string | null }; /** The materialized, reviewed definition consumers see. */ @@ -155,7 +155,7 @@ function identifierText(value: string, where: string, maxBytes: number): void { } /** Exact brain-relative target paths only; protected namespaces are refused. */ -export function validateTargetPath(path: string): void { +function validateTargetPath(path: string): void { identifierText(path, "target", MAX_PATH_BYTES); if (path.startsWith("/") || path.includes("\\") || /^[A-Za-z][A-Za-z0-9+.-]*:/.test(path)) fail("target must be a brain-relative path"); diff --git a/packages/ui-server/src/schedules/service.ts b/packages/ui-server/src/schedules/service.ts index b8ccad8faf..2aa968d078 100644 --- a/packages/ui-server/src/schedules/service.ts +++ b/packages/ui-server/src/schedules/service.ts @@ -16,7 +16,7 @@ import { isUsablePrincipal, resolvePrincipal, type Principal } from "../db/princ import { encodeError, type SqliteWriter } from "../db/write-worker.js"; import { scheduleWrites } from "./service-writes.js"; import { ScheduleError } from "./errors.js"; -export { ScheduleError, type ScheduleErrorCode } from "./errors.js"; +export { ScheduleError } from "./errors.js"; import { canonicalJson, scheduleFingerprint, sha256Hex } from "./canonical.js"; import { DEFINITIONS_DIR, @@ -38,9 +38,9 @@ import { createHostBoundary, type HostBoundary } from "../brain/host-boundary.js import { WorkerStateError } from "@schlessera/brain-ui-sdk/internal"; import { subprocessEnv } from "../config/env.js"; -export const PROPOSAL_TTL_MS = 15 * 60_000; -export const CURSOR_TTL_MS = 15 * 60_000; -export const MAX_RESPONSE_BYTES = 512 * 1024; +const PROPOSAL_TTL_MS = 15 * 60_000; +const CURSOR_TTL_MS = 15 * 60_000; +const MAX_RESPONSE_BYTES = 512 * 1024; const MAX_CURSOR_BYTES = 1024; /** Envelope fields plus the largest signed cursor, budgeted before any row. */ const ENVELOPE_RESERVE = 256 + MAX_CURSOR_BYTES; @@ -53,29 +53,29 @@ export interface ExecutionPolicy { profileId: string | null; inferenceOrigins: string[]; } -export type TaskState = "publishing" | "active" | "paused" | "cancelled" | "completed" | "failed" | "expired"; -export type OccurrenceState = "queued" | "running" | "unwinding" | "waiting_for_action" | "retrying" +type TaskState = "publishing" | "active" | "paused" | "cancelled" | "completed" | "failed" | "expired"; +type OccurrenceState = "queued" | "running" | "unwinding" | "waiting_for_action" | "retrying" | "completed" | "failed" | "cancelled" | "expired" | "unknown"; -export type BlockedReason = "dispatch_disabled" | "budget_disabled" | "capacity" | "authority_unusable" +type BlockedReason = "dispatch_disabled" | "budget_disabled" | "capacity" | "authority_unusable" | "definition_drift" | "backend_unavailable" | "unknown_effect" | "occurrence_limit" | "restore_pending"; -export const TASK_STATES: readonly TaskState[] = ["publishing", "active", "paused", "cancelled", "completed", "failed", "expired"]; +const TASK_STATES: readonly TaskState[] = ["publishing", "active", "paused", "cancelled", "completed", "failed", "expired"]; export const OUTSTANDING_STATES: readonly OccurrenceState[] = ["queued", "running", "unwinding", "waiting_for_action", "retrying"]; -export interface ScheduleOccurrence { +interface ScheduleOccurrence { id: string; taskId: string; dueAt: string; expiresAt: string; state: OccurrenceState; operationsUsed: number; maxOperations: number; runIds: string[]; result: { state: "available" | "pruned" | "unavailable"; text: string | null }; } -export interface ScheduleTask { +interface ScheduleTask { id: string; definition: ScheduleDefinition; creatorPrincipalId: string; createdAt: string; zoneSource: ZoneSource; state: TaskState; executionAvailable: boolean; blockedReason: BlockedReason | null; nextDueAt: string | null; lastOccurrence: ScheduleOccurrence | null; compensationPending: boolean; } -export interface ScheduleProposal { +interface ScheduleProposal { id: string; taskId: string; key: string; definition: ScheduleDefinition; zoneSource: ZoneSource; executionPolicy: ExecutionPolicy; fingerprint: string; expiresAt: string; approvalState: "pending" | "approved"; } -export interface DueCandidate { +interface DueCandidate { taskId: string; occurrenceId: string; dueAt: string; expiresAt: string; admittable: boolean; blockedReason: BlockedReason | null; } diff --git a/packages/ui-server/src/schedules/time.ts b/packages/ui-server/src/schedules/time.ts index c186db3c00..89a3f4df88 100644 --- a/packages/ui-server/src/schedules/time.ts +++ b/packages/ui-server/src/schedules/time.ts @@ -103,7 +103,7 @@ export function wallTimeInstant(zone: string, year: number, month: number, day: // Cron // --------------------------------------------------------------------------- -export interface CronSpec { +interface CronSpec { minutes: number[]; hours: number[]; days: Set; @@ -258,4 +258,3 @@ export function cronInstantsBetween(spec: CronSpec, zone: string, fromMs: number } export const SCHEDULE_FRESHNESS_MS = DAY_MS; -export { MINUTE_MS }; diff --git a/packages/ui-server/src/share/staging.ts b/packages/ui-server/src/share/staging.ts index 1884162e00..1413e93432 100644 --- a/packages/ui-server/src/share/staging.ts +++ b/packages/ui-server/src/share/staging.ts @@ -23,7 +23,6 @@ import { at, listDirectory, makeDirectory, openStagingRoot, publishDirectory, removeEntry, verifyEntry, writeExclusive, type StagingDirectory, type StagingRoot, } from "./staging-fs.js"; -export { StagingTopologyError } from "./staging-fs.js"; /** * Staging for an incoming system share. @@ -47,7 +46,7 @@ export class EmptyShareError extends Error { } } -export type ShareLimitReason = +type ShareLimitReason = | "too_many_files" | "file_too_large" | "share_too_large" diff --git a/packages/ui-server/src/skills/install.ts b/packages/ui-server/src/skills/install.ts index 203a6c8ffa..c011d9a4df 100644 --- a/packages/ui-server/src/skills/install.ts +++ b/packages/ui-server/src/skills/install.ts @@ -27,15 +27,15 @@ import { dirname, join } from "path"; import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; export const MAX_ARCHIVE_BYTES = 100 * 1024 * 1024; -export const MAX_INFLATED_BYTES = 250 * 1024 * 1024; -export const MAX_FILES_PER_SKILL = 400; -export const MAX_FILE_BYTES = 10 * 1024 * 1024; +const MAX_INFLATED_BYTES = 250 * 1024 * 1024; +const MAX_FILES_PER_SKILL = 400; +const MAX_FILE_BYTES = 10 * 1024 * 1024; const NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/; export class InstallError extends Error {} -export interface InstallOutcome { +interface InstallOutcome { /** Installed-as name (frontmatter), or the archive folder for failures. */ name: string; status: "installed" | "replaced" | "skipped"; @@ -43,13 +43,13 @@ export interface InstallOutcome { files?: number; } -export interface InstallOptions { +interface InstallOptions { overwrite?: boolean; /** Only consider entries under this archive subpath (GitHub `tree` URLs). */ subpath?: string; } -export interface InstallDeps { +interface InstallDeps { brainPath: string; } @@ -80,7 +80,7 @@ function concatChunks(chunks: Uint8Array[], total: number): Uint8Array { return whole; } -export interface UnzipCaps { +interface UnzipCaps { maxFileBytes: number; maxInflatedBytes: number; } @@ -296,7 +296,7 @@ export function installSkillsFromZip( // GitHub // --------------------------------------------------------------------------- -export interface GitHubSource { +interface GitHubSource { owner: string; repo: string; ref?: string; diff --git a/packages/ui-server/src/skills/manager.ts b/packages/ui-server/src/skills/manager.ts index de470caa3b..29abd0f0bd 100644 --- a/packages/ui-server/src/skills/manager.ts +++ b/packages/ui-server/src/skills/manager.ts @@ -40,9 +40,9 @@ import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter" /** Agent Skills standard: lowercase kebab, no traversal, bounded. */ const NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/; /** A SKILL.md past this is not a skill, it's a document dump. */ -export const MAX_SKILL_CONTENT_BYTES = 128 * 1024; +const MAX_SKILL_CONTENT_BYTES = 128 * 1024; -export interface SkillEntry { +interface SkillEntry { /** Directory name (= the skill's identity for enable/disable/remove). */ name: string; /** Frontmatter description, or empty when unparseable. */ @@ -54,7 +54,7 @@ export interface SkillEntry { warning?: string; } -export interface SkillDetail extends SkillEntry { +interface SkillDetail extends SkillEntry { content: string; /** Files in the skill directory besides SKILL.md (repo-relative names). */ extraFiles: string[]; @@ -64,7 +64,7 @@ export class SkillValidationError extends Error {} export class SkillNotFoundError extends Error {} export class SkillConflictError extends Error {} -export interface SkillManager { +interface SkillManager { list(): SkillEntry[]; get(name: string): SkillDetail; create(name: string, content: string): SkillEntry; diff --git a/packages/ui-server/src/storage/history-evidence.ts b/packages/ui-server/src/storage/history-evidence.ts index 9ad25c18b1..3483a7fbef 100644 --- a/packages/ui-server/src/storage/history-evidence.ts +++ b/packages/ui-server/src/storage/history-evidence.ts @@ -1,13 +1,13 @@ import { DAY, HOUR, RECENT, bucket, type Capacity, type HistoryPayload, type Sample } from "./history-model.js"; -export type EvidenceReason = "no-observation" | "stale" | "future" | "incomplete" | "changed-scope" | "changed-capacity" | "gap" | "ordering" | "insufficient-count" | "insufficient-span" | "mixed-direction" | "single-burst" | "arithmetic"; +type EvidenceReason = "no-observation" | "stale" | "future" | "incomplete" | "changed-scope" | "changed-capacity" | "gap" | "ordering" | "insufficient-count" | "insufficient-span" | "mixed-direction" | "single-burst" | "arithmetic"; export interface WindowEvidence { state: "unavailable" | "finite" | "non-depleting"; reason: EvidenceReason | null; start: number | null; end: number | null; samples: number; depletionPerDay: number | null; days: number | null; } -export interface ObservedRate { start: number; end: number; samples: number; bytesPerDay: number } +interface ObservedRate { start: number; end: number; samples: number; bytesPerDay: number } export interface CapacityEvidence { identity: string; rootScope: string; at: number; total: number | null; available: number | null; diff --git a/packages/ui-server/src/storage/history-model.ts b/packages/ui-server/src/storage/history-model.ts index 74b3c9dfc6..9691a4a308 100644 --- a/packages/ui-server/src/storage/history-model.ts +++ b/packages/ui-server/src/storage/history-model.ts @@ -4,15 +4,15 @@ import { storageTotals } from "./collect.js"; export const HISTORY_LIMITS = Object.freeze({ slots: [64, 90, 32] as const, sampleBytes: 1152, metadataBytes: 40960, payloadBytes: 262144, capacities: 4, writeInterval: 60_000 }); export const HOUR = 3_600_000, DAY = 24 * HOUR, RECENT = 6 * HOUR; -export type Quantity = number | null; -export type Coverage = 0 | 1 | 2; -export type Tier = 0 | 1 | 2; +type Quantity = number | null; +type Coverage = 0 | 1 | 2; +type Tier = 0 | 1 | 2; export type Source = 0 | 1 | 2; export type Capacity = [number, Quantity, Quantity, Quantity, Quantity, Coverage, Quantity, Quantity, Quantity, Quantity, Quantity, Quantity, Quantity, Quantity]; export type Sample = [1, Tier, 0 | 1, number, number, Source, number, Coverage, 0 | 1 | 2 | 3 | 4 | 5, Capacity[]]; -export type SampleDescriptor = [string, string, 1]; -export type CapacityDescriptor = [string, string]; -export interface HistoryMetadata { +type SampleDescriptor = [string, string, 1]; +type CapacityDescriptor = [string, string]; +interface HistoryMetadata { samples: Record; capacities: Record; state: S; @@ -25,7 +25,7 @@ export interface Aggregate { } type OmitFirst = T extends [unknown, ...infer Rest] ? Rest : never; export const hashScope = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 32); -export const coverage = (value: "complete" | "partial" | "unknown"): Coverage => value === "complete" ? 0 : value === "partial" ? 1 : 2; +const coverage = (value: "complete" | "partial" | "unknown"): Coverage => value === "complete" ? 0 : value === "partial" ? 1 : 2; export const bucket = (tier: Tier, at: number) => Math.floor((at - (tier === 2 ? 4 * DAY : 0)) / (tier === 0 ? RECENT : tier === 1 ? DAY : 7 * DAY)); export const bucketStart = (tier: Tier, index: number) => index * (tier === 0 ? RECENT : tier === 1 ? DAY : 7 * DAY) + (tier === 2 ? 4 * DAY : 0); export const jsonBytes = (value: unknown) => Buffer.byteLength(JSON.stringify(value)); diff --git a/packages/ui-server/src/storage/notify.ts b/packages/ui-server/src/storage/notify.ts index 0544dd85c7..0ad414b1d8 100644 --- a/packages/ui-server/src/storage/notify.ts +++ b/packages/ui-server/src/storage/notify.ts @@ -5,7 +5,7 @@ import type { StorageHistory } from "./history-store.js"; import { procedureCaller, type SqliteWriter } from "../db/write-worker.js"; import * as noticeWrites from "./notify-writes.js"; export type StorageNoticeOutcome = "accepted" | "failed" | "unknown" | "gone"; -export type StorageNoticeState = "pending" | "sending" | "accepted" | "failed" | "unknown" | "suppressed"; +type StorageNoticeState = "pending" | "sending" | "accepted" | "failed" | "unknown" | "suppressed"; export interface Receipt { episode: string; endpoint: string; principal_id: string; state: StorageNoticeState; attempts: number; attempted_at: number | null; next_at: number | null; pid: number | null; process_start: string | null } export interface StorageNoticeAttempt { id: string; diff --git a/packages/ui-server/src/storage/pressure.ts b/packages/ui-server/src/storage/pressure.ts index 58b814880c..18147c1d92 100644 --- a/packages/ui-server/src/storage/pressure.ts +++ b/packages/ui-server/src/storage/pressure.ts @@ -1,7 +1,7 @@ import { randomUUID } from "node:crypto"; import type { CapacityEvidence, WindowEvidence } from "./history-evidence.js"; import { RECENT } from "./history-model.js"; -export type Severity = "observed" | "low" | "critical"; +type Severity = "observed" | "low" | "critical"; export interface Refusal { target: string; resource: "bytes" | "quota" | "inodes" | "unknown"; diff --git a/packages/ui-server/src/storage/removal.ts b/packages/ui-server/src/storage/removal.ts index 234aac2406..40da9cd3e8 100644 --- a/packages/ui-server/src/storage/removal.ts +++ b/packages/ui-server/src/storage/removal.ts @@ -18,7 +18,7 @@ import { readRemovalFacts } from "./removal-facts.js"; import { storageObservation } from "./maintenance.js"; import { coreReader } from "./process.js"; -export const STORAGE_REMOVAL_LIMITS = Object.freeze({ items: 32, fileBytes: 64 * 1024 * 1024, totalBytes: 128 * 1024 * 1024, milliseconds: 300_000, reviewMilliseconds: 60_000, receiptBytes: 262_144, receipts: 128 }); +const STORAGE_REMOVAL_LIMITS = Object.freeze({ items: 32, fileBytes: 64 * 1024 * 1024, totalBytes: 128 * 1024 * 1024, milliseconds: 300_000, reviewMilliseconds: 60_000, receiptBytes: 262_144, receipts: 128 }); const REVIEW_TTL = 10 * 60_000, runningHere = new Set(); const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex"); const prefix = (path: string, root: string) => root === "." || path === root || path.startsWith(`${root}/`); diff --git a/packages/ui-server/src/tracks/read.ts b/packages/ui-server/src/tracks/read.ts index 41c17eff51..b7d1a9ba8b 100644 --- a/packages/ui-server/src/tracks/read.ts +++ b/packages/ui-server/src/tracks/read.ts @@ -63,8 +63,8 @@ export async function resolveChatFiles(brainRoot: string | undefined, files: { k return result; } -export const TRACK_CONTEXT_OPEN = "\n\n\n"; -export const TRACK_CONTEXT_CLOSE = "\n"; +const TRACK_CONTEXT_OPEN = "\n\n\n"; +const TRACK_CONTEXT_CLOSE = "\n"; /** Appended to the user prompt as explicitly quoted data, never agent-authored assertions. */ export function withTrackFiles(text: string, files: readonly SharedFileMeta[] | undefined): string { if (!files?.length) return text; diff --git a/packages/ui-server/src/voice/keyterm-builder.ts b/packages/ui-server/src/voice/keyterm-builder.ts index 570e90ebc7..e318460b63 100644 --- a/packages/ui-server/src/voice/keyterm-builder.ts +++ b/packages/ui-server/src/voice/keyterm-builder.ts @@ -40,7 +40,7 @@ function overridesPath(brainPath: string): string { return join(brainPath, ".voice-overrides.md"); } -export interface KeytermsCache { +interface KeytermsCache { version: number; keyterms: string[]; generatedAt: number; @@ -56,7 +56,7 @@ export interface KeytermsCache { degraded?: true; } -export function loadOverrides(brainPath: string, log?: Logger): PronunciationOverride[] { +function loadOverrides(brainPath: string, log?: Logger): PronunciationOverride[] { const path = overridesPath(brainPath); if (!existsSync(path)) return []; try { @@ -154,7 +154,7 @@ export function writeCache(settings: KeytermSettings, cache: KeytermsCache): voi writeFileSync(path, JSON.stringify(cache, null, 2), "utf-8"); } -export function readCache(settings: KeytermSettings): KeytermsCache | null { +function readCache(settings: KeytermSettings): KeytermsCache | null { const path = cachePath(settings); if (!existsSync(path)) return null; try { diff --git a/packages/ui-server/src/voice/speech-providers.ts b/packages/ui-server/src/voice/speech-providers.ts index f9fb37987a..94029344db 100644 --- a/packages/ui-server/src/voice/speech-providers.ts +++ b/packages/ui-server/src/voice/speech-providers.ts @@ -155,7 +155,7 @@ export function pickSpeechProvider(voice: VoiceConfig, supplied?: SpeechProvider } /** Validate a by-value implementation before invoking it or building keyterms. */ -export function assertSpeechProvider(provider: SpeechProvider): void { +function assertSpeechProvider(provider: SpeechProvider): void { if (!provider || typeof provider !== "object" || typeof provider.id !== "string" || !provider.id || provider.id !== provider.id.trim().toLowerCase()) { throw new Error("Invalid SpeechProvider: id must be a nonempty, trimmed, lowercase string."); diff --git a/packages/ui-server/src/ws/ask-answers.ts b/packages/ui-server/src/ws/ask-answers.ts index 2d1e0bbe88..4773d5c910 100644 --- a/packages/ui-server/src/ws/ask-answers.ts +++ b/packages/ui-server/src/ws/ask-answers.ts @@ -53,7 +53,7 @@ const ANSWER_KIND: Record = { }; /** The pending ask with this id, of whichever kind. The kinds share one id space. */ -export function findPendingAsk(coordinator: TurnCoordinator, requestId: string): PendingAsk | undefined { +function findPendingAsk(coordinator: TurnCoordinator, requestId: string): PendingAsk | undefined { const ask = coordinator.pendingAskUser.get(requestId); if (ask) return { kind: "ask_user", entry: ask }; const list = coordinator.pendingAskUserList.get(requestId); diff --git a/packages/ui-server/src/ws/chat-deletion.ts b/packages/ui-server/src/ws/chat-deletion.ts index 1e0933ab71..c05612ef44 100644 --- a/packages/ui-server/src/ws/chat-deletion.ts +++ b/packages/ui-server/src/ws/chat-deletion.ts @@ -23,7 +23,7 @@ type Retired = Extract; * (an older one can restore text), and devices that are offline until they * reconnect and learn the chat was retired. */ -export const CHAT_DELETION_RETAINED: readonly ChatDeletionRetained[] = ["independent_content", "effects_and_audit", "provider_copies", "backups", "offline_devices"]; +const CHAT_DELETION_RETAINED: readonly ChatDeletionRetained[] = ["independent_content", "effects_and_audit", "provider_copies", "backups", "offline_devices"]; export interface ChatDeletionDeps { catalog: Pick; @@ -38,7 +38,7 @@ export interface ChatDeletionDeps { export type ChatDeletionResult = { status: "refused"; reason: RetireRefusal } | { status: "retired"; receipt: ChatDeletionReceipt }; /** The wire receipt: store categories and outcomes only. */ -export function chatDeletionReceipt(retirement: Retired): ChatDeletionReceipt { +function chatDeletionReceipt(retirement: Retired): ChatDeletionReceipt { return { operationId: retirement.operationId, generation: retirement.generation, status: retirement.cleanup, stores: { ...retirement.stores }, retained: [...CHAT_DELETION_RETAINED] }; } diff --git a/packages/ui-server/src/ws/chat-lifecycle.ts b/packages/ui-server/src/ws/chat-lifecycle.ts index 0ef957f564..43232abe7c 100644 --- a/packages/ui-server/src/ws/chat-lifecycle.ts +++ b/packages/ui-server/src/ws/chat-lifecycle.ts @@ -8,7 +8,7 @@ import type { Database } from "bun:sqlite"; import { isUsablePrincipal, resolvePrincipal } from "../db/principals.js"; -export type RetiredKind = "session" | "dialogue_owner" | "conversation" | "task" | "request" | "native_task"; +type RetiredKind = "session" | "dialogue_owner" | "conversation" | "task" | "request" | "native_task"; export const CHAT_STORES = ["native", "dialogue", "tasks", "projections", "drafts"] as const; export type ChatStore = (typeof CHAT_STORES)[number]; export type ChatStoreOutcome = "pending" | "partial" | "unknown" | "removed"; @@ -126,7 +126,7 @@ function stored(db: Database, lifecycleId: string): Partial [row.store, row.outcome])); } /** Completed only when every selected store confirmed removal; unknown dominates partial, partial dominates pending. */ -export function cleanupStatus(stores: Partial>): ChatRetirementStatus { +function cleanupStatus(stores: Partial>): ChatRetirementStatus { const outcomes = Object.values(stores); if (!outcomes.length) return "pending"; if (outcomes.includes("unknown")) return "unknown"; diff --git a/packages/ui-server/src/ws/connection.ts b/packages/ui-server/src/ws/connection.ts index fdf1f71c84..3b698a1caf 100644 --- a/packages/ui-server/src/ws/connection.ts +++ b/packages/ui-server/src/ws/connection.ts @@ -24,7 +24,7 @@ export { websocket }; * principal from an httpOnly cookie. A one-way digest says "same principal or * not" without handing the id itself to every page. */ -export function answerQueueKey(principalId: string): string { +function answerQueueKey(principalId: string): string { return createHash("sha256").update(`brain-ui-answer-queue\u0000${principalId}`).digest("base64url").slice(0, 22); } diff --git a/packages/ui-server/src/ws/conversation.ts b/packages/ui-server/src/ws/conversation.ts index d40fc33969..d005a1b56e 100644 --- a/packages/ui-server/src/ws/conversation.ts +++ b/packages/ui-server/src/ws/conversation.ts @@ -52,15 +52,15 @@ import { MAX_RETAINED_RESULT_CHARS } from "./conversation-storage.js"; import { handleChatMessage } from "./run-session.js"; /** Conversations kept for resumption, live or detached, per host. */ -export const MAX_RETAINED_CONVERSATIONS = 16; +const MAX_RETAINED_CONVERSATIONS = 16; /** Receipts one conversation keeps for resync; the oldest settled go first. */ -export const MAX_CONVERSATION_RECEIPTS = 64; +const MAX_CONVERSATION_RECEIPTS = 64; /** * Request ids one conversation remembers as used. Receipts are evicted; the * id stays, so a reused id is refused rather than run a second time. A * conversation that has used this many asks the client to start a new one. */ -export const MAX_CONVERSATION_REQUEST_IDS = 4_096; +const MAX_CONVERSATION_REQUEST_IDS = 4_096; interface Fragment { sequence: number; diff --git a/packages/ui-server/src/ws/handoff.ts b/packages/ui-server/src/ws/handoff.ts index d16a7cf6d7..cd86ca34c2 100644 --- a/packages/ui-server/src/ws/handoff.ts +++ b/packages/ui-server/src/ws/handoff.ts @@ -40,11 +40,11 @@ import { handleChatMessage, resolveRunBilling } from "./run-session.js"; import { requireWorkerHostRecorded } from "../agent/worker-host.js"; /** The Activity name of the summary run on the source session. */ -export const HANDOFF_PREPARATION_RUN_NAME = "handoff preparation"; +const HANDOFF_PREPARATION_RUN_NAME = "handoff preparation"; /** Upper bound on one preparation run, independent of the turn timeout. */ -export const HANDOFF_PREPARATION_TIMEOUT_MS = 120_000; +const HANDOFF_PREPARATION_TIMEOUT_MS = 120_000; /** Most transcript characters handed to the summarizer, newest kept. */ -export const HANDOFF_TRANSCRIPT_BUDGET_CHARS = 40_000; +const HANDOFF_TRANSCRIPT_BUDGET_CHARS = 40_000; const SUMMARY_SYSTEM_PROMPT = [ "You are writing a handoff: a summary of a conversation so that a different assistant can continue it in a new chat.", @@ -53,14 +53,14 @@ const SUMMARY_SYSTEM_PROMPT = [ `Stay under ${HANDOFF_MAX_CHARS} characters. Reply with the summary only.`, ].join(" "); -export type ReferenceState = "readable" | "missing" | "unreadable"; +type ReferenceState = "readable" | "missing" | "unreadable"; /** * Whether the destination may be offered each referenced brain file. The * same check the file browser applies: contained in the brain, an existing * file, and not tooling (dot paths, databases, lockfiles). */ -export async function checkHandoffReferences( +async function checkHandoffReferences( brainPath: string | undefined, references: readonly string[] ): Promise> { @@ -232,7 +232,7 @@ export function throughTurns(messages: readonly SessionHistoryMessage[], turns: } /** The prompt the summarizer reads: the snapshot as a plain transcript, newest kept. */ -export function handoffTranscript(messages: readonly SessionHistoryMessage[], budget = HANDOFF_TRANSCRIPT_BUDGET_CHARS): string { +function handoffTranscript(messages: readonly SessionHistoryMessage[], budget = HANDOFF_TRANSCRIPT_BUDGET_CHARS): string { const lines: string[] = []; let used = 0; for (let index = messages.length - 1; index >= 0; index--) { diff --git a/packages/ui-server/src/ws/local-exchanges.ts b/packages/ui-server/src/ws/local-exchanges.ts index 762e37fa79..5aa524db6c 100644 --- a/packages/ui-server/src/ws/local-exchanges.ts +++ b/packages/ui-server/src/ws/local-exchanges.ts @@ -62,30 +62,6 @@ export function saveLocalExchange( ); } -/** - * The exchanges no prompt has carried yet, marked as carried. Called at the - * moment a prompt is handed to the backend, so each context reaches the - * agent once. - */ -export function takePendingLocalExchanges(db: Database, sessionId: string): LocalExchange[] { - return db.transaction(() => { - const rows = db - .query( - `SELECT seq, exchange_id, command, prompt, answer, context, delivered_at - FROM local_exchanges WHERE session_id = ? AND delivered_at IS NULL ORDER BY seq` - ) - .all(sessionId) as ExchangeRow[]; - if (rows.length === 0) return []; - db.prepare( - `UPDATE local_exchanges SET delivered_at = ? WHERE session_id = ? AND delivered_at IS NULL` - ).run(Date.now(), sessionId); - return rows.flatMap((row) => { - const record = fromRow(row); - return record ? [record] : []; - }); - }).immediate(); -} - /** * Mark exactly these exchanges carried (#2850): the catalog takes pending * exchanges where the prompt is handed over and records the hand-over here, diff --git a/packages/ui-server/src/ws/message-sources.ts b/packages/ui-server/src/ws/message-sources.ts index 0755926be1..bca8f338ff 100644 --- a/packages/ui-server/src/ws/message-sources.ts +++ b/packages/ui-server/src/ws/message-sources.ts @@ -29,7 +29,7 @@ import { isThinkingLevel } from "@schlessera/brain-ui-sdk/protocol"; import { sharedFileMetaSchema, messageSourceSchema } from "@schlessera/brain-ui-sdk/schemas"; /** The key one message's text gets. Exported so the writer and the joiner agree by construction. */ -export function messageTextHash(text: string): string { +function messageTextHash(text: string): string { return new Bun.CryptoHasher("sha256").update(text).digest("hex"); } diff --git a/packages/ui-server/src/ws/rate-limit.ts b/packages/ui-server/src/ws/rate-limit.ts index 5cc61667f1..91b6b8eb89 100644 --- a/packages/ui-server/src/ws/rate-limit.ts +++ b/packages/ui-server/src/ws/rate-limit.ts @@ -26,7 +26,7 @@ export interface Clock { const realClock: Clock = { now: () => Date.now() }; -export interface RateLimitOptions { +interface RateLimitOptions { /** Sustained frames per second. */ ratePerSecond: number; /** Frames absorbable in one burst before the sustained rate applies. */ @@ -34,7 +34,7 @@ export interface RateLimitOptions { clock?: Clock; } -export interface RateLimitDecision { +interface RateLimitDecision { allowed: boolean; /** Tokens left after this decision, for reporting. */ remaining: number; diff --git a/packages/ui-server/src/ws/recovery.ts b/packages/ui-server/src/ws/recovery.ts index 91afed4751..1d9cef450d 100644 --- a/packages/ui-server/src/ws/recovery.ts +++ b/packages/ui-server/src/ws/recovery.ts @@ -62,7 +62,7 @@ export function acceptRequest( } /** The outcome of one recovery read, before it becomes an HTTP response. */ -export type RecoveryRead = +type RecoveryRead = | { kind: "ok"; recovery: SessionRecovery } | { kind: "unauthorized" } | { kind: "not_found" }; @@ -169,7 +169,7 @@ function pendingOf(host: WsHost, sessionId: string): SessionRecoveryPending[] { const NO_HISTORY = Symbol("no history"); /** How long one backend may take to say whether it holds a session, as `/api/sessions` allows. */ -export const RECOVERY_PROBE_MS = 3_000; +const RECOVERY_PROBE_MS = 3_000; /** * Unfinished existence probes, per host, by backend and session. A backend diff --git a/packages/ui-server/src/ws/turn-failures.ts b/packages/ui-server/src/ws/turn-failures.ts index fe1196dcaa..00be94a7e6 100644 --- a/packages/ui-server/src/ws/turn-failures.ts +++ b/packages/ui-server/src/ws/turn-failures.ts @@ -13,7 +13,7 @@ export interface RecordedTurnFailure { } /** Position is among backend-normalized assistants, before local exchanges are inserted. */ -export function assistantCount(messages: SessionHistoryMessage[]): number { +function assistantCount(messages: SessionHistoryMessage[]): number { return messages.filter((message) => message.role === "assistant").length; } diff --git a/packages/ui-server/src/ws/turns.ts b/packages/ui-server/src/ws/turns.ts index e62529b381..3a13f4a8c2 100644 --- a/packages/ui-server/src/ws/turns.ts +++ b/packages/ui-server/src/ws/turns.ts @@ -112,12 +112,12 @@ export interface QueuedFollowUp { * clips the list itself: every pending follow-up is always reported, and * only a very long prompt is shortened. */ -export const FOLLOW_UP_VIEW_TEXT_BYTES = 8_000; +const FOLLOW_UP_VIEW_TEXT_BYTES = 8_000; const wireBytes = (text: string) => Buffer.byteLength(JSON.stringify(text), "utf8"); /** Head of `text` within `bytes` serialized bytes, with an elision note when cut. */ -export function boundFollowUpText(text: string, bytes: number = FOLLOW_UP_VIEW_TEXT_BYTES): string { +function boundFollowUpText(text: string, bytes: number = FOLLOW_UP_VIEW_TEXT_BYTES): string { if (wireBytes(text) <= bytes) return text; const budget = Math.max(0, bytes - 64); // The longest head that fits: wire size grows with length, so bisect. @@ -278,7 +278,7 @@ export interface RunningTurn { // Pending interactive requests are tagged with their turn so a per-session // cancel/disconnect can drain only that session's pending entries, and with // the turnId that raised them (the slot's id mutates across queued follow-ups). -export interface PendingApproval { +interface PendingApproval { turn: RunningTurn; turnId: string; /** @@ -299,7 +299,7 @@ export interface PendingApproval { * happened (#957). `expired` is a terminal turn that resolved the request * itself; it never needed a `tool_result`. */ -export interface ToolResolutionRecord { +interface ToolResolutionRecord { outcome: "granted" | "denied" | "expired"; turnId: string; sessionId: string | null; @@ -308,7 +308,7 @@ export interface ToolResolutionRecord { } /** Settled outcomes retained for late replies; the oldest is evicted first. */ -export const MAX_RESOLVED_APPROVALS = 512; +const MAX_RESOLVED_APPROVALS = 512; export interface PendingAskUser { turn: RunningTurn; @@ -358,7 +358,7 @@ export type AskKind = "ask_user" | "ask_user_list" | "ask_user_rank" | "ask_user * repeated or late answer, or a status query after a lost receipt, gets the * host's actual outcome instead of silence. */ -export interface AskOutcome { +interface AskOutcome { requestId: string; sessionId: string | null; turnId: string; @@ -378,17 +378,17 @@ export interface AskOutcome { * deal from growing this without limit; the oldest outcome goes first, and a * forgotten request answers `not_recognized`, which stops replay just the same. */ -export const ASK_OUTCOME_TTL_MS = 24 * 60 * 60 * 1000; -export const ASK_OUTCOME_MAX = 1024; +const ASK_OUTCOME_TTL_MS = 24 * 60 * 60 * 1000; +const ASK_OUTCOME_MAX = 1024; -export interface PendingLocation { +interface PendingLocation { turn: RunningTurn; turnId: string; resolve: (result: LocationFix) => void; reject: (err: Error) => void; } -export interface PendingMask { +interface PendingMask { turn: RunningTurn; turnId: string; resolve: (png: Uint8Array) => void; diff --git a/scripts/check-citations.ts b/scripts/check-citations.ts index 2a7d657640..31bbfbcea7 100644 --- a/scripts/check-citations.ts +++ b/scripts/check-citations.ts @@ -437,11 +437,6 @@ export const CITATION_EXCEPTIONS: Record = { "docs/plans/index-query-api.md|https://github.com/schlessera/brain-kit/blob/33af7e2972873286144dbcc93c232c904e3ced47/packages/ui-server/package.json#L70": "verified commit-pinned source-audit evidence before the supported-query consumer migrations; the historical SQL/package/context implementation is intentionally preserved", "docs/plans/index-query-api.md|https://github.com/schlessera/brain-kit/blob/33af7e2972873286144dbcc93c232c904e3ced47/tests/allowed-edges.ts#L92": "verified commit-pinned source-audit evidence before the supported-query consumer migrations; the historical SQL/package/context implementation is intentionally preserved", "docs/plans/index-query-api.md|https://github.com/schlessera/brain-kit/blob/33af7e2972873286144dbcc93c232c904e3ced47/packages/ui-server/src/graph/reader.ts#L33": "verified commit-pinned source-audit evidence before the supported-query consumer migrations; the historical SQL/package/context implementation is intentionally preserved", - "docs/plans/navigation-recovery.md|https://github.com/schlessera/brain-kit/blob/18d5ddee154b5dbebb3dbd6c487bc8ea1fc036db/packages/ui-react/src/components/layout/desktop-palette.tsx#L84": "verified commit-pinned palette baseline before #946 moved destinations to desktop-routes.ts and opening state to the root UI store", - "docs/plans/navigation-recovery.md|https://github.com/schlessera/brain-kit/blob/18d5ddee154b5dbebb3dbd6c487bc8ea1fc036db/packages/ui-react/src/components/layout/desktop-palette.tsx#L52": "verified commit-pinned palette baseline before #946 moved destinations to desktop-routes.ts and opening state to the root UI store", - "docs/plans/navigation-recovery.md|https://github.com/schlessera/brain-kit/blob/7bfdc71074f4ff6243e0d7133e83dbb36eb2a971/packages/ui-react/src/components/chat/composer.tsx#L62": "verified commit-pinned composer draft and receipt handling before #951 moved them to the draft store and draft client", - "docs/plans/navigation-recovery.md|https://github.com/schlessera/brain-kit/blob/7bfdc71074f4ff6243e0d7133e83dbb36eb2a971/packages/ui-react/src/components/chat/composer.tsx#L161": "verified commit-pinned composer draft and receipt handling before #951 moved them to the draft store and draft client", - "docs/plans/navigation-recovery.md|https://github.com/schlessera/brain-kit/blob/ea8506b0eb511a3e16dba685d250d34e5340afa4/packages/ui-react/src/components/chat/session-drawer.tsx#L59": "verified commit-pinned single background-session drawer row before #950 replaced it with the Working group", "docs/investigations/turn-surface-routing-investigation.md|https://github.com/schlessera/brain-kit/blob/91995dcf1bbf0dbbc3aa7b0f3b2fda6a07c63e6a/packages/ui-backend-claude/src/sdk-options.ts#L54": "verified source-pinned measured eight-tool assembly before application tools and worker spawn changed the current implementation", "docs/investigations/turn-surface-routing-investigation.md|https://github.com/schlessera/brain-kit/blob/91995dcf1bbf0dbbc3aa7b0f3b2fda6a07c63e6a/packages/ui-backend-claude/src/ask-user-tool.ts#L91": "verified source-pinned measured eight-tool assembly before application tools and worker spawn changed the current implementation", // A dependency's installed source, at the version the record measured. diff --git a/scripts/check-unused-exports.ts b/scripts/check-unused-exports.ts new file mode 100644 index 0000000000..b5a063b337 --- /dev/null +++ b/scripts/check-unused-exports.ts @@ -0,0 +1,376 @@ +// Reports an exported declaration in a scanned package's `src/` that no other +// file in the repository imports (#2536). +// +// Why a gate: the api-report (tests/api-surface.test.ts) governs only names a +// package entry point reaches. A module-level `export` that no entry re-exports +// and no other file imports passed every gate, and a 2026-10-22 review found +// more than 200 of them in the three ui packages. A hand clean-up regrows. +// +// What counts as a use is read from the import graph, not from a name grep: the +// TypeScript compiler API parses every tracked source file in the repository, +// and each import, re-export, `import("…")` type and dynamic import is resolved +// to the file it names. A name is used when another file imports it from the +// declaring file directly, or through any chain of re-exports. A namespace +// import, `export *` from an entry, a dynamic `import()` or a `require()` of a +// file marks every export of that file used, because which names it reads is +// not visible syntactically. So does loading a file by path (`new URL(…, +// import.meta.url)`, `Bun.resolveSync`, `import.meta.resolve`), and so does a +// file that publishes its own `const url = import.meta.url` for a loader. +// +// What is never reported, by rule rather than by allowlist entry: +// +// - a package entry point's own exports (the package.json `exports` targets): +// tests/api-surface.test.ts governs those, and their re-exports count as +// uses of the declarations they forward; +// - a declaration the package's `api-report/.txt` records in its +// signatures section: a type reachable from a public signature is public +// with it (docs/decisions/public-export-boundary.md, "Public"); +// - test, spec and story files under `src/`, whose exports a runner reads. +// +// Anything else that must stay exported needs an ALLOWLIST entry below with a +// one-line reason. A stale entry fails the gate, so the list cannot outlive the +// export it excuses. +// +// The scanned package list is explicit. Other workspace packages are not +// scanned: adding one is a reviewed change to SCANNED_PACKAGES. +// +// bun scripts/check-unused-exports.ts [root] [--json] + +import { existsSync, readFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import ts from "typescript"; + +/** The packages (directory names under packages/) whose `src/` is scanned. */ +export const SCANNED_PACKAGES = ["ui-server", "ui-kit", "ui-react"] as const; + +export interface AllowlistEntry { file: string; name: string; reason: string } + +// The import graph cannot see one kind of use: another file's exported +// declaration whose type is *inferred* through this name. No file imports the +// name, yet dropping its export makes that file's declaration emit fail with +// TS4023/TS4058 ("has or is using name … but cannot be named"), the same +// failure #2534 found for ui-sdk's internal entry. Each entry below names the +// declaration whose emit needs it; the package's tsconfig.build.json proves it. +const INFERRED = (by: string) => `inferred into the emitted declaration of ${by}; dropping the export fails declaration emit (TS4023/TS4058)`; + +/** Exports that stay although no other file imports them, each with its reason. */ +export const ALLOWLIST: AllowlistEntry[] = [ + { file: "packages/ui-react/src/stores/follow-up-state.ts", name: "FollowUpState", reason: INFERRED("useFollowUpStore and createBrainStores") }, + { file: "packages/ui-react/src/stores/graph-state.ts", name: "GraphState", reason: INFERRED("useGraphStore and createBrainStores") }, + { file: "packages/ui-react/src/stores/handoff-state.ts", name: "HandoffState", reason: INFERRED("useHandoffStore and createBrainStores") }, + { file: "packages/ui-react/src/stores/inbox-state.ts", name: "InboxState", reason: INFERRED("useInboxStore and createBrainStores") }, + { file: "packages/ui-react/src/stores/mask-state.ts", name: "MaskState", reason: INFERRED("useMaskStore and createBrainStores") }, + { file: "packages/ui-react/src/stores/principal-state.ts", name: "PrincipalState", reason: INFERRED("usePrincipalStore and createBrainStores") }, + { file: "packages/ui-react/src/stores/session-list-state.ts", name: "SessionListState", reason: INFERRED("createBrainStores") }, + { file: "packages/ui-react/src/stores/share-state.ts", name: "ShareIntakeState", reason: INFERRED("useShareStore and createBrainStores") }, + { file: "packages/ui-react/src/stores/tracker-state.ts", name: "TrackerStoreState", reason: INFERRED("createBrainStores") }, + { file: "packages/ui-server/src/brain/native-journal-observer.ts", name: "NativeJournalReleaseAccounting", reason: INFERRED("createNativeJournalCapture") }, + { file: "packages/ui-server/src/inbox/cleanup.ts", name: "CleanupReport", reason: INFERRED("createInboxRuntime") }, + { file: "packages/ui-server/src/inbox/cleanup.ts", name: "CleanupRequest", reason: INFERRED("createInboxRuntime") }, + // Readers of source text rather than importers. + { file: "packages/ui-server/src/bin/brain-ui-cron.ts", name: "USAGE", reason: "tests/release-manifest.test.ts reads the subcommand list from the `export const USAGE` source text" }, + ...["listSpecFromInput", "formSpecFromInput", "rankSpecFromInput"].map(name => ({ + file: "packages/ui-react/src/hooks/websocket-handlers/chat.ts", name, + reason: "scripts/source-browser-dispatch.ts pins this file's sha256; an edit needs a reviewed re-pin there", + })), +]; + +export interface Finding { file: string; line: number; name: string; kind: "declaration" | "re-export" } + +export interface Report { + schemaVersion: 1; + packages: string[]; + scannedFiles: number; + findings: Finding[]; + allowlisted: AllowlistEntry[]; + staleAllowlist: AllowlistEntry[]; +} + +const SOURCE = /\.(?:[cm]?tsx?|[cm]?jsx?)$/; +const TEST_FILE = /(?:^|\/)(?:__tests__|__mocks__)\/|\.(?:test|spec|stories)\.[cm]?[jt]sx?$/; +const ALL = "*"; + +/** One file's exports, in the shape the usage propagation needs. */ +interface ModuleInfo { + /** Exported name -> line, for declarations and local export lists. */ + local: Map; + /** Exported name -> the file and name it forwards (`export { a as b } from`). */ + forwards: Map; + /** `export * from` targets. */ + stars: string[]; +} + +interface Graph { + modules: Map; + /** File -> names other files import from it directly. */ + uses: Map>; +} + +/** Every tracked or untracked-but-not-ignored file, repository-relative. */ +function listFiles(root: string): string[] { + const run = Bun.spawnSync(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"], { cwd: root }); + if (run.exitCode !== 0) throw new Error(`git ls-files failed: ${run.stderr.toString()}`); + return run.stdout.toString().split("\0").filter(file => file && existsSync(join(root, file))); +} + +/** `@schlessera/brain-[/sub]` -> repository-relative source file. */ +function packageEntries(root: string, files: string[]): Map { + const entries = new Map(); + for (const manifest of files.filter(file => /^packages\/[^/]+\/package\.json$/.test(file))) { + const pkg = JSON.parse(readFileSync(join(root, manifest), "utf8")); + const dir = dirname(manifest); + for (const [subpath, target] of Object.entries(pkg.exports ?? {})) { + const file = typeof target === "string" ? target : (target as Record)?.bun; + if (typeof file !== "string" || !SOURCE.test(file) || subpath.includes("*")) continue; + entries.set(subpath === "." ? pkg.name : `${pkg.name}/${subpath.slice(2)}`, join(dir, file)); + } + } + return entries; +} + +function makeResolver(files: Set, entries: Map) { + const candidates = (base: string) => { + const stripped = base.replace(/\.(?:[cm]?js|jsx)$/, ""); + return [base, ...[".ts", ".tsx", ".mts", ".cts", ".js", ".mjs", ".jsx"].map(ext => stripped + ext), + ...["ts", "tsx", "js"].map(ext => `${base}/index.${ext}`)]; + }; + return (from: string, specifier: string): string | undefined => { + if (entries.has(specifier)) return entries.get(specifier); + if (!specifier.startsWith(".")) return undefined; + const base = join(dirname(from), specifier); + return candidates(base).find(file => files.has(file)); + }; +} + +const exported = (node: ts.Node) => ts.canHaveModifiers(node) && + (ts.getModifiers(node) ?? []).some(m => m.kind === ts.SyntaxKind.ExportKeyword); +const isDefault = (node: ts.Node) => ts.canHaveModifiers(node) && + (ts.getModifiers(node) ?? []).some(m => m.kind === ts.SyntaxKind.DefaultKeyword); + +function bindingNames(name: ts.BindingName, out: string[]) { + if (ts.isIdentifier(name)) out.push(name.text); + else for (const element of name.elements) if (!ts.isOmittedExpression(element)) bindingNames(element.name, out); +} + +function buildGraph(root: string, files: string[], entries: Map): Graph { + const fileSet = new Set(files); + const resolveSpecifier = makeResolver(fileSet, entries); + const modules = new Map(); + const uses = new Map>(); + const use = (file: string | undefined, name: string) => { + if (!file) return; + let set = uses.get(file); + if (!set) uses.set(file, set = new Set()); + set.add(name); + }; + + for (const file of files) { + const text = readFileSync(join(root, file), "utf8"); + const kind = /\.[cm]?tsx$|\.jsx$/.test(file) ? ts.ScriptKind.TSX : /\.[cm]?jsx?$/.test(file) ? ts.ScriptKind.JS : ts.ScriptKind.TS; + const source = ts.createSourceFile(file, text, ts.ScriptTarget.ESNext, true, kind); + const info: ModuleInfo = { local: new Map(), forwards: new Map(), stars: [] }; + modules.set(file, info); + const lineOf = (node: ts.Node) => source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1; + const target = (specifier: ts.Expression | undefined) => + specifier && ts.isStringLiteralLike(specifier) ? resolveSpecifier(file, specifier.text) : undefined; + + for (const statement of source.statements) { + if (ts.isImportDeclaration(statement)) { + const from = target(statement.moduleSpecifier); + const clause = statement.importClause; + if (!from || !clause) continue; + if (clause.name) use(from, "default"); + const bindings = clause.namedBindings; + if (bindings && ts.isNamespaceImport(bindings)) use(from, ALL); + else if (bindings) for (const element of bindings.elements) use(from, (element.propertyName ?? element.name).text); + } else if (ts.isExportDeclaration(statement)) { + const from = target(statement.moduleSpecifier); + const clause = statement.exportClause; + if (statement.moduleSpecifier) { + if (!from) continue; + if (!clause) info.stars.push(from); + else if (ts.isNamespaceExport(clause)) info.forwards.set(clause.name.text, { file: from, name: ALL, line: lineOf(statement) }); + else for (const element of clause.elements) { + info.forwards.set(element.name.text, { file: from, name: (element.propertyName ?? element.name).text, line: lineOf(element) }); + } + } else if (clause && ts.isNamedExports(clause)) { + for (const element of clause.elements) info.local.set(element.name.text, lineOf(element)); + } + } else if (ts.isVariableStatement(statement) && statement.declarationList.declarations.some(declaration => + declaration.initializer && ts.isPropertyAccessExpression(declaration.initializer) && + ts.isMetaProperty(declaration.initializer.expression) && declaration.initializer.name.text === "url")) { + // `const url = import.meta.url`: the module publishes its own URL so a + // loader can import it by path (the ui-server write-procedure modules, + // whose `setup` the write worker reads). Every export is reachable. + use(file, ALL); + if (exported(statement)) for (const declaration of statement.declarationList.declarations) { + const names: string[] = []; + bindingNames(declaration.name, names); + for (const name of names) info.local.set(name, lineOf(statement)); + } + } else if (ts.isExportAssignment(statement)) { + info.local.set("default", lineOf(statement)); + } else if (exported(statement)) { + const line = lineOf(statement); + if (isDefault(statement)) info.local.set("default", line); + else if (ts.isVariableStatement(statement)) { + const names: string[] = []; + for (const declaration of statement.declarationList.declarations) bindingNames(declaration.name, names); + for (const name of names) info.local.set(name, line); + } else if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement) || ts.isInterfaceDeclaration(statement) || + ts.isTypeAliasDeclaration(statement) || ts.isEnumDeclaration(statement) || ts.isModuleDeclaration(statement)) && + statement.name && ts.isIdentifier(statement.name)) { + info.local.set(statement.name.text, line); + } + } + } + + // Uses that are not top-level statements: `import("…")`, `require("…")` + // and `import("…").Name` types, and a module loaded by path — + // `new URL("./x", import.meta.url)`, `Bun.resolveSync("./x", …)` or + // `import.meta.resolve("./x")` — whose exports a worker, a loader or + // generated source reads. A template path counts up to its first `${`. + const loadedByPath = (argument: ts.Expression | undefined) => { + const text = argument && (ts.isStringLiteralLike(argument) ? argument.text : ts.isTemplateExpression(argument) ? argument.head.text : undefined); + if (text) use(resolveSpecifier(file, text), ALL); + }; + const visit = (node: ts.Node) => { + if (ts.isCallExpression(node) && node.arguments.length > 0 && + (node.expression.kind === ts.SyntaxKind.ImportKeyword || (ts.isIdentifier(node.expression) && node.expression.text === "require"))) { + use(target(node.arguments[0]), ALL); + } else if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && + ((node.expression.name.text === "resolveSync" && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === "Bun") || + (node.expression.name.text === "resolve" && ts.isMetaProperty(node.expression.expression)))) { + loadedByPath(node.arguments[0]); + } else if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "URL" && + node.arguments?.[1] && ts.isPropertyAccessExpression(node.arguments[1]) && ts.isMetaProperty(node.arguments[1].expression)) { + loadedByPath(node.arguments[0]); + } else if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument)) { + const from = target(node.argument.literal as ts.Expression); + const qualifier = node.qualifier; + if (!qualifier) use(from, ALL); + else { + let first: ts.EntityName = qualifier; + while (ts.isQualifiedName(first)) first = first.left; + use(from, first.text); + } + } + ts.forEachChild(node, visit); + }; + visit(source); + } + return { modules, uses }; +} + +/** Every (file, name) pair some other file reaches, following re-export chains. */ +function propagate(graph: Graph, publicFiles: Iterable): Map> { + const used = new Map>(); + const queue: Array<[string, string]> = []; + const mark = (file: string, name: string) => { + let set = used.get(file); + if (!set) used.set(file, set = new Set()); + if (set.has(name) || set.has(ALL)) return; + set.add(name); + queue.push([file, name]); + }; + for (const [file, names] of graph.uses) for (const name of names) mark(file, name); + for (const file of publicFiles) mark(file, ALL); + while (queue.length > 0) { + const [file, name] = queue.pop()!; + const info = graph.modules.get(file); + if (!info) continue; + if (name === ALL) { + for (const forward of info.forwards.values()) mark(forward.file, forward.name); + for (const star of info.stars) mark(star, ALL); + continue; + } + const forward = info.forwards.get(name); + if (forward) mark(forward.file, forward.name); + else if (!info.local.has(name)) for (const star of info.stars) mark(star, name); + } + return used; +} + +/** (file, name) pairs the api-report signatures section records. */ +function reportedSignatures(root: string, pkg: string): Set { + const path = join(root, "api-report", `${pkg}.txt`); + const out = new Set(); + if (!existsSync(path)) return out; + let inSignatures = false; + for (const line of readFileSync(path, "utf8").split("\n")) { + if (/^signatures\b/.test(line)) { inSignatures = true; continue; } + if (/^\S/.test(line)) inSignatures = false; + const match = inSignatures && line.match(/^ {2}([A-Za-z_$][\w$]*) \(([^)]+)\)$/); + if (match) out.add(`${match[2]}\0${match[1]}`); + } + return out; +} + +export interface CheckOptions { + packages?: readonly string[]; + allowlist?: AllowlistEntry[]; + /** Repository-relative files to read instead of `git ls-files` (tests). */ + files?: string[]; +} + +export function check(root: string, options: CheckOptions = {}): Report { + const packages = options.packages ?? SCANNED_PACKAGES; + const allowlist = options.allowlist ?? ALLOWLIST; + const listed = options.files ?? listFiles(root); + const files = listed.filter(file => SOURCE.test(file) && !file.endsWith(".d.ts")); + const entries = packageEntries(root, listed); + const graph = buildGraph(root, files, entries); + const entryFiles = new Set(entries.values()); + const used = propagate(graph, entryFiles); + const allowed = new Map(allowlist.map(entry => [`${entry.file}\0${entry.name}`, entry])); + const findings: Finding[] = []; + const allowlisted: AllowlistEntry[] = []; + let scannedFiles = 0; + + for (const pkg of packages) { + const signatures = reportedSignatures(root, pkg); + const prefix = `packages/${pkg}/src/`; + for (const file of files) { + if (!file.startsWith(prefix) || TEST_FILE.test(file) || entryFiles.has(file)) continue; + scannedFiles++; + const info = graph.modules.get(file)!; + const reached = used.get(file) ?? new Set(); + if (reached.has(ALL)) continue; + const exports: Array<[string, number, Finding["kind"]]> = [ + ...[...info.local].map(([name, line]) => [name, line, "declaration"] as [string, number, Finding["kind"]]), + ...[...info.forwards].map(([name, f]) => [name, f.line, "re-export"] as [string, number, Finding["kind"]]), + ]; + for (const [name, line, kind] of exports) { + if (reached.has(name) || signatures.has(`${file}\0${name}`)) continue; + const entry = allowed.get(`${file}\0${name}`); + if (entry) { allowlisted.push(entry); continue; } + findings.push({ file, line, name, kind }); + } + } + } + const hit = new Set(allowlisted); + const staleAllowlist = allowlist.filter(entry => !hit.has(entry)); + findings.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line); + return { schemaVersion: 1, packages: [...packages], scannedFiles, findings, allowlisted, staleAllowlist }; +} + +if (import.meta.main) { + const args = process.argv.slice(2); + const json = args.includes("--json"); + const root = resolve(args.find(arg => !arg.startsWith("--")) ?? join(import.meta.dir, "..")); + const report = check(root); + const failed = report.findings.length > 0 || report.staleAllowlist.length > 0; + if (json) console.log(JSON.stringify(report, null, 2)); + else { + for (const f of report.findings) { + console.error(`${f.file}:${f.line}: \`${f.name}\` is exported but no other file imports it — drop the export, delete it, or allowlist it with a reason in scripts/check-unused-exports.ts`); + } + for (const entry of report.staleAllowlist) { + console.error(`scripts/check-unused-exports.ts: stale allowlist entry ${entry.file} \`${entry.name}\` — it is imported, recorded, or gone; remove the entry`); + } + if (!failed) { + console.log(`unused exports: ${report.scannedFiles} files in ${report.packages.join(", ")} clean (${report.allowlisted.length} allowlisted)`); + } + } + process.exit(failed ? 1 : 0); +} diff --git a/scripts/generated-inputs.ts b/scripts/generated-inputs.ts deleted file mode 100644 index 1861f8caa0..0000000000 --- a/scripts/generated-inputs.ts +++ /dev/null @@ -1,56 +0,0 @@ -/** Audited ephemeral producers. A producer receipt alone never resolves a consumer root. */ -import { createHash } from "node:crypto"; -import { readFileSync, realpathSync } from "node:fs"; -import { resolve } from "node:path"; -import ts from "typescript"; -export interface GeneratedProducer { - owner: string; root: string; expression: string; -} -export interface ProducerReceipt { - owner: string; root: string; relativePath: string; contentDigest: string; - producerDigest: string; consumerBound: false; -} -/** Only fixed literal bytes in a newly owned temp root; external/parameter roots do not qualify. */ -export function inspectGeneratedProducer(root: string, binding: GeneratedProducer): ProducerReceipt { - if (binding.owner.includes("..") || binding.owner.startsWith("/") || !/^[A-Za-z_$][\w$]*$/.test(binding.root)) throw Error("Invalid generated producer identity"); - const path = resolve(root, binding.owner); - if (!/\.[cm]?[jt]sx?$/.test(binding.owner) || realpathSync(path) !== path) throw Error("Unsupported generated producer source"); - const source = readFileSync(path, "utf8"), ast = ts.createSourceFile(binding.owner, source, ts.ScriptTarget.Latest, true); - if ((ast as ts.SourceFile & { parseDiagnostics: readonly ts.Diagnostic[] }).parseDiagnostics.length) throw Error("Invalid generated producer source"); - const imports = new Map(), declarations: ts.VariableDeclaration[] = [], calls: ts.CallExpression[] = []; - for (const statement of ast.statements) if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) { - const module = statement.moduleSpecifier.text.replace(/^node:/, ""), names = statement.importClause?.namedBindings; - if (names && ts.isNamedImports(names)) for (const element of names.elements) imports.set(element.name.text, `${module}:${element.propertyName?.text ?? element.name.text}`); - } - const walk = (node: ts.Node) => { if (ts.isVariableDeclaration(node)) declarations.push(node); if (ts.isCallExpression(node)) calls.push(node); ts.forEachChild(node, walk); }; - walk(ast); - const named = (node: ts.Node | undefined, name: string) => Boolean(node && ts.isIdentifier(node) && node.text === name); - const imported = (node: ts.Node | undefined, identity: string) => Boolean(node && ts.isIdentifier(node) && imports.get(node.text) === identity); - const rootDeclarations = declarations.filter(node => named(node.name, binding.root)); - const rootDeclaration = rootDeclarations[0], initializer = rootDeclaration?.initializer; - if (rootDeclarations.length !== 1 || !initializer || !ts.isCallExpression(initializer) || !imported(initializer.expression, "fs:mkdtempSync") || initializer.arguments.length !== 1) throw Error("Generated producer requires one owned mkdtemp root"); - if (!(rootDeclaration.parent.flags & ts.NodeFlags.Const)) throw Error("Generated root must be immutable"); - const temp = initializer.arguments[0]; - if (!temp || !ts.isCallExpression(temp) || !imported(temp.expression, "path:join") || temp.arguments.length !== 2 || !ts.isCallExpression(temp.arguments[0]!) || !imported(temp.arguments[0]!.expression, "os:tmpdir") || !ts.isStringLiteral(temp.arguments[1]!) || !/^[A-Za-z0-9-]+$/.test(temp.arguments[1]!.text)) throw Error("Generated root is not a bounded fresh temporary directory"); - const matching = calls.filter(node => node.getText(ast) === binding.expression); - if (matching.length !== 1) throw Error("Missing or ambiguous generated producer call"); - const call = matching[0]!; - const functionOwner = (node: ts.Node) => { for (let parent = node.parent; parent; parent = parent.parent) if (ts.isFunctionDeclaration(parent) || ts.isFunctionExpression(parent) || ts.isArrowFunction(parent)) return parent; }; - if (functionOwner(call) !== functionOwner(rootDeclaration)) throw Error("Generated producer call has another root scope"); - if (!ts.isIdentifier(call.expression) || call.arguments.length !== 2 || !ts.isStringLiteral(call.arguments[0]!) || !ts.isStringLiteral(call.arguments[1]!)) throw Error("Generated producer must write literal path and bytes"); - const relativePath = call.arguments[0]!.text, content = call.arguments[1]!.text; - if (!relativePath || relativePath.startsWith("/") || relativePath.split("/").some(part => !part || part === "." || part === "..") || /[\\\r\n\0]/.test(relativePath)) throw Error("Generated path escapes its owned root"); - const writers = declarations.filter(node => named(node.name, call.expression.getText(ast))); - const writer = writers[0]?.initializer; - if (writers.length !== 1 || !writer || !ts.isArrowFunction(writer) || writer.parameters.length !== 2 || !ts.isIdentifier(writer.parameters[0]!.name) || !ts.isIdentifier(writer.parameters[1]!.name)) throw Error("Unsupported generated writer binding"); - if (writers[0]!.parent.parent.parent !== rootDeclaration.parent.parent.parent || !(writers[0]!.parent.flags & ts.NodeFlags.Const)) throw Error("Generated writer and root have different lexical owners"); - if (writer.parameters.some(parameter => named(parameter.name, binding.root))) throw Error("Generated writer shadows its owned root"); - const writes: ts.CallExpression[] = []; - const collect = (node: ts.Node) => { if (ts.isCallExpression(node) && imported(node.expression, "fs:writeFileSync")) writes.push(node); ts.forEachChild(node, collect); }; - collect(writer.body); - const write = writes[0], target = write?.arguments[0]; - if (writes.length !== 1 || !write || write.arguments.length !== 2 || !named(write.arguments[1], writer.parameters[1]!.name.text) || !target || !ts.isCallExpression(target) || !imported(target.expression, "path:join") || target.arguments.length !== 2 || !named(target.arguments[0], binding.root) || !named(target.arguments[1], writer.parameters[0]!.name.text)) throw Error("Generated writer does not preserve its root/path/bytes binding"); - return { owner: binding.owner, root: binding.root, relativePath, - contentDigest: createHash("sha256").update(content).digest("hex"), - producerDigest: createHash("sha256").update(source).digest("hex"), consumerBound: false }; -} diff --git a/scripts/lint.ts b/scripts/lint.ts index 88c3010247..ead06c18bd 100644 --- a/scripts/lint.ts +++ b/scripts/lint.ts @@ -21,6 +21,7 @@ const LINTS = [ "check-raw-buttons.ts", // raw