Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.50.0.0 fix: secure client consent, background jobs, and data handling (#5027)
Garry Tana6be012a3bcf
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex e64548f965..fdcd57dcfa 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.49.0.0",+ "version": "0.50.0.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 5c957810c0..cfaf9488cf 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.49.0.0",+ "version": "0.50.0.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex f92f9e7fa1..b774e69e8a 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -56,6 +56,8 @@ jobs:tar -xzf "/tmp/gitleaks-dl/${BASE}" -C /tmp gitleaksinstall /tmp/gitleaks /usr/local/bin/gitleaksgitleaks version+ - name: Verify scanner detects secrets outside exact fixture exceptions+ run: bash scripts/test-gitleaks-config.sh- name: Scan for secrets (gitleaks CLI, .gitleaks.toml)run: |set -euo pipefail@@ -71,6 +73,40 @@ jobs:echo "Scanning commit range: $RANGE"gitleaks detect --redact --no-banner --log-opts "$RANGE"+ security-regressions:+ runs-on: ${{ matrix.os }}+ timeout-minutes: 10+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-latest, macos-latest, windows-latest]+ bun: ['1.3.11', '1.3.13']+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: ${{ matrix.bun }}+ - run: bun install --frozen-lockfile --ignore-scripts+ - name: Boundary and transport regressions+ run: bun test --timeout 60000 test/frontmatter-security.test.ts test/data-frontmatter.test.ts test/authorization-boundaries.test.ts test/url-safety.test.ts test/guarded-http.test.ts+ - name: Isolated TLS and proxy regressions+ run: bun test --timeout 60000 test/guarded-http-tls.serial.test.ts++ dependency-audit:+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: 1.3.13+ - run: bun install --frozen-lockfile --ignore-scripts+ - run: bun audit+ - run: bun install --frozen-lockfile --ignore-scripts+ working-directory: admin+ - run: bun audit+ working-directory: admin+verify:# Pre-test gates: privacy/jsonb/source-id/etc + typecheck + admin-build.# Lives in its own runner so the matrix shards aren't carrying ~2-3min@@ -493,7 +529,7 @@ jobs:# The stable aggregate succeeds only when every required lane ran successfully.# Coverage percentages remain advisory until their separate graduation.test-status:- needs: [gitleaks, verify, serial-tests, slow-eval-longmemeval, slow-entity-resolve-perf, slow-brainbench-e2e, brainbench, test]+ needs: [gitleaks, security-regressions, dependency-audit, verify, serial-tests, slow-eval-longmemeval, slow-entity-resolve-perf, slow-brainbench-e2e, brainbench, test]if: always()runs-on: ubuntu-latesttimeout-minutes: 5@@ -501,6 +537,8 @@ jobs:- name: Aggregate resultrun: |GITLEAKS="${{ needs.gitleaks.result }}"+ SECURITY="${{ needs.security-regressions.result }}"+ AUDIT="${{ needs.dependency-audit.result }}"VERIFY="${{ needs.verify.result }}"SERIAL="${{ needs.serial-tests.result }}"SLOW_EVAL="${{ needs.slow-eval-longmemeval.result }}"@@ -508,8 +546,8 @@ jobs:SLOW_BRAINBENCH="${{ needs.slow-brainbench-e2e.result }}"BRAINBENCH="${{ needs.brainbench.result }}"TEST="${{ needs.test.result }}"- echo "gitleaks=$GITLEAKS verify=$VERIFY serial-tests=$SERIAL slow-eval-longmemeval=$SLOW_EVAL slow-entity-resolve-perf=$SLOW_PERF slow-brainbench-e2e=$SLOW_BRAINBENCH brainbench=$BRAINBENCH test=$TEST"- for r in "$GITLEAKS" "$VERIFY" "$SERIAL" "$SLOW_EVAL" "$SLOW_PERF" "$SLOW_BRAINBENCH" "$BRAINBENCH" "$TEST"; do+ echo "gitleaks=$GITLEAKS security-regressions=$SECURITY dependency-audit=$AUDIT verify=$VERIFY serial-tests=$SERIAL slow-eval-longmemeval=$SLOW_EVAL slow-entity-resolve-perf=$SLOW_PERF slow-brainbench-e2e=$SLOW_BRAINBENCH brainbench=$BRAINBENCH test=$TEST"+ for r in "$GITLEAKS" "$SECURITY" "$AUDIT" "$VERIFY" "$SERIAL" "$SLOW_EVAL" "$SLOW_PERF" "$SLOW_BRAINBENCH" "$BRAINBENCH" "$TEST"; doif [ "$r" != "success" ]; thenecho "✗ gated job did not succeed (got $r) — CI fail"exit 1diff --git a/.gitleaks.toml b/.gitleaks.tomlindex 413f31b71f..2bec03e5b5 100644--- a/.gitleaks.toml+++ b/.gitleaks.toml@@ -1,11 +1,63 @@title = "GBrain gitleaks config"-[allowlist]+[extend]+useDefault = true++[[allowlists]]+description = "Documented nonfunctional environment examples"paths = [- '''.env\.testing\.example''',- '''.env\.example''',- '''test/''',- '''skills/''',- '''.claude/skills/''',- '''GBRAIN_SKILLPACK\.md''',+ # These tracked files contain documented, nonfunctional configuration examples.+ '''^\.env\.testing\.example$''',+ '''^\.env\.example$''',+ # Public upstream localhost-only TLS fixture, never a deployed credential.+ '''^test/fixtures/guarded-http-localhost\.key$''',]++[[allowlists]]+description = "Exact nonfunctional credentials used by authentication and redaction tests"+targetRules = ["generic-api-key", "aws-access-token", "github-pat", "jwt", "openai-api-key"]+condition = "AND"+paths = [+ '''^test/(auth-register-client-output-pin|claw-test-cli|config|config-get-plane|google-access|google-auth|mcp-registration-blocks|secret-scan|session-receipts|tty-harness|transcript-render)\.test\.ts$''',+ '''^test/creds-vault\.serial\.test\.ts$''',+ '''^test/e2e/transcripts-ingest-pglite\.test\.ts$''',+ '''^\.claude/skills/gstack/(browse/test/commands|test/skill-e2e-cso)\.test\.ts$''',+]+regexTarget = "secret"+# The AWS fixture uses a character class so this exact match does not itself+# resemble a credential to other scanners. The accepted fixture is unchanged.+regexes = [+ '''^(gbrain_cs_secret456|or-sentinel-91c4|eyJhbGciOiJIUzI1NiJ9|ghp-test3943-db-secret|GOCSPX-test1234567890|GOCSPX-abc123|tok-abcdef123|sekret_xyz789|aB3xK9mQ2pR7|K9fjq2LmX0pQ7rTz|Ab3xK9mQ2pR7sT1vW4yZ8bC5dE6f|straddling-secret-99|AKI[A]ABCDEFGHIJKLMNOP|ghp_abc123def456|sk-1234567890abcdef1234567890abcdef)$''',+]++[[allowlists]]+description = "SQL column and prose identifiers misclassified as API keys"+targetRules = ["generic-api-key"]+condition = "AND"+paths = ['''^src/(schema\.sql|core/(pglite-schema|schema-embedded(?:\.generated)?|link-extraction)\.ts)$''']+regexTarget = "secret"+regexes = ['''^(receipt_sha8_corpus|raw/lower/slugified)$''']++[[allowlists]]+description = "Generated admin curl example reads the secret from an environment variable"+targetRules = ["generic-api-key"]+condition = "AND"+paths = ['''^admin/dist/assets/index-[A-Za-z0-9_-]+\.js$''']+regexTarget = "match"+regexes = ['''client_secret=\$GBRAIN_CS''']++[[allowlists]]+description = "Literal placeholders in generated admin curl instructions"+targetRules = ["curl-auth-header"]+condition = "AND"+paths = ['''^admin/dist/assets/index-[A-Za-z0-9_-]+\.js$''']+regexTarget = "secret"+regexes = ['''^(PASTE_TOKEN_FROM_ABOVE|PASTE_YOUR_API_KEY_HERE)$''']++[[allowlists]]+description = "Upstream telemetry's explicitly public Supabase publishable key; never a service-role key"+targetRules = ["generic-api-key"]+condition = "AND"+paths = ['''^\.claude/skills/gstack/supabase/config\.sh$''']+regexTarget = "secret"+regexes = ['''^sb_publishable_[A-Za-z0-9_-]+$''']diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex a867e7a656..d04d22825e 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.49.0.0 -->+<!-- gbrain-runbook-stamp: 0.50.0.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ee667c95e6..10e73d890f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,56 @@All notable changes to GBrain will be documented in this file.+## [0.50.0.0] - 2026-09-10++**Approve client connection requests and keep background work within the access you granted.**++New authorization-code connections now bring you to the existing admin login to review the client, destination, permissions and source before approving. Existing active sessions stay signed in. Background work keeps the authority it was accepted with and checks current permissions before starting, so a later permission change takes effect on pending work.++This release also tightens document handling and outbound requests. Your notes retain their existing metadata types and formatting behavior. Imports report rejected documents as errors and keep useful retry checkpoints. There is no bulk rewrite, reindex or content migration.++### What to expect++| When you… | What happens |+|---|---|+| Start an authorization-code connection | Review its requested access in the admin page, then approve or deny. |+| Upgrade an existing installation | Keep active sessions; stop services and explicitly review pending work before restarting. |+| Submit background filesystem work remotely | Use the registered source with the supported sync, import and lint parameters. |+| Check URLs or load remote images | Use bounded direct requests; remove ambient proxy settings for these operations. |++### Things to watch++The minimum Bun version is **1.3.11**. Builds use **1.3.13**, and CI tests both versions. This release requires a coordinated queue cutover: pause ingress, producers and automatic upgraders; drain active work; stop the remaining services and back up; then install matching versions and review or cancel nonterminal legacy jobs. Do not run old and new workers together. Read the [authorization upgrade guide](docs/guides/authorization-upgrade.md) before upgrading an existing installation.++## To take advantage of v0.50.0.0++**Say to your agent:** *“Help me upgrade GBrain and review pending jobs before restarting services.”* Your agent follows `skills/migrations/v0.50.0.0.md` and the authorization upgrade guide.++With the backup verified and all services stopped, install the chosen release+without starting its setup phases. Published binary installations use+`gbrain upgrade --swap-only`; Bun installations must follow the guide's+`--ignore-scripts` path. Then apply only schema migrations:++```bash+gbrain --version+gbrain apply-migrations --force-schema --yes+gbrain jobs list --json+```++Preview only selected legacy job IDs with `gbrain jobs authorize-legacy --ids <ids> --json`. Apply the reviewed snapshot only with its digest and `--yes`, or cancel unwanted jobs. Resolve all nonterminal legacy work before restarting the new services. If migration or review fails, keep services stopped and follow the guide's recovery steps. Verify with `gbrain doctor` and the existing admin agent-management page; report upgrade problems without posting credentials or private content.++### Itemized changes++- New authorization-code connections use owner consent through the existing admin authentication flow. Grant issuance, replacement and client revocation share transactional enforcement while preserving active sessions.+- Background jobs retain immutable submission authority through queue lifecycle operations. Migration 149 and the explicit legacy-review command support coordinated upgrades.+- Generic remote filesystem jobs use registered roots and constrained parameters. Delegated tools and source grants follow the same authorization boundaries as direct operations.+- Shared data-only frontmatter handling preserves ordinary YAML/JSON behavior. CLI and queued imports report parse failures accurately.+- Outbound status checks and image requests share destination validation, bounded decoding and a single deadline. Error diagnostics omit caller credentials and content.++### For contributors++Dependency patches cover the root application and admin audit gates. CI checks supported Bun versions, trust-boundary regressions and narrowly documented secret-scanner fixtures.+## [0.49.0.0] - 2026-09-10**Add GBrain memory to the agent you already use, or connect that agent todiff --git a/README.md b/README.mdindex 6b24f44c54..8e6cae6dde 100644--- a/README.md+++ b/README.md@@ -72,6 +72,10 @@ This is the difference between a search engine and a brain. Search finds the pag## Install+Requires **Bun 1.3.11 or newer**. Existing worker installations should follow the+[authorization and queue upgrade guide](docs/guides/authorization-upgrade.md)+before restarting services with this version.+> [!WARNING]> **GBrain is NOT distributed on npm.** The npm package named `gbrain` is an unrelated> package with no connection to this project. Do not run `npm install -g gbrain` ordiff --git a/SECURITY.md b/SECURITY.mdindex 56cec2677f..7b9269ce9f 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -153,6 +153,18 @@ grant is allowed. Pre-registering clients via the CLI / admin API is unchanged.### Token Management+New authorization-code connections require owner approval in the admin UI and+S256 PKCE for public and confidential clients. Consent requests expire after+ten minutes; restart the client connection after expiry or a server restart.+Existing active-client sessions remain valid. Review and revoke unwanted+clients in the existing Agents page.++Queued work also retains its submitting authority and is revalidated before+execution. Worker upgrades require a stopped-service cutover; see the+[authorization and worker upgrade guide](docs/guides/authorization-upgrade.md)+before migrating an existing queue. That guide also covers the Bun 1.3.11+minimum and guarded outbound connections.+```bashgbrain auth create "claude-desktop" # Create a new tokengbrain auth list # List all tokensdiff --git a/TODOS.md b/TODOS.mdindex 5f14fe794f..992185227b 100644--- a/TODOS.md+++ b/TODOS.md@@ -4,9 +4,6 @@- [ ] **P2 — bump MARKDOWN_CHUNKER_VERSION to 5 so already-indexed CJK-dominant pages pick up the CJK overlap fix.****What:** #4871 (wave adoption) made `extractTrailingContext` count chars for CJK-dominant chunks (the unit `countCJKAwareWords` uses) instead of whitespace tokens, so CJK pages get a real, bounded overlap instead of none / a near-total duplicate; the L4 char-slice fallback also stopped halving astral pairs. Both change chunk boundaries for CJK-dominant text only and apply to pages chunked from now on — pages already in the index keep their old boundaries until the chunker version moves. **How:** `export const MARKDOWN_CHUNKER_VERSION = 5;` in `src/core/chunkers/recursive.ts`, DECOUPLED from `SAFE_FENCE_CHUNKER_VERSION` (stays 4 as the safe-chunks provenance floor; `safeChunksFilter` is `>= 4`, so 5 passes); update the `MARKDOWN_CHUNKER_VERSION is 4` pin in `test/chunkers/recursive.test.ts`. **Cost (why this is a maintainer decision, not a fix-wave change):** the post-upgrade sweep re-chunks AND re-embeds every markdown page in every brain (markdown import has no embedding reuse) — the same full-brain re-embed shape as the v4 bump in 0.48.3.0, for a boundary change that only affects CJK-dominant pages. Coalescing it with the next planned chunker bump spares a standalone sweep. English output is byte-identical (pinned by `test/chunkers/recursive-cjk-overlap.test.ts`). **Effort:** S.-## Community fix wave follow-ups (filed 2026-09-07, sync-import train)-- [ ] **P3 — `gbrain import` human summary labels returned per-file failures as "unchanged".**- **What:** the non-`--json` summary line in `src/commands/import.ts` prints `${skipped - errors} unchanged`, but `skipped` also counts the failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) while `errors` counts only the thrown ones, so a returned failure reads as an unchanged no-op. The `--json` payload was fixed in #4803 (`unchanged` / `malformed_skipped` / `failures`); the human line was deliberately left alone in that wave. **How:** reuse the same `skipped - failures.length - malformedFileSkips` arithmetic and print the returned-failure count as its own term. **Effort:** S. **Priority:** P3.## Community fix wave follow-ups (filed 2026-09-07, minions-autopilot train)- [ ] **P3 — pglite-lock `readProcessArgs` has the same win32 gap as #4563, failing the other way.** **What:** `src/core/pglite-lock.ts` `readProcessArgs` probes `ps` then `/proc` with no Windows branch; on win32 it returns null, which that caller treats as "unknowable => alive", so a recycled-pid PGLite lock is never reaped and `acquire` waits out its timeout instead of stealing. Distinct symptom from the autopilot classifier (which now has the CIM branch in `src/core/autopilot-lock.ts` `readProcessCommand`). **How:** route `readProcessArgs` through the shared `readProcessCommand(pid)` (already handles /proc, ps, and win32 CIM) and delete the duplicate probe. **Effort:** S. **Priority:** P3.@@ -7116,6 +7113,14 @@ keeping both skills' triggers intact for chaining.## Completed+### ~~Report returned import failures accurately in the human summary~~+**Completed:** v0.50.0.0 (2026-09-10)++The human and JSON summaries distinguish unchanged files, malformed files, and+returned or thrown failures. Imports report errors with a nonzero exit and+preserve retry checkpoints; queued imports also fail when documents are rejected.+Covered by the import stdout/checkpoint and queued-import error regressions.+- [x] **P2 — archived sources keep previously-granted federated reads untilre-registration.** **What:** grants are validated at mint time only — aclient whose `federated_read` names a source that is archived AFTERdiff --git a/VERSION b/VERSIONindex f44b94e1c1..d7c2f20c92 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.49.0.0+0.50.0.0diff --git a/admin/dist/assets/index-B5gNvpC1.js b/admin/dist/assets/index-B5gNvpC1.jsdeleted file mode 100644index 5bb9faa2e8..0000000000--- a/admin/dist/assets/index-B5gNvpC1.js+++ /dev/null@@ -1,52 +0,0 @@-(function(){const E=document.createElement("link").relList;if(E&&E.supports&&E.supports("modulepreload"))return;for(const D of document.querySelectorAll('link[rel="modulepreload"]'))r(D);new MutationObserver(D=>{for(const _ of D)if(_.type==="childList")for(const H of _.addedNodes)H.tagName==="LINK"&&H.rel==="modulepreload"&&r(H)}).observe(document,{childList:!0,subtree:!0});function T(D){const _={};return D.integrity&&(_.integrity=D.integrity),D.referrerPolicy&&(_.referrerPolicy=D.referrerPolicy),D.crossOrigin==="use-credentials"?_.credentials="include":D.crossOrigin==="anonymous"?_.credentials="omit":_.credentials="same-origin",_}function r(D){if(D.ep)return;D.ep=!0;const _=T(D);fetch(D.href,_)}})();function Cd(f){return f&&f.__esModule&&Object.prototype.hasOwnProperty.call(f,"default")?f.default:f}var sf={exports:{}},zn={};/**- * @license React- * react-jsx-runtime.production.js- *- * Copyright (c) Meta Platforms, Inc. and affiliates.- *- * This source code is licensed under the MIT license found in the- * LICENSE file in the root directory of this source tree.- */var bd;function fy(){if(bd)return zn;bd=1;var f=Symbol.for("react.transitional.element"),E=Symbol.for("react.fragment");function T(r,D,_){var H=null;if(_!==void 0&&(H=""+_),D.key!==void 0&&(H=""+D.key),"key"in D){_={};for(var G in D)G!=="key"&&(_[G]=D[G])}else _=D;return D=_.ref,{$$typeof:f,type:r,key:H,ref:D!==void 0?D:null,props:_}}return zn.Fragment=E,zn.jsx=T,zn.jsxs=T,zn}var Sd;function sy(){return Sd||(Sd=1,sf.exports=fy()),sf.exports}var c=sy(),of={exports:{}},K={};/**- * @license React- * react.production.js- *- * Copyright (c) Meta Platforms, Inc. and affiliates.- *- * This source code is licensed under the MIT license found in the- * LICENSE file in the root directory of this source tree.- */var xd;function oy(){if(xd)return K;xd=1;var f=Symbol.for("react.transitional.element"),E=Symbol.for("react.portal"),T=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),D=Symbol.for("react.profiler"),_=Symbol.for("react.consumer"),H=Symbol.for("react.context"),G=Symbol.for("react.forward_ref"),O=Symbol.for("react.suspense"),h=Symbol.for("react.memo"),C=Symbol.for("react.lazy"),M=Symbol.for("react.activity"),N=Symbol.iterator;function w(m){return m===null||typeof m!="object"?null:(m=N&&m[N]||m["@@iterator"],typeof m=="function"?m:null)}var J={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},il=Object.assign,jl={};function ul(m,A,R){this.props=m,this.context=A,this.refs=jl,this.updater=R||J}ul.prototype.isReactComponent={},ul.prototype.setState=function(m,A){if(typeof m!="object"&&typeof m!="function"&&m!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,m,A,"setState")},ul.prototype.forceUpdate=function(m){this.updater.enqueueForceUpdate(this,m,"forceUpdate")};function k(){}k.prototype=ul.prototype;function Z(m,A,R){this.props=m,this.context=A,this.refs=jl,this.updater=R||J}var Tl=Z.prototype=new k;Tl.constructor=Z,il(Tl,ul.prototype),Tl.isPureReactComponent=!0;var wl=Array.isArray;function Hl(){}var al={H:null,A:null,T:null,S:null},kl=Object.prototype.hasOwnProperty;function _e(m,A,R){var q=R.ref;return{$$typeof:f,type:m,key:A,ref:q!==void 0?q:null,props:R}}function Lt(m,A){return _e(m.type,A,m.props)}function Oe(m){return typeof m=="object"&&m!==null&&m.$$typeof===f}function Wl(m){var A={"=":"=0",":":"=2"};return"$"+m.replace(/[=:]/g,function(R){return A[R]})}var zt=/\/+/g;function Ue(m,A){return typeof m=="object"&&m!==null&&m.key!=null?Wl(""+m.key):A.toString(36)}function ze(m){switch(m.status){case"fulfilled":return m.value;case"rejected":throw m.reason;default:switch(typeof m.status=="string"?m.then(Hl,Hl):(m.status="pending",m.then(function(A){m.status==="pending"&&(m.status="fulfilled",m.value=A)},function(A){m.status==="pending"&&(m.status="rejected",m.reason=A)})),m.status){case"fulfilled":return m.value;case"rejected":throw m.reason}}throw m}function x(m,A,R,q,W){var I=typeof m;(I==="undefined"||I==="boolean")&&(m=null);var ol=!1;if(m===null)ol=!0;else switch(I){case"bigint":case"string":case"number":ol=!0;break;case"object":switch(m.$$typeof){case f:case E:ol=!0;break;case C:return ol=m._init,x(ol(m._payload),A,R,q,W)}}if(ol)return W=W(m),ol=q===""?"."+Ue(m,0):q,wl(W)?(R="",ol!=null&&(R=ol.replace(zt,"$&/")+"/"),x(W,A,R,"",function(Na){return Na})):W!=null&&(Oe(W)&&(W=Lt(W,R+(W.key==null||m&&m.key===W.key?"":(""+W.key).replace(zt,"$&/")+"/")+ol)),A.push(W)),1;ol=0;var Kl=q===""?".":q+":";if(wl(m))for(var _l=0;_l<m.length;_l++)q=m[_l],I=Kl+Ue(q,_l),ol+=x(q,A,R,I,W);else if(_l=w(m),typeof _l=="function")for(m=_l.call(m),_l=0;!(q=m.next()).done;)q=q.value,I=Kl+Ue(q,_l++),ol+=x(q,A,R,I,W);else if(I==="object"){if(typeof m.then=="function")return x(ze(m),A,R,q,W);throw A=String(m),Error("Objects are not valid as a React child (found: "+(A==="[object Object]"?"object with keys {"+Object.keys(m).join(", ")+"}":A)+"). If you meant to render a collection of children, use an array instead.")}return ol}function U(m,A,R){if(m==null)return m;var q=[],W=0;return x(m,q,"","",function(I){return A.call(R,I,W++)}),q}function V(m){if(m._status===-1){var A=m._result;A=A(),A.then(function(R){(m._status===0||m._status===-1)&&(m._status=1,m._result=R)},function(R){(m._status===0||m._status===-1)&&(m._status=2,m._result=R)}),m._status===-1&&(m._status=0,m._result=A)}if(m._status===1)return m._result.default;throw m._result}var hl=typeof reportError=="function"?reportError:function(m){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var A=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof m=="object"&&m!==null&&typeof m.message=="string"?String(m.message):String(m),error:m});if(!window.dispatchEvent(A))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",m);return}console.error(m)},gl={map:U,forEach:function(m,A,R){U(m,function(){A.apply(this,arguments)},R)},count:function(m){var A=0;return U(m,function(){A++}),A},toArray:function(m){return U(m,function(A){return A})||[]},only:function(m){if(!Oe(m))throw Error("React.Children.only expected to receive a single React element child.");return m}};return K.Activity=M,K.Children=gl,K.Component=ul,K.Fragment=T,K.Profiler=D,K.PureComponent=Z,K.StrictMode=r,K.Suspense=O,K.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=al,K.__COMPILER_RUNTIME={__proto__:null,c:function(m){return al.H.useMemoCache(m)}},K.cache=function(m){return function(){return m.apply(null,arguments)}},K.cacheSignal=function(){return null},K.cloneElement=function(m,A,R){if(m==null)throw Error("The argument must be a React element, but you passed "+m+".");var q=il({},m.props),W=m.key;if(A!=null)for(I in A.key!==void 0&&(W=""+A.key),A)!kl.call(A,I)||I==="key"||I==="__self"||I==="__source"||I==="ref"&&A.ref===void 0||(q[I]=A[I]);var I=arguments.length-2;if(I===1)q.children=R;else if(1<I){for(var ol=Array(I),Kl=0;Kl<I;Kl++)ol[Kl]=arguments[Kl+2];q.children=ol}return _e(m.type,W,q)},K.createContext=function(m){return m={$$typeof:H,_currentValue:m,_currentValue2:m,_threadCount:0,Provider:null,Consumer:null},m.Provider=m,m.Consumer={$$typeof:_,_context:m},m},K.createElement=function(m,A,R){var q,W={},I=null;if(A!=null)for(q in A.key!==void 0&&(I=""+A.key),A)kl.call(A,q)&&q!=="key"&&q!=="__self"&&q!=="__source"&&(W[q]=A[q]);var ol=arguments.length-2;if(ol===1)W.children=R;else if(1<ol){for(var Kl=Array(ol),_l=0;_l<ol;_l++)Kl[_l]=arguments[_l+2];W.children=Kl}if(m&&m.defaultProps)for(q in ol=m.defaultProps,ol)W[q]===void 0&&(W[q]=ol[q]);return _e(m,I,W)},K.createRef=function(){return{current:null}},K.forwardRef=function(m){return{$$typeof:G,render:m}},K.isValidElement=Oe,K.lazy=function(m){return{$$typeof:C,_payload:{_status:-1,_result:m},_init:V}},K.memo=function(m,A){return{$$typeof:h,type:m,compare:A===void 0?null:A}},K.startTransition=function(m){var A=al.T,R={};al.T=R;try{var q=m(),W=al.S;W!==null&&W(R,q),typeof q=="object"&&q!==null&&typeof q.then=="function"&&q.then(Hl,hl)}catch(I){hl(I)}finally{A!==null&&R.types!==null&&(A.types=R.types),al.T=A}},K.unstable_useCacheRefresh=function(){return al.H.useCacheRefresh()},K.use=function(m){return al.H.use(m)},K.useActionState=function(m,A,R){return al.H.useActionState(m,A,R)},K.useCallback=function(m,A){return al.H.useCallback(m,A)},K.useContext=function(m){return al.H.useContext(m)},K.useDebugValue=function(){},K.useDeferredValue=function(m,A){return al.H.useDeferredValue(m,A)},K.useEffect=function(m,A){return al.H.useEffect(m,A)},K.useEffectEvent=function(m){return al.H.useEffectEvent(m)},K.useId=function(){return al.H.useId()},K.useImperativeHandle=function(m,A,R){return al.H.useImperativeHandle(m,A,R)},K.useInsertionEffect=function(m,A){return al.H.useInsertionEffect(m,A)},K.useLayoutEffect=function(m,A){return al.H.useLayoutEffect(m,A)},K.useMemo=function(m,A){return al.H.useMemo(m,A)},K.useOptimistic=function(m,A){return al.H.useOptimistic(m,A)},K.useReducer=function(m,A,R){return al.H.useReducer(m,A,R)},K.useRef=function(m){return al.H.useRef(m)},K.useState=function(m){return al.H.useState(m)},K.useSyncExternalStore=function(m,A,R){return al.H.useSyncExternalStore(m,A,R)},K.useTransition=function(){return al.H.useTransition()},K.version="19.2.5",K}var jd;function vf(){return jd||(jd=1,of.exports=oy()),of.exports}var Y=vf();const Ud=Cd(Y);var rf={exports:{}},Tn={},df={exports:{}},hf={};/**- * @license React- * scheduler.production.js- *- * Copyright (c) Meta Platforms, Inc. and affiliates.- *- * This source code is licensed under the MIT license found in the- * LICENSE file in the root directory of this source tree.- */var zd;function ry(){return zd||(zd=1,(function(f){function E(x,U){var V=x.length;x.push(U);l:for(;0<V;){var hl=V-1>>>1,gl=x[hl];if(0<D(gl,U))x[hl]=U,x[V]=gl,V=hl;else break l}}function T(x){return x.length===0?null:x[0]}function r(x){if(x.length===0)return null;var U=x[0],V=x.pop();if(V!==U){x[0]=V;l:for(var hl=0,gl=x.length,m=gl>>>1;hl<m;){var A=2*(hl+1)-1,R=x[A],q=A+1,W=x[q];if(0>D(R,V))q<gl&&0>D(W,R)?(x[hl]=W,x[q]=V,hl=q):(x[hl]=R,x[A]=V,hl=A);else if(q<gl&&0>D(W,V))x[hl]=W,x[q]=V,hl=q;else break l}}return U}function D(x,U){var V=x.sortIndex-U.sortIndex;return V!==0?V:x.id-U.id}if(f.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var _=performance;f.unstable_now=function(){return _.now()}}else{var H=Date,G=H.now();f.unstable_now=function(){return H.now()-G}}var O=[],h=[],C=1,M=null,N=3,w=!1,J=!1,il=!1,jl=!1,ul=typeof setTimeout=="function"?setTimeout:null,k=typeof clearTimeout=="function"?clearTimeout:null,Z=typeof setImmediate<"u"?setImmediate:null;function Tl(x){for(var U=T(h);U!==null;){if(U.callback===null)r(h);else if(U.startTime<=x)r(h),U.sortIndex=U.expirationTime,E(O,U);else break;U=T(h)}}function wl(x){if(il=!1,Tl(x),!J)if(T(O)!==null)J=!0,Hl||(Hl=!0,Wl());else{var U=T(h);U!==null&&ze(wl,U.startTime-x)}}var Hl=!1,al=-1,kl=5,_e=-1;function Lt(){return jl?!0:!(f.unstable_now()-_e<kl)}function Oe(){if(jl=!1,Hl){var x=f.unstable_now();_e=x;var U=!0;try{l:{J=!1,il&&(il=!1,k(al),al=-1),w=!0;var V=N;try{e:{for(Tl(x),M=T(O);M!==null&&!(M.expirationTime>x&&Lt());){var hl=M.callback;if(typeof hl=="function"){M.callback=null,N=M.priorityLevel;var gl=hl(M.expirationTime<=x);if(x=f.unstable_now(),typeof gl=="function"){M.callback=gl,Tl(x),U=!0;break e}M===T(O)&&r(O),Tl(x)}else r(O);M=T(O)}if(M!==null)U=!0;else{var m=T(h);m!==null&&ze(wl,m.startTime-x),U=!1}}break l}finally{M=null,N=V,w=!1}U=void 0}}finally{U?Wl():Hl=!1}}}var Wl;if(typeof Z=="function")Wl=function(){Z(Oe)};else if(typeof MessageChannel<"u"){var zt=new MessageChannel,Ue=zt.port2;zt.port1.onmessage=Oe,Wl=function(){Ue.postMessage(null)}}else Wl=function(){ul(Oe,0)};function ze(x,U){al=ul(function(){x(f.unstable_now())},U)}f.unstable_IdlePriority=5,f.unstable_ImmediatePriority=1,f.unstable_LowPriority=4,f.unstable_NormalPriority=3,f.unstable_Profiling=null,f.unstable_UserBlockingPriority=2,f.unstable_cancelCallback=function(x){x.callback=null},f.unstable_forceFrameRate=function(x){0>x||125<x?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):kl=0<x?Math.floor(1e3/x):5},f.unstable_getCurrentPriorityLevel=function(){return N},f.unstable_next=function(x){switch(N){case 1:case 2:case 3:var U=3;break;default:U=N}var V=N;N=U;try{return x()}finally{N=V}},f.unstable_requestPaint=function(){jl=!0},f.unstable_runWithPriority=function(x,U){switch(x){case 1:case 2:case 3:case 4:case 5:break;default:x=3}var V=N;N=x;try{return U()}finally{N=V}},f.unstable_scheduleCallback=function(x,U,V){var hl=f.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0<V?hl+V:hl):V=hl,x){case 1:var gl=-1;break;case 2:gl=250;break;case 5:gl=1073741823;break;case 4:gl=1e4;break;default:gl=5e3}return gl=V+gl,x={id:C++,callback:U,priorityLevel:x,startTime:V,expirationTime:gl,sortIndex:-1},V>hl?(x.sortIndex=V,E(h,x),T(O)===null&&x===T(h)&&(il?(k(al),al=-1):il=!0,ze(wl,V-hl))):(x.sortIndex=gl,E(O,x),J||w||(J=!0,Hl||(Hl=!0,Wl()))),x},f.unstable_shouldYield=Lt,f.unstable_wrapCallback=function(x){var U=N;return function(){var V=N;N=U;try{return x.apply(this,arguments)}finally{N=V}}}})(hf)),hf}var Td;function dy(){return Td||(Td=1,df.exports=ry()),df.exports}var mf={exports:{}},Vl={};/**- * @license React- * react-dom.production.js- *- * Copyright (c) Meta Platforms, Inc. and affiliates.- *- * This source code is licensed under the MIT license found in the- * LICENSE file in the root directory of this source tree.- */var Ad;function hy(){if(Ad)return Vl;Ad=1;var f=vf();function E(O){var h="https://react.dev/errors/"+O;if(1<arguments.length){h+="?args[]="+encodeURIComponent(arguments[1]);for(var C=2;C<arguments.length;C++)h+="&args[]="+encodeURIComponent(arguments[C])}return"Minified React error #"+O+"; visit "+h+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function T(){}var r={d:{f:T,r:function(){throw Error(E(522))},D:T,C:T,L:T,m:T,X:T,S:T,M:T},p:0,findDOMNode:null},D=Symbol.for("react.portal");function _(O,h,C){var M=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:D,key:M==null?null:""+M,children:O,containerInfo:h,implementation:C}}var H=f.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function G(O,h){if(O==="font")return"";if(typeof h=="string")return h==="use-credentials"?h:""}return Vl.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,Vl.createPortal=function(O,h){var C=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!h||h.nodeType!==1&&h.nodeType!==9&&h.nodeType!==11)throw Error(E(299));return _(O,h,null,C)},Vl.flushSync=function(O){var h=H.T,C=r.p;try{if(H.T=null,r.p=2,O)return O()}finally{H.T=h,r.p=C,r.d.f()}},Vl.preconnect=function(O,h){typeof O=="string"&&(h?(h=h.crossOrigin,h=typeof h=="string"?h==="use-credentials"?h:"":void 0):h=null,r.d.C(O,h))},Vl.prefetchDNS=function(O){typeof O=="string"&&r.d.D(O)},Vl.preinit=function(O,h){if(typeof O=="string"&&h&&typeof h.as=="string"){var C=h.as,M=G(C,h.crossOrigin),N=typeof h.integrity=="string"?h.integrity:void 0,w=typeof h.fetchPriority=="string"?h.fetchPriority:void 0;C==="style"?r.d.S(O,typeof h.precedence=="string"?h.precedence:void 0,{crossOrigin:M,integrity:N,fetchPriority:w}):C==="script"&&r.d.X(O,{crossOrigin:M,integrity:N,fetchPriority:w,nonce:typeof h.nonce=="string"?h.nonce:void 0})}},Vl.preinitModule=function(O,h){if(typeof O=="string")if(typeof h=="object"&&h!==null){if(h.as==null||h.as==="script"){var C=G(h.as,h.crossOrigin);r.d.M(O,{crossOrigin:C,integrity:typeof h.integrity=="string"?h.integrity:void 0,nonce:typeof h.nonce=="string"?h.nonce:void 0})}}else h==null&&r.d.M(O)},Vl.preload=function(O,h){if(typeof O=="string"&&typeof h=="object"&&h!==null&&typeof h.as=="string"){var C=h.as,M=G(C,h.crossOrigin);r.d.L(O,C,{crossOrigin:M,integrity:typeof h.integrity=="string"?h.integrity:void 0,nonce:typeof h.nonce=="string"?h.nonce:void 0,type:typeof h.type=="string"?h.type:void 0,fetchPriority:typeof h.fetchPriority=="string"?h.fetchPriority:void 0,referrerPolicy:typeof h.referrerPolicy=="string"?h.referrerPolicy:void 0,imageSrcSet:typeof h.imageSrcSet=="string"?h.imageSrcSet:void 0,imageSizes:typeof h.imageSizes=="string"?h.imageSizes:void 0,media:typeof h.media=="string"?h.media:void 0})}},Vl.preloadModule=function(O,h){if(typeof O=="string")if(h){var C=G(h.as,h.crossOrigin);r.d.m(O,{as:typeof h.as=="string"&&h.as!=="script"?h.as:void 0,crossOrigin:C,integrity:typeof h.integrity=="string"?h.integrity:void 0})}else r.d.m(O)},Vl.requestFormReset=function(O){r.d.r(O)},Vl.unstable_batchedUpdates=function(O,h){return O(h)},Vl.useFormState=function(O,h,C){return H.H.useFormState(O,h,C)},Vl.useFormStatus=function(){return H.H.useHostTransitionStatus()},Vl.version="19.2.5",Vl}var Ed;function my(){if(Ed)return mf.exports;Ed=1;function f(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(f)}catch(E){console.error(E)}}return f(),mf.exports=hy(),mf.exports}/**- * @license React- * react-dom-client.production.js- *- * Copyright (c) Meta Platforms, Inc. and affiliates.- *- * This source code is licensed under the MIT license found in the- * LICENSE file in the root directory of this source tree.- */var _d;function yy(){if(_d)return Tn;_d=1;var f=dy(),E=vf(),T=my();function r(l){var e="https://react.dev/errors/"+l;if(1<arguments.length){e+="?args[]="+encodeURIComponent(arguments[1]);for(var t=2;t<arguments.length;t++)e+="&args[]="+encodeURIComponent(arguments[t])}return"Minified React error #"+l+"; visit "+e+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function D(l){return!(!l||l.nodeType!==1&&l.nodeType!==9&&l.nodeType!==11)}function _(l){var e=l,t=l;if(l.alternate)for(;e.return;)e=e.return;else{l=e;do e=l,(e.flags&4098)!==0&&(t=e.return),l=e.return;while(l)}return e.tag===3?t:null}function H(l){if(l.tag===13){var e=l.memoizedState;if(e===null&&(l=l.alternate,l!==null&&(e=l.memoizedState)),e!==null)return e.dehydrated}return null}function G(l){if(l.tag===31){var e=l.memoizedState;if(e===null&&(l=l.alternate,l!==null&&(e=l.memoizedState)),e!==null)return e.dehydrated}return null}function O(l){if(_(l)!==l)throw Error(r(188))}function h(l){var e=l.alternate;if(!e){if(e=_(l),e===null)throw Error(r(188));return e!==l?null:l}for(var t=l,a=e;;){var n=t.return;if(n===null)break;var u=n.alternate;if(u===null){if(a=n.return,a!==null){t=a;continue}break}if(n.child===u.child){for(u=n.child;u;){if(u===t)return O(n),l;if(u===a)return O(n),e;u=u.sibling}throw Error(r(188))}if(t.return!==a.return)t=n,a=u;else{for(var i=!1,s=n.child;s;){if(s===t){i=!0,t=n,a=u;break}if(s===a){i=!0,a=n,t=u;break}s=s.sibling}if(!i){for(s=u.child;s;){if(s===t){i=!0,t=u,a=n;break}if(s===a){i=!0,a=u,t=n;break}s=s.sibling}if(!i)throw Error(r(189))}}if(t.alternate!==a)throw Error(r(190))}if(t.tag!==3)throw Error(r(188));return t.stateNode.current===t?l:e}function C(l){var e=l.tag;if(e===5||e===26||e===27||e===6)return l;for(l=l.child;l!==null;){if(e=C(l),e!==null)return e;l=l.sibling}return null}var M=Object.assign,N=Symbol.for("react.element"),w=Symbol.for("react.transitional.element"),J=Symbol.for("react.portal"),il=Symbol.for("react.fragment"),jl=Symbol.for("react.strict_mode"),ul=Symbol.for("react.profiler"),k=Symbol.for("react.consumer"),Z=Symbol.for("react.context"),Tl=Symbol.for("react.forward_ref"),wl=Symbol.for("react.suspense"),Hl=Symbol.for("react.suspense_list"),al=Symbol.for("react.memo"),kl=Symbol.for("react.lazy"),_e=Symbol.for("react.activity"),Lt=Symbol.for("react.memo_cache_sentinel"),Oe=Symbol.iterator;function Wl(l){return l===null||typeof l!="object"?null:(l=Oe&&l[Oe]||l["@@iterator"],typeof l=="function"?l:null)}var zt=Symbol.for("react.client.reference");function Ue(l){if(l==null)return null;if(typeof l=="function")return l.$$typeof===zt?null:l.displayName||l.name||null;if(typeof l=="string")return l;switch(l){case il:return"Fragment";case ul:return"Profiler";case jl:return"StrictMode";case wl:return"Suspense";case Hl:return"SuspenseList";case _e:return"Activity"}if(typeof l=="object")switch(l.$$typeof){case J:return"Portal";case Z:return l.displayName||"Context";case k:return(l._context.displayName||"Context")+".Consumer";case Tl:var e=l.render;return l=l.displayName,l||(l=e.displayName||e.name||"",l=l!==""?"ForwardRef("+l+")":"ForwardRef"),l;case al:return e=l.displayName||null,e!==null?e:Ue(l.type)||"Memo";case kl:e=l._payload,l=l._init;try{return Ue(l(e))}catch{}}return null}var ze=Array.isArray,x=E.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,U=T.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,V={pending:!1,data:null,method:null,action:null},hl=[],gl=-1;function m(l){return{current:l}}function A(l){0>gl||(l.current=hl[gl],hl[gl]=null,gl--)}function R(l,e){gl++,hl[gl]=l.current,l.current=e}var q=m(null),W=m(null),I=m(null),ol=m(null);function Kl(l,e){switch(R(I,e),R(W,l),R(q,null),e.nodeType){case 9:case 11:l=(l=e.documentElement)&&(l=l.namespaceURI)?Zr(l):0;break;default:if(l=e.tagName,e=e.namespaceURI)e=Zr(e),l=Lr(e,l);else switch(l){case"svg":l=1;break;case"math":l=2;break;default:l=0}}A(q),R(q,l)}function _l(){A(q),A(W),A(I)}function Na(l){l.memoizedState!==null&&R(ol,l);var e=q.current,t=Lr(e,l.type);e!==t&&(R(W,l),R(q,t))}function An(l){W.current===l&&(A(q),A(W)),ol.current===l&&(A(ol),bn._currentValue=V)}var Vu,gf;function Tt(l){if(Vu===void 0)try{throw Error()}catch(t){var e=t.stack.trim().match(/\n( *(at )?)/);Vu=e&&e[1]||"",gf=-1<t.stack.indexOf(`- at`)?" (<anonymous>)":-1<t.stack.indexOf("@")?"@unknown:0:0":""}return`-`+Vu+l+gf}var Ku=!1;function Ju(l,e){if(!l||Ku)return"";Ku=!0;var t=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var a={DetermineComponentFrameRoot:function(){try{if(e){var z=function(){throw Error()};if(Object.defineProperty(z.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(z,[])}catch(b){var p=b}Reflect.construct(l,[],z)}else{try{z.call()}catch(b){p=b}l.call(z.prototype)}}else{try{throw Error()}catch(b){p=b}(z=l())&&typeof z.catch=="function"&&z.catch(function(){})}}catch(b){if(b&&p&&typeof b.stack=="string")return[b.stack,p.stack]}return[null,null]}};a.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var n=Object.getOwnPropertyDescriptor(a.DetermineComponentFrameRoot,"name");n&&n.configurable&&Object.defineProperty(a.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var u=a.DetermineComponentFrameRoot(),i=u[0],s=u[1];if(i&&s){var o=i.split(`-`),g=s.split(`-`);for(n=a=0;a<o.length&&!o[a].includes("DetermineComponentFrameRoot");)a++;for(;n<g.length&&!g[n].includes("DetermineComponentFrameRoot");)n++;if(a===o.length||n===g.length)for(a=o.length-1,n=g.length-1;1<=a&&0<=n&&o[a]!==g[n];)n--;for(;1<=a&&0<=n;a--,n--)if(o[a]!==g[n]){if(a!==1||n!==1)do if(a--,n--,0>n||o[a]!==g[n]){var S=`-`+o[a].replace(" at new "," at ");return l.displayName&&S.includes("<anonymous>")&&(S=S.replace("<anonymous>",l.displayName)),S}while(1<=a&&0<=n);break}}}finally{Ku=!1,Error.prepareStackTrace=t}return(t=l?l.displayName||l.name:"")?Tt(t):""}function Gd(l,e){switch(l.tag){case 26:case 27:case 5:return Tt(l.type);case 16:return Tt("Lazy");case 13:return l.child!==e&&e!==null?Tt("Suspense Fallback"):Tt("Suspense");case 19:return Tt("SuspenseList");case 0:case 15:return Ju(l.type,!1);case 11:return Ju(l.type.render,!1);case 1:return Ju(l.type,!0);case 31:return Tt("Activity");default:return""}}function pf(l){try{var e="",t=null;do e+=Gd(l,t),t=l,l=l.return;while(l);return e}catch(a){return`-Error generating stack: `+a.message+`-`+a.stack}}var wu=Object.prototype.hasOwnProperty,ku=f.unstable_scheduleCallback,Wu=f.unstable_cancelCallback,Xd=f.unstable_shouldYield,Qd=f.unstable_requestPaint,ae=f.unstable_now,Zd=f.unstable_getCurrentPriorityLevel,bf=f.unstable_ImmediatePriority,Sf=f.unstable_UserBlockingPriority,En=f.unstable_NormalPriority,Ld=f.unstable_LowPriority,xf=f.unstable_IdlePriority,Vd=f.log,Kd=f.unstable_setDisableYieldValue,Da=null,ne=null;function Ie(l){if(typeof Vd=="function"&&Kd(l),ne&&typeof ne.setStrictMode=="function")try{ne.setStrictMode(Da,l)}catch{}}var ue=Math.clz32?Math.clz32:kd,Jd=Math.log,wd=Math.LN2;function kd(l){return l>>>=0,l===0?32:31-(Jd(l)/wd|0)|0}var _n=256,On=262144,Nn=4194304;function At(l){var e=l&42;if(e!==0)return e;switch(l&-l){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return l&261888;case 262144:case 524288:case 1048576:case 2097152:return l&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return l&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return l}}function Dn(l,e,t){var a=l.pendingLanes;if(a===0)return 0;var n=0,u=l.suspendedLanes,i=l.pingedLanes;l=l.warmLanes;var s=a&134217727;return s!==0?(a=s&~u,a!==0?n=At(a):(i&=s,i!==0?n=At(i):t||(t=s&~l,t!==0&&(n=At(t))))):(s=a&~u,s!==0?n=At(s):i!==0?n=At(i):t||(t=a&~l,t!==0&&(n=At(t)))),n===0?0:e!==0&&e!==n&&(e&u)===0&&(u=n&-n,t=e&-e,u>=t||u===32&&(t&4194048)!==0)?e:n}function Ma(l,e){return(l.pendingLanes&~(l.suspendedLanes&~l.pingedLanes)&e)===0}function Wd(l,e){switch(l){case 1:case 2:case 4:case 8:case 64:return e+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function jf(){var l=Nn;return Nn<<=1,(Nn&62914560)===0&&(Nn=4194304),l}function $u(l){for(var e=[],t=0;31>t;t++)e.push(l);return e}function Ca(l,e){l.pendingLanes|=e,e!==268435456&&(l.suspendedLanes=0,l.pingedLanes=0,l.warmLanes=0)}function $d(l,e,t,a,n,u){var i=l.pendingLanes;l.pendingLanes=t,l.suspendedLanes=0,l.pingedLanes=0,l.warmLanes=0,l.expiredLanes&=t,l.entangledLanes&=t,l.errorRecoveryDisabledLanes&=t,l.shellSuspendCounter=0;var s=l.entanglements,o=l.expirationTimes,g=l.hiddenUpdates;for(t=i&~t;0<t;){var S=31-ue(t),z=1<<S;s[S]=0,o[S]=-1;var p=g[S];if(p!==null)for(g[S]=null,S=0;S<p.length;S++){var b=p[S];b!==null&&(b.lane&=-536870913)}t&=~z}a!==0&&zf(l,a,0),u!==0&&n===0&&l.tag!==0&&(l.suspendedLanes|=u&~(i&~e))}function zf(l,e,t){l.pendingLanes|=e,l.suspendedLanes&=~e;var a=31-ue(e);l.entangledLanes|=e,l.entanglements[a]=l.entanglements[a]|1073741824|t&261930}function Tf(l,e){var t=l.entangledLanes|=e;for(l=l.entanglements;t;){var a=31-ue(t),n=1<<a;n&e|l[a]&e&&(l[a]|=e),t&=~n}}function Af(l,e){var t=e&-e;return t=(t&42)!==0?1:Fu(t),(t&(l.suspendedLanes|e))!==0?0:t}function Fu(l){switch(l){case 2:l=1;break;case 8:l=4;break;case 32:l=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:l=128;break;case 268435456:l=134217728;break;default:l=0}return l}function Iu(l){return l&=-l,2<l?8<l?(l&134217727)!==0?32:268435456:8:2}function Ef(){var l=U.p;return l!==0?l:(l=window.event,l===void 0?32:dd(l.type))}function _f(l,e){var t=U.p;try{return U.p=l,e()}finally{U.p=t}}var Pe=Math.random().toString(36).slice(2),Gl="__reactFiber$"+Pe,$l="__reactProps$"+Pe,Vt="__reactContainer$"+Pe,Pu="__reactEvents$"+Pe,Fd="__reactListeners$"+Pe,Id="__reactHandles$"+Pe,Of="__reactResources$"+Pe,Ua="__reactMarker$"+Pe;function li(l){delete l[Gl],delete l[$l],delete l[Pu],delete l[Fd],delete l[Id]}function Kt(l){var e=l[Gl];if(e)return e;for(var t=l.parentNode;t;){if(e=t[Vt]||t[Gl]){if(t=e.alternate,e.child!==null||t!==null&&t.child!==null)for(l=$r(l);l!==null;){if(t=l[Gl])return t;l=$r(l)}return e}l=t,t=l.parentNode}return null}function Jt(l){if(l=l[Gl]||l[Vt]){var e=l.tag;if(e===5||e===6||e===13||e===31||e===26||e===27||e===3)return l}return null}function Ra(l){var e=l.tag;if(e===5||e===26||e===27||e===6)return l.stateNode;throw Error(r(33))}function wt(l){var e=l[Of];return e||(e=l[Of]={hoistableStyles:new Map,hoistableScripts:new Map}),e}function ql(l){l[Ua]=!0}var Nf=new Set,Df={};function Et(l,e){kt(l,e),kt(l+"Capture",e)}function kt(l,e){for(Df[l]=e,l=0;l<e.length;l++)Nf.add(e[l])}var Pd=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),Mf={},Cf={};function lh(l){return wu.call(Cf,l)?!0:wu.call(Mf,l)?!1:Pd.test(l)?Cf[l]=!0:(Mf[l]=!0,!1)}function Mn(l,e,t){if(lh(e))if(t===null)l.removeAttribute(e);else{switch(typeof t){case"undefined":case"function":case"symbol":l.removeAttribute(e);return;case"boolean":var a=e.toLowerCase().slice(0,5);if(a!=="data-"&&a!=="aria-"){l.removeAttribute(e);return}}l.setAttribute(e,""+t)}}function Cn(l,e,t){if(t===null)l.removeAttribute(e);else{switch(typeof t){case"undefined":case"function":case"symbol":case"boolean":l.removeAttribute(e);return}l.setAttribute(e,""+t)}}function Re(l,e,t,a){if(a===null)l.removeAttribute(t);else{switch(typeof a){case"undefined":case"function":case"symbol":case"boolean":l.removeAttribute(t);return}l.setAttributeNS(e,t,""+a)}}function he(l){switch(typeof l){case"bigint":case"boolean":case"number":case"string":case"undefined":return l;case"object":return l;default:return""}}function Uf(l){var e=l.type;return(l=l.nodeName)&&l.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function eh(l,e,t){var a=Object.getOwnPropertyDescriptor(l.constructor.prototype,e);if(!l.hasOwnProperty(e)&&typeof a<"u"&&typeof a.get=="function"&&typeof a.set=="function"){var n=a.get,u=a.set;return Object.defineProperty(l,e,{configurable:!0,get:function(){return n.call(this)},set:function(i){t=""+i,u.call(this,i)}}),Object.defineProperty(l,e,{enumerable:a.enumerable}),{getValue:function(){return t},setValue:function(i){t=""+i},stopTracking:function(){l._valueTracker=null,delete l[e]}}}}function ei(l){if(!l._valueTracker){var e=Uf(l)?"checked":"value";l._valueTracker=eh(l,e,""+l[e])}}function Rf(l){if(!l)return!1;var e=l._valueTracker;if(!e)return!0;var t=e.getValue(),a="";return l&&(a=Uf(l)?l.checked?"true":"false":l.value),l=a,l!==t?(e.setValue(l),!0):!1}function Un(l){if(l=l||(typeof document<"u"?document:void 0),typeof l>"u")return null;try{return l.activeElement||l.body}catch{return l.body}}var th=/[\n"\\]/g;function me(l){return l.replace(th,function(e){return"\\"+e.charCodeAt(0).toString(16)+" "})}function ti(l,e,t,a,n,u,i,s){l.name="",i!=null&&typeof i!="function"&&typeof i!="symbol"&&typeof i!="boolean"?l.type=i:l.removeAttribute("type"),e!=null?i==="number"?(e===0&&l.value===""||l.value!=e)&&(l.value=""+he(e)):l.value!==""+he(e)&&(l.value=""+he(e)):i!=="submit"&&i!=="reset"||l.removeAttribute("value"),e!=null?ai(l,i,he(e)):t!=null?ai(l,i,he(t)):a!=null&&l.removeAttribute("value"),n==null&&u!=null&&(l.defaultChecked=!!u),n!=null&&(l.checked=n&&typeof n!="function"&&typeof n!="symbol"),s!=null&&typeof s!="function"&&typeof s!="symbol"&&typeof s!="boolean"?l.name=""+he(s):l.removeAttribute("name")}function Hf(l,e,t,a,n,u,i,s){if(u!=null&&typeof u!="function"&&typeof u!="symbol"&&typeof u!="boolean"&&(l.type=u),e!=null||t!=null){if(!(u!=="submit"&&u!=="reset"||e!=null)){ei(l);return}t=t!=null?""+he(t):"",e=e!=null?""+he(e):t,s||e===l.value||(l.value=e),l.defaultValue=e}a=a??n,a=typeof a!="function"&&typeof a!="symbol"&&!!a,l.checked=s?l.checked:!!a,l.defaultChecked=!!a,i!=null&&typeof i!="function"&&typeof i!="symbol"&&typeof i!="boolean"&&(l.name=i),ei(l)}function ai(l,e,t){e==="number"&&Un(l.ownerDocument)===l||l.defaultValue===""+t||(l.defaultValue=""+t)}function Wt(l,e,t,a){if(l=l.options,e){e={};for(var n=0;n<t.length;n++)e["$"+t[n]]=!0;for(t=0;t<l.length;t++)n=e.hasOwnProperty("$"+l[t].value),l[t].selected!==n&&(l[t].selected=n),n&&a&&(l[t].defaultSelected=!0)}else{for(t=""+he(t),e=null,n=0;n<l.length;n++){if(l[n].value===t){l[n].selected=!0,a&&(l[n].defaultSelected=!0);return}e!==null||l[n].disabled||(e=l[n])}e!==null&&(e.selected=!0)}}function Bf(l,e,t){if(e!=null&&(e=""+he(e),e!==l.value&&(l.value=e),t==null)){l.defaultValue!==e&&(l.defaultValue=e);return}l.defaultValue=t!=null?""+he(t):""}function qf(l,e,t,a){if(e==null){if(a!=null){if(t!=null)throw Error(r(92));if(ze(a)){if(1<a.length)throw Error(r(93));a=a[0]}t=a}t==null&&(t=""),e=t}t=he(e),l.defaultValue=t,a=l.textContent,a===t&&a!==""&&a!==null&&(l.value=a),ei(l)}function $t(l,e){if(e){var t=l.firstChild;if(t&&t===l.lastChild&&t.nodeType===3){t.nodeValue=e;return}}l.textContent=e}var ah=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function Yf(l,e,t){var a=e.indexOf("--")===0;t==null||typeof t=="boolean"||t===""?a?l.setProperty(e,""):e==="float"?l.cssFloat="":l[e]="":a?l.setProperty(e,t):typeof t!="number"||t===0||ah.has(e)?e==="float"?l.cssFloat=t:l[e]=(""+t).trim():l[e]=t+"px"}function Gf(l,e,t){if(e!=null&&typeof e!="object")throw Error(r(62));if(l=l.style,t!=null){for(var a in t)!t.hasOwnProperty(a)||e!=null&&e.hasOwnProperty(a)||(a.indexOf("--")===0?l.setProperty(a,""):a==="float"?l.cssFloat="":l[a]="");for(var n in e)a=e[n],e.hasOwnProperty(n)&&t[n]!==a&&Yf(l,n,a)}else for(var u in e)e.hasOwnProperty(u)&&Yf(l,u,e[u])}function ni(l){if(l.indexOf("-")===-1)return!1;switch(l){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var nh=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),uh=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function Rn(l){return uh.test(""+l)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":l}function He(){}var ui=null;function ii(l){return l=l.target||l.srcElement||window,l.correspondingUseElement&&(l=l.correspondingUseElement),l.nodeType===3?l.parentNode:l}var Ft=null,It=null;function Xf(l){var e=Jt(l);if(e&&(l=e.stateNode)){var t=l[$l]||null;l:switch(l=e.stateNode,e.type){case"input":if(ti(l,t.value,t.defaultValue,t.defaultValue,t.checked,t.defaultChecked,t.type,t.name),e=t.name,t.type==="radio"&&e!=null){for(t=l;t.parentNode;)t=t.parentNode;for(t=t.querySelectorAll('input[name="'+me(""+e)+'"][type="radio"]'),e=0;e<t.length;e++){var a=t[e];if(a!==l&&a.form===l.form){var n=a[$l]||null;if(!n)throw Error(r(90));ti(a,n.value,n.defaultValue,n.defaultValue,n.checked,n.defaultChecked,n.type,n.name)}}for(e=0;e<t.length;e++)a=t[e],a.form===l.form&&Rf(a)}break l;case"textarea":Bf(l,t.value,t.defaultValue);break l;case"select":e=t.value,e!=null&&Wt(l,!!t.multiple,e,!1)}}}var ci=!1;function Qf(l,e,t){if(ci)return l(e,t);ci=!0;try{var a=l(e);return a}finally{if(ci=!1,(Ft!==null||It!==null)&&(xu(),Ft&&(e=Ft,l=It,It=Ft=null,Xf(e),l)))for(e=0;e<l.length;e++)Xf(l[e])}}function Ha(l,e){var t=l.stateNode;if(t===null)return null;var a=t[$l]||null;if(a===null)return null;t=a[e];l:switch(e){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(a=!a.disabled)||(l=l.type,a=!(l==="button"||l==="input"||l==="select"||l==="textarea")),l=!a;break l;default:l=!1}if(l)return null;if(t&&typeof t!="function")throw Error(r(231,e,typeof t));return t}var Be=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),fi=!1;if(Be)try{var Ba={};Object.defineProperty(Ba,"passive",{get:function(){fi=!0}}),window.addEventListener("test",Ba,Ba),window.removeEventListener("test",Ba,Ba)}catch{fi=!1}var lt=null,si=null,Hn=null;function Zf(){if(Hn)return Hn;var l,e=si,t=e.length,a,n="value"in lt?lt.value:lt.textContent,u=n.length;for(l=0;l<t&&e[l]===n[l];l++);var i=t-l;for(a=1;a<=i&&e[t-a]===n[u-a];a++);return Hn=n.slice(l,1<a?1-a:void 0)}function Bn(l){var e=l.keyCode;return"charCode"in l?(l=l.charCode,l===0&&e===13&&(l=13)):l=e,l===10&&(l=13),32<=l||l===13?l:0}function qn(){return!0}function Lf(){return!1}function Fl(l){function e(t,a,n,u,i){this._reactName=t,this._targetInst=n,this.type=a,this.nativeEvent=u,this.target=i,this.currentTarget=null;for(var s in l)l.hasOwnProperty(s)&&(t=l[s],this[s]=t?t(u):u[s]);return this.isDefaultPrevented=(u.defaultPrevented!=null?u.defaultPrevented:u.returnValue===!1)?qn:Lf,this.isPropagationStopped=Lf,this}return M(e.prototype,{preventDefault:function(){this.defaultPrevented=!0;var t=this.nativeEvent;t&&(t.preventDefault?t.preventDefault():typeof t.returnValue!="unknown"&&(t.returnValue=!1),this.isDefaultPrevented=qn)},stopPropagation:function(){var t=this.nativeEvent;t&&(t.stopPropagation?t.stopPropagation():typeof t.cancelBubble!="unknown"&&(t.cancelBubble=!0),this.isPropagationStopped=qn)},persist:function(){},isPersistent:qn}),e}var _t={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(l){return l.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Yn=Fl(_t),qa=M({},_t,{view:0,detail:0}),ih=Fl(qa),oi,ri,Ya,Gn=M({},qa,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:hi,button:0,buttons:0,relatedTarget:function(l){return l.relatedTarget===void 0?l.fromElement===l.srcElement?l.toElement:l.fromElement:l.relatedTarget},movementX:function(l){return"movementX"in l?l.movementX:(l!==Ya&&(Ya&&l.type==="mousemove"?(oi=l.screenX-Ya.screenX,ri=l.screenY-Ya.screenY):ri=oi=0,Ya=l),oi)},movementY:function(l){return"movementY"in l?l.movementY:ri}}),Vf=Fl(Gn),ch=M({},Gn,{dataTransfer:0}),fh=Fl(ch),sh=M({},qa,{relatedTarget:0}),di=Fl(sh),oh=M({},_t,{animationName:0,elapsedTime:0,pseudoElement:0}),rh=Fl(oh),dh=M({},_t,{clipboardData:function(l){return"clipboardData"in l?l.clipboardData:window.clipboardData}}),hh=Fl(dh),mh=M({},_t,{data:0}),Kf=Fl(mh),yh={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},vh={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},gh={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function ph(l){var e=this.nativeEvent;return e.getModifierState?e.getModifierState(l):(l=gh[l])?!!e[l]:!1}function hi(){return ph}var bh=M({},qa,{key:function(l){if(l.key){var e=yh[l.key]||l.key;if(e!=="Unidentified")return e}return l.type==="keypress"?(l=Bn(l),l===13?"Enter":String.fromCharCode(l)):l.type==="keydown"||l.type==="keyup"?vh[l.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:hi,charCode:function(l){return l.type==="keypress"?Bn(l):0},keyCode:function(l){return l.type==="keydown"||l.type==="keyup"?l.keyCode:0},which:function(l){return l.type==="keypress"?Bn(l):l.type==="keydown"||l.type==="keyup"?l.keyCode:0}}),Sh=Fl(bh),xh=M({},Gn,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Jf=Fl(xh),jh=M({},qa,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:hi}),zh=Fl(jh),Th=M({},_t,{propertyName:0,elapsedTime:0,pseudoElement:0}),Ah=Fl(Th),Eh=M({},Gn,{deltaX:function(l){return"deltaX"in l?l.deltaX:"wheelDeltaX"in l?-l.wheelDeltaX:0},deltaY:function(l){return"deltaY"in l?l.deltaY:"wheelDeltaY"in l?-l.wheelDeltaY:"wheelDelta"in l?-l.wheelDelta:0},deltaZ:0,deltaMode:0}),_h=Fl(Eh),Oh=M({},_t,{newState:0,oldState:0}),Nh=Fl(Oh),Dh=[9,13,27,32],mi=Be&&"CompositionEvent"in window,Ga=null;Be&&"documentMode"in document&&(Ga=document.documentMode);var Mh=Be&&"TextEvent"in window&&!Ga,wf=Be&&(!mi||Ga&&8<Ga&&11>=Ga),kf=" ",Wf=!1;function $f(l,e){switch(l){case"keyup":return Dh.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Ff(l){return l=l.detail,typeof l=="object"&&"data"in l?l.data:null}var Pt=!1;function Ch(l,e){switch(l){case"compositionend":return Ff(e);case"keypress":return e.which!==32?null:(Wf=!0,kf);case"textInput":return l=e.data,l===kf&&Wf?null:l;default:return null}}function Uh(l,e){if(Pt)return l==="compositionend"||!mi&&$f(l,e)?(l=Zf(),Hn=si=lt=null,Pt=!1,l):null;switch(l){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1<e.char.length)return e.char;if(e.which)return String.fromCharCode(e.which)}return null;case"compositionend":return wf&&e.locale!=="ko"?null:e.data;default:return null}}var Rh={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function If(l){var e=l&&l.nodeName&&l.nodeName.toLowerCase();return e==="input"?!!Rh[l.type]:e==="textarea"}function Pf(l,e,t,a){Ft?It?It.push(a):It=[a]:Ft=a,e=Ou(e,"onChange"),0<e.length&&(t=new Yn("onChange","change",null,t,a),l.push({event:t,listeners:e}))}var Xa=null,Qa=null;function Hh(l){Br(l,0)}function Xn(l){var e=Ra(l);if(Rf(e))return l}function ls(l,e){if(l==="change")return e}var es=!1;if(Be){var yi;if(Be){var vi="oninput"in document;if(!vi){var ts=document.createElement("div");ts.setAttribute("oninput","return;"),vi=typeof ts.oninput=="function"}yi=vi}else yi=!1;es=yi&&(!document.documentMode||9<document.documentMode)}function as(){Xa&&(Xa.detachEvent("onpropertychange",ns),Qa=Xa=null)}function ns(l){if(l.propertyName==="value"&&Xn(Qa)){var e=[];Pf(e,Qa,l,ii(l)),Qf(Hh,e)}}function Bh(l,e,t){l==="focusin"?(as(),Xa=e,Qa=t,Xa.attachEvent("onpropertychange",ns)):l==="focusout"&&as()}function qh(l){if(l==="selectionchange"||l==="keyup"||l==="keydown")return Xn(Qa)}function Yh(l,e){if(l==="click")return Xn(e)}function Gh(l,e){if(l==="input"||l==="change")return Xn(e)}function Xh(l,e){return l===e&&(l!==0||1/l===1/e)||l!==l&&e!==e}var ie=typeof Object.is=="function"?Object.is:Xh;function Za(l,e){if(ie(l,e))return!0;if(typeof l!="object"||l===null||typeof e!="object"||e===null)return!1;var t=Object.keys(l),a=Object.keys(e);if(t.length!==a.length)return!1;for(a=0;a<t.length;a++){var n=t[a];if(!wu.call(e,n)||!ie(l[n],e[n]))return!1}return!0}function us(l){for(;l&&l.firstChild;)l=l.firstChild;return l}function is(l,e){var t=us(l);l=0;for(var a;t;){if(t.nodeType===3){if(a=l+t.textContent.length,l<=e&&a>=e)return{node:t,offset:e-l};l=a}l:{for(;t;){if(t.nextSibling){t=t.nextSibling;break l}t=t.parentNode}t=void 0}t=us(t)}}function cs(l,e){return l&&e?l===e?!0:l&&l.nodeType===3?!1:e&&e.nodeType===3?cs(l,e.parentNode):"contains"in l?l.contains(e):l.compareDocumentPosition?!!(l.compareDocumentPosition(e)&16):!1:!1}function fs(l){l=l!=null&&l.ownerDocument!=null&&l.ownerDocument.defaultView!=null?l.ownerDocument.defaultView:window;for(var e=Un(l.document);e instanceof l.HTMLIFrameElement;){try{var t=typeof e.contentWindow.location.href=="string"}catch{t=!1}if(t)l=e.contentWindow;else break;e=Un(l.document)}return e}function gi(l){var e=l&&l.nodeName&&l.nodeName.toLowerCase();return e&&(e==="input"&&(l.type==="text"||l.type==="search"||l.type==="tel"||l.type==="url"||l.type==="password")||e==="textarea"||l.contentEditable==="true")}var Qh=Be&&"documentMode"in document&&11>=document.documentMode,la=null,pi=null,La=null,bi=!1;function ss(l,e,t){var a=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;bi||la==null||la!==Un(a)||(a=la,"selectionStart"in a&&gi(a)?a={start:a.selectionStart,end:a.selectionEnd}:(a=(a.ownerDocument&&a.ownerDocument.defaultView||window).getSelection(),a={anchorNode:a.anchorNode,anchorOffset:a.anchorOffset,focusNode:a.focusNode,focusOffset:a.focusOffset}),La&&Za(La,a)||(La=a,a=Ou(pi,"onSelect"),0<a.length&&(e=new Yn("onSelect","select",null,e,t),l.push({event:e,listeners:a}),e.target=la)))}function Ot(l,e){var t={};return t[l.toLowerCase()]=e.toLowerCase(),t["Webkit"+l]="webkit"+e,t["Moz"+l]="moz"+e,t}var ea={animationend:Ot("Animation","AnimationEnd"),animationiteration:Ot("Animation","AnimationIteration"),animationstart:Ot("Animation","AnimationStart"),transitionrun:Ot("Transition","TransitionRun"),transitionstart:Ot("Transition","TransitionStart"),transitioncancel:Ot("Transition","TransitionCancel"),transitionend:Ot("Transition","TransitionEnd")},Si={},os={};Be&&(os=document.createElement("div").style,"AnimationEvent"in window||(delete ea.animationend.animation,delete ea.animationiteration.animation,delete ea.animationstart.animation),"TransitionEvent"in window||delete ea.transitionend.transition);function Nt(l){if(Si[l])return Si[l];if(!ea[l])return l;var e=ea[l],t;for(t in e)if(e.hasOwnProperty(t)&&t in os)return Si[l]=e[t];return l}var rs=Nt("animationend"),ds=Nt("animationiteration"),hs=Nt("animationstart"),Zh=Nt("transitionrun"),Lh=Nt("transitionstart"),Vh=Nt("transitioncancel"),ms=Nt("transitionend"),ys=new Map,xi="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");xi.push("scrollEnd");function Te(l,e){ys.set(l,e),Et(e,[l])}var Qn=typeof reportError=="function"?reportError:function(l){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof l=="object"&&l!==null&&typeof l.message=="string"?String(l.message):String(l),error:l});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",l);return}console.error(l)},ye=[],ta=0,ji=0;function Zn(){for(var l=ta,e=ji=ta=0;e<l;){var t=ye[e];ye[e++]=null;var a=ye[e];ye[e++]=null;var n=ye[e];ye[e++]=null;var u=ye[e];if(ye[e++]=null,a!==null&&n!==null){var i=a.pending;i===null?n.next=n:(n.next=i.next,i.next=n),a.pending=n}u!==0&&vs(t,n,u)}}function Ln(l,e,t,a){ye[ta++]=l,ye[ta++]=e,ye[ta++]=t,ye[ta++]=a,ji|=a,l.lanes|=a,l=l.alternate,l!==null&&(l.lanes|=a)}function zi(l,e,t,a){return Ln(l,e,t,a),Vn(l)}function Dt(l,e){return Ln(l,null,null,e),Vn(l)}function vs(l,e,t){l.lanes|=t;var a=l.alternate;a!==null&&(a.lanes|=t);for(var n=!1,u=l.return;u!==null;)u.childLanes|=t,a=u.alternate,a!==null&&(a.childLanes|=t),u.tag===22&&(l=u.stateNode,l===null||l._visibility&1||(n=!0)),l=u,u=u.return;return l.tag===3?(u=l.stateNode,n&&e!==null&&(n=31-ue(t),l=u.hiddenUpdates,a=l[n],a===null?l[n]=[e]:a.push(e),e.lane=t|536870912),u):null}function Vn(l){if(50<dn)throw dn=0,Cc=null,Error(r(185));for(var e=l.return;e!==null;)l=e,e=l.return;return l.tag===3?l.stateNode:null}var aa={};function Kh(l,e,t,a){this.tag=l,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=a,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function ce(l,e,t,a){return new Kh(l,e,t,a)}function Ti(l){return l=l.prototype,!(!l||!l.isReactComponent)}function qe(l,e){var t=l.alternate;return t===null?(t=ce(l.tag,e,l.key,l.mode),t.elementType=l.elementType,t.type=l.type,t.stateNode=l.stateNode,t.alternate=l,l.alternate=t):(t.pendingProps=e,t.type=l.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=l.flags&65011712,t.childLanes=l.childLanes,t.lanes=l.lanes,t.child=l.child,t.memoizedProps=l.memoizedProps,t.memoizedState=l.memoizedState,t.updateQueue=l.updateQueue,e=l.dependencies,t.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},t.sibling=l.sibling,t.index=l.index,t.ref=l.ref,t.refCleanup=l.refCleanup,t}function gs(l,e){l.flags&=65011714;var t=l.alternate;return t===null?(l.childLanes=0,l.lanes=e,l.child=null,l.subtreeFlags=0,l.memoizedProps=null,l.memoizedState=null,l.updateQueue=null,l.dependencies=null,l.stateNode=null):(l.childLanes=t.childLanes,l.lanes=t.lanes,l.child=t.child,l.subtreeFlags=0,l.deletions=null,l.memoizedProps=t.memoizedProps,l.memoizedState=t.memoizedState,l.updateQueue=t.updateQueue,l.type=t.type,e=t.dependencies,l.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext}),l}function Kn(l,e,t,a,n,u){var i=0;if(a=l,typeof l=="function")Ti(l)&&(i=1);else if(typeof l=="string")i=$m(l,t,q.current)?26:l==="html"||l==="head"||l==="body"?27:5;else l:switch(l){case _e:return l=ce(31,t,e,n),l.elementType=_e,l.lanes=u,l;case il:return Mt(t.children,n,u,e);case jl:i=8,n|=24;break;case ul:return l=ce(12,t,e,n|2),l.elementType=ul,l.lanes=u,l;case wl:return l=ce(13,t,e,n),l.elementType=wl,l.lanes=u,l;case Hl:return l=ce(19,t,e,n),l.elementType=Hl,l.lanes=u,l;default:if(typeof l=="object"&&l!==null)switch(l.$$typeof){case Z:i=10;break l;case k:i=9;break l;case Tl:i=11;break l;case al:i=14;break l;case kl:i=16,a=null;break l}i=29,t=Error(r(130,l===null?"null":typeof l,"")),a=null}return e=ce(i,t,e,n),e.elementType=l,e.type=a,e.lanes=u,e}function Mt(l,e,t,a){return l=ce(7,l,a,e),l.lanes=t,l}function Ai(l,e,t){return l=ce(6,l,null,e),l.lanes=t,l}function ps(l){var e=ce(18,null,null,0);return e.stateNode=l,e}function Ei(l,e,t){return e=ce(4,l.children!==null?l.children:[],l.key,e),e.lanes=t,e.stateNode={containerInfo:l.containerInfo,pendingChildren:null,implementation:l.implementation},e}var bs=new WeakMap;function ve(l,e){if(typeof l=="object"&&l!==null){var t=bs.get(l);return t!==void 0?t:(e={value:l,source:e,stack:pf(e)},bs.set(l,e),e)}return{value:l,source:e,stack:pf(e)}}var na=[],ua=0,Jn=null,Va=0,ge=[],pe=0,et=null,Ne=1,De="";function Ye(l,e){na[ua++]=Va,na[ua++]=Jn,Jn=l,Va=e}function Ss(l,e,t){ge[pe++]=Ne,ge[pe++]=De,ge[pe++]=et,et=l;var a=Ne;l=De;var n=32-ue(a)-1;a&=~(1<<n),t+=1;var u=32-ue(e)+n;if(30<u){var i=n-n%5;u=(a&(1<<i)-1).toString(32),a>>=i,n-=i,Ne=1<<32-ue(e)+n|t<<n|a,De=u+l}else Ne=1<<u|t<<n|a,De=l}function _i(l){l.return!==null&&(Ye(l,1),Ss(l,1,0))}function Oi(l){for(;l===Jn;)Jn=na[--ua],na[ua]=null,Va=na[--ua],na[ua]=null;for(;l===et;)et=ge[--pe],ge[pe]=null,De=ge[--pe],ge[pe]=null,Ne=ge[--pe],ge[pe]=null}function xs(l,e){ge[pe++]=Ne,ge[pe++]=De,ge[pe++]=et,Ne=e.id,De=e.overflow,et=l}var Xl=null,bl=null,nl=!1,tt=null,be=!1,Ni=Error(r(519));function at(l){var e=Error(r(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw Ka(ve(e,l)),Ni}function js(l){var e=l.stateNode,t=l.type,a=l.memoizedProps;switch(e[Gl]=l,e[$l]=a,t){case"dialog":ll("cancel",e),ll("close",e);break;case"iframe":case"object":case"embed":ll("load",e);break;case"video":case"audio":for(t=0;t<mn.length;t++)ll(mn[t],e);break;case"source":ll("error",e);break;case"img":case"image":case"link":ll("error",e),ll("load",e);break;case"details":ll("toggle",e);break;case"input":ll("invalid",e),Hf(e,a.value,a.defaultValue,a.checked,a.defaultChecked,a.type,a.name,!0);break;case"select":ll("invalid",e);break;case"textarea":ll("invalid",e),qf(e,a.value,a.defaultValue,a.children)}t=a.children,typeof t!="string"&&typeof t!="number"&&typeof t!="bigint"||e.textContent===""+t||a.suppressHydrationWarning===!0||Xr(e.textContent,t)?(a.popover!=null&&(ll("beforetoggle",e),ll("toggle",e)),a.onScroll!=null&&ll("scroll",e),a.onScrollEnd!=null&&ll("scrollend",e),a.onClick!=null&&(e.onclick=He),e=!0):e=!1,e||at(l,!0)}function zs(l){for(Xl=l.return;Xl;)switch(Xl.tag){case 5:case 31:case 13:be=!1;return;case 27:case 3:be=!0;return;default:Xl=Xl.return}}function ia(l){if(l!==Xl)return!1;if(!nl)return zs(l),nl=!0,!1;var e=l.tag,t;if((t=e!==3&&e!==27)&&((t=e===5)&&(t=l.type,t=!(t!=="form"&&t!=="button")||wc(l.type,l.memoizedProps)),t=!t),t&&bl&&at(l),zs(l),e===13){if(l=l.memoizedState,l=l!==null?l.dehydrated:null,!l)throw Error(r(317));bl=Wr(l)}else if(e===31){if(l=l.memoizedState,l=l!==null?l.dehydrated:null,!l)throw Error(r(317));bl=Wr(l)}else e===27?(e=bl,gt(l.type)?(l=Ic,Ic=null,bl=l):bl=e):bl=Xl?xe(l.stateNode.nextSibling):null;return!0}function Ct(){bl=Xl=null,nl=!1}function Di(){var l=tt;return l!==null&&(ee===null?ee=l:ee.push.apply(ee,l),tt=null),l}function Ka(l){tt===null?tt=[l]:tt.push(l)}var Mi=m(null),Ut=null,Ge=null;function nt(l,e,t){R(Mi,e._currentValue),e._currentValue=t}function Xe(l){l._currentValue=Mi.current,A(Mi)}function Ci(l,e,t){for(;l!==null;){var a=l.alternate;if((l.childLanes&e)!==e?(l.childLanes|=e,a!==null&&(a.childLanes|=e)):a!==null&&(a.childLanes&e)!==e&&(a.childLanes|=e),l===t)break;l=l.return}}function Ui(l,e,t,a){var n=l.child;for(n!==null&&(n.return=l);n!==null;){var u=n.dependencies;if(u!==null){var i=n.child;u=u.firstContext;l:for(;u!==null;){var s=u;u=n;for(var o=0;o<e.length;o++)if(s.context===e[o]){u.lanes|=t,s=u.alternate,s!==null&&(s.lanes|=t),Ci(u.return,t,l),a||(i=null);break l}u=s.next}}else if(n.tag===18){if(i=n.return,i===null)throw Error(r(341));i.lanes|=t,u=i.alternate,u!==null&&(u.lanes|=t),Ci(i,t,l),i=null}else i=n.child;if(i!==null)i.return=n;else for(i=n;i!==null;){if(i===l){i=null;break}if(n=i.sibling,n!==null){n.return=i.return,i=n;break}i=i.return}n=i}}function ca(l,e,t,a){l=null;for(var n=e,u=!1;n!==null;){if(!u){if((n.flags&524288)!==0)u=!0;else if((n.flags&262144)!==0)break}if(n.tag===10){var i=n.alternate;if(i===null)throw Error(r(387));if(i=i.memoizedProps,i!==null){var s=n.type;ie(n.pendingProps.value,i.value)||(l!==null?l.push(s):l=[s])}}else if(n===ol.current){if(i=n.alternate,i===null)throw Error(r(387));i.memoizedState.memoizedState!==n.memoizedState.memoizedState&&(l!==null?l.push(bn):l=[bn])}n=n.return}l!==null&&Ui(e,l,t,a),e.flags|=262144}function wn(l){for(l=l.firstContext;l!==null;){if(!ie(l.context._currentValue,l.memoizedValue))return!0;l=l.next}return!1}function Rt(l){Ut=l,Ge=null,l=l.dependencies,l!==null&&(l.firstContext=null)}function Ql(l){return Ts(Ut,l)}function kn(l,e){return Ut===null&&Rt(l),Ts(l,e)}function Ts(l,e){var t=e._currentValue;if(e={context:e,memoizedValue:t,next:null},Ge===null){if(l===null)throw Error(r(308));Ge=e,l.dependencies={lanes:0,firstContext:e},l.flags|=524288}else Ge=Ge.next=e;return t}var Jh=typeof AbortController<"u"?AbortController:function(){var l=[],e=this.signal={aborted:!1,addEventListener:function(t,a){l.push(a)}};this.abort=function(){e.aborted=!0,l.forEach(function(t){return t()})}},wh=f.unstable_scheduleCallback,kh=f.unstable_NormalPriority,Ml={$$typeof:Z,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Ri(){return{controller:new Jh,data:new Map,refCount:0}}function Ja(l){l.refCount--,l.refCount===0&&wh(kh,function(){l.controller.abort()})}var wa=null,Hi=0,fa=0,sa=null;function Wh(l,e){if(wa===null){var t=wa=[];Hi=0,fa=Yc(),sa={status:"pending",value:void 0,then:function(a){t.push(a)}}}return Hi++,e.then(As,As),e}function As(){if(--Hi===0&&wa!==null){sa!==null&&(sa.status="fulfilled");var l=wa;wa=null,fa=0,sa=null;for(var e=0;e<l.length;e++)(0,l[e])()}}function $h(l,e){var t=[],a={status:"pending",value:null,reason:null,then:function(n){t.push(n)}};return l.then(function(){a.status="fulfilled",a.value=e;for(var n=0;n<t.length;n++)(0,t[n])(e)},function(n){for(a.status="rejected",a.reason=n,n=0;n<t.length;n++)(0,t[n])(void 0)}),a}var Es=x.S;x.S=function(l,e){or=ae(),typeof e=="object"&&e!==null&&typeof e.then=="function"&&Wh(l,e),Es!==null&&Es(l,e)};var Ht=m(null);function Bi(){var l=Ht.current;return l!==null?l:pl.pooledCache}function Wn(l,e){e===null?R(Ht,Ht.current):R(Ht,e.pool)}function _s(){var l=Bi();return l===null?null:{parent:Ml._currentValue,pool:l}}var oa=Error(r(460)),qi=Error(r(474)),$n=Error(r(542)),Fn={then:function(){}};function Os(l){return l=l.status,l==="fulfilled"||l==="rejected"}function Ns(l,e,t){switch(t=l[t],t===void 0?l.push(e):t!==e&&(e.then(He,He),e=t),e.status){case"fulfilled":return e.value;case"rejected":throw l=e.reason,Ms(l),l;default:if(typeof e.status=="string")e.then(He,He);else{if(l=pl,l!==null&&100<l.shellSuspendCounter)throw Error(r(482));l=e,l.status="pending",l.then(function(a){if(e.status==="pending"){var n=e;n.status="fulfilled",n.value=a}},function(a){if(e.status==="pending"){var n=e;n.status="rejected",n.reason=a}})}switch(e.status){case"fulfilled":return e.value;case"rejected":throw l=e.reason,Ms(l),l}throw qt=e,oa}}function Bt(l){try{var e=l._init;return e(l._payload)}catch(t){throw t!==null&&typeof t=="object"&&typeof t.then=="function"?(qt=t,oa):t}}var qt=null;function Ds(){if(qt===null)throw Error(r(459));var l=qt;return qt=null,l}function Ms(l){if(l===oa||l===$n)throw Error(r(483))}var ra=null,ka=0;function In(l){var e=ka;return ka+=1,ra===null&&(ra=[]),Ns(ra,l,e)}function Wa(l,e){e=e.props.ref,l.ref=e!==void 0?e:null}function Pn(l,e){throw e.$$typeof===N?Error(r(525)):(l=Object.prototype.toString.call(e),Error(r(31,l==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":l)))}function Cs(l){function e(y,d){if(l){var v=y.deletions;v===null?(y.deletions=[d],y.flags|=16):v.push(d)}}function t(y,d){if(!l)return null;for(;d!==null;)e(y,d),d=d.sibling;return null}function a(y){for(var d=new Map;y!==null;)y.key!==null?d.set(y.key,y):d.set(y.index,y),y=y.sibling;return d}function n(y,d){return y=qe(y,d),y.index=0,y.sibling=null,y}function u(y,d,v){return y.index=v,l?(v=y.alternate,v!==null?(v=v.index,v<d?(y.flags|=67108866,d):v):(y.flags|=67108866,d)):(y.flags|=1048576,d)}function i(y){return l&&y.alternate===null&&(y.flags|=67108866),y}function s(y,d,v,j){return d===null||d.tag!==6?(d=Ai(v,y.mode,j),d.return=y,d):(d=n(d,v),d.return=y,d)}function o(y,d,v,j){var Q=v.type;return Q===il?S(y,d,v.props.children,j,v.key):d!==null&&(d.elementType===Q||typeof Q=="object"&&Q!==null&&Q.$$typeof===kl&&Bt(Q)===d.type)?(d=n(d,v.props),Wa(d,v),d.return=y,d):(d=Kn(v.type,v.key,v.props,null,y.mode,j),Wa(d,v),d.return=y,d)}function g(y,d,v,j){return d===null||d.tag!==4||d.stateNode.containerInfo!==v.containerInfo||d.stateNode.implementation!==v.implementation?(d=Ei(v,y.mode,j),d.return=y,d):(d=n(d,v.children||[]),d.return=y,d)}function S(y,d,v,j,Q){return d===null||d.tag!==7?(d=Mt(v,y.mode,j,Q),d.return=y,d):(d=n(d,v),d.return=y,d)}function z(y,d,v){if(typeof d=="string"&&d!==""||typeof d=="number"||typeof d=="bigint")return d=Ai(""+d,y.mode,v),d.return=y,d;if(typeof d=="object"&&d!==null){switch(d.$$typeof){case w:return v=Kn(d.type,d.key,d.props,null,y.mode,v),Wa(v,d),v.return=y,v;case J:return d=Ei(d,y.mode,v),d.return=y,d;case kl:return d=Bt(d),z(y,d,v)}if(ze(d)||Wl(d))return d=Mt(d,y.mode,v,null),d.return=y,d;if(typeof d.then=="function")return z(y,In(d),v);if(d.$$typeof===Z)return z(y,kn(y,d),v);Pn(y,d)}return null}function p(y,d,v,j){var Q=d!==null?d.key:null;if(typeof v=="string"&&v!==""||typeof v=="number"||typeof v=="bigint")return Q!==null?null:s(y,d,""+v,j);if(typeof v=="object"&&v!==null){switch(v.$$typeof){case w:return v.key===Q?o(y,d,v,j):null;case J:return v.key===Q?g(y,d,v,j):null;case kl:return v=Bt(v),p(y,d,v,j)}if(ze(v)||Wl(v))return Q!==null?null:S(y,d,v,j,null);if(typeof v.then=="function")return p(y,d,In(v),j);if(v.$$typeof===Z)return p(y,d,kn(y,v),j);Pn(y,v)}return null}function b(y,d,v,j,Q){if(typeof j=="string"&&j!==""||typeof j=="number"||typeof j=="bigint")return y=y.get(v)||null,s(d,y,""+j,Q);if(typeof j=="object"&&j!==null){switch(j.$$typeof){case w:return y=y.get(j.key===null?v:j.key)||null,o(d,y,j,Q);case J:return y=y.get(j.key===null?v:j.key)||null,g(d,y,j,Q);case kl:return j=Bt(j),b(y,d,v,j,Q)}if(ze(j)||Wl(j))return y=y.get(v)||null,S(d,y,j,Q,null);if(typeof j.then=="function")return b(y,d,v,In(j),Q);if(j.$$typeof===Z)return b(y,d,v,kn(d,j),Q);Pn(d,j)}return null}function B(y,d,v,j){for(var Q=null,cl=null,X=d,F=d=0,tl=null;X!==null&&F<v.length;F++){X.index>F?(tl=X,X=null):tl=X.sibling;var fl=p(y,X,v[F],j);if(fl===null){X===null&&(X=tl);break}l&&X&&fl.alternate===null&&e(y,X),d=u(fl,d,F),cl===null?Q=fl:cl.sibling=fl,cl=fl,X=tl}if(F===v.length)return t(y,X),nl&&Ye(y,F),Q;if(X===null){for(;F<v.length;F++)X=z(y,v[F],j),X!==null&&(d=u(X,d,F),cl===null?Q=X:cl.sibling=X,cl=X);return nl&&Ye(y,F),Q}for(X=a(X);F<v.length;F++)tl=b(X,y,F,v[F],j),tl!==null&&(l&&tl.alternate!==null&&X.delete(tl.key===null?F:tl.key),d=u(tl,d,F),cl===null?Q=tl:cl.sibling=tl,cl=tl);return l&&X.forEach(function(jt){return e(y,jt)}),nl&&Ye(y,F),Q}function L(y,d,v,j){if(v==null)throw Error(r(151));for(var Q=null,cl=null,X=d,F=d=0,tl=null,fl=v.next();X!==null&&!fl.done;F++,fl=v.next()){X.index>F?(tl=X,X=null):tl=X.sibling;var jt=p(y,X,fl.value,j);if(jt===null){X===null&&(X=tl);break}l&&X&&jt.alternate===null&&e(y,X),d=u(jt,d,F),cl===null?Q=jt:cl.sibling=jt,cl=jt,X=tl}if(fl.done)return t(y,X),nl&&Ye(y,F),Q;if(X===null){for(;!fl.done;F++,fl=v.next())fl=z(y,fl.value,j),fl!==null&&(d=u(fl,d,F),cl===null?Q=fl:cl.sibling=fl,cl=fl);return nl&&Ye(y,F),Q}for(X=a(X);!fl.done;F++,fl=v.next())fl=b(X,y,F,fl.value,j),fl!==null&&(l&&fl.alternate!==null&&X.delete(fl.key===null?F:fl.key),d=u(fl,d,F),cl===null?Q=fl:cl.sibling=fl,cl=fl);return l&&X.forEach(function(cy){return e(y,cy)}),nl&&Ye(y,F),Q}function vl(y,d,v,j){if(typeof v=="object"&&v!==null&&v.type===il&&v.key===null&&(v=v.props.children),typeof v=="object"&&v!==null){switch(v.$$typeof){case w:l:{for(var Q=v.key;d!==null;){if(d.key===Q){if(Q=v.type,Q===il){if(d.tag===7){t(y,d.sibling),j=n(d,v.props.children),j.return=y,y=j;break l}}else if(d.elementType===Q||typeof Q=="object"&&Q!==null&&Q.$$typeof===kl&&Bt(Q)===d.type){t(y,d.sibling),j=n(d,v.props),Wa(j,v),j.return=y,y=j;break l}t(y,d);break}else e(y,d);d=d.sibling}v.type===il?(j=Mt(v.props.children,y.mode,j,v.key),j.return=y,y=j):(j=Kn(v.type,v.key,v.props,null,y.mode,j),Wa(j,v),j.return=y,y=j)}return i(y);case J:l:{for(Q=v.key;d!==null;){if(d.key===Q)if(d.tag===4&&d.stateNode.containerInfo===v.containerInfo&&d.stateNode.implementation===v.implementation){t(y,d.sibling),j=n(d,v.children||[]),j.return=y,y=j;break l}else{t(y,d);break}else e(y,d);d=d.sibling}j=Ei(v,y.mode,j),j.return=y,y=j}return i(y);case kl:return v=Bt(v),vl(y,d,v,j)}if(ze(v))return B(y,d,v,j);if(Wl(v)){if(Q=Wl(v),typeof Q!="function")throw Error(r(150));return v=Q.call(v),L(y,d,v,j)}if(typeof v.then=="function")return vl(y,d,In(v),j);if(v.$$typeof===Z)return vl(y,d,kn(y,v),j);Pn(y,v)}return typeof v=="string"&&v!==""||typeof v=="number"||typeof v=="bigint"?(v=""+v,d!==null&&d.tag===6?(t(y,d.sibling),j=n(d,v),j.return=y,y=j):(t(y,d),j=Ai(v,y.mode,j),j.return=y,y=j),i(y)):t(y,d)}return function(y,d,v,j){try{ka=0;var Q=vl(y,d,v,j);return ra=null,Q}catch(X){if(X===oa||X===$n)throw X;var cl=ce(29,X,null,y.mode);return cl.lanes=j,cl.return=y,cl}finally{}}}var Yt=Cs(!0),Us=Cs(!1),ut=!1;function Yi(l){l.updateQueue={baseState:l.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Gi(l,e){l=l.updateQueue,e.updateQueue===l&&(e.updateQueue={baseState:l.baseState,firstBaseUpdate:l.firstBaseUpdate,lastBaseUpdate:l.lastBaseUpdate,shared:l.shared,callbacks:null})}function it(l){return{lane:l,tag:0,payload:null,callback:null,next:null}}function ct(l,e,t){var a=l.updateQueue;if(a===null)return null;if(a=a.shared,(sl&2)!==0){var n=a.pending;return n===null?e.next=e:(e.next=n.next,n.next=e),a.pending=e,e=Vn(l),vs(l,null,t),e}return Ln(l,a,e,t),Vn(l)}function $a(l,e,t){if(e=e.updateQueue,e!==null&&(e=e.shared,(t&4194048)!==0)){var a=e.lanes;a&=l.pendingLanes,t|=a,e.lanes=t,Tf(l,t)}}function Xi(l,e){var t=l.updateQueue,a=l.alternate;if(a!==null&&(a=a.updateQueue,t===a)){var n=null,u=null;if(t=t.firstBaseUpdate,t!==null){do{var i={lane:t.lane,tag:t.tag,payload:t.payload,callback:null,next:null};u===null?n=u=i:u=u.next=i,t=t.next}while(t!==null);u===null?n=u=e:u=u.next=e}else n=u=e;t={baseState:a.baseState,firstBaseUpdate:n,lastBaseUpdate:u,shared:a.shared,callbacks:a.callbacks},l.updateQueue=t;return}l=t.lastBaseUpdate,l===null?t.firstBaseUpdate=e:l.next=e,t.lastBaseUpdate=e}var Qi=!1;function Fa(){if(Qi){var l=sa;if(l!==null)throw l}}function Ia(l,e,t,a){Qi=!1;var n=l.updateQueue;ut=!1;var u=n.firstBaseUpdate,i=n.lastBaseUpdate,s=n.shared.pending;if(s!==null){n.shared.pending=null;var o=s,g=o.next;o.next=null,i===null?u=g:i.next=g,i=o;var S=l.alternate;S!==null&&(S=S.updateQueue,s=S.lastBaseUpdate,s!==i&&(s===null?S.firstBaseUpdate=g:s.next=g,S.lastBaseUpdate=o))}if(u!==null){var z=n.baseState;i=0,S=g=o=null,s=u;do{var p=s.lane&-536870913,b=p!==s.lane;if(b?(el&p)===p:(a&p)===p){p!==0&&p===fa&&(Qi=!0),S!==null&&(S=S.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});l:{var B=l,L=s;p=e;var vl=t;switch(L.tag){case 1:if(B=L.payload,typeof B=="function"){z=B.call(vl,z,p);break l}z=B;break l;case 3:B.flags=B.flags&-65537|128;case 0:if(B=L.payload,p=typeof B=="function"?B.call(vl,z,p):B,p==null)break l;z=M({},z,p);break l;case 2:ut=!0}}p=s.callback,p!==null&&(l.flags|=64,b&&(l.flags|=8192),b=n.callbacks,b===null?n.callbacks=[p]:b.push(p))}else b={lane:p,tag:s.tag,payload:s.payload,callback:s.callback,next:null},S===null?(g=S=b,o=z):S=S.next=b,i|=p;if(s=s.next,s===null){if(s=n.shared.pending,s===null)break;b=s,s=b.next,b.next=null,n.lastBaseUpdate=b,n.shared.pending=null}}while(!0);S===null&&(o=z),n.baseState=o,n.firstBaseUpdate=g,n.lastBaseUpdate=S,u===null&&(n.shared.lanes=0),dt|=i,l.lanes=i,l.memoizedState=z}}function Rs(l,e){if(typeof l!="function")throw Error(r(191,l));l.call(e)}function Hs(l,e){var t=l.callbacks;if(t!==null)for(l.callbacks=null,l=0;l<t.length;l++)Rs(t[l],e)}var da=m(null),lu=m(0);function Bs(l,e){l=We,R(lu,l),R(da,e),We=l|e.baseLanes}function Zi(){R(lu,We),R(da,da.current)}function Li(){We=lu.current,A(da),A(lu)}var fe=m(null),Se=null;function ft(l){var e=l.alternate;R(Ol,Ol.current&1),R(fe,l),Se===null&&(e===null||da.current!==null||e.memoizedState!==null)&&(Se=l)}function Vi(l){R(Ol,Ol.current),R(fe,l),Se===null&&(Se=l)}function qs(l){l.tag===22?(R(Ol,Ol.current),R(fe,l),Se===null&&(Se=l)):st()}function st(){R(Ol,Ol.current),R(fe,fe.current)}function se(l){A(fe),Se===l&&(Se=null),A(Ol)}var Ol=m(0);function eu(l){for(var e=l;e!==null;){if(e.tag===13){var t=e.memoizedState;if(t!==null&&(t=t.dehydrated,t===null||$c(t)||Fc(t)))return e}else if(e.tag===19&&(e.memoizedProps.revealOrder==="forwards"||e.memoizedProps.revealOrder==="backwards"||e.memoizedProps.revealOrder==="unstable_legacy-backwards"||e.memoizedProps.revealOrder==="together")){if((e.flags&128)!==0)return e}else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===l)break;for(;e.sibling===null;){if(e.return===null||e.return===l)return null;e=e.return}e.sibling.return=e.return,e=e.sibling}return null}var Qe=0,$=null,ml=null,Cl=null,tu=!1,ha=!1,Gt=!1,au=0,Pa=0,ma=null,Fh=0;function Al(){throw Error(r(321))}function Ki(l,e){if(e===null)return!1;for(var t=0;t<e.length&&t<l.length;t++)if(!ie(l[t],e[t]))return!1;return!0}function Ji(l,e,t,a,n,u){return Qe=u,$=e,e.memoizedState=null,e.updateQueue=null,e.lanes=0,x.H=l===null||l.memoizedState===null?xo:cc,Gt=!1,u=t(a,n),Gt=!1,ha&&(u=Gs(e,t,a,n)),Ys(l),u}function Ys(l){x.H=tn;var e=ml!==null&&ml.next!==null;if(Qe=0,Cl=ml=$=null,tu=!1,Pa=0,ma=null,e)throw Error(r(300));l===null||Ul||(l=l.dependencies,l!==null&&wn(l)&&(Ul=!0))}function Gs(l,e,t,a){$=l;var n=0;do{if(ha&&(ma=null),Pa=0,ha=!1,25<=n)throw Error(r(301));if(n+=1,Cl=ml=null,l.updateQueue!=null){var u=l.updateQueue;u.lastEffect=null,u.events=null,u.stores=null,u.memoCache!=null&&(u.memoCache.index=0)}x.H=jo,u=e(t,a)}while(ha);return u}function Ih(){var l=x.H,e=l.useState()[0];return e=typeof e.then=="function"?ln(e):e,l=l.useState()[0],(ml!==null?ml.memoizedState:null)!==l&&($.flags|=1024),e}function wi(){var l=au!==0;return au=0,l}function ki(l,e,t){e.updateQueue=l.updateQueue,e.flags&=-2053,l.lanes&=~t}function Wi(l){if(tu){for(l=l.memoizedState;l!==null;){var e=l.queue;e!==null&&(e.pending=null),l=l.next}tu=!1}Qe=0,Cl=ml=$=null,ha=!1,Pa=au=0,ma=null}function Jl(){var l={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Cl===null?$.memoizedState=Cl=l:Cl=Cl.next=l,Cl}function Nl(){if(ml===null){var l=$.alternate;l=l!==null?l.memoizedState:null}else l=ml.next;var e=Cl===null?$.memoizedState:Cl.next;if(e!==null)Cl=e,ml=l;else{if(l===null)throw $.alternate===null?Error(r(467)):Error(r(310));ml=l,l={memoizedState:ml.memoizedState,baseState:ml.baseState,baseQueue:ml.baseQueue,queue:ml.queue,next:null},Cl===null?$.memoizedState=Cl=l:Cl=Cl.next=l}return Cl}function nu(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function ln(l){var e=Pa;return Pa+=1,ma===null&&(ma=[]),l=Ns(ma,l,e),e=$,(Cl===null?e.memoizedState:Cl.next)===null&&(e=e.alternate,x.H=e===null||e.memoizedState===null?xo:cc),l}function uu(l){if(l!==null&&typeof l=="object"){if(typeof l.then=="function")return ln(l);if(l.$$typeof===Z)return Ql(l)}throw Error(r(438,String(l)))}function $i(l){var e=null,t=$.updateQueue;if(t!==null&&(e=t.memoCache),e==null){var a=$.alternate;a!==null&&(a=a.updateQueue,a!==null&&(a=a.memoCache,a!=null&&(e={data:a.data.map(function(n){return n.slice()}),index:0})))}if(e==null&&(e={data:[],index:0}),t===null&&(t=nu(),$.updateQueue=t),t.memoCache=e,t=e.data[e.index],t===void 0)for(t=e.data[e.index]=Array(l),a=0;a<l;a++)t[a]=Lt;return e.index++,t}function Ze(l,e){return typeof e=="function"?e(l):e}function iu(l){var e=Nl();return Fi(e,ml,l)}function Fi(l,e,t){var a=l.queue;if(a===null)throw Error(r(311));a.lastRenderedReducer=t;var n=l.baseQueue,u=a.pending;if(u!==null){if(n!==null){var i=n.next;n.next=u.next,u.next=i}e.baseQueue=n=u,a.pending=null}if(u=l.baseState,n===null)l.memoizedState=u;else{e=n.next;var s=i=null,o=null,g=e,S=!1;do{var z=g.lane&-536870913;if(z!==g.lane?(el&z)===z:(Qe&z)===z){var p=g.revertLane;if(p===0)o!==null&&(o=o.next={lane:0,revertLane:0,gesture:null,action:g.action,hasEagerState:g.hasEagerState,eagerState:g.eagerState,next:null}),z===fa&&(S=!0);else if((Qe&p)===p){g=g.next,p===fa&&(S=!0);continue}else z={lane:0,revertLane:g.revertLane,gesture:null,action:g.action,hasEagerState:g.hasEagerState,eagerState:g.eagerState,next:null},o===null?(s=o=z,i=u):o=o.next=z,$.lanes|=p,dt|=p;z=g.action,Gt&&t(u,z),u=g.hasEagerState?g.eagerState:t(u,z)}else p={lane:z,revertLane:g.revertLane,gesture:g.gesture,action:g.action,hasEagerState:g.hasEagerState,eagerState:g.eagerState,next:null},o===null?(s=o=p,i=u):o=o.next=p,$.lanes|=z,dt|=z;g=g.next}while(g!==null&&g!==e);if(o===null?i=u:o.next=s,!ie(u,l.memoizedState)&&(Ul=!0,S&&(t=sa,t!==null)))throw t;l.memoizedState=u,l.baseState=i,l.baseQueue=o,a.lastRenderedState=u}return n===null&&(a.lanes=0),[l.memoizedState,a.dispatch]}function Ii(l){var e=Nl(),t=e.queue;if(t===null)throw Error(r(311));t.lastRenderedReducer=l;var a=t.dispatch,n=t.pending,u=e.memoizedState;if(n!==null){t.pending=null;var i=n=n.next;do u=l(u,i.action),i=i.next;while(i!==n);ie(u,e.memoizedState)||(Ul=!0),e.memoizedState=u,e.baseQueue===null&&(e.baseState=u),t.lastRenderedState=u}return[u,a]}function Xs(l,e,t){var a=$,n=Nl(),u=nl;if(u){if(t===void 0)throw Error(r(407));t=t()}else t=e();var i=!ie((ml||n).memoizedState,t);if(i&&(n.memoizedState=t,Ul=!0),n=n.queue,ec(Ls.bind(null,a,n,l),[l]),n.getSnapshot!==e||i||Cl!==null&&Cl.memoizedState.tag&1){if(a.flags|=2048,ya(9,{destroy:void 0},Zs.bind(null,a,n,t,e),null),pl===null)throw Error(r(349));u||(Qe&127)!==0||Qs(a,e,t)}return t}function Qs(l,e,t){l.flags|=16384,l={getSnapshot:e,value:t},e=$.updateQueue,e===null?(e=nu(),$.updateQueue=e,e.stores=[l]):(t=e.stores,t===null?e.stores=[l]:t.push(l))}function Zs(l,e,t,a){e.value=t,e.getSnapshot=a,Vs(e)&&Ks(l)}function Ls(l,e,t){return t(function(){Vs(e)&&Ks(l)})}function Vs(l){var e=l.getSnapshot;l=l.value;try{var t=e();return!ie(l,t)}catch{return!0}}function Ks(l){var e=Dt(l,2);e!==null&&te(e,l,2)}function Pi(l){var e=Jl();if(typeof l=="function"){var t=l;if(l=t(),Gt){Ie(!0);try{t()}finally{Ie(!1)}}}return e.memoizedState=e.baseState=l,e.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ze,lastRenderedState:l},e}function Js(l,e,t,a){return l.baseState=t,Fi(l,ml,typeof a=="function"?a:Ze)}function Ph(l,e,t,a,n){if(su(l))throw Error(r(485));if(l=e.action,l!==null){var u={payload:n,action:l,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(i){u.listeners.push(i)}};x.T!==null?t(!0):u.isTransition=!1,a(u),t=e.pending,t===null?(u.next=e.pending=u,ws(e,u)):(u.next=t.next,e.pending=t.next=u)}}function ws(l,e){var t=e.action,a=e.payload,n=l.state;if(e.isTransition){var u=x.T,i={};x.T=i;try{var s=t(n,a),o=x.S;o!==null&&o(i,s),ks(l,e,s)}catch(g){lc(l,e,g)}finally{u!==null&&i.types!==null&&(u.types=i.types),x.T=u}}else try{u=t(n,a),ks(l,e,u)}catch(g){lc(l,e,g)}}function ks(l,e,t){t!==null&&typeof t=="object"&&typeof t.then=="function"?t.then(function(a){Ws(l,e,a)},function(a){return lc(l,e,a)}):Ws(l,e,t)}function Ws(l,e,t){e.status="fulfilled",e.value=t,$s(e),l.state=t,e=l.pending,e!==null&&(t=e.next,t===e?l.pending=null:(t=t.next,e.next=t,ws(l,t)))}function lc(l,e,t){var a=l.pending;if(l.pending=null,a!==null){a=a.next;do e.status="rejected",e.reason=t,$s(e),e=e.next;while(e!==a)}l.action=null}function $s(l){l=l.listeners;for(var e=0;e<l.length;e++)(0,l[e])()}function Fs(l,e){return e}function Is(l,e){if(nl){var t=pl.formState;if(t!==null){l:{var a=$;if(nl){if(bl){e:{for(var n=bl,u=be;n.nodeType!==8;){if(!u){n=null;break e}if(n=xe(n.nextSibling),n===null){n=null;break e}}u=n.data,n=u==="F!"||u==="F"?n:null}if(n){bl=xe(n.nextSibling),a=n.data==="F!";break l}}at(a)}a=!1}a&&(e=t[0])}}return t=Jl(),t.memoizedState=t.baseState=e,a={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Fs,lastRenderedState:e},t.queue=a,t=po.bind(null,$,a),a.dispatch=t,a=Pi(!1),u=ic.bind(null,$,!1,a.queue),a=Jl(),n={state:e,dispatch:null,action:l,pending:null},a.queue=n,t=Ph.bind(null,$,n,u,t),n.dispatch=t,a.memoizedState=l,[e,t,!1]}function Ps(l){var e=Nl();return lo(e,ml,l)}function lo(l,e,t){if(e=Fi(l,e,Fs)[0],l=iu(Ze)[0],typeof e=="object"&&e!==null&&typeof e.then=="function")try{var a=ln(e)}catch(i){throw i===oa?$n:i}else a=e;e=Nl();var n=e.queue,u=n.dispatch;return t!==e.memoizedState&&($.flags|=2048,ya(9,{destroy:void 0},lm.bind(null,n,t),null)),[a,u,l]}function lm(l,e){l.action=e}function eo(l){var e=Nl(),t=ml;if(t!==null)return lo(e,t,l);Nl(),e=e.memoizedState,t=Nl();var a=t.queue.dispatch;return t.memoizedState=l,[e,a,!1]}function ya(l,e,t,a){return l={tag:l,create:t,deps:a,inst:e,next:null},e=$.updateQueue,e===null&&(e=nu(),$.updateQueue=e),t=e.lastEffect,t===null?e.lastEffect=l.next=l:(a=t.next,t.next=l,l.next=a,e.lastEffect=l),l}function to(){return Nl().memoizedState}function cu(l,e,t,a){var n=Jl();$.flags|=l,n.memoizedState=ya(1|e,{destroy:void 0},t,a===void 0?null:a)}function fu(l,e,t,a){var n=Nl();a=a===void 0?null:a;var u=n.memoizedState.inst;ml!==null&&a!==null&&Ki(a,ml.memoizedState.deps)?n.memoizedState=ya(e,u,t,a):($.flags|=l,n.memoizedState=ya(1|e,u,t,a))}function ao(l,e){cu(8390656,8,l,e)}function ec(l,e){fu(2048,8,l,e)}function em(l){$.flags|=4;var e=$.updateQueue;if(e===null)e=nu(),$.updateQueue=e,e.events=[l];else{var t=e.events;t===null?e.events=[l]:t.push(l)}}function no(l){var e=Nl().memoizedState;return em({ref:e,nextImpl:l}),function(){if((sl&2)!==0)throw Error(r(440));return e.impl.apply(void 0,arguments)}}function uo(l,e){return fu(4,2,l,e)}function io(l,e){return fu(4,4,l,e)}function co(l,e){if(typeof e=="function"){l=l();var t=e(l);return function(){typeof t=="function"?t():e(null)}}if(e!=null)return l=l(),e.current=l,function(){e.current=null}}function fo(l,e,t){t=t!=null?t.concat([l]):null,fu(4,4,co.bind(null,e,l),t)}function tc(){}function so(l,e){var t=Nl();e=e===void 0?null:e;var a=t.memoizedState;return e!==null&&Ki(e,a[1])?a[0]:(t.memoizedState=[l,e],l)}function oo(l,e){var t=Nl();e=e===void 0?null:e;var a=t.memoizedState;if(e!==null&&Ki(e,a[1]))return a[0];if(a=l(),Gt){Ie(!0);try{l()}finally{Ie(!1)}}return t.memoizedState=[a,e],a}function ac(l,e,t){return t===void 0||(Qe&1073741824)!==0&&(el&261930)===0?l.memoizedState=e:(l.memoizedState=t,l=dr(),$.lanes|=l,dt|=l,t)}function ro(l,e,t,a){return ie(t,e)?t:da.current!==null?(l=ac(l,t,a),ie(l,e)||(Ul=!0),l):(Qe&42)===0||(Qe&1073741824)!==0&&(el&261930)===0?(Ul=!0,l.memoizedState=t):(l=dr(),$.lanes|=l,dt|=l,e)}function ho(l,e,t,a,n){var u=U.p;U.p=u!==0&&8>u?u:8;var i=x.T,s={};x.T=s,ic(l,!1,e,t);try{var o=n(),g=x.S;if(g!==null&&g(s,o),o!==null&&typeof o=="object"&&typeof o.then=="function"){var S=$h(o,a);en(l,e,S,de(l))}else en(l,e,a,de(l))}catch(z){en(l,e,{then:function(){},status:"rejected",reason:z},de())}finally{U.p=u,i!==null&&s.types!==null&&(i.types=s.types),x.T=i}}function tm(){}function nc(l,e,t,a){if(l.tag!==5)throw Error(r(476));var n=mo(l).queue;ho(l,n,e,V,t===null?tm:function(){return yo(l),t(a)})}function mo(l){var e=l.memoizedState;if(e!==null)return e;e={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ze,lastRenderedState:V},next:null};var t={};return e.next={memoizedState:t,baseState:t,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ze,lastRenderedState:t},next:null},l.memoizedState=e,l=l.alternate,l!==null&&(l.memoizedState=e),e}function yo(l){var e=mo(l);e.next===null&&(e=l.alternate.memoizedState),en(l,e.next.queue,{},de())}function uc(){return Ql(bn)}function vo(){return Nl().memoizedState}function go(){return Nl().memoizedState}function am(l){for(var e=l.return;e!==null;){switch(e.tag){case 24:case 3:var t=de();l=it(t);var a=ct(e,l,t);a!==null&&(te(a,e,t),$a(a,e,t)),e={cache:Ri()},l.payload=e;return}e=e.return}}function nm(l,e,t){var a=de();t={lane:a,revertLane:0,gesture:null,action:t,hasEagerState:!1,eagerState:null,next:null},su(l)?bo(e,t):(t=zi(l,e,t,a),t!==null&&(te(t,l,a),So(t,e,a)))}function po(l,e,t){var a=de();en(l,e,t,a)}function en(l,e,t,a){var n={lane:a,revertLane:0,gesture:null,action:t,hasEagerState:!1,eagerState:null,next:null};if(su(l))bo(e,n);else{var u=l.alternate;if(l.lanes===0&&(u===null||u.lanes===0)&&(u=e.lastRenderedReducer,u!==null))try{var i=e.lastRenderedState,s=u(i,t);if(n.hasEagerState=!0,n.eagerState=s,ie(s,i))return Ln(l,e,n,0),pl===null&&Zn(),!1}catch{}finally{}if(t=zi(l,e,n,a),t!==null)return te(t,l,a),So(t,e,a),!0}return!1}function ic(l,e,t,a){if(a={lane:2,revertLane:Yc(),gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null},su(l)){if(e)throw Error(r(479))}else e=zi(l,t,a,2),e!==null&&te(e,l,2)}function su(l){var e=l.alternate;return l===$||e!==null&&e===$}function bo(l,e){ha=tu=!0;var t=l.pending;t===null?e.next=e:(e.next=t.next,t.next=e),l.pending=e}function So(l,e,t){if((t&4194048)!==0){var a=e.lanes;a&=l.pendingLanes,t|=a,e.lanes=t,Tf(l,t)}}var tn={readContext:Ql,use:uu,useCallback:Al,useContext:Al,useEffect:Al,useImperativeHandle:Al,useLayoutEffect:Al,useInsertionEffect:Al,useMemo:Al,useReducer:Al,useRef:Al,useState:Al,useDebugValue:Al,useDeferredValue:Al,useTransition:Al,useSyncExternalStore:Al,useId:Al,useHostTransitionStatus:Al,useFormState:Al,useActionState:Al,useOptimistic:Al,useMemoCache:Al,useCacheRefresh:Al};tn.useEffectEvent=Al;var xo={readContext:Ql,use:uu,useCallback:function(l,e){return Jl().memoizedState=[l,e===void 0?null:e],l},useContext:Ql,useEffect:ao,useImperativeHandle:function(l,e,t){t=t!=null?t.concat([l]):null,cu(4194308,4,co.bind(null,e,l),t)},useLayoutEffect:function(l,e){return cu(4194308,4,l,e)},useInsertionEffect:function(l,e){cu(4,2,l,e)},useMemo:function(l,e){var t=Jl();e=e===void 0?null:e;var a=l();if(Gt){Ie(!0);try{l()}finally{Ie(!1)}}return t.memoizedState=[a,e],a},useReducer:function(l,e,t){var a=Jl();if(t!==void 0){var n=t(e);if(Gt){Ie(!0);try{t(e)}finally{Ie(!1)}}}else n=e;return a.memoizedState=a.baseState=n,l={pending:null,lanes:0,dispatch:null,lastRenderedReducer:l,lastRenderedState:n},a.queue=l,l=l.dispatch=nm.bind(null,$,l),[a.memoizedState,l]},useRef:function(l){var e=Jl();return l={current:l},e.memoizedState=l},useState:function(l){l=Pi(l);var e=l.queue,t=po.bind(null,$,e);return e.dispatch=t,[l.memoizedState,t]},useDebugValue:tc,useDeferredValue:function(l,e){var t=Jl();return ac(t,l,e)},useTransition:function(){var l=Pi(!1);return l=ho.bind(null,$,l.queue,!0,!1),Jl().memoizedState=l,[!1,l]},useSyncExternalStore:function(l,e,t){var a=$,n=Jl();if(nl){if(t===void 0)throw Error(r(407));t=t()}else{if(t=e(),pl===null)throw Error(r(349));(el&127)!==0||Qs(a,e,t)}n.memoizedState=t;var u={value:t,getSnapshot:e};return n.queue=u,ao(Ls.bind(null,a,u,l),[l]),a.flags|=2048,ya(9,{destroy:void 0},Zs.bind(null,a,u,t,e),null),t},useId:function(){var l=Jl(),e=pl.identifierPrefix;if(nl){var t=De,a=Ne;t=(a&~(1<<32-ue(a)-1)).toString(32)+t,e="_"+e+"R_"+t,t=au++,0<t&&(e+="H"+t.toString(32)),e+="_"}else t=Fh++,e="_"+e+"r_"+t.toString(32)+"_";return l.memoizedState=e},useHostTransitionStatus:uc,useFormState:Is,useActionState:Is,useOptimistic:function(l){var e=Jl();e.memoizedState=e.baseState=l;var t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return e.queue=t,e=ic.bind(null,$,!0,t),t.dispatch=e,[l,e]},useMemoCache:$i,useCacheRefresh:function(){return Jl().memoizedState=am.bind(null,$)},useEffectEvent:function(l){var e=Jl(),t={impl:l};return e.memoizedState=t,function(){if((sl&2)!==0)throw Error(r(440));return t.impl.apply(void 0,arguments)}}},cc={readContext:Ql,use:uu,useCallback:so,useContext:Ql,useEffect:ec,useImperativeHandle:fo,useInsertionEffect:uo,useLayoutEffect:io,useMemo:oo,useReducer:iu,useRef:to,useState:function(){return iu(Ze)},useDebugValue:tc,useDeferredValue:function(l,e){var t=Nl();return ro(t,ml.memoizedState,l,e)},useTransition:function(){var l=iu(Ze)[0],e=Nl().memoizedState;return[typeof l=="boolean"?l:ln(l),e]},useSyncExternalStore:Xs,useId:vo,useHostTransitionStatus:uc,useFormState:Ps,useActionState:Ps,useOptimistic:function(l,e){var t=Nl();return Js(t,ml,l,e)},useMemoCache:$i,useCacheRefresh:go};cc.useEffectEvent=no;var jo={readContext:Ql,use:uu,useCallback:so,useContext:Ql,useEffect:ec,useImperativeHandle:fo,useInsertionEffect:uo,useLayoutEffect:io,useMemo:oo,useReducer:Ii,useRef:to,useState:function(){return Ii(Ze)},useDebugValue:tc,useDeferredValue:function(l,e){var t=Nl();return ml===null?ac(t,l,e):ro(t,ml.memoizedState,l,e)},useTransition:function(){var l=Ii(Ze)[0],e=Nl().memoizedState;return[typeof l=="boolean"?l:ln(l),e]},useSyncExternalStore:Xs,useId:vo,useHostTransitionStatus:uc,useFormState:eo,useActionState:eo,useOptimistic:function(l,e){var t=Nl();return ml!==null?Js(t,ml,l,e):(t.baseState=l,[l,t.queue.dispatch])},useMemoCache:$i,useCacheRefresh:go};jo.useEffectEvent=no;function fc(l,e,t,a){e=l.memoizedState,t=t(a,e),t=t==null?e:M({},e,t),l.memoizedState=t,l.lanes===0&&(l.updateQueue.baseState=t)}var sc={enqueueSetState:function(l,e,t){l=l._reactInternals;var a=de(),n=it(a);n.payload=e,t!=null&&(n.callback=t),e=ct(l,n,a),e!==null&&(te(e,l,a),$a(e,l,a))},enqueueReplaceState:function(l,e,t){l=l._reactInternals;var a=de(),n=it(a);n.tag=1,n.payload=e,t!=null&&(n.callback=t),e=ct(l,n,a),e!==null&&(te(e,l,a),$a(e,l,a))},enqueueForceUpdate:function(l,e){l=l._reactInternals;var t=de(),a=it(t);a.tag=2,e!=null&&(a.callback=e),e=ct(l,a,t),e!==null&&(te(e,l,t),$a(e,l,t))}};function zo(l,e,t,a,n,u,i){return l=l.stateNode,typeof l.shouldComponentUpdate=="function"?l.shouldComponentUpdate(a,u,i):e.prototype&&e.prototype.isPureReactComponent?!Za(t,a)||!Za(n,u):!0}function To(l,e,t,a){l=e.state,typeof e.componentWillReceiveProps=="function"&&e.componentWillReceiveProps(t,a),typeof e.UNSAFE_componentWillReceiveProps=="function"&&e.UNSAFE_componentWillReceiveProps(t,a),e.state!==l&&sc.enqueueReplaceState(e,e.state,null)}function Xt(l,e){var t=e;if("ref"in e){t={};for(var a in e)a!=="ref"&&(t[a]=e[a])}if(l=l.defaultProps){t===e&&(t=M({},t));for(var n in l)t[n]===void 0&&(t[n]=l[n])}return t}function Ao(l){Qn(l)}function Eo(l){console.error(l)}function _o(l){Qn(l)}function ou(l,e){try{var t=l.onUncaughtError;t(e.value,{componentStack:e.stack})}catch(a){setTimeout(function(){throw a})}}function Oo(l,e,t){try{var a=l.onCaughtError;a(t.value,{componentStack:t.stack,errorBoundary:e.tag===1?e.stateNode:null})}catch(n){setTimeout(function(){throw n})}}function oc(l,e,t){return t=it(t),t.tag=3,t.payload={element:null},t.callback=function(){ou(l,e)},t}function No(l){return l=it(l),l.tag=3,l}function Do(l,e,t,a){var n=t.type.getDerivedStateFromError;if(typeof n=="function"){var u=a.value;l.payload=function(){return n(u)},l.callback=function(){Oo(e,t,a)}}var i=t.stateNode;i!==null&&typeof i.componentDidCatch=="function"&&(l.callback=function(){Oo(e,t,a),typeof n!="function"&&(ht===null?ht=new Set([this]):ht.add(this));var s=a.stack;this.componentDidCatch(a.value,{componentStack:s!==null?s:""})})}function um(l,e,t,a,n){if(t.flags|=32768,a!==null&&typeof a=="object"&&typeof a.then=="function"){if(e=t.alternate,e!==null&&ca(e,t,n,!0),t=fe.current,t!==null){switch(t.tag){case 31:case 13:return Se===null?ju():t.alternate===null&&El===0&&(El=3),t.flags&=-257,t.flags|=65536,t.lanes=n,a===Fn?t.flags|=16384:(e=t.updateQueue,e===null?t.updateQueue=new Set([a]):e.add(a),Hc(l,a,n)),!1;case 22:return t.flags|=65536,a===Fn?t.flags|=16384:(e=t.updateQueue,e===null?(e={transitions:null,markerInstances:null,retryQueue:new Set([a])},t.updateQueue=e):(t=e.retryQueue,t===null?e.retryQueue=new Set([a]):t.add(a)),Hc(l,a,n)),!1}throw Error(r(435,t.tag))}return Hc(l,a,n),ju(),!1}if(nl)return e=fe.current,e!==null?((e.flags&65536)===0&&(e.flags|=256),e.flags|=65536,e.lanes=n,a!==Ni&&(l=Error(r(422),{cause:a}),Ka(ve(l,t)))):(a!==Ni&&(e=Error(r(423),{cause:a}),Ka(ve(e,t))),l=l.current.alternate,l.flags|=65536,n&=-n,l.lanes|=n,a=ve(a,t),n=oc(l.stateNode,a,n),Xi(l,n),El!==4&&(El=2)),!1;var u=Error(r(520),{cause:a});if(u=ve(u,t),rn===null?rn=[u]:rn.push(u),El!==4&&(El=2),e===null)return!0;a=ve(a,t),t=e;do{switch(t.tag){case 3:return t.flags|=65536,l=n&-n,t.lanes|=l,l=oc(t.stateNode,a,l),Xi(t,l),!1;case 1:if(e=t.type,u=t.stateNode,(t.flags&128)===0&&(typeof e.getDerivedStateFromError=="function"||u!==null&&typeof u.componentDidCatch=="function"&&(ht===null||!ht.has(u))))return t.flags|=65536,n&=-n,t.lanes|=n,n=No(n),Do(n,l,t,a),Xi(t,n),!1}t=t.return}while(t!==null);return!1}var rc=Error(r(461)),Ul=!1;function Zl(l,e,t,a){e.child=l===null?Us(e,null,t,a):Yt(e,l.child,t,a)}function Mo(l,e,t,a,n){t=t.render;var u=e.ref;if("ref"in a){var i={};for(var s in a)s!=="ref"&&(i[s]=a[s])}else i=a;return Rt(e),a=Ji(l,e,t,i,u,n),s=wi(),l!==null&&!Ul?(ki(l,e,n),Le(l,e,n)):(nl&&s&&_i(e),e.flags|=1,Zl(l,e,a,n),e.child)}function Co(l,e,t,a,n){if(l===null){var u=t.type;return typeof u=="function"&&!Ti(u)&&u.defaultProps===void 0&&t.compare===null?(e.tag=15,e.type=u,Uo(l,e,u,a,n)):(l=Kn(t.type,null,a,e,e.mode,n),l.ref=e.ref,l.return=e,e.child=l)}if(u=l.child,!bc(l,n)){var i=u.memoizedProps;if(t=t.compare,t=t!==null?t:Za,t(i,a)&&l.ref===e.ref)return Le(l,e,n)}return e.flags|=1,l=qe(u,a),l.ref=e.ref,l.return=e,e.child=l}function Uo(l,e,t,a,n){if(l!==null){var u=l.memoizedProps;if(Za(u,a)&&l.ref===e.ref)if(Ul=!1,e.pendingProps=a=u,bc(l,n))(l.flags&131072)!==0&&(Ul=!0);else return e.lanes=l.lanes,Le(l,e,n)}return dc(l,e,t,a,n)}function Ro(l,e,t,a){var n=a.children,u=l!==null?l.memoizedState:null;if(l===null&&e.stateNode===null&&(e.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),a.mode==="hidden"){if((e.flags&128)!==0){if(u=u!==null?u.baseLanes|t:t,l!==null){for(a=e.child=l.child,n=0;a!==null;)n=n|a.lanes|a.childLanes,a=a.sibling;a=n&~u}else a=0,e.child=null;return Ho(l,e,u,t,a)}if((t&536870912)!==0)e.memoizedState={baseLanes:0,cachePool:null},l!==null&&Wn(e,u!==null?u.cachePool:null),u!==null?Bs(e,u):Zi(),qs(e);else return a=e.lanes=536870912,Ho(l,e,u!==null?u.baseLanes|t:t,t,a)}else u!==null?(Wn(e,u.cachePool),Bs(e,u),st(),e.memoizedState=null):(l!==null&&Wn(e,null),Zi(),st());return Zl(l,e,n,t),e.child}function an(l,e){return l!==null&&l.tag===22||e.stateNode!==null||(e.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),e.sibling}function Ho(l,e,t,a,n){var u=Bi();return u=u===null?null:{parent:Ml._currentValue,pool:u},e.memoizedState={baseLanes:t,cachePool:u},l!==null&&Wn(e,null),Zi(),qs(e),l!==null&&ca(l,e,a,!0),e.childLanes=n,null}function ru(l,e){return e=hu({mode:e.mode,children:e.children},l.mode),e.ref=l.ref,l.child=e,e.return=l,e}function Bo(l,e,t){return Yt(e,l.child,null,t),l=ru(e,e.pendingProps),l.flags|=2,se(e),e.memoizedState=null,l}function im(l,e,t){var a=e.pendingProps,n=(e.flags&128)!==0;if(e.flags&=-129,l===null){if(nl){if(a.mode==="hidden")return l=ru(e,a),e.lanes=536870912,an(null,l);if(Vi(e),(l=bl)?(l=kr(l,be),l=l!==null&&l.data==="&"?l:null,l!==null&&(e.memoizedState={dehydrated:l,treeContext:et!==null?{id:Ne,overflow:De}:null,retryLane:536870912,hydrationErrors:null},t=ps(l),t.return=e,e.child=t,Xl=e,bl=null)):l=null,l===null)throw at(e);return e.lanes=536870912,null}return ru(e,a)}var u=l.memoizedState;if(u!==null){var i=u.dehydrated;if(Vi(e),n)if(e.flags&256)e.flags&=-257,e=Bo(l,e,t);else if(e.memoizedState!==null)e.child=l.child,e.flags|=128,e=null;else throw Error(r(558));else if(Ul||ca(l,e,t,!1),n=(t&l.childLanes)!==0,Ul||n){if(a=pl,a!==null&&(i=Af(a,t),i!==0&&i!==u.retryLane))throw u.retryLane=i,Dt(l,i),te(a,l,i),rc;ju(),e=Bo(l,e,t)}else l=u.treeContext,bl=xe(i.nextSibling),Xl=e,nl=!0,tt=null,be=!1,l!==null&&xs(e,l),e=ru(e,a),e.flags|=4096;return e}return l=qe(l.child,{mode:a.mode,children:a.children}),l.ref=e.ref,e.child=l,l.return=e,l}function du(l,e){var t=e.ref;if(t===null)l!==null&&l.ref!==null&&(e.flags|=4194816);else{if(typeof t!="function"&&typeof t!="object")throw Error(r(284));(l===null||l.ref!==t)&&(e.flags|=4194816)}}function dc(l,e,t,a,n){return Rt(e),t=Ji(l,e,t,a,void 0,n),a=wi(),l!==null&&!Ul?(ki(l,e,n),Le(l,e,n)):(nl&&a&&_i(e),e.flags|=1,Zl(l,e,t,n),e.child)}function qo(l,e,t,a,n,u){return Rt(e),e.updateQueue=null,t=Gs(e,a,t,n),Ys(l),a=wi(),l!==null&&!Ul?(ki(l,e,u),Le(l,e,u)):(nl&&a&&_i(e),e.flags|=1,Zl(l,e,t,u),e.child)}function Yo(l,e,t,a,n){if(Rt(e),e.stateNode===null){var u=aa,i=t.contextType;typeof i=="object"&&i!==null&&(u=Ql(i)),u=new t(a,u),e.memoizedState=u.state!==null&&u.state!==void 0?u.state:null,u.updater=sc,e.stateNode=u,u._reactInternals=e,u=e.stateNode,u.props=a,u.state=e.memoizedState,u.refs={},Yi(e),i=t.contextType,u.context=typeof i=="object"&&i!==null?Ql(i):aa,u.state=e.memoizedState,i=t.getDerivedStateFromProps,typeof i=="function"&&(fc(e,t,i,a),u.state=e.memoizedState),typeof t.getDerivedStateFromProps=="function"||typeof u.getSnapshotBeforeUpdate=="function"||typeof u.UNSAFE_componentWillMount!="function"&&typeof u.componentWillMount!="function"||(i=u.state,typeof u.componentWillMount=="function"&&u.componentWillMount(),typeof u.UNSAFE_componentWillMount=="function"&&u.UNSAFE_componentWillMount(),i!==u.state&&sc.enqueueReplaceState(u,u.state,null),Ia(e,a,u,n),Fa(),u.state=e.memoizedState),typeof u.componentDidMount=="function"&&(e.flags|=4194308),a=!0}else if(l===null){u=e.stateNode;var s=e.memoizedProps,o=Xt(t,s);u.props=o;var g=u.context,S=t.contextType;i=aa,typeof S=="object"&&S!==null&&(i=Ql(S));var z=t.getDerivedStateFromProps;S=typeof z=="function"||typeof u.getSnapshotBeforeUpdate=="function",s=e.pendingProps!==s,S||typeof u.UNSAFE_componentWillReceiveProps!="function"&&typeof u.componentWillReceiveProps!="function"||(s||g!==i)&&To(e,u,a,i),ut=!1;var p=e.memoizedState;u.state=p,Ia(e,a,u,n),Fa(),g=e.memoizedState,s||p!==g||ut?(typeof z=="function"&&(fc(e,t,z,a),g=e.memoizedState),(o=ut||zo(e,t,o,a,p,g,i))?(S||typeof u.UNSAFE_componentWillMount!="function"&&typeof u.componentWillMount!="function"||(typeof u.componentWillMount=="function"&&u.componentWillMount(),typeof u.UNSAFE_componentWillMount=="function"&&u.UNSAFE_componentWillMount()),typeof u.componentDidMount=="function"&&(e.flags|=4194308)):(typeof u.componentDidMount=="function"&&(e.flags|=4194308),e.memoizedProps=a,e.memoizedState=g),u.props=a,u.state=g,u.context=i,a=o):(typeof u.componentDidMount=="function"&&(e.flags|=4194308),a=!1)}else{u=e.stateNode,Gi(l,e),i=e.memoizedProps,S=Xt(t,i),u.props=S,z=e.pendingProps,p=u.context,g=t.contextType,o=aa,typeof g=="object"&&g!==null&&(o=Ql(g)),s=t.getDerivedStateFromProps,(g=typeof s=="function"||typeof u.getSnapshotBeforeUpdate=="function")||typeof u.UNSAFE_componentWillReceiveProps!="function"&&typeof u.componentWillReceiveProps!="function"||(i!==z||p!==o)&&To(e,u,a,o),ut=!1,p=e.memoizedState,u.state=p,Ia(e,a,u,n),Fa();var b=e.memoizedState;i!==z||p!==b||ut||l!==null&&l.dependencies!==null&&wn(l.dependencies)?(typeof s=="function"&&(fc(e,t,s,a),b=e.memoizedState),(S=ut||zo(e,t,S,a,p,b,o)||l!==null&&l.dependencies!==null&&wn(l.dependencies))?(g||typeof u.UNSAFE_componentWillUpdate!="function"&&typeof u.componentWillUpdate!="function"||(typeof u.componentWillUpdate=="function"&&u.componentWillUpdate(a,b,o),typeof u.UNSAFE_componentWillUpdate=="function"&&u.UNSAFE_componentWillUpdate(a,b,o)),typeof u.componentDidUpdate=="function"&&(e.flags|=4),typeof u.getSnapshotBeforeUpdate=="function"&&(e.flags|=1024)):(typeof u.componentDidUpdate!="function"||i===l.memoizedProps&&p===l.memoizedState||(e.flags|=4),typeof u.getSnapshotBeforeUpdate!="function"||i===l.memoizedProps&&p===l.memoizedState||(e.flags|=1024),e.memoizedProps=a,e.memoizedState=b),u.props=a,u.state=b,u.context=o,a=S):(typeof u.componentDidUpdate!="function"||i===l.memoizedProps&&p===l.memoizedState||(e.flags|=4),typeof u.getSnapshotBeforeUpdate!="function"||i===l.memoizedProps&&p===l.memoizedState||(e.flags|=1024),a=!1)}return u=a,du(l,e),a=(e.flags&128)!==0,u||a?(u=e.stateNode,t=a&&typeof t.getDerivedStateFromError!="function"?null:u.render(),e.flags|=1,l!==null&&a?(e.child=Yt(e,l.child,null,n),e.child=Yt(e,null,t,n)):Zl(l,e,t,n),e.memoizedState=u.state,l=e.child):l=Le(l,e,n),l}function Go(l,e,t,a){return Ct(),e.flags|=256,Zl(l,e,t,a),e.child}var hc={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function mc(l){return{baseLanes:l,cachePool:_s()}}function yc(l,e,t){return l=l!==null?l.childLanes&~t:0,e&&(l|=re),l}function Xo(l,e,t){var a=e.pendingProps,n=!1,u=(e.flags&128)!==0,i;if((i=u)||(i=l!==null&&l.memoizedState===null?!1:(Ol.current&2)!==0),i&&(n=!0,e.flags&=-129),i=(e.flags&32)!==0,e.flags&=-33,l===null){if(nl){if(n?ft(e):st(),(l=bl)?(l=kr(l,be),l=l!==null&&l.data!=="&"?l:null,l!==null&&(e.memoizedState={dehydrated:l,treeContext:et!==null?{id:Ne,overflow:De}:null,retryLane:536870912,hydrationErrors:null},t=ps(l),t.return=e,e.child=t,Xl=e,bl=null)):l=null,l===null)throw at(e);return Fc(l)?e.lanes=32:e.lanes=536870912,null}var s=a.children;return a=a.fallback,n?(st(),n=e.mode,s=hu({mode:"hidden",children:s},n),a=Mt(a,n,t,null),s.return=e,a.return=e,s.sibling=a,e.child=s,a=e.child,a.memoizedState=mc(t),a.childLanes=yc(l,i,t),e.memoizedState=hc,an(null,a)):(ft(e),vc(e,s))}var o=l.memoizedState;if(o!==null&&(s=o.dehydrated,s!==null)){if(u)e.flags&256?(ft(e),e.flags&=-257,e=gc(l,e,t)):e.memoizedState!==null?(st(),e.child=l.child,e.flags|=128,e=null):(st(),s=a.fallback,n=e.mode,a=hu({mode:"visible",children:a.children},n),s=Mt(s,n,t,null),s.flags|=2,a.return=e,s.return=e,a.sibling=s,e.child=a,Yt(e,l.child,null,t),a=e.child,a.memoizedState=mc(t),a.childLanes=yc(l,i,t),e.memoizedState=hc,e=an(null,a));else if(ft(e),Fc(s)){if(i=s.nextSibling&&s.nextSibling.dataset,i)var g=i.dgst;i=g,a=Error(r(419)),a.stack="",a.digest=i,Ka({value:a,source:null,stack:null}),e=gc(l,e,t)}else if(Ul||ca(l,e,t,!1),i=(t&l.childLanes)!==0,Ul||i){if(i=pl,i!==null&&(a=Af(i,t),a!==0&&a!==o.retryLane))throw o.retryLane=a,Dt(l,a),te(i,l,a),rc;$c(s)||ju(),e=gc(l,e,t)}else $c(s)?(e.flags|=192,e.child=l.child,e=null):(l=o.treeContext,bl=xe(s.nextSibling),Xl=e,nl=!0,tt=null,be=!1,l!==null&&xs(e,l),e=vc(e,a.children),e.flags|=4096);return e}return n?(st(),s=a.fallback,n=e.mode,o=l.child,g=o.sibling,a=qe(o,{mode:"hidden",children:a.children}),a.subtreeFlags=o.subtreeFlags&65011712,g!==null?s=qe(g,s):(s=Mt(s,n,t,null),s.flags|=2),s.return=e,a.return=e,a.sibling=s,e.child=a,an(null,a),a=e.child,s=l.child.memoizedState,s===null?s=mc(t):(n=s.cachePool,n!==null?(o=Ml._currentValue,n=n.parent!==o?{parent:o,pool:o}:n):n=_s(),s={baseLanes:s.baseLanes|t,cachePool:n}),a.memoizedState=s,a.childLanes=yc(l,i,t),e.memoizedState=hc,an(l.child,a)):(ft(e),t=l.child,l=t.sibling,t=qe(t,{mode:"visible",children:a.children}),t.return=e,t.sibling=null,l!==null&&(i=e.deletions,i===null?(e.deletions=[l],e.flags|=16):i.push(l)),e.child=t,e.memoizedState=null,t)}function vc(l,e){return e=hu({mode:"visible",children:e},l.mode),e.return=l,l.child=e}function hu(l,e){return l=ce(22,l,null,e),l.lanes=0,l}function gc(l,e,t){return Yt(e,l.child,null,t),l=vc(e,e.pendingProps.children),l.flags|=2,e.memoizedState=null,l}function Qo(l,e,t){l.lanes|=e;var a=l.alternate;a!==null&&(a.lanes|=e),Ci(l.return,e,t)}function pc(l,e,t,a,n,u){var i=l.memoizedState;i===null?l.memoizedState={isBackwards:e,rendering:null,renderingStartTime:0,last:a,tail:t,tailMode:n,treeForkCount:u}:(i.isBackwards=e,i.rendering=null,i.renderingStartTime=0,i.last=a,i.tail=t,i.tailMode=n,i.treeForkCount=u)}function Zo(l,e,t){var a=e.pendingProps,n=a.revealOrder,u=a.tail;a=a.children;var i=Ol.current,s=(i&2)!==0;if(s?(i=i&1|2,e.flags|=128):i&=1,R(Ol,i),Zl(l,e,a,t),a=nl?Va:0,!s&&l!==null&&(l.flags&128)!==0)l:for(l=e.child;l!==null;){if(l.tag===13)l.memoizedState!==null&&Qo(l,t,e);else if(l.tag===19)Qo(l,t,e);else if(l.child!==null){l.child.return=l,l=l.child;continue}if(l===e)break l;for(;l.sibling===null;){if(l.return===null||l.return===e)break l;l=l.return}l.sibling.return=l.return,l=l.sibling}switch(n){case"forwards":for(t=e.child,n=null;t!==null;)l=t.alternate,l!==null&&eu(l)===null&&(n=t),t=t.sibling;t=n,t===null?(n=e.child,e.child=null):(n=t.sibling,t.sibling=null),pc(e,!1,n,t,u,a);break;case"backwards":case"unstable_legacy-backwards":for(t=null,n=e.child,e.child=null;n!==null;){if(l=n.alternate,l!==null&&eu(l)===null){e.child=n;break}l=n.sibling,n.sibling=t,t=n,n=l}pc(e,!0,t,null,u,a);break;case"together":pc(e,!1,null,null,void 0,a);break;default:e.memoizedState=null}return e.child}function Le(l,e,t){if(l!==null&&(e.dependencies=l.dependencies),dt|=e.lanes,(t&e.childLanes)===0)if(l!==null){if(ca(l,e,t,!1),(t&e.childLanes)===0)return null}else return null;if(l!==null&&e.child!==l.child)throw Error(r(153));if(e.child!==null){for(l=e.child,t=qe(l,l.pendingProps),e.child=t,t.return=e;l.sibling!==null;)l=l.sibling,t=t.sibling=qe(l,l.pendingProps),t.return=e;t.sibling=null}return e.child}function bc(l,e){return(l.lanes&e)!==0?!0:(l=l.dependencies,!!(l!==null&&wn(l)))}function cm(l,e,t){switch(e.tag){case 3:Kl(e,e.stateNode.containerInfo),nt(e,Ml,l.memoizedState.cache),Ct();break;case 27:case 5:Na(e);break;case 4:Kl(e,e.stateNode.containerInfo);break;case 10:nt(e,e.type,e.memoizedProps.value);break;case 31:if(e.memoizedState!==null)return e.flags|=128,Vi(e),null;break;case 13:var a=e.memoizedState;if(a!==null)return a.dehydrated!==null?(ft(e),e.flags|=128,null):(t&e.child.childLanes)!==0?Xo(l,e,t):(ft(e),l=Le(l,e,t),l!==null?l.sibling:null);ft(e);break;case 19:var n=(l.flags&128)!==0;if(a=(t&e.childLanes)!==0,a||(ca(l,e,t,!1),a=(t&e.childLanes)!==0),n){if(a)return Zo(l,e,t);e.flags|=128}if(n=e.memoizedState,n!==null&&(n.rendering=null,n.tail=null,n.lastEffect=null),R(Ol,Ol.current),a)break;return null;case 22:return e.lanes=0,Ro(l,e,t,e.pendingProps);case 24:nt(e,Ml,l.memoizedState.cache)}return Le(l,e,t)}function Lo(l,e,t){if(l!==null)if(l.memoizedProps!==e.pendingProps)Ul=!0;else{if(!bc(l,t)&&(e.flags&128)===0)return Ul=!1,cm(l,e,t);Ul=(l.flags&131072)!==0}else Ul=!1,nl&&(e.flags&1048576)!==0&&Ss(e,Va,e.index);switch(e.lanes=0,e.tag){case 16:l:{var a=e.pendingProps;if(l=Bt(e.elementType),e.type=l,typeof l=="function")Ti(l)?(a=Xt(l,a),e.tag=1,e=Yo(null,e,l,a,t)):(e.tag=0,e=dc(null,e,l,a,t));else{if(l!=null){var n=l.$$typeof;if(n===Tl){e.tag=11,e=Mo(null,e,l,a,t);break l}else if(n===al){e.tag=14,e=Co(null,e,l,a,t);break l}}throw e=Ue(l)||l,Error(r(306,e,""))}}return e;case 0:return dc(l,e,e.type,e.pendingProps,t);case 1:return a=e.type,n=Xt(a,e.pendingProps),Yo(l,e,a,n,t);case 3:l:{if(Kl(e,e.stateNode.containerInfo),l===null)throw Error(r(387));a=e.pendingProps;var u=e.memoizedState;n=u.element,Gi(l,e),Ia(e,a,null,t);var i=e.memoizedState;if(a=i.cache,nt(e,Ml,a),a!==u.cache&&Ui(e,[Ml],t,!0),Fa(),a=i.element,u.isDehydrated)if(u={element:a,isDehydrated:!1,cache:i.cache},e.updateQueue.baseState=u,e.memoizedState=u,e.flags&256){e=Go(l,e,a,t);break l}else if(a!==n){n=ve(Error(r(424)),e),Ka(n),e=Go(l,e,a,t);break l}else{switch(l=e.stateNode.containerInfo,l.nodeType){case 9:l=l.body;break;default:l=l.nodeName==="HTML"?l.ownerDocument.body:l}for(bl=xe(l.firstChild),Xl=e,nl=!0,tt=null,be=!0,t=Us(e,null,a,t),e.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling}else{if(Ct(),a===n){e=Le(l,e,t);break l}Zl(l,e,a,t)}e=e.child}return e;case 26:return du(l,e),l===null?(t=ld(e.type,null,e.pendingProps,null))?e.memoizedState=t:nl||(t=e.type,l=e.pendingProps,a=Nu(I.current).createElement(t),a[Gl]=e,a[$l]=l,Ll(a,t,l),ql(a),e.stateNode=a):e.memoizedState=ld(e.type,l.memoizedProps,e.pendingProps,l.memoizedState),null;case 27:return Na(e),l===null&&nl&&(a=e.stateNode=Fr(e.type,e.pendingProps,I.current),Xl=e,be=!0,n=bl,gt(e.type)?(Ic=n,bl=xe(a.firstChild)):bl=n),Zl(l,e,e.pendingProps.children,t),du(l,e),l===null&&(e.flags|=4194304),e.child;case 5:return l===null&&nl&&((n=a=bl)&&(a=qm(a,e.type,e.pendingProps,be),a!==null?(e.stateNode=a,Xl=e,bl=xe(a.firstChild),be=!1,n=!0):n=!1),n||at(e)),Na(e),n=e.type,u=e.pendingProps,i=l!==null?l.memoizedProps:null,a=u.children,wc(n,u)?a=null:i!==null&&wc(n,i)&&(e.flags|=32),e.memoizedState!==null&&(n=Ji(l,e,Ih,null,null,t),bn._currentValue=n),du(l,e),Zl(l,e,a,t),e.child;case 6:return l===null&&nl&&((l=t=bl)&&(t=Ym(t,e.pendingProps,be),t!==null?(e.stateNode=t,Xl=e,bl=null,l=!0):l=!1),l||at(e)),null;case 13:return Xo(l,e,t);case 4:return Kl(e,e.stateNode.containerInfo),a=e.pendingProps,l===null?e.child=Yt(e,null,a,t):Zl(l,e,a,t),e.child;case 11:return Mo(l,e,e.type,e.pendingProps,t);case 7:return Zl(l,e,e.pendingProps,t),e.child;case 8:return Zl(l,e,e.pendingProps.children,t),e.child;case 12:return Zl(l,e,e.pendingProps.children,t),e.child;case 10:return a=e.pendingProps,nt(e,e.type,a.value),Zl(l,e,a.children,t),e.child;case 9:return n=e.type._context,a=e.pendingProps.children,Rt(e),n=Ql(n),a=a(n),e.flags|=1,Zl(l,e,a,t),e.child;case 14:return Co(l,e,e.type,e.pendingProps,t);case 15:return Uo(l,e,e.type,e.pendingProps,t);case 19:return Zo(l,e,t);case 31:return im(l,e,t);case 22:return Ro(l,e,t,e.pendingProps);case 24:return Rt(e),a=Ql(Ml),l===null?(n=Bi(),n===null&&(n=pl,u=Ri(),n.pooledCache=u,u.refCount++,u!==null&&(n.pooledCacheLanes|=t),n=u),e.memoizedState={parent:a,cache:n},Yi(e),nt(e,Ml,n)):((l.lanes&t)!==0&&(Gi(l,e),Ia(e,null,null,t),Fa()),n=l.memoizedState,u=e.memoizedState,n.parent!==a?(n={parent:a,cache:a},e.memoizedState=n,e.lanes===0&&(e.memoizedState=e.updateQueue.baseState=n),nt(e,Ml,a)):(a=u.cache,nt(e,Ml,a),a!==n.cache&&Ui(e,[Ml],t,!0))),Zl(l,e,e.pendingProps.children,t),e.child;case 29:throw e.pendingProps}throw Error(r(156,e.tag))}function Ve(l){l.flags|=4}function Sc(l,e,t,a,n){if((e=(l.mode&32)!==0)&&(e=!1),e){if(l.flags|=16777216,(n&335544128)===n)if(l.stateNode.complete)l.flags|=8192;else if(vr())l.flags|=8192;else throw qt=Fn,qi}else l.flags&=-16777217}function Vo(l,e){if(e.type!=="stylesheet"||(e.state.loading&4)!==0)l.flags&=-16777217;else if(l.flags|=16777216,!ud(e))if(vr())l.flags|=8192;else throw qt=Fn,qi}function mu(l,e){e!==null&&(l.flags|=4),l.flags&16384&&(e=l.tag!==22?jf():536870912,l.lanes|=e,ba|=e)}function nn(l,e){if(!nl)switch(l.tailMode){case"hidden":e=l.tail;for(var t=null;e!==null;)e.alternate!==null&&(t=e),e=e.sibling;t===null?l.tail=null:t.sibling=null;break;case"collapsed":t=l.tail;for(var a=null;t!==null;)t.alternate!==null&&(a=t),t=t.sibling;a===null?e||l.tail===null?l.tail=null:l.tail.sibling=null:a.sibling=null}}function Sl(l){var e=l.alternate!==null&&l.alternate.child===l.child,t=0,a=0;if(e)for(var n=l.child;n!==null;)t|=n.lanes|n.childLanes,a|=n.subtreeFlags&65011712,a|=n.flags&65011712,n.return=l,n=n.sibling;else for(n=l.child;n!==null;)t|=n.lanes|n.childLanes,a|=n.subtreeFlags,a|=n.flags,n.return=l,n=n.sibling;return l.subtreeFlags|=a,l.childLanes=t,e}function fm(l,e,t){var a=e.pendingProps;switch(Oi(e),e.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Sl(e),null;case 1:return Sl(e),null;case 3:return t=e.stateNode,a=null,l!==null&&(a=l.memoizedState.cache),e.memoizedState.cache!==a&&(e.flags|=2048),Xe(Ml),_l(),t.pendingContext&&(t.context=t.pendingContext,t.pendingContext=null),(l===null||l.child===null)&&(ia(e)?Ve(e):l===null||l.memoizedState.isDehydrated&&(e.flags&256)===0||(e.flags|=1024,Di())),Sl(e),null;case 26:var n=e.type,u=e.memoizedState;return l===null?(Ve(e),u!==null?(Sl(e),Vo(e,u)):(Sl(e),Sc(e,n,null,a,t))):u?u!==l.memoizedState?(Ve(e),Sl(e),Vo(e,u)):(Sl(e),e.flags&=-16777217):(l=l.memoizedProps,l!==a&&Ve(e),Sl(e),Sc(e,n,l,a,t)),null;case 27:if(An(e),t=I.current,n=e.type,l!==null&&e.stateNode!=null)l.memoizedProps!==a&&Ve(e);else{if(!a){if(e.stateNode===null)throw Error(r(166));return Sl(e),null}l=q.current,ia(e)?js(e):(l=Fr(n,a,t),e.stateNode=l,Ve(e))}return Sl(e),null;case 5:if(An(e),n=e.type,l!==null&&e.stateNode!=null)l.memoizedProps!==a&&Ve(e);else{if(!a){if(e.stateNode===null)throw Error(r(166));return Sl(e),null}if(u=q.current,ia(e))js(e);else{var i=Nu(I.current);switch(u){case 1:u=i.createElementNS("http://www.w3.org/2000/svg",n);break;case 2:u=i.createElementNS("http://www.w3.org/1998/Math/MathML",n);break;default:switch(n){case"svg":u=i.createElementNS("http://www.w3.org/2000/svg",n);break;case"math":u=i.createElementNS("http://www.w3.org/1998/Math/MathML",n);break;case"script":u=i.createElement("div"),u.innerHTML="<script><\/script>",u=u.removeChild(u.firstChild);break;case"select":u=typeof a.is=="string"?i.createElement("select",{is:a.is}):i.createElement("select"),a.multiple?u.multiple=!0:a.size&&(u.size=a.size);break;default:u=typeof a.is=="string"?i.createElement(n,{is:a.is}):i.createElement(n)}}u[Gl]=e,u[$l]=a;l:for(i=e.child;i!==null;){if(i.tag===5||i.tag===6)u.appendChild(i.stateNode);else if(i.tag!==4&&i.tag!==27&&i.child!==null){i.child.return=i,i=i.child;continue}if(i===e)break l;for(;i.sibling===null;){if(i.return===null||i.return===e)break l;i=i.return}i.sibling.return=i.return,i=i.sibling}e.stateNode=u;l:switch(Ll(u,n,a),n){case"button":case"input":case"select":case"textarea":a=!!a.autoFocus;break l;case"img":a=!0;break l;default:a=!1}a&&Ve(e)}}return Sl(e),Sc(e,e.type,l===null?null:l.memoizedProps,e.pendingProps,t),null;case 6:if(l&&e.stateNode!=null)l.memoizedProps!==a&&Ve(e);else{if(typeof a!="string"&&e.stateNode===null)throw Error(r(166));if(l=I.current,ia(e)){if(l=e.stateNode,t=e.memoizedProps,a=null,n=Xl,n!==null)switch(n.tag){case 27:case 5:a=n.memoizedProps}l[Gl]=e,l=!!(l.nodeValue===t||a!==null&&a.suppressHydrationWarning===!0||Xr(l.nodeValue,t)),l||at(e,!0)}else l=Nu(l).createTextNode(a),l[Gl]=e,e.stateNode=l}return Sl(e),null;case 31:if(t=e.memoizedState,l===null||l.memoizedState!==null){if(a=ia(e),t!==null){if(l===null){if(!a)throw Error(r(318));if(l=e.memoizedState,l=l!==null?l.dehydrated:null,!l)throw Error(r(557));l[Gl]=e}else Ct(),(e.flags&128)===0&&(e.memoizedState=null),e.flags|=4;Sl(e),l=!1}else t=Di(),l!==null&&l.memoizedState!==null&&(l.memoizedState.hydrationErrors=t),l=!0;if(!l)return e.flags&256?(se(e),e):(se(e),null);if((e.flags&128)!==0)throw Error(r(558))}return Sl(e),null;case 13:if(a=e.memoizedState,l===null||l.memoizedState!==null&&l.memoizedState.dehydrated!==null){if(n=ia(e),a!==null&&a.dehydrated!==null){if(l===null){if(!n)throw Error(r(318));if(n=e.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(r(317));n[Gl]=e}else Ct(),(e.flags&128)===0&&(e.memoizedState=null),e.flags|=4;Sl(e),n=!1}else n=Di(),l!==null&&l.memoizedState!==null&&(l.memoizedState.hydrationErrors=n),n=!0;if(!n)return e.flags&256?(se(e),e):(se(e),null)}return se(e),(e.flags&128)!==0?(e.lanes=t,e):(t=a!==null,l=l!==null&&l.memoizedState!==null,t&&(a=e.child,n=null,a.alternate!==null&&a.alternate.memoizedState!==null&&a.alternate.memoizedState.cachePool!==null&&(n=a.alternate.memoizedState.cachePool.pool),u=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(u=a.memoizedState.cachePool.pool),u!==n&&(a.flags|=2048)),t!==l&&t&&(e.child.flags|=8192),mu(e,e.updateQueue),Sl(e),null);case 4:return _l(),l===null&&Zc(e.stateNode.containerInfo),Sl(e),null;case 10:return Xe(e.type),Sl(e),null;case 19:if(A(Ol),a=e.memoizedState,a===null)return Sl(e),null;if(n=(e.flags&128)!==0,u=a.rendering,u===null)if(n)nn(a,!1);else{if(El!==0||l!==null&&(l.flags&128)!==0)for(l=e.child;l!==null;){if(u=eu(l),u!==null){for(e.flags|=128,nn(a,!1),l=u.updateQueue,e.updateQueue=l,mu(e,l),e.subtreeFlags=0,l=t,t=e.child;t!==null;)gs(t,l),t=t.sibling;return R(Ol,Ol.current&1|2),nl&&Ye(e,a.treeForkCount),e.child}l=l.sibling}a.tail!==null&&ae()>bu&&(e.flags|=128,n=!0,nn(a,!1),e.lanes=4194304)}else{if(!n)if(l=eu(u),l!==null){if(e.flags|=128,n=!0,l=l.updateQueue,e.updateQueue=l,mu(e,l),nn(a,!0),a.tail===null&&a.tailMode==="hidden"&&!u.alternate&&!nl)return Sl(e),null}else 2*ae()-a.renderingStartTime>bu&&t!==536870912&&(e.flags|=128,n=!0,nn(a,!1),e.lanes=4194304);a.isBackwards?(u.sibling=e.child,e.child=u):(l=a.last,l!==null?l.sibling=u:e.child=u,a.last=u)}return a.tail!==null?(l=a.tail,a.rendering=l,a.tail=l.sibling,a.renderingStartTime=ae(),l.sibling=null,t=Ol.current,R(Ol,n?t&1|2:t&1),nl&&Ye(e,a.treeForkCount),l):(Sl(e),null);case 22:case 23:return se(e),Li(),a=e.memoizedState!==null,l!==null?l.memoizedState!==null!==a&&(e.flags|=8192):a&&(e.flags|=8192),a?(t&536870912)!==0&&(e.flags&128)===0&&(Sl(e),e.subtreeFlags&6&&(e.flags|=8192)):Sl(e),t=e.updateQueue,t!==null&&mu(e,t.retryQueue),t=null,l!==null&&l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(t=l.memoizedState.cachePool.pool),a=null,e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(a=e.memoizedState.cachePool.pool),a!==t&&(e.flags|=2048),l!==null&&A(Ht),null;case 24:return t=null,l!==null&&(t=l.memoizedState.cache),e.memoizedState.cache!==t&&(e.flags|=2048),Xe(Ml),Sl(e),null;case 25:return null;case 30:return null}throw Error(r(156,e.tag))}function sm(l,e){switch(Oi(e),e.tag){case 1:return l=e.flags,l&65536?(e.flags=l&-65537|128,e):null;case 3:return Xe(Ml),_l(),l=e.flags,(l&65536)!==0&&(l&128)===0?(e.flags=l&-65537|128,e):null;case 26:case 27:case 5:return An(e),null;case 31:if(e.memoizedState!==null){if(se(e),e.alternate===null)throw Error(r(340));Ct()}return l=e.flags,l&65536?(e.flags=l&-65537|128,e):null;case 13:if(se(e),l=e.memoizedState,l!==null&&l.dehydrated!==null){if(e.alternate===null)throw Error(r(340));Ct()}return l=e.flags,l&65536?(e.flags=l&-65537|128,e):null;case 19:return A(Ol),null;case 4:return _l(),null;case 10:return Xe(e.type),null;case 22:case 23:return se(e),Li(),l!==null&&A(Ht),l=e.flags,l&65536?(e.flags=l&-65537|128,e):null;case 24:return Xe(Ml),null;case 25:return null;default:return null}}function Ko(l,e){switch(Oi(e),e.tag){case 3:Xe(Ml),_l();break;case 26:case 27:case 5:An(e);break;case 4:_l();break;case 31:e.memoizedState!==null&&se(e);break;case 13:se(e);break;case 19:A(Ol);break;case 10:Xe(e.type);break;case 22:case 23:se(e),Li(),l!==null&&A(Ht);break;case 24:Xe(Ml)}}function un(l,e){try{var t=e.updateQueue,a=t!==null?t.lastEffect:null;if(a!==null){var n=a.next;t=n;do{if((t.tag&l)===l){a=void 0;var u=t.create,i=t.inst;a=u(),i.destroy=a}t=t.next}while(t!==n)}}catch(s){dl(e,e.return,s)}}function ot(l,e,t){try{var a=e.updateQueue,n=a!==null?a.lastEffect:null;if(n!==null){var u=n.next;a=u;do{if((a.tag&l)===l){var i=a.inst,s=i.destroy;if(s!==void 0){i.destroy=void 0,n=e;var o=t,g=s;try{g()}catch(S){dl(n,o,S)}}}a=a.next}while(a!==u)}}catch(S){dl(e,e.return,S)}}function Jo(l){var e=l.updateQueue;if(e!==null){var t=l.stateNode;try{Hs(e,t)}catch(a){dl(l,l.return,a)}}}function wo(l,e,t){t.props=Xt(l.type,l.memoizedProps),t.state=l.memoizedState;try{t.componentWillUnmount()}catch(a){dl(l,e,a)}}function cn(l,e){try{var t=l.ref;if(t!==null){switch(l.tag){case 26:case 27:case 5:var a=l.stateNode;break;case 30:a=l.stateNode;break;default:a=l.stateNode}typeof t=="function"?l.refCleanup=t(a):t.current=a}}catch(n){dl(l,e,n)}}function Me(l,e){var t=l.ref,a=l.refCleanup;if(t!==null)if(typeof a=="function")try{a()}catch(n){dl(l,e,n)}finally{l.refCleanup=null,l=l.alternate,l!=null&&(l.refCleanup=null)}else if(typeof t=="function")try{t(null)}catch(n){dl(l,e,n)}else t.current=null}function ko(l){var e=l.type,t=l.memoizedProps,a=l.stateNode;try{l:switch(e){case"button":case"input":case"select":case"textarea":t.autoFocus&&a.focus();break l;case"img":t.src?a.src=t.src:t.srcSet&&(a.srcset=t.srcSet)}}catch(n){dl(l,l.return,n)}}function xc(l,e,t){try{var a=l.stateNode;Mm(a,l.type,t,e),a[$l]=e}catch(n){dl(l,l.return,n)}}function Wo(l){return l.tag===5||l.tag===3||l.tag===26||l.tag===27&>(l.type)||l.tag===4}function jc(l){l:for(;;){for(;l.sibling===null;){if(l.return===null||Wo(l.return))return null;l=l.return}for(l.sibling.return=l.return,l=l.sibling;l.tag!==5&&l.tag!==6&&l.tag!==18;){if(l.tag===27&>(l.type)||l.flags&2||l.child===null||l.tag===4)continue l;l.child.return=l,l=l.child}if(!(l.flags&2))return l.stateNode}}function zc(l,e,t){var a=l.tag;if(a===5||a===6)l=l.stateNode,e?(t.nodeType===9?t.body:t.nodeName==="HTML"?t.ownerDocument.body:t).insertBefore(l,e):(e=t.nodeType===9?t.body:t.nodeName==="HTML"?t.ownerDocument.body:t,e.appendChild(l),t=t._reactRootContainer,t!=null||e.onclick!==null||(e.onclick=He));else if(a!==4&&(a===27&>(l.type)&&(t=l.stateNode,e=null),l=l.child,l!==null))for(zc(l,e,t),l=l.sibling;l!==null;)zc(l,e,t),l=l.sibling}function yu(l,e,t){var a=l.tag;if(a===5||a===6)l=l.stateNode,e?t.insertBefore(l,e):t.appendChild(l);else if(a!==4&&(a===27&>(l.type)&&(t=l.stateNode),l=l.child,l!==null))for(yu(l,e,t),l=l.sibling;l!==null;)yu(l,e,t),l=l.sibling}function $o(l){var e=l.stateNode,t=l.memoizedProps;try{for(var a=l.type,n=e.attributes;n.length;)e.removeAttributeNode(n[0]);Ll(e,a,t),e[Gl]=l,e[$l]=t}catch(u){dl(l,l.return,u)}}var Ke=!1,Rl=!1,Tc=!1,Fo=typeof WeakSet=="function"?WeakSet:Set,Yl=null;function om(l,e){if(l=l.containerInfo,Kc=Bu,l=fs(l),gi(l)){if("selectionStart"in l)var t={start:l.selectionStart,end:l.selectionEnd};else l:{t=(t=l.ownerDocument)&&t.defaultView||window;var a=t.getSelection&&t.getSelection();if(a&&a.rangeCount!==0){t=a.anchorNode;var n=a.anchorOffset,u=a.focusNode;a=a.focusOffset;try{t.nodeType,u.nodeType}catch{t=null;break l}var i=0,s=-1,o=-1,g=0,S=0,z=l,p=null;e:for(;;){for(var b;z!==t||n!==0&&z.nodeType!==3||(s=i+n),z!==u||a!==0&&z.nodeType!==3||(o=i+a),z.nodeType===3&&(i+=z.nodeValue.length),(b=z.firstChild)!==null;)p=z,z=b;for(;;){if(z===l)break e;if(p===t&&++g===n&&(s=i),p===u&&++S===a&&(o=i),(b=z.nextSibling)!==null)break;z=p,p=z.parentNode}z=b}t=s===-1||o===-1?null:{start:s,end:o}}else t=null}t=t||{start:0,end:0}}else t=null;for(Jc={focusedElem:l,selectionRange:t},Bu=!1,Yl=e;Yl!==null;)if(e=Yl,l=e.child,(e.subtreeFlags&1028)!==0&&l!==null)l.return=e,Yl=l;else for(;Yl!==null;){switch(e=Yl,u=e.alternate,l=e.flags,e.tag){case 0:if((l&4)!==0&&(l=e.updateQueue,l=l!==null?l.events:null,l!==null))for(t=0;t<l.length;t++)n=l[t],n.ref.impl=n.nextImpl;break;case 11:case 15:break;case 1:if((l&1024)!==0&&u!==null){l=void 0,t=e,n=u.memoizedProps,u=u.memoizedState,a=t.stateNode;try{var B=Xt(t.type,n);l=a.getSnapshotBeforeUpdate(B,u),a.__reactInternalSnapshotBeforeUpdate=l}catch(L){dl(t,t.return,L)}}break;case 3:if((l&1024)!==0){if(l=e.stateNode.containerInfo,t=l.nodeType,t===9)Wc(l);else if(t===1)switch(l.nodeName){case"HEAD":case"HTML":case"BODY":Wc(l);break;default:l.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((l&1024)!==0)throw Error(r(163))}if(l=e.sibling,l!==null){l.return=e.return,Yl=l;break}Yl=e.return}}function Io(l,e,t){var a=t.flags;switch(t.tag){case 0:case 11:case 15:we(l,t),a&4&&un(5,t);break;case 1:if(we(l,t),a&4)if(l=t.stateNode,e===null)try{l.componentDidMount()}catch(i){dl(t,t.return,i)}else{var n=Xt(t.type,e.memoizedProps);e=e.memoizedState;try{l.componentDidUpdate(n,e,l.__reactInternalSnapshotBeforeUpdate)}catch(i){dl(t,t.return,i)}}a&64&&Jo(t),a&512&&cn(t,t.return);break;case 3:if(we(l,t),a&64&&(l=t.updateQueue,l!==null)){if(e=null,t.child!==null)switch(t.child.tag){case 27:case 5:e=t.child.stateNode;break;case 1:e=t.child.stateNode}try{Hs(l,e)}catch(i){dl(t,t.return,i)}}break;case 27:e===null&&a&4&&$o(t);case 26:case 5:we(l,t),e===null&&a&4&&ko(t),a&512&&cn(t,t.return);break;case 12:we(l,t);break;case 31:we(l,t),a&4&&er(l,t);break;case 13:we(l,t),a&4&&tr(l,t),a&64&&(l=t.memoizedState,l!==null&&(l=l.dehydrated,l!==null&&(t=bm.bind(null,t),Gm(l,t))));break;case 22:if(a=t.memoizedState!==null||Ke,!a){e=e!==null&&e.memoizedState!==null||Rl,n=Ke;var u=Rl;Ke=a,(Rl=e)&&!u?ke(l,t,(t.subtreeFlags&8772)!==0):we(l,t),Ke=n,Rl=u}break;case 30:break;default:we(l,t)}}function Po(l){var e=l.alternate;e!==null&&(l.alternate=null,Po(e)),l.child=null,l.deletions=null,l.sibling=null,l.tag===5&&(e=l.stateNode,e!==null&&li(e)),l.stateNode=null,l.return=null,l.dependencies=null,l.memoizedProps=null,l.memoizedState=null,l.pendingProps=null,l.stateNode=null,l.updateQueue=null}var zl=null,Il=!1;function Je(l,e,t){for(t=t.child;t!==null;)lr(l,e,t),t=t.sibling}function lr(l,e,t){if(ne&&typeof ne.onCommitFiberUnmount=="function")try{ne.onCommitFiberUnmount(Da,t)}catch{}switch(t.tag){case 26:Rl||Me(t,e),Je(l,e,t),t.memoizedState?t.memoizedState.count--:t.stateNode&&(t=t.stateNode,t.parentNode.removeChild(t));break;case 27:Rl||Me(t,e);var a=zl,n=Il;gt(t.type)&&(zl=t.stateNode,Il=!1),Je(l,e,t),vn(t.stateNode),zl=a,Il=n;break;case 5:Rl||Me(t,e);case 6:if(a=zl,n=Il,zl=null,Je(l,e,t),zl=a,Il=n,zl!==null)if(Il)try{(zl.nodeType===9?zl.body:zl.nodeName==="HTML"?zl.ownerDocument.body:zl).removeChild(t.stateNode)}catch(u){dl(t,e,u)}else try{zl.removeChild(t.stateNode)}catch(u){dl(t,e,u)}break;case 18:zl!==null&&(Il?(l=zl,Jr(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,t.stateNode),_a(l)):Jr(zl,t.stateNode));break;case 4:a=zl,n=Il,zl=t.stateNode.containerInfo,Il=!0,Je(l,e,t),zl=a,Il=n;break;case 0:case 11:case 14:case 15:ot(2,t,e),Rl||ot(4,t,e),Je(l,e,t);break;case 1:Rl||(Me(t,e),a=t.stateNode,typeof a.componentWillUnmount=="function"&&wo(t,e,a)),Je(l,e,t);break;case 21:Je(l,e,t);break;case 22:Rl=(a=Rl)||t.memoizedState!==null,Je(l,e,t),Rl=a;break;default:Je(l,e,t)}}function er(l,e){if(e.memoizedState===null&&(l=e.alternate,l!==null&&(l=l.memoizedState,l!==null))){l=l.dehydrated;try{_a(l)}catch(t){dl(e,e.return,t)}}}function tr(l,e){if(e.memoizedState===null&&(l=e.alternate,l!==null&&(l=l.memoizedState,l!==null&&(l=l.dehydrated,l!==null))))try{_a(l)}catch(t){dl(e,e.return,t)}}function rm(l){switch(l.tag){case 31:case 13:case 19:var e=l.stateNode;return e===null&&(e=l.stateNode=new Fo),e;case 22:return l=l.stateNode,e=l._retryCache,e===null&&(e=l._retryCache=new Fo),e;default:throw Error(r(435,l.tag))}}function vu(l,e){var t=rm(l);e.forEach(function(a){if(!t.has(a)){t.add(a);var n=Sm.bind(null,l,a);a.then(n,n)}})}function Pl(l,e){var t=e.deletions;if(t!==null)for(var a=0;a<t.length;a++){var n=t[a],u=l,i=e,s=i;l:for(;s!==null;){switch(s.tag){case 27:if(gt(s.type)){zl=s.stateNode,Il=!1;break l}break;case 5:zl=s.stateNode,Il=!1;break l;case 3:case 4:zl=s.stateNode.containerInfo,Il=!0;break l}s=s.return}if(zl===null)throw Error(r(160));lr(u,i,n),zl=null,Il=!1,u=n.alternate,u!==null&&(u.return=null),n.return=null}if(e.subtreeFlags&13886)for(e=e.child;e!==null;)ar(e,l),e=e.sibling}var Ae=null;function ar(l,e){var t=l.alternate,a=l.flags;switch(l.tag){case 0:case 11:case 14:case 15:Pl(e,l),le(l),a&4&&(ot(3,l,l.return),un(3,l),ot(5,l,l.return));break;case 1:Pl(e,l),le(l),a&512&&(Rl||t===null||Me(t,t.return)),a&64&&Ke&&(l=l.updateQueue,l!==null&&(a=l.callbacks,a!==null&&(t=l.shared.hiddenCallbacks,l.shared.hiddenCallbacks=t===null?a:t.concat(a))));break;case 26:var n=Ae;if(Pl(e,l),le(l),a&512&&(Rl||t===null||Me(t,t.return)),a&4){var u=t!==null?t.memoizedState:null;if(a=l.memoizedState,t===null)if(a===null)if(l.stateNode===null){l:{a=l.type,t=l.memoizedProps,n=n.ownerDocument||n;e:switch(a){case"title":u=n.getElementsByTagName("title")[0],(!u||u[Ua]||u[Gl]||u.namespaceURI==="http://www.w3.org/2000/svg"||u.hasAttribute("itemprop"))&&(u=n.createElement(a),n.head.insertBefore(u,n.querySelector("head > title"))),Ll(u,a,t),u[Gl]=l,ql(u),a=u;break l;case"link":var i=ad("link","href",n).get(a+(t.href||""));if(i){for(var s=0;s<i.length;s++)if(u=i[s],u.getAttribute("href")===(t.href==null||t.href===""?null:t.href)&&u.getAttribute("rel")===(t.rel==null?null:t.rel)&&u.getAttribute("title")===(t.title==null?null:t.title)&&u.getAttribute("crossorigin")===(t.crossOrigin==null?null:t.crossOrigin)){i.splice(s,1);break e}}u=n.createElement(a),Ll(u,a,t),n.head.appendChild(u);break;case"meta":if(i=ad("meta","content",n).get(a+(t.content||""))){for(s=0;s<i.length;s++)if(u=i[s],u.getAttribute("content")===(t.content==null?null:""+t.content)&&u.getAttribute("name")===(t.name==null?null:t.name)&&u.getAttribute("property")===(t.property==null?null:t.property)&&u.getAttribute("http-equiv")===(t.httpEquiv==null?null:t.httpEquiv)&&u.getAttribute("charset")===(t.charSet==null?null:t.charSet)){i.splice(s,1);break e}}u=n.createElement(a),Ll(u,a,t),n.head.appendChild(u);break;default:throw Error(r(468,a))}u[Gl]=l,ql(u),a=u}l.stateNode=a}else nd(n,l.type,l.stateNode);else l.stateNode=td(n,a,l.memoizedProps);else u!==a?(u===null?t.stateNode!==null&&(t=t.stateNode,t.parentNode.removeChild(t)):u.count--,a===null?nd(n,l.type,l.stateNode):td(n,a,l.memoizedProps)):a===null&&l.stateNode!==null&&xc(l,l.memoizedProps,t.memoizedProps)}break;case 27:Pl(e,l),le(l),a&512&&(Rl||t===null||Me(t,t.return)),t!==null&&a&4&&xc(l,l.memoizedProps,t.memoizedProps);break;case 5:if(Pl(e,l),le(l),a&512&&(Rl||t===null||Me(t,t.return)),l.flags&32){n=l.stateNode;try{$t(n,"")}catch(B){dl(l,l.return,B)}}a&4&&l.stateNode!=null&&(n=l.memoizedProps,xc(l,n,t!==null?t.memoizedProps:n)),a&1024&&(Tc=!0);break;case 6:if(Pl(e,l),le(l),a&4){if(l.stateNode===null)throw Error(r(162));a=l.memoizedProps,t=l.stateNode;try{t.nodeValue=a}catch(B){dl(l,l.return,B)}}break;case 3:if(Cu=null,n=Ae,Ae=Du(e.containerInfo),Pl(e,l),Ae=n,le(l),a&4&&t!==null&&t.memoizedState.isDehydrated)try{_a(e.containerInfo)}catch(B){dl(l,l.return,B)}Tc&&(Tc=!1,nr(l));break;case 4:a=Ae,Ae=Du(l.stateNode.containerInfo),Pl(e,l),le(l),Ae=a;break;case 12:Pl(e,l),le(l);break;case 31:Pl(e,l),le(l),a&4&&(a=l.updateQueue,a!==null&&(l.updateQueue=null,vu(l,a)));break;case 13:Pl(e,l),le(l),l.child.flags&8192&&l.memoizedState!==null!=(t!==null&&t.memoizedState!==null)&&(pu=ae()),a&4&&(a=l.updateQueue,a!==null&&(l.updateQueue=null,vu(l,a)));break;case 22:n=l.memoizedState!==null;var o=t!==null&&t.memoizedState!==null,g=Ke,S=Rl;if(Ke=g||n,Rl=S||o,Pl(e,l),Rl=S,Ke=g,le(l),a&8192)l:for(e=l.stateNode,e._visibility=n?e._visibility&-2:e._visibility|1,n&&(t===null||o||Ke||Rl||Qt(l)),t=null,e=l;;){if(e.tag===5||e.tag===26){if(t===null){o=t=e;try{if(u=o.stateNode,n)i=u.style,typeof i.setProperty=="function"?i.setProperty("display","none","important"):i.display="none";else{s=o.stateNode;var z=o.memoizedProps.style,p=z!=null&&z.hasOwnProperty("display")?z.display:null;s.style.display=p==null||typeof p=="boolean"?"":(""+p).trim()}}catch(B){dl(o,o.return,B)}}}else if(e.tag===6){if(t===null){o=e;try{o.stateNode.nodeValue=n?"":o.memoizedProps}catch(B){dl(o,o.return,B)}}}else if(e.tag===18){if(t===null){o=e;try{var b=o.stateNode;n?wr(b,!0):wr(o.stateNode,!1)}catch(B){dl(o,o.return,B)}}}else if((e.tag!==22&&e.tag!==23||e.memoizedState===null||e===l)&&e.child!==null){e.child.return=e,e=e.child;continue}if(e===l)break l;for(;e.sibling===null;){if(e.return===null||e.return===l)break l;t===e&&(t=null),e=e.return}t===e&&(t=null),e.sibling.return=e.return,e=e.sibling}a&4&&(a=l.updateQueue,a!==null&&(t=a.retryQueue,t!==null&&(a.retryQueue=null,vu(l,t))));break;case 19:Pl(e,l),le(l),a&4&&(a=l.updateQueue,a!==null&&(l.updateQueue=null,vu(l,a)));break;case 30:break;case 21:break;default:Pl(e,l),le(l)}}function le(l){var e=l.flags;if(e&2){try{for(var t,a=l.return;a!==null;){if(Wo(a)){t=a;break}a=a.return}if(t==null)throw Error(r(160));switch(t.tag){case 27:var n=t.stateNode,u=jc(l);yu(l,u,n);break;case 5:var i=t.stateNode;t.flags&32&&($t(i,""),t.flags&=-33);var s=jc(l);yu(l,s,i);break;case 3:case 4:var o=t.stateNode.containerInfo,g=jc(l);zc(l,g,o);break;default:throw Error(r(161))}}catch(S){dl(l,l.return,S)}l.flags&=-3}e&4096&&(l.flags&=-4097)}function nr(l){if(l.subtreeFlags&1024)for(l=l.child;l!==null;){var e=l;nr(e),e.tag===5&&e.flags&1024&&e.stateNode.reset(),l=l.sibling}}function we(l,e){if(e.subtreeFlags&8772)for(e=e.child;e!==null;)Io(l,e.alternate,e),e=e.sibling}function Qt(l){for(l=l.child;l!==null;){var e=l;switch(e.tag){case 0:case 11:case 14:case 15:ot(4,e,e.return),Qt(e);break;case 1:Me(e,e.return);var t=e.stateNode;typeof t.componentWillUnmount=="function"&&wo(e,e.return,t),Qt(e);break;case 27:vn(e.stateNode);case 26:case 5:Me(e,e.return),Qt(e);break;case 22:e.memoizedState===null&&Qt(e);break;case 30:Qt(e);break;default:Qt(e)}l=l.sibling}}function ke(l,e,t){for(t=t&&(e.subtreeFlags&8772)!==0,e=e.child;e!==null;){var a=e.alternate,n=l,u=e,i=u.flags;switch(u.tag){case 0:case 11:case 15:ke(n,u,t),un(4,u);break;case 1:if(ke(n,u,t),a=u,n=a.stateNode,typeof n.componentDidMount=="function")try{n.componentDidMount()}catch(g){dl(a,a.return,g)}if(a=u,n=a.updateQueue,n!==null){var s=a.stateNode;try{var o=n.shared.hiddenCallbacks;if(o!==null)for(n.shared.hiddenCallbacks=null,n=0;n<o.length;n++)Rs(o[n],s)}catch(g){dl(a,a.return,g)}}t&&i&64&&Jo(u),cn(u,u.return);break;case 27:$o(u);case 26:case 5:ke(n,u,t),t&&a===null&&i&4&&ko(u),cn(u,u.return);break;case 12:ke(n,u,t);break;case 31:ke(n,u,t),t&&i&4&&er(n,u);break;case 13:ke(n,u,t),t&&i&4&&tr(n,u);break;case 22:u.memoizedState===null&&ke(n,u,t),cn(u,u.return);break;case 30:break;default:ke(n,u,t)}e=e.sibling}}function Ac(l,e){var t=null;l!==null&&l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(t=l.memoizedState.cachePool.pool),l=null,e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(l=e.memoizedState.cachePool.pool),l!==t&&(l!=null&&l.refCount++,t!=null&&Ja(t))}function Ec(l,e){l=null,e.alternate!==null&&(l=e.alternate.memoizedState.cache),e=e.memoizedState.cache,e!==l&&(e.refCount++,l!=null&&Ja(l))}function Ee(l,e,t,a){if(e.subtreeFlags&10256)for(e=e.child;e!==null;)ur(l,e,t,a),e=e.sibling}function ur(l,e,t,a){var n=e.flags;switch(e.tag){case 0:case 11:case 15:Ee(l,e,t,a),n&2048&&un(9,e);break;case 1:Ee(l,e,t,a);break;case 3:Ee(l,e,t,a),n&2048&&(l=null,e.alternate!==null&&(l=e.alternate.memoizedState.cache),e=e.memoizedState.cache,e!==l&&(e.refCount++,l!=null&&Ja(l)));break;case 12:if(n&2048){Ee(l,e,t,a),l=e.stateNode;try{var u=e.memoizedProps,i=u.id,s=u.onPostCommit;typeof s=="function"&&s(i,e.alternate===null?"mount":"update",l.passiveEffectDuration,-0)}catch(o){dl(e,e.return,o)}}else Ee(l,e,t,a);break;case 31:Ee(l,e,t,a);break;case 13:Ee(l,e,t,a);break;case 23:break;case 22:u=e.stateNode,i=e.alternate,e.memoizedState!==null?u._visibility&2?Ee(l,e,t,a):fn(l,e):u._visibility&2?Ee(l,e,t,a):(u._visibility|=2,va(l,e,t,a,(e.subtreeFlags&10256)!==0||!1)),n&2048&&Ac(i,e);break;case 24:Ee(l,e,t,a),n&2048&&Ec(e.alternate,e);break;default:Ee(l,e,t,a)}}function va(l,e,t,a,n){for(n=n&&((e.subtreeFlags&10256)!==0||!1),e=e.child;e!==null;){var u=l,i=e,s=t,o=a,g=i.flags;switch(i.tag){case 0:case 11:case 15:va(u,i,s,o,n),un(8,i);break;case 23:break;case 22:var S=i.stateNode;i.memoizedState!==null?S._visibility&2?va(u,i,s,o,n):fn(u,i):(S._visibility|=2,va(u,i,s,o,n)),n&&g&2048&&Ac(i.alternate,i);break;case 24:va(u,i,s,o,n),n&&g&2048&&Ec(i.alternate,i);break;default:va(u,i,s,o,n)}e=e.sibling}}function fn(l,e){if(e.subtreeFlags&10256)for(e=e.child;e!==null;){var t=l,a=e,n=a.flags;switch(a.tag){case 22:fn(t,a),n&2048&&Ac(a.alternate,a);break;case 24:fn(t,a),n&2048&&Ec(a.alternate,a);break;default:fn(t,a)}e=e.sibling}}var sn=8192;function ga(l,e,t){if(l.subtreeFlags&sn)for(l=l.child;l!==null;)ir(l,e,t),l=l.sibling}function ir(l,e,t){switch(l.tag){case 26:ga(l,e,t),l.flags&sn&&l.memoizedState!==null&&Fm(t,Ae,l.memoizedState,l.memoizedProps);break;case 5:ga(l,e,t);break;case 3:case 4:var a=Ae;Ae=Du(l.stateNode.containerInfo),ga(l,e,t),Ae=a;break;case 22:l.memoizedState===null&&(a=l.alternate,a!==null&&a.memoizedState!==null?(a=sn,sn=16777216,ga(l,e,t),sn=a):ga(l,e,t));break;default:ga(l,e,t)}}function cr(l){var e=l.alternate;if(e!==null&&(l=e.child,l!==null)){e.child=null;do e=l.sibling,l.sibling=null,l=e;while(l!==null)}}function on(l){var e=l.deletions;if((l.flags&16)!==0){if(e!==null)for(var t=0;t<e.length;t++){var a=e[t];Yl=a,sr(a,l)}cr(l)}if(l.subtreeFlags&10256)for(l=l.child;l!==null;)fr(l),l=l.sibling}function fr(l){switch(l.tag){case 0:case 11:case 15:on(l),l.flags&2048&&ot(9,l,l.return);break;case 3:on(l);break;case 12:on(l);break;case 22:var e=l.stateNode;l.memoizedState!==null&&e._visibility&2&&(l.return===null||l.return.tag!==13)?(e._visibility&=-3,gu(l)):on(l);break;default:on(l)}}function gu(l){var e=l.deletions;if((l.flags&16)!==0){if(e!==null)for(var t=0;t<e.length;t++){var a=e[t];Yl=a,sr(a,l)}cr(l)}for(l=l.child;l!==null;){switch(e=l,e.tag){case 0:case 11:case 15:ot(8,e,e.return),gu(e);break;case 22:t=e.stateNode,t._visibility&2&&(t._visibility&=-3,gu(e));break;default:gu(e)}l=l.sibling}}function sr(l,e){for(;Yl!==null;){var t=Yl;switch(t.tag){case 0:case 11:case 15:ot(8,t,e);break;case 23:case 22:if(t.memoizedState!==null&&t.memoizedState.cachePool!==null){var a=t.memoizedState.cachePool.pool;a!=null&&a.refCount++}break;case 24:Ja(t.memoizedState.cache)}if(a=t.child,a!==null)a.return=t,Yl=a;else l:for(t=l;Yl!==null;){a=Yl;var n=a.sibling,u=a.return;if(Po(a),a===t){Yl=null;break l}if(n!==null){n.return=u,Yl=n;break l}Yl=u}}}var dm={getCacheForType:function(l){var e=Ql(Ml),t=e.data.get(l);return t===void 0&&(t=l(),e.data.set(l,t)),t},cacheSignal:function(){return Ql(Ml).controller.signal}},hm=typeof WeakMap=="function"?WeakMap:Map,sl=0,pl=null,P=null,el=0,rl=0,oe=null,rt=!1,pa=!1,_c=!1,We=0,El=0,dt=0,Zt=0,Oc=0,re=0,ba=0,rn=null,ee=null,Nc=!1,pu=0,or=0,bu=1/0,Su=null,ht=null,Bl=0,mt=null,Sa=null,$e=0,Dc=0,Mc=null,rr=null,dn=0,Cc=null;function de(){return(sl&2)!==0&&el!==0?el&-el:x.T!==null?Yc():Ef()}function dr(){if(re===0)if((el&536870912)===0||nl){var l=On;On<<=1,(On&3932160)===0&&(On=262144),re=l}else re=536870912;return l=fe.current,l!==null&&(l.flags|=32),re}function te(l,e,t){(l===pl&&(rl===2||rl===9)||l.cancelPendingCommit!==null)&&(xa(l,0),yt(l,el,re,!1)),Ca(l,t),((sl&2)===0||l!==pl)&&(l===pl&&((sl&2)===0&&(Zt|=t),El===4&&yt(l,el,re,!1)),Ce(l))}function hr(l,e,t){if((sl&6)!==0)throw Error(r(327));var a=!t&&(e&127)===0&&(e&l.expiredLanes)===0||Ma(l,e),n=a?vm(l,e):Rc(l,e,!0),u=a;do{if(n===0){pa&&!a&&yt(l,e,0,!1);break}else{if(t=l.current.alternate,u&&!mm(t)){n=Rc(l,e,!1),u=!1;continue}if(n===2){if(u=e,l.errorRecoveryDisabledLanes&u)var i=0;else i=l.pendingLanes&-536870913,i=i!==0?i:i&536870912?536870912:0;if(i!==0){e=i;l:{var s=l;n=rn;var o=s.current.memoizedState.isDehydrated;if(o&&(xa(s,i).flags|=256),i=Rc(s,i,!1),i!==2){if(_c&&!o){s.errorRecoveryDisabledLanes|=u,Zt|=u,n=4;break l}u=ee,ee=n,u!==null&&(ee===null?ee=u:ee.push.apply(ee,u))}n=i}if(u=!1,n!==2)continue}}if(n===1){xa(l,0),yt(l,e,0,!0);break}l:{switch(a=l,u=n,u){case 0:case 1:throw Error(r(345));case 4:if((e&4194048)!==e)break;case 6:yt(a,e,re,!rt);break l;case 2:ee=null;break;case 3:case 5:break;default:throw Error(r(329))}if((e&62914560)===e&&(n=pu+300-ae(),10<n)){if(yt(a,e,re,!rt),Dn(a,0,!0)!==0)break l;$e=e,a.timeoutHandle=Vr(mr.bind(null,a,t,ee,Su,Nc,e,re,Zt,ba,rt,u,"Throttled",-0,0),n);break l}mr(a,t,ee,Su,Nc,e,re,Zt,ba,rt,u,null,-0,0)}}break}while(!0);Ce(l)}function mr(l,e,t,a,n,u,i,s,o,g,S,z,p,b){if(l.timeoutHandle=-1,z=e.subtreeFlags,z&8192||(z&16785408)===16785408){z={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:He},ir(e,u,z);var B=(u&62914560)===u?pu-ae():(u&4194048)===u?or-ae():0;if(B=Im(z,B),B!==null){$e=u,l.cancelPendingCommit=B(jr.bind(null,l,e,u,t,a,n,i,s,o,S,z,null,p,b)),yt(l,u,i,!g);return}}jr(l,e,u,t,a,n,i,s,o)}function mm(l){for(var e=l;;){var t=e.tag;if((t===0||t===11||t===15)&&e.flags&16384&&(t=e.updateQueue,t!==null&&(t=t.stores,t!==null)))for(var a=0;a<t.length;a++){var n=t[a],u=n.getSnapshot;n=n.value;try{if(!ie(u(),n))return!1}catch{return!1}}if(t=e.child,e.subtreeFlags&16384&&t!==null)t.return=e,e=t;else{if(e===l)break;for(;e.sibling===null;){if(e.return===null||e.return===l)return!0;e=e.return}e.sibling.return=e.return,e=e.sibling}}return!0}function yt(l,e,t,a){e&=~Oc,e&=~Zt,l.suspendedLanes|=e,l.pingedLanes&=~e,a&&(l.warmLanes|=e),a=l.expirationTimes;for(var n=e;0<n;){var u=31-ue(n),i=1<<u;a[u]=-1,n&=~i}t!==0&&zf(l,t,e)}function xu(){return(sl&6)===0?(hn(0),!1):!0}function Uc(){if(P!==null){if(rl===0)var l=P.return;else l=P,Ge=Ut=null,Wi(l),ra=null,ka=0,l=P;for(;l!==null;)Ko(l.alternate,l),l=l.return;P=null}}function xa(l,e){var t=l.timeoutHandle;t!==-1&&(l.timeoutHandle=-1,Rm(t)),t=l.cancelPendingCommit,t!==null&&(l.cancelPendingCommit=null,t()),$e=0,Uc(),pl=l,P=t=qe(l.current,null),el=e,rl=0,oe=null,rt=!1,pa=Ma(l,e),_c=!1,ba=re=Oc=Zt=dt=El=0,ee=rn=null,Nc=!1,(e&8)!==0&&(e|=e&32);var a=l.entangledLanes;if(a!==0)for(l=l.entanglements,a&=e;0<a;){var n=31-ue(a),u=1<<n;e|=l[n],a&=~u}return We=e,Zn(),t}function yr(l,e){$=null,x.H=tn,e===oa||e===$n?(e=Ds(),rl=3):e===qi?(e=Ds(),rl=4):rl=e===rc?8:e!==null&&typeof e=="object"&&typeof e.then=="function"?6:1,oe=e,P===null&&(El=1,ou(l,ve(e,l.current)))}function vr(){var l=fe.current;return l===null?!0:(el&4194048)===el?Se===null:(el&62914560)===el||(el&536870912)!==0?l===Se:!1}function gr(){var l=x.H;return x.H=tn,l===null?tn:l}function pr(){var l=x.A;return x.A=dm,l}function ju(){El=4,rt||(el&4194048)!==el&&fe.current!==null||(pa=!0),(dt&134217727)===0&&(Zt&134217727)===0||pl===null||yt(pl,el,re,!1)}function Rc(l,e,t){var a=sl;sl|=2;var n=gr(),u=pr();(pl!==l||el!==e)&&(Su=null,xa(l,e)),e=!1;var i=El;l:do try{if(rl!==0&&P!==null){var s=P,o=oe;switch(rl){case 8:Uc(),i=6;break l;case 3:case 2:case 9:case 6:fe.current===null&&(e=!0);var g=rl;if(rl=0,oe=null,ja(l,s,o,g),t&&pa){i=0;break l}break;default:g=rl,rl=0,oe=null,ja(l,s,o,g)}}ym(),i=El;break}catch(S){yr(l,S)}while(!0);return e&&l.shellSuspendCounter++,Ge=Ut=null,sl=a,x.H=n,x.A=u,P===null&&(pl=null,el=0,Zn()),i}function ym(){for(;P!==null;)br(P)}function vm(l,e){var t=sl;sl|=2;var a=gr(),n=pr();pl!==l||el!==e?(Su=null,bu=ae()+500,xa(l,e)):pa=Ma(l,e);l:do try{if(rl!==0&&P!==null){e=P;var u=oe;e:switch(rl){case 1:rl=0,oe=null,ja(l,e,u,1);break;case 2:case 9:if(Os(u)){rl=0,oe=null,Sr(e);break}e=function(){rl!==2&&rl!==9||pl!==l||(rl=7),Ce(l)},u.then(e,e);break l;case 3:rl=7;break l;case 4:rl=5;break l;case 7:Os(u)?(rl=0,oe=null,Sr(e)):(rl=0,oe=null,ja(l,e,u,7));break;case 5:var i=null;switch(P.tag){case 26:i=P.memoizedState;case 5:case 27:var s=P;if(i?ud(i):s.stateNode.complete){rl=0,oe=null;var o=s.sibling;if(o!==null)P=o;else{var g=s.return;g!==null?(P=g,zu(g)):P=null}break e}}rl=0,oe=null,ja(l,e,u,5);break;case 6:rl=0,oe=null,ja(l,e,u,6);break;case 8:Uc(),El=6;break l;default:throw Error(r(462))}}gm();break}catch(S){yr(l,S)}while(!0);return Ge=Ut=null,x.H=a,x.A=n,sl=t,P!==null?0:(pl=null,el=0,Zn(),El)}function gm(){for(;P!==null&&!Xd();)br(P)}function br(l){var e=Lo(l.alternate,l,We);l.memoizedProps=l.pendingProps,e===null?zu(l):P=e}function Sr(l){var e=l,t=e.alternate;switch(e.tag){case 15:case 0:e=qo(t,e,e.pendingProps,e.type,void 0,el);break;case 11:e=qo(t,e,e.pendingProps,e.type.render,e.ref,el);break;case 5:Wi(e);default:Ko(t,e),e=P=gs(e,We),e=Lo(t,e,We)}l.memoizedProps=l.pendingProps,e===null?zu(l):P=e}function ja(l,e,t,a){Ge=Ut=null,Wi(e),ra=null,ka=0;var n=e.return;try{if(um(l,n,e,t,el)){El=1,ou(l,ve(t,l.current)),P=null;return}}catch(u){if(n!==null)throw P=n,u;El=1,ou(l,ve(t,l.current)),P=null;return}e.flags&32768?(nl||a===1?l=!0:pa||(el&536870912)!==0?l=!1:(rt=l=!0,(a===2||a===9||a===3||a===6)&&(a=fe.current,a!==null&&a.tag===13&&(a.flags|=16384))),xr(e,l)):zu(e)}function zu(l){var e=l;do{if((e.flags&32768)!==0){xr(e,rt);return}l=e.return;var t=fm(e.alternate,e,We);if(t!==null){P=t;return}if(e=e.sibling,e!==null){P=e;return}P=e=l}while(e!==null);El===0&&(El=5)}function xr(l,e){do{var t=sm(l.alternate,l);if(t!==null){t.flags&=32767,P=t;return}if(t=l.return,t!==null&&(t.flags|=32768,t.subtreeFlags=0,t.deletions=null),!e&&(l=l.sibling,l!==null)){P=l;return}P=l=t}while(l!==null);El=6,P=null}function jr(l,e,t,a,n,u,i,s,o){l.cancelPendingCommit=null;do Tu();while(Bl!==0);if((sl&6)!==0)throw Error(r(327));if(e!==null){if(e===l.current)throw Error(r(177));if(u=e.lanes|e.childLanes,u|=ji,$d(l,t,u,i,s,o),l===pl&&(P=pl=null,el=0),Sa=e,mt=l,$e=t,Dc=u,Mc=n,rr=a,(e.subtreeFlags&10256)!==0||(e.flags&10256)!==0?(l.callbackNode=null,l.callbackPriority=0,xm(En,function(){return _r(),null})):(l.callbackNode=null,l.callbackPriority=0),a=(e.flags&13878)!==0,(e.subtreeFlags&13878)!==0||a){a=x.T,x.T=null,n=U.p,U.p=2,i=sl,sl|=4;try{om(l,e,t)}finally{sl=i,U.p=n,x.T=a}}Bl=1,zr(),Tr(),Ar()}}function zr(){if(Bl===1){Bl=0;var l=mt,e=Sa,t=(e.flags&13878)!==0;if((e.subtreeFlags&13878)!==0||t){t=x.T,x.T=null;var a=U.p;U.p=2;var n=sl;sl|=4;try{ar(e,l);var u=Jc,i=fs(l.containerInfo),s=u.focusedElem,o=u.selectionRange;if(i!==s&&s&&s.ownerDocument&&cs(s.ownerDocument.documentElement,s)){if(o!==null&&gi(s)){var g=o.start,S=o.end;if(S===void 0&&(S=g),"selectionStart"in s)s.selectionStart=g,s.selectionEnd=Math.min(S,s.value.length);else{var z=s.ownerDocument||document,p=z&&z.defaultView||window;if(p.getSelection){var b=p.getSelection(),B=s.textContent.length,L=Math.min(o.start,B),vl=o.end===void 0?L:Math.min(o.end,B);!b.extend&&L>vl&&(i=vl,vl=L,L=i);var y=is(s,L),d=is(s,vl);if(y&&d&&(b.rangeCount!==1||b.anchorNode!==y.node||b.anchorOffset!==y.offset||b.focusNode!==d.node||b.focusOffset!==d.offset)){var v=z.createRange();v.setStart(y.node,y.offset),b.removeAllRanges(),L>vl?(b.addRange(v),b.extend(d.node,d.offset)):(v.setEnd(d.node,d.offset),b.addRange(v))}}}}for(z=[],b=s;b=b.parentNode;)b.nodeType===1&&z.push({element:b,left:b.scrollLeft,top:b.scrollTop});for(typeof s.focus=="function"&&s.focus(),s=0;s<z.length;s++){var j=z[s];j.element.scrollLeft=j.left,j.element.scrollTop=j.top}}Bu=!!Kc,Jc=Kc=null}finally{sl=n,U.p=a,x.T=t}}l.current=e,Bl=2}}function Tr(){if(Bl===2){Bl=0;var l=mt,e=Sa,t=(e.flags&8772)!==0;if((e.subtreeFlags&8772)!==0||t){t=x.T,x.T=null;var a=U.p;U.p=2;var n=sl;sl|=4;try{Io(l,e.alternate,e)}finally{sl=n,U.p=a,x.T=t}}Bl=3}}function Ar(){if(Bl===4||Bl===3){Bl=0,Qd();var l=mt,e=Sa,t=$e,a=rr;(e.subtreeFlags&10256)!==0||(e.flags&10256)!==0?Bl=5:(Bl=0,Sa=mt=null,Er(l,l.pendingLanes));var n=l.pendingLanes;if(n===0&&(ht=null),Iu(t),e=e.stateNode,ne&&typeof ne.onCommitFiberRoot=="function")try{ne.onCommitFiberRoot(Da,e,void 0,(e.current.flags&128)===128)}catch{}if(a!==null){e=x.T,n=U.p,U.p=2,x.T=null;try{for(var u=l.onRecoverableError,i=0;i<a.length;i++){var s=a[i];u(s.value,{componentStack:s.stack})}}finally{x.T=e,U.p=n}}($e&3)!==0&&Tu(),Ce(l),n=l.pendingLanes,(t&261930)!==0&&(n&42)!==0?l===Cc?dn++:(dn=0,Cc=l):dn=0,hn(0)}}function Er(l,e){(l.pooledCacheLanes&=e)===0&&(e=l.pooledCache,e!=null&&(l.pooledCache=null,Ja(e)))}function Tu(){return zr(),Tr(),Ar(),_r()}function _r(){if(Bl!==5)return!1;var l=mt,e=Dc;Dc=0;var t=Iu($e),a=x.T,n=U.p;try{U.p=32>t?32:t,x.T=null,t=Mc,Mc=null;var u=mt,i=$e;if(Bl=0,Sa=mt=null,$e=0,(sl&6)!==0)throw Error(r(331));var s=sl;if(sl|=4,fr(u.current),ur(u,u.current,i,t),sl=s,hn(0,!1),ne&&typeof ne.onPostCommitFiberRoot=="function")try{ne.onPostCommitFiberRoot(Da,u)}catch{}return!0}finally{U.p=n,x.T=a,Er(l,e)}}function Or(l,e,t){e=ve(t,e),e=oc(l.stateNode,e,2),l=ct(l,e,2),l!==null&&(Ca(l,2),Ce(l))}function dl(l,e,t){if(l.tag===3)Or(l,l,t);else for(;e!==null;){if(e.tag===3){Or(e,l,t);break}else if(e.tag===1){var a=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof a.componentDidCatch=="function"&&(ht===null||!ht.has(a))){l=ve(t,l),t=No(2),a=ct(e,t,2),a!==null&&(Do(t,a,e,l),Ca(a,2),Ce(a));break}}e=e.return}}function Hc(l,e,t){var a=l.pingCache;if(a===null){a=l.pingCache=new hm;var n=new Set;a.set(e,n)}else n=a.get(e),n===void 0&&(n=new Set,a.set(e,n));n.has(t)||(_c=!0,n.add(t),l=pm.bind(null,l,e,t),e.then(l,l))}function pm(l,e,t){var a=l.pingCache;a!==null&&a.delete(e),l.pingedLanes|=l.suspendedLanes&t,l.warmLanes&=~t,pl===l&&(el&t)===t&&(El===4||El===3&&(el&62914560)===el&&300>ae()-pu?(sl&2)===0&&xa(l,0):Oc|=t,ba===el&&(ba=0)),Ce(l)}function Nr(l,e){e===0&&(e=jf()),l=Dt(l,e),l!==null&&(Ca(l,e),Ce(l))}function bm(l){var e=l.memoizedState,t=0;e!==null&&(t=e.retryLane),Nr(l,t)}function Sm(l,e){var t=0;switch(l.tag){case 31:case 13:var a=l.stateNode,n=l.memoizedState;n!==null&&(t=n.retryLane);break;case 19:a=l.stateNode;break;case 22:a=l.stateNode._retryCache;break;default:throw Error(r(314))}a!==null&&a.delete(e),Nr(l,t)}function xm(l,e){return ku(l,e)}var Au=null,za=null,Bc=!1,Eu=!1,qc=!1,vt=0;function Ce(l){l!==za&&l.next===null&&(za===null?Au=za=l:za=za.next=l),Eu=!0,Bc||(Bc=!0,zm())}function hn(l,e){if(!qc&&Eu){qc=!0;do for(var t=!1,a=Au;a!==null;){if(l!==0){var n=a.pendingLanes;if(n===0)var u=0;else{var i=a.suspendedLanes,s=a.pingedLanes;u=(1<<31-ue(42|l)+1)-1,u&=n&~(i&~s),u=u&201326741?u&201326741|1:u?u|2:0}u!==0&&(t=!0,Ur(a,u))}else u=el,u=Dn(a,a===pl?u:0,a.cancelPendingCommit!==null||a.timeoutHandle!==-1),(u&3)===0||Ma(a,u)||(t=!0,Ur(a,u));a=a.next}while(t);qc=!1}}function jm(){Dr()}function Dr(){Eu=Bc=!1;var l=0;vt!==0&&Um()&&(l=vt);for(var e=ae(),t=null,a=Au;a!==null;){var n=a.next,u=Mr(a,e);u===0?(a.next=null,t===null?Au=n:t.next=n,n===null&&(za=t)):(t=a,(l!==0||(u&3)!==0)&&(Eu=!0)),a=n}Bl!==0&&Bl!==5||hn(l),vt!==0&&(vt=0)}function Mr(l,e){for(var t=l.suspendedLanes,a=l.pingedLanes,n=l.expirationTimes,u=l.pendingLanes&-62914561;0<u;){var i=31-ue(u),s=1<<i,o=n[i];o===-1?((s&t)===0||(s&a)!==0)&&(n[i]=Wd(s,e)):o<=e&&(l.expiredLanes|=s),u&=~s}if(e=pl,t=el,t=Dn(l,l===e?t:0,l.cancelPendingCommit!==null||l.timeoutHandle!==-1),a=l.callbackNode,t===0||l===e&&(rl===2||rl===9)||l.cancelPendingCommit!==null)return a!==null&&a!==null&&Wu(a),l.callbackNode=null,l.callbackPriority=0;if((t&3)===0||Ma(l,t)){if(e=t&-t,e===l.callbackPriority)return e;switch(a!==null&&Wu(a),Iu(t)){case 2:case 8:t=Sf;break;case 32:t=En;break;case 268435456:t=xf;break;default:t=En}return a=Cr.bind(null,l),t=ku(t,a),l.callbackPriority=e,l.callbackNode=t,e}return a!==null&&a!==null&&Wu(a),l.callbackPriority=2,l.callbackNode=null,2}function Cr(l,e){if(Bl!==0&&Bl!==5)return l.callbackNode=null,l.callbackPriority=0,null;var t=l.callbackNode;if(Tu()&&l.callbackNode!==t)return null;var a=el;return a=Dn(l,l===pl?a:0,l.cancelPendingCommit!==null||l.timeoutHandle!==-1),a===0?null:(hr(l,a,e),Mr(l,ae()),l.callbackNode!=null&&l.callbackNode===t?Cr.bind(null,l):null)}function Ur(l,e){if(Tu())return null;hr(l,e,!0)}function zm(){Hm(function(){(sl&6)!==0?ku(bf,jm):Dr()})}function Yc(){if(vt===0){var l=fa;l===0&&(l=_n,_n<<=1,(_n&261888)===0&&(_n=256)),vt=l}return vt}function Rr(l){return l==null||typeof l=="symbol"||typeof l=="boolean"?null:typeof l=="function"?l:Rn(""+l)}function Hr(l,e){var t=e.ownerDocument.createElement("input");return t.name=e.name,t.value=e.value,l.id&&t.setAttribute("form",l.id),e.parentNode.insertBefore(t,e),l=new FormData(l),t.parentNode.removeChild(t),l}function Tm(l,e,t,a,n){if(e==="submit"&&t&&t.stateNode===n){var u=Rr((n[$l]||null).action),i=a.submitter;i&&(e=(e=i[$l]||null)?Rr(e.formAction):i.getAttribute("formAction"),e!==null&&(u=e,i=null));var s=new Yn("action","action",null,a,n);l.push({event:s,listeners:[{instance:null,listener:function(){if(a.defaultPrevented){if(vt!==0){var o=i?Hr(n,i):new FormData(n);nc(t,{pending:!0,data:o,method:n.method,action:u},null,o)}}else typeof u=="function"&&(s.preventDefault(),o=i?Hr(n,i):new FormData(n),nc(t,{pending:!0,data:o,method:n.method,action:u},u,o))},currentTarget:n}]})}}for(var Gc=0;Gc<xi.length;Gc++){var Xc=xi[Gc],Am=Xc.toLowerCase(),Em=Xc[0].toUpperCase()+Xc.slice(1);Te(Am,"on"+Em)}Te(rs,"onAnimationEnd"),Te(ds,"onAnimationIteration"),Te(hs,"onAnimationStart"),Te("dblclick","onDoubleClick"),Te("focusin","onFocus"),Te("focusout","onBlur"),Te(Zh,"onTransitionRun"),Te(Lh,"onTransitionStart"),Te(Vh,"onTransitionCancel"),Te(ms,"onTransitionEnd"),kt("onMouseEnter",["mouseout","mouseover"]),kt("onMouseLeave",["mouseout","mouseover"]),kt("onPointerEnter",["pointerout","pointerover"]),kt("onPointerLeave",["pointerout","pointerover"]),Et("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),Et("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),Et("onBeforeInput",["compositionend","keypress","textInput","paste"]),Et("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),Et("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),Et("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var mn="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),_m=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(mn));function Br(l,e){e=(e&4)!==0;for(var t=0;t<l.length;t++){var a=l[t],n=a.event;a=a.listeners;l:{var u=void 0;if(e)for(var i=a.length-1;0<=i;i--){var s=a[i],o=s.instance,g=s.currentTarget;if(s=s.listener,o!==u&&n.isPropagationStopped())break l;u=s,n.currentTarget=g;try{u(n)}catch(S){Qn(S)}n.currentTarget=null,u=o}else for(i=0;i<a.length;i++){if(s=a[i],o=s.instance,g=s.currentTarget,s=s.listener,o!==u&&n.isPropagationStopped())break l;u=s,n.currentTarget=g;try{u(n)}catch(S){Qn(S)}n.currentTarget=null,u=o}}}}function ll(l,e){var t=e[Pu];t===void 0&&(t=e[Pu]=new Set);var a=l+"__bubble";t.has(a)||(qr(e,l,2,!1),t.add(a))}function Qc(l,e,t){var a=0;e&&(a|=4),qr(t,l,a,e)}var _u="_reactListening"+Math.random().toString(36).slice(2);function Zc(l){if(!l[_u]){l[_u]=!0,Nf.forEach(function(t){t!=="selectionchange"&&(_m.has(t)||Qc(t,!1,l),Qc(t,!0,l))});var e=l.nodeType===9?l:l.ownerDocument;e===null||e[_u]||(e[_u]=!0,Qc("selectionchange",!1,e))}}function qr(l,e,t,a){switch(dd(e)){case 2:var n=ey;break;case 8:n=ty;break;default:n=af}t=n.bind(null,e,t,l),n=void 0,!fi||e!=="touchstart"&&e!=="touchmove"&&e!=="wheel"||(n=!0),a?n!==void 0?l.addEventListener(e,t,{capture:!0,passive:n}):l.addEventListener(e,t,!0):n!==void 0?l.addEventListener(e,t,{passive:n}):l.addEventListener(e,t,!1)}function Lc(l,e,t,a,n){var u=a;if((e&1)===0&&(e&2)===0&&a!==null)l:for(;;){if(a===null)return;var i=a.tag;if(i===3||i===4){var s=a.stateNode.containerInfo;if(s===n)break;if(i===4)for(i=a.return;i!==null;){var o=i.tag;if((o===3||o===4)&&i.stateNode.containerInfo===n)return;i=i.return}for(;s!==null;){if(i=Kt(s),i===null)return;if(o=i.tag,o===5||o===6||o===26||o===27){a=u=i;continue l}s=s.parentNode}}a=a.return}Qf(function(){var g=u,S=ii(t),z=[];l:{var p=ys.get(l);if(p!==void 0){var b=Yn,B=l;switch(l){case"keypress":if(Bn(t)===0)break l;case"keydown":case"keyup":b=Sh;break;case"focusin":B="focus",b=di;break;case"focusout":B="blur",b=di;break;case"beforeblur":case"afterblur":b=di;break;case"click":if(t.button===2)break l;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":b=Vf;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":b=fh;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":b=zh;break;case rs:case ds:case hs:b=rh;break;case ms:b=Ah;break;case"scroll":case"scrollend":b=ih;break;case"wheel":b=_h;break;case"copy":case"cut":case"paste":b=hh;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":b=Jf;break;case"toggle":case"beforetoggle":b=Nh}var L=(e&4)!==0,vl=!L&&(l==="scroll"||l==="scrollend"),y=L?p!==null?p+"Capture":null:p;L=[];for(var d=g,v;d!==null;){var j=d;if(v=j.stateNode,j=j.tag,j!==5&&j!==26&&j!==27||v===null||y===null||(j=Ha(d,y),j!=null&&L.push(yn(d,j,v))),vl)break;d=d.return}0<L.length&&(p=new b(p,B,null,t,S),z.push({event:p,listeners:L}))}}if((e&7)===0){l:{if(p=l==="mouseover"||l==="pointerover",b=l==="mouseout"||l==="pointerout",p&&t!==ui&&(B=t.relatedTarget||t.fromElement)&&(Kt(B)||B[Vt]))break l;if((b||p)&&(p=S.window===S?S:(p=S.ownerDocument)?p.defaultView||p.parentWindow:window,b?(B=t.relatedTarget||t.toElement,b=g,B=B?Kt(B):null,B!==null&&(vl=_(B),L=B.tag,B!==vl||L!==5&&L!==27&&L!==6)&&(B=null)):(b=null,B=g),b!==B)){if(L=Vf,j="onMouseLeave",y="onMouseEnter",d="mouse",(l==="pointerout"||l==="pointerover")&&(L=Jf,j="onPointerLeave",y="onPointerEnter",d="pointer"),vl=b==null?p:Ra(b),v=B==null?p:Ra(B),p=new L(j,d+"leave",b,t,S),p.target=vl,p.relatedTarget=v,j=null,Kt(S)===g&&(L=new L(y,d+"enter",B,t,S),L.target=v,L.relatedTarget=vl,j=L),vl=j,b&&B)e:{for(L=Om,y=b,d=B,v=0,j=y;j;j=L(j))v++;j=0;for(var Q=d;Q;Q=L(Q))j++;for(;0<v-j;)y=L(y),v--;for(;0<j-v;)d=L(d),j--;for(;v--;){if(y===d||d!==null&&y===d.alternate){L=y;break e}y=L(y),d=L(d)}L=null}else L=null;b!==null&&Yr(z,p,b,L,!1),B!==null&&vl!==null&&Yr(z,vl,B,L,!0)}}l:{if(p=g?Ra(g):window,b=p.nodeName&&p.nodeName.toLowerCase(),b==="select"||b==="input"&&p.type==="file")var cl=ls;else if(If(p))if(es)cl=Gh;else{cl=qh;var X=Bh}else b=p.nodeName,!b||b.toLowerCase()!=="input"||p.type!=="checkbox"&&p.type!=="radio"?g&&ni(g.elementType)&&(cl=ls):cl=Yh;if(cl&&(cl=cl(l,g))){Pf(z,cl,t,S);break l}X&&X(l,p,g),l==="focusout"&&g&&p.type==="number"&&g.memoizedProps.value!=null&&ai(p,"number",p.value)}switch(X=g?Ra(g):window,l){case"focusin":(If(X)||X.contentEditable==="true")&&(la=X,pi=g,La=null);break;case"focusout":La=pi=la=null;break;case"mousedown":bi=!0;break;case"contextmenu":case"mouseup":case"dragend":bi=!1,ss(z,t,S);break;case"selectionchange":if(Qh)break;case"keydown":case"keyup":ss(z,t,S)}var F;if(mi)l:{switch(l){case"compositionstart":var tl="onCompositionStart";break l;case"compositionend":tl="onCompositionEnd";break l;case"compositionupdate":tl="onCompositionUpdate";break l}tl=void 0}else Pt?$f(l,t)&&(tl="onCompositionEnd"):l==="keydown"&&t.keyCode===229&&(tl="onCompositionStart");tl&&(wf&&t.locale!=="ko"&&(Pt||tl!=="onCompositionStart"?tl==="onCompositionEnd"&&Pt&&(F=Zf()):(lt=S,si="value"in lt?lt.value:lt.textContent,Pt=!0)),X=Ou(g,tl),0<X.length&&(tl=new Kf(tl,l,null,t,S),z.push({event:tl,listeners:X}),F?tl.data=F:(F=Ff(t),F!==null&&(tl.data=F)))),(F=Mh?Ch(l,t):Uh(l,t))&&(tl=Ou(g,"onBeforeInput"),0<tl.length&&(X=new Kf("onBeforeInput","beforeinput",null,t,S),z.push({event:X,listeners:tl}),X.data=F)),Tm(z,l,g,t,S)}Br(z,e)})}function yn(l,e,t){return{instance:l,listener:e,currentTarget:t}}function Ou(l,e){for(var t=e+"Capture",a=[];l!==null;){var n=l,u=n.stateNode;if(n=n.tag,n!==5&&n!==26&&n!==27||u===null||(n=Ha(l,t),n!=null&&a.unshift(yn(l,n,u)),n=Ha(l,e),n!=null&&a.push(yn(l,n,u))),l.tag===3)return a;l=l.return}return[]}function Om(l){if(l===null)return null;do l=l.return;while(l&&l.tag!==5&&l.tag!==27);return l||null}function Yr(l,e,t,a,n){for(var u=e._reactName,i=[];t!==null&&t!==a;){var s=t,o=s.alternate,g=s.stateNode;if(s=s.tag,o!==null&&o===a)break;s!==5&&s!==26&&s!==27||g===null||(o=g,n?(g=Ha(t,u),g!=null&&i.unshift(yn(t,g,o))):n||(g=Ha(t,u),g!=null&&i.push(yn(t,g,o)))),t=t.return}i.length!==0&&l.push({event:e,listeners:i})}var Nm=/\r\n?/g,Dm=/\u0000|\uFFFD/g;function Gr(l){return(typeof l=="string"?l:""+l).replace(Nm,`-`).replace(Dm,"")}function Xr(l,e){return e=Gr(e),Gr(l)===e}function yl(l,e,t,a,n,u){switch(t){case"children":typeof a=="string"?e==="body"||e==="textarea"&&a===""||$t(l,a):(typeof a=="number"||typeof a=="bigint")&&e!=="body"&&$t(l,""+a);break;case"className":Cn(l,"class",a);break;case"tabIndex":Cn(l,"tabindex",a);break;case"dir":case"role":case"viewBox":case"width":case"height":Cn(l,t,a);break;case"style":Gf(l,a,u);break;case"data":if(e!=="object"){Cn(l,"data",a);break}case"src":case"href":if(a===""&&(e!=="a"||t!=="href")){l.removeAttribute(t);break}if(a==null||typeof a=="function"||typeof a=="symbol"||typeof a=="boolean"){l.removeAttribute(t);break}a=Rn(""+a),l.setAttribute(t,a);break;case"action":case"formAction":if(typeof a=="function"){l.setAttribute(t,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof u=="function"&&(t==="formAction"?(e!=="input"&&yl(l,e,"name",n.name,n,null),yl(l,e,"formEncType",n.formEncType,n,null),yl(l,e,"formMethod",n.formMethod,n,null),yl(l,e,"formTarget",n.formTarget,n,null)):(yl(l,e,"encType",n.encType,n,null),yl(l,e,"method",n.method,n,null),yl(l,e,"target",n.target,n,null)));if(a==null||typeof a=="symbol"||typeof a=="boolean"){l.removeAttribute(t);break}a=Rn(""+a),l.setAttribute(t,a);break;case"onClick":a!=null&&(l.onclick=He);break;case"onScroll":a!=null&&ll("scroll",l);break;case"onScrollEnd":a!=null&&ll("scrollend",l);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(r(61));if(t=a.__html,t!=null){if(n.children!=null)throw Error(r(60));l.innerHTML=t}}break;case"multiple":l.multiple=a&&typeof a!="function"&&typeof a!="symbol";break;case"muted":l.muted=a&&typeof a!="function"&&typeof a!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(a==null||typeof a=="function"||typeof a=="boolean"||typeof a=="symbol"){l.removeAttribute("xlink:href");break}t=Rn(""+a),l.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",t);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":a!=null&&typeof a!="function"&&typeof a!="symbol"?l.setAttribute(t,""+a):l.removeAttribute(t);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":a&&typeof a!="function"&&typeof a!="symbol"?l.setAttribute(t,""):l.removeAttribute(t);break;case"capture":case"download":a===!0?l.setAttribute(t,""):a!==!1&&a!=null&&typeof a!="function"&&typeof a!="symbol"?l.setAttribute(t,a):l.removeAttribute(t);break;case"cols":case"rows":case"size":case"span":a!=null&&typeof a!="function"&&typeof a!="symbol"&&!isNaN(a)&&1<=a?l.setAttribute(t,a):l.removeAttribute(t);break;case"rowSpan":case"start":a==null||typeof a=="function"||typeof a=="symbol"||isNaN(a)?l.removeAttribute(t):l.setAttribute(t,a);break;case"popover":ll("beforetoggle",l),ll("toggle",l),Mn(l,"popover",a);break;case"xlinkActuate":Re(l,"http://www.w3.org/1999/xlink","xlink:actuate",a);break;case"xlinkArcrole":Re(l,"http://www.w3.org/1999/xlink","xlink:arcrole",a);break;case"xlinkRole":Re(l,"http://www.w3.org/1999/xlink","xlink:role",a);break;case"xlinkShow":Re(l,"http://www.w3.org/1999/xlink","xlink:show",a);break;case"xlinkTitle":Re(l,"http://www.w3.org/1999/xlink","xlink:title",a);break;case"xlinkType":Re(l,"http://www.w3.org/1999/xlink","xlink:type",a);break;case"xmlBase":Re(l,"http://www.w3.org/XML/1998/namespace","xml:base",a);break;case"xmlLang":Re(l,"http://www.w3.org/XML/1998/namespace","xml:lang",a);break;case"xmlSpace":Re(l,"http://www.w3.org/XML/1998/namespace","xml:space",a);break;case"is":Mn(l,"is",a);break;case"innerText":case"textContent":break;default:(!(2<t.length)||t[0]!=="o"&&t[0]!=="O"||t[1]!=="n"&&t[1]!=="N")&&(t=nh.get(t)||t,Mn(l,t,a))}}function Vc(l,e,t,a,n,u){switch(t){case"style":Gf(l,a,u);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(r(61));if(t=a.__html,t!=null){if(n.children!=null)throw Error(r(60));l.innerHTML=t}}break;case"children":typeof a=="string"?$t(l,a):(typeof a=="number"||typeof a=="bigint")&&$t(l,""+a);break;case"onScroll":a!=null&&ll("scroll",l);break;case"onScrollEnd":a!=null&&ll("scrollend",l);break;case"onClick":a!=null&&(l.onclick=He);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!Df.hasOwnProperty(t))l:{if(t[0]==="o"&&t[1]==="n"&&(n=t.endsWith("Capture"),e=t.slice(2,n?t.length-7:void 0),u=l[$l]||null,u=u!=null?u[t]:null,typeof u=="function"&&l.removeEventListener(e,u,n),typeof a=="function")){typeof u!="function"&&u!==null&&(t in l?l[t]=null:l.hasAttribute(t)&&l.removeAttribute(t)),l.addEventListener(e,a,n);break l}t in l?l[t]=a:a===!0?l.setAttribute(t,""):Mn(l,t,a)}}}function Ll(l,e,t){switch(e){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":ll("error",l),ll("load",l);var a=!1,n=!1,u;for(u in t)if(t.hasOwnProperty(u)){var i=t[u];if(i!=null)switch(u){case"src":a=!0;break;case"srcSet":n=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(r(137,e));default:yl(l,e,u,i,t,null)}}n&&yl(l,e,"srcSet",t.srcSet,t,null),a&&yl(l,e,"src",t.src,t,null);return;case"input":ll("invalid",l);var s=u=i=n=null,o=null,g=null;for(a in t)if(t.hasOwnProperty(a)){var S=t[a];if(S!=null)switch(a){case"name":n=S;break;case"type":i=S;break;case"checked":o=S;break;case"defaultChecked":g=S;break;case"value":u=S;break;case"defaultValue":s=S;break;case"children":case"dangerouslySetInnerHTML":if(S!=null)throw Error(r(137,e));break;default:yl(l,e,a,S,t,null)}}Hf(l,u,s,o,g,i,n,!1);return;case"select":ll("invalid",l),a=i=u=null;for(n in t)if(t.hasOwnProperty(n)&&(s=t[n],s!=null))switch(n){case"value":u=s;break;case"defaultValue":i=s;break;case"multiple":a=s;default:yl(l,e,n,s,t,null)}e=u,t=i,l.multiple=!!a,e!=null?Wt(l,!!a,e,!1):t!=null&&Wt(l,!!a,t,!0);return;case"textarea":ll("invalid",l),u=n=a=null;for(i in t)if(t.hasOwnProperty(i)&&(s=t[i],s!=null))switch(i){case"value":a=s;break;case"defaultValue":n=s;break;case"children":u=s;break;case"dangerouslySetInnerHTML":if(s!=null)throw Error(r(91));break;default:yl(l,e,i,s,t,null)}qf(l,a,n,u);return;case"option":for(o in t)if(t.hasOwnProperty(o)&&(a=t[o],a!=null))switch(o){case"selected":l.selected=a&&typeof a!="function"&&typeof a!="symbol";break;default:yl(l,e,o,a,t,null)}return;case"dialog":ll("beforetoggle",l),ll("toggle",l),ll("cancel",l),ll("close",l);break;case"iframe":case"object":ll("load",l);break;case"video":case"audio":for(a=0;a<mn.length;a++)ll(mn[a],l);break;case"image":ll("error",l),ll("load",l);break;case"details":ll("toggle",l);break;case"embed":case"source":case"link":ll("error",l),ll("load",l);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(g in t)if(t.hasOwnProperty(g)&&(a=t[g],a!=null))switch(g){case"children":case"dangerouslySetInnerHTML":throw Error(r(137,e));default:yl(l,e,g,a,t,null)}return;default:if(ni(e)){for(S in t)t.hasOwnProperty(S)&&(a=t[S],a!==void 0&&Vc(l,e,S,a,t,void 0));return}}for(s in t)t.hasOwnProperty(s)&&(a=t[s],a!=null&&yl(l,e,s,a,t,null))}function Mm(l,e,t,a){switch(e){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var n=null,u=null,i=null,s=null,o=null,g=null,S=null;for(b in t){var z=t[b];if(t.hasOwnProperty(b)&&z!=null)switch(b){case"checked":break;case"value":break;case"defaultValue":o=z;default:a.hasOwnProperty(b)||yl(l,e,b,null,a,z)}}for(var p in a){var b=a[p];if(z=t[p],a.hasOwnProperty(p)&&(b!=null||z!=null))switch(p){case"type":u=b;break;case"name":n=b;break;case"checked":g=b;break;case"defaultChecked":S=b;break;case"value":i=b;break;case"defaultValue":s=b;break;case"children":case"dangerouslySetInnerHTML":if(b!=null)throw Error(r(137,e));break;default:b!==z&&yl(l,e,p,b,a,z)}}ti(l,i,s,o,g,S,u,n);return;case"select":b=i=s=p=null;for(u in t)if(o=t[u],t.hasOwnProperty(u)&&o!=null)switch(u){case"value":break;case"multiple":b=o;default:a.hasOwnProperty(u)||yl(l,e,u,null,a,o)}for(n in a)if(u=a[n],o=t[n],a.hasOwnProperty(n)&&(u!=null||o!=null))switch(n){case"value":p=u;break;case"defaultValue":s=u;break;case"multiple":i=u;default:u!==o&&yl(l,e,n,u,a,o)}e=s,t=i,a=b,p!=null?Wt(l,!!t,p,!1):!!a!=!!t&&(e!=null?Wt(l,!!t,e,!0):Wt(l,!!t,t?[]:"",!1));return;case"textarea":b=p=null;for(s in t)if(n=t[s],t.hasOwnProperty(s)&&n!=null&&!a.hasOwnProperty(s))switch(s){case"value":break;case"children":break;default:yl(l,e,s,null,a,n)}for(i in a)if(n=a[i],u=t[i],a.hasOwnProperty(i)&&(n!=null||u!=null))switch(i){case"value":p=n;break;case"defaultValue":b=n;break;case"children":break;case"dangerouslySetInnerHTML":if(n!=null)throw Error(r(91));break;default:n!==u&&yl(l,e,i,n,a,u)}Bf(l,p,b);return;case"option":for(var B in t)if(p=t[B],t.hasOwnProperty(B)&&p!=null&&!a.hasOwnProperty(B))switch(B){case"selected":l.selected=!1;break;default:yl(l,e,B,null,a,p)}for(o in a)if(p=a[o],b=t[o],a.hasOwnProperty(o)&&p!==b&&(p!=null||b!=null))switch(o){case"selected":l.selected=p&&typeof p!="function"&&typeof p!="symbol";break;default:yl(l,e,o,p,a,b)}return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var L in t)p=t[L],t.hasOwnProperty(L)&&p!=null&&!a.hasOwnProperty(L)&&yl(l,e,L,null,a,p);for(g in a)if(p=a[g],b=t[g],a.hasOwnProperty(g)&&p!==b&&(p!=null||b!=null))switch(g){case"children":case"dangerouslySetInnerHTML":if(p!=null)throw Error(r(137,e));break;default:yl(l,e,g,p,a,b)}return;default:if(ni(e)){for(var vl in t)p=t[vl],t.hasOwnProperty(vl)&&p!==void 0&&!a.hasOwnProperty(vl)&&Vc(l,e,vl,void 0,a,p);for(S in a)p=a[S],b=t[S],!a.hasOwnProperty(S)||p===b||p===void 0&&b===void 0||Vc(l,e,S,p,a,b);return}}for(var y in t)p=t[y],t.hasOwnProperty(y)&&p!=null&&!a.hasOwnProperty(y)&&yl(l,e,y,null,a,p);for(z in a)p=a[z],b=t[z],!a.hasOwnProperty(z)||p===b||p==null&&b==null||yl(l,e,z,p,a,b)}function Qr(l){switch(l){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function Cm(){if(typeof performance.getEntriesByType=="function"){for(var l=0,e=0,t=performance.getEntriesByType("resource"),a=0;a<t.length;a++){var n=t[a],u=n.transferSize,i=n.initiatorType,s=n.duration;if(u&&s&&Qr(i)){for(i=0,s=n.responseEnd,a+=1;a<t.length;a++){var o=t[a],g=o.startTime;if(g>s)break;var S=o.transferSize,z=o.initiatorType;S&&Qr(z)&&(o=o.responseEnd,i+=S*(o<s?1:(s-g)/(o-g)))}if(--a,e+=8*(u+i)/(n.duration/1e3),l++,10<l)break}}if(0<l)return e/l/1e6}return navigator.connection&&(l=navigator.connection.downlink,typeof l=="number")?l:5}var Kc=null,Jc=null;function Nu(l){return l.nodeType===9?l:l.ownerDocument}function Zr(l){switch(l){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function Lr(l,e){if(l===0)switch(e){case"svg":return 1;case"math":return 2;default:return 0}return l===1&&e==="foreignObject"?0:l}function wc(l,e){return l==="textarea"||l==="noscript"||typeof e.children=="string"||typeof e.children=="number"||typeof e.children=="bigint"||typeof e.dangerouslySetInnerHTML=="object"&&e.dangerouslySetInnerHTML!==null&&e.dangerouslySetInnerHTML.__html!=null}var kc=null;function Um(){var l=window.event;return l&&l.type==="popstate"?l===kc?!1:(kc=l,!0):(kc=null,!1)}var Vr=typeof setTimeout=="function"?setTimeout:void 0,Rm=typeof clearTimeout=="function"?clearTimeout:void 0,Kr=typeof Promise=="function"?Promise:void 0,Hm=typeof queueMicrotask=="function"?queueMicrotask:typeof Kr<"u"?function(l){return Kr.resolve(null).then(l).catch(Bm)}:Vr;function Bm(l){setTimeout(function(){throw l})}function gt(l){return l==="head"}function Jr(l,e){var t=e,a=0;do{var n=t.nextSibling;if(l.removeChild(t),n&&n.nodeType===8)if(t=n.data,t==="/$"||t==="/&"){if(a===0){l.removeChild(n),_a(e);return}a--}else if(t==="$"||t==="$?"||t==="$~"||t==="$!"||t==="&")a++;else if(t==="html")vn(l.ownerDocument.documentElement);else if(t==="head"){t=l.ownerDocument.head,vn(t);for(var u=t.firstChild;u;){var i=u.nextSibling,s=u.nodeName;u[Ua]||s==="SCRIPT"||s==="STYLE"||s==="LINK"&&u.rel.toLowerCase()==="stylesheet"||t.removeChild(u),u=i}}else t==="body"&&vn(l.ownerDocument.body);t=n}while(t);_a(e)}function wr(l,e){var t=l;l=0;do{var a=t.nextSibling;if(t.nodeType===1?e?(t._stashedDisplay=t.style.display,t.style.display="none"):(t.style.display=t._stashedDisplay||"",t.getAttribute("style")===""&&t.removeAttribute("style")):t.nodeType===3&&(e?(t._stashedText=t.nodeValue,t.nodeValue=""):t.nodeValue=t._stashedText||""),a&&a.nodeType===8)if(t=a.data,t==="/$"){if(l===0)break;l--}else t!=="$"&&t!=="$?"&&t!=="$~"&&t!=="$!"||l++;t=a}while(t)}function Wc(l){var e=l.firstChild;for(e&&e.nodeType===10&&(e=e.nextSibling);e;){var t=e;switch(e=e.nextSibling,t.nodeName){case"HTML":case"HEAD":case"BODY":Wc(t),li(t);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(t.rel.toLowerCase()==="stylesheet")continue}l.removeChild(t)}}function qm(l,e,t,a){for(;l.nodeType===1;){var n=t;if(l.nodeName.toLowerCase()!==e.toLowerCase()){if(!a&&(l.nodeName!=="INPUT"||l.type!=="hidden"))break}else if(a){if(!l[Ua])switch(e){case"meta":if(!l.hasAttribute("itemprop"))break;return l;case"link":if(u=l.getAttribute("rel"),u==="stylesheet"&&l.hasAttribute("data-precedence"))break;if(u!==n.rel||l.getAttribute("href")!==(n.href==null||n.href===""?null:n.href)||l.getAttribute("crossorigin")!==(n.crossOrigin==null?null:n.crossOrigin)||l.getAttribute("title")!==(n.title==null?null:n.title))break;return l;case"style":if(l.hasAttribute("data-precedence"))break;return l;case"script":if(u=l.getAttribute("src"),(u!==(n.src==null?null:n.src)||l.getAttribute("type")!==(n.type==null?null:n.type)||l.getAttribute("crossorigin")!==(n.crossOrigin==null?null:n.crossOrigin))&&u&&l.hasAttribute("async")&&!l.hasAttribute("itemprop"))break;return l;default:return l}}else if(e==="input"&&l.type==="hidden"){var u=n.name==null?null:""+n.name;if(n.type==="hidden"&&l.getAttribute("name")===u)return l}else return l;if(l=xe(l.nextSibling),l===null)break}return null}function Ym(l,e,t){if(e==="")return null;for(;l.nodeType!==3;)if((l.nodeType!==1||l.nodeName!=="INPUT"||l.type!=="hidden")&&!t||(l=xe(l.nextSibling),l===null))return null;return l}function kr(l,e){for(;l.nodeType!==8;)if((l.nodeType!==1||l.nodeName!=="INPUT"||l.type!=="hidden")&&!e||(l=xe(l.nextSibling),l===null))return null;return l}function $c(l){return l.data==="$?"||l.data==="$~"}function Fc(l){return l.data==="$!"||l.data==="$?"&&l.ownerDocument.readyState!=="loading"}function Gm(l,e){var t=l.ownerDocument;if(l.data==="$~")l._reactRetry=e;else if(l.data!=="$?"||t.readyState!=="loading")e();else{var a=function(){e(),t.removeEventListener("DOMContentLoaded",a)};t.addEventListener("DOMContentLoaded",a),l._reactRetry=a}}function xe(l){for(;l!=null;l=l.nextSibling){var e=l.nodeType;if(e===1||e===3)break;if(e===8){if(e=l.data,e==="$"||e==="$!"||e==="$?"||e==="$~"||e==="&"||e==="F!"||e==="F")break;if(e==="/$"||e==="/&")return null}}return l}var Ic=null;function Wr(l){l=l.nextSibling;for(var e=0;l;){if(l.nodeType===8){var t=l.data;if(t==="/$"||t==="/&"){if(e===0)return xe(l.nextSibling);e--}else t!=="$"&&t!=="$!"&&t!=="$?"&&t!=="$~"&&t!=="&"||e++}l=l.nextSibling}return null}function $r(l){l=l.previousSibling;for(var e=0;l;){if(l.nodeType===8){var t=l.data;if(t==="$"||t==="$!"||t==="$?"||t==="$~"||t==="&"){if(e===0)return l;e--}else t!=="/$"&&t!=="/&"||e++}l=l.previousSibling}return null}function Fr(l,e,t){switch(e=Nu(t),l){case"html":if(l=e.documentElement,!l)throw Error(r(452));return l;case"head":if(l=e.head,!l)throw Error(r(453));return l;case"body":if(l=e.body,!l)throw Error(r(454));return l;default:throw Error(r(451))}}function vn(l){for(var e=l.attributes;e.length;)l.removeAttributeNode(e[0]);li(l)}var je=new Map,Ir=new Set;function Du(l){return typeof l.getRootNode=="function"?l.getRootNode():l.nodeType===9?l:l.ownerDocument}var Fe=U.d;U.d={f:Xm,r:Qm,D:Zm,C:Lm,L:Vm,m:Km,X:wm,S:Jm,M:km};function Xm(){var l=Fe.f(),e=xu();return l||e}function Qm(l){var e=Jt(l);e!==null&&e.tag===5&&e.type==="form"?yo(e):Fe.r(l)}var Ta=typeof document>"u"?null:document;function Pr(l,e,t){var a=Ta;if(a&&typeof e=="string"&&e){var n=me(e);n='link[rel="'+l+'"][href="'+n+'"]',typeof t=="string"&&(n+='[crossorigin="'+t+'"]'),Ir.has(n)||(Ir.add(n),l={rel:l,crossOrigin:t,href:e},a.querySelector(n)===null&&(e=a.createElement("link"),Ll(e,"link",l),ql(e),a.head.appendChild(e)))}}function Zm(l){Fe.D(l),Pr("dns-prefetch",l,null)}function Lm(l,e){Fe.C(l,e),Pr("preconnect",l,e)}function Vm(l,e,t){Fe.L(l,e,t);var a=Ta;if(a&&l&&e){var n='link[rel="preload"][as="'+me(e)+'"]';e==="image"&&t&&t.imageSrcSet?(n+='[imagesrcset="'+me(t.imageSrcSet)+'"]',typeof t.imageSizes=="string"&&(n+='[imagesizes="'+me(t.imageSizes)+'"]')):n+='[href="'+me(l)+'"]';var u=n;switch(e){case"style":u=Aa(l);break;case"script":u=Ea(l)}je.has(u)||(l=M({rel:"preload",href:e==="image"&&t&&t.imageSrcSet?void 0:l,as:e},t),je.set(u,l),a.querySelector(n)!==null||e==="style"&&a.querySelector(gn(u))||e==="script"&&a.querySelector(pn(u))||(e=a.createElement("link"),Ll(e,"link",l),ql(e),a.head.appendChild(e)))}}function Km(l,e){Fe.m(l,e);var t=Ta;if(t&&l){var a=e&&typeof e.as=="string"?e.as:"script",n='link[rel="modulepreload"][as="'+me(a)+'"][href="'+me(l)+'"]',u=n;switch(a){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":u=Ea(l)}if(!je.has(u)&&(l=M({rel:"modulepreload",href:l},e),je.set(u,l),t.querySelector(n)===null)){switch(a){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(t.querySelector(pn(u)))return}a=t.createElement("link"),Ll(a,"link",l),ql(a),t.head.appendChild(a)}}}function Jm(l,e,t){Fe.S(l,e,t);var a=Ta;if(a&&l){var n=wt(a).hoistableStyles,u=Aa(l);e=e||"default";var i=n.get(u);if(!i){var s={loading:0,preload:null};if(i=a.querySelector(gn(u)))s.loading=5;else{l=M({rel:"stylesheet",href:l,"data-precedence":e},t),(t=je.get(u))&&Pc(l,t);var o=i=a.createElement("link");ql(o),Ll(o,"link",l),o._p=new Promise(function(g,S){o.onload=g,o.onerror=S}),o.addEventListener("load",function(){s.loading|=1}),o.addEventListener("error",function(){s.loading|=2}),s.loading|=4,Mu(i,e,a)}i={type:"stylesheet",instance:i,count:1,state:s},n.set(u,i)}}}function wm(l,e){Fe.X(l,e);var t=Ta;if(t&&l){var a=wt(t).hoistableScripts,n=Ea(l),u=a.get(n);u||(u=t.querySelector(pn(n)),u||(l=M({src:l,async:!0},e),(e=je.get(n))&&lf(l,e),u=t.createElement("script"),ql(u),Ll(u,"link",l),t.head.appendChild(u)),u={type:"script",instance:u,count:1,state:null},a.set(n,u))}}function km(l,e){Fe.M(l,e);var t=Ta;if(t&&l){var a=wt(t).hoistableScripts,n=Ea(l),u=a.get(n);u||(u=t.querySelector(pn(n)),u||(l=M({src:l,async:!0,type:"module"},e),(e=je.get(n))&&lf(l,e),u=t.createElement("script"),ql(u),Ll(u,"link",l),t.head.appendChild(u)),u={type:"script",instance:u,count:1,state:null},a.set(n,u))}}function ld(l,e,t,a){var n=(n=I.current)?Du(n):null;if(!n)throw Error(r(446));switch(l){case"meta":case"title":return null;case"style":return typeof t.precedence=="string"&&typeof t.href=="string"?(e=Aa(t.href),t=wt(n).hoistableStyles,a=t.get(e),a||(a={type:"style",instance:null,count:0,state:null},t.set(e,a)),a):{type:"void",instance:null,count:0,state:null};case"link":if(t.rel==="stylesheet"&&typeof t.href=="string"&&typeof t.precedence=="string"){l=Aa(t.href);var u=wt(n).hoistableStyles,i=u.get(l);if(i||(n=n.ownerDocument||n,i={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},u.set(l,i),(u=n.querySelector(gn(l)))&&!u._p&&(i.instance=u,i.state.loading=5),je.has(l)||(t={rel:"preload",as:"style",href:t.href,crossOrigin:t.crossOrigin,integrity:t.integrity,media:t.media,hrefLang:t.hrefLang,referrerPolicy:t.referrerPolicy},je.set(l,t),u||Wm(n,l,t,i.state))),e&&a===null)throw Error(r(528,""));return i}if(e&&a!==null)throw Error(r(529,""));return null;case"script":return e=t.async,t=t.src,typeof t=="string"&&e&&typeof e!="function"&&typeof e!="symbol"?(e=Ea(t),t=wt(n).hoistableScripts,a=t.get(e),a||(a={type:"script",instance:null,count:0,state:null},t.set(e,a)),a):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,l))}}function Aa(l){return'href="'+me(l)+'"'}function gn(l){return'link[rel="stylesheet"]['+l+"]"}function ed(l){return M({},l,{"data-precedence":l.precedence,precedence:null})}function Wm(l,e,t,a){l.querySelector('link[rel="preload"][as="style"]['+e+"]")?a.loading=1:(e=l.createElement("link"),a.preload=e,e.addEventListener("load",function(){return a.loading|=1}),e.addEventListener("error",function(){return a.loading|=2}),Ll(e,"link",t),ql(e),l.head.appendChild(e))}function Ea(l){return'[src="'+me(l)+'"]'}function pn(l){return"script[async]"+l}function td(l,e,t){if(e.count++,e.instance===null)switch(e.type){case"style":var a=l.querySelector('style[data-href~="'+me(t.href)+'"]');if(a)return e.instance=a,ql(a),a;var n=M({},t,{"data-href":t.href,"data-precedence":t.precedence,href:null,precedence:null});return a=(l.ownerDocument||l).createElement("style"),ql(a),Ll(a,"style",n),Mu(a,t.precedence,l),e.instance=a;case"stylesheet":n=Aa(t.href);var u=l.querySelector(gn(n));if(u)return e.state.loading|=4,e.instance=u,ql(u),u;a=ed(t),(n=je.get(n))&&Pc(a,n),u=(l.ownerDocument||l).createElement("link"),ql(u);var i=u;return i._p=new Promise(function(s,o){i.onload=s,i.onerror=o}),Ll(u,"link",a),e.state.loading|=4,Mu(u,t.precedence,l),e.instance=u;case"script":return u=Ea(t.src),(n=l.querySelector(pn(u)))?(e.instance=n,ql(n),n):(a=t,(n=je.get(u))&&(a=M({},t),lf(a,n)),l=l.ownerDocument||l,n=l.createElement("script"),ql(n),Ll(n,"link",a),l.head.appendChild(n),e.instance=n);case"void":return null;default:throw Error(r(443,e.type))}else e.type==="stylesheet"&&(e.state.loading&4)===0&&(a=e.instance,e.state.loading|=4,Mu(a,t.precedence,l));return e.instance}function Mu(l,e,t){for(var a=t.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),n=a.length?a[a.length-1]:null,u=n,i=0;i<a.length;i++){var s=a[i];if(s.dataset.precedence===e)u=s;else if(u!==n)break}u?u.parentNode.insertBefore(l,u.nextSibling):(e=t.nodeType===9?t.head:t,e.insertBefore(l,e.firstChild))}function Pc(l,e){l.crossOrigin==null&&(l.crossOrigin=e.crossOrigin),l.referrerPolicy==null&&(l.referrerPolicy=e.referrerPolicy),l.title==null&&(l.title=e.title)}function lf(l,e){l.crossOrigin==null&&(l.crossOrigin=e.crossOrigin),l.referrerPolicy==null&&(l.referrerPolicy=e.referrerPolicy),l.integrity==null&&(l.integrity=e.integrity)}var Cu=null;function ad(l,e,t){if(Cu===null){var a=new Map,n=Cu=new Map;n.set(t,a)}else n=Cu,a=n.get(t),a||(a=new Map,n.set(t,a));if(a.has(l))return a;for(a.set(l,null),t=t.getElementsByTagName(l),n=0;n<t.length;n++){var u=t[n];if(!(u[Ua]||u[Gl]||l==="link"&&u.getAttribute("rel")==="stylesheet")&&u.namespaceURI!=="http://www.w3.org/2000/svg"){var i=u.getAttribute(e)||"";i=l+i;var s=a.get(i);s?s.push(u):a.set(i,[u])}}return a}function nd(l,e,t){l=l.ownerDocument||l,l.head.insertBefore(t,e==="title"?l.querySelector("head > title"):null)}function $m(l,e,t){if(t===1||e.itemProp!=null)return!1;switch(l){case"meta":case"title":return!0;case"style":if(typeof e.precedence!="string"||typeof e.href!="string"||e.href==="")break;return!0;case"link":if(typeof e.rel!="string"||typeof e.href!="string"||e.href===""||e.onLoad||e.onError)break;switch(e.rel){case"stylesheet":return l=e.disabled,typeof e.precedence=="string"&&l==null;default:return!0}case"script":if(e.async&&typeof e.async!="function"&&typeof e.async!="symbol"&&!e.onLoad&&!e.onError&&e.src&&typeof e.src=="string")return!0}return!1}function ud(l){return!(l.type==="stylesheet"&&(l.state.loading&3)===0)}function Fm(l,e,t,a){if(t.type==="stylesheet"&&(typeof a.media!="string"||matchMedia(a.media).matches!==!1)&&(t.state.loading&4)===0){if(t.instance===null){var n=Aa(a.href),u=e.querySelector(gn(n));if(u){e=u._p,e!==null&&typeof e=="object"&&typeof e.then=="function"&&(l.count++,l=Uu.bind(l),e.then(l,l)),t.state.loading|=4,t.instance=u,ql(u);return}u=e.ownerDocument||e,a=ed(a),(n=je.get(n))&&Pc(a,n),u=u.createElement("link"),ql(u);var i=u;i._p=new Promise(function(s,o){i.onload=s,i.onerror=o}),Ll(u,"link",a),t.instance=u}l.stylesheets===null&&(l.stylesheets=new Map),l.stylesheets.set(t,e),(e=t.state.preload)&&(t.state.loading&3)===0&&(l.count++,t=Uu.bind(l),e.addEventListener("load",t),e.addEventListener("error",t))}}var ef=0;function Im(l,e){return l.stylesheets&&l.count===0&&Hu(l,l.stylesheets),0<l.count||0<l.imgCount?function(t){var a=setTimeout(function(){if(l.stylesheets&&Hu(l,l.stylesheets),l.unsuspend){var u=l.unsuspend;l.unsuspend=null,u()}},6e4+e);0<l.imgBytes&&ef===0&&(ef=62500*Cm());var n=setTimeout(function(){if(l.waitingForImages=!1,l.count===0&&(l.stylesheets&&Hu(l,l.stylesheets),l.unsuspend)){var u=l.unsuspend;l.unsuspend=null,u()}},(l.imgBytes>ef?50:800)+e);return l.unsuspend=t,function(){l.unsuspend=null,clearTimeout(a),clearTimeout(n)}}:null}function Uu(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Hu(this,this.stylesheets);else if(this.unsuspend){var l=this.unsuspend;this.unsuspend=null,l()}}}var Ru=null;function Hu(l,e){l.stylesheets=null,l.unsuspend!==null&&(l.count++,Ru=new Map,e.forEach(Pm,l),Ru=null,Uu.call(l))}function Pm(l,e){if(!(e.state.loading&4)){var t=Ru.get(l);if(t)var a=t.get(null);else{t=new Map,Ru.set(l,t);for(var n=l.querySelectorAll("link[data-precedence],style[data-precedence]"),u=0;u<n.length;u++){var i=n[u];(i.nodeName==="LINK"||i.getAttribute("media")!=="not all")&&(t.set(i.dataset.precedence,i),a=i)}a&&t.set(null,a)}n=e.instance,i=n.getAttribute("data-precedence"),u=t.get(i)||a,u===a&&t.set(null,n),t.set(i,n),this.count++,a=Uu.bind(this),n.addEventListener("load",a),n.addEventListener("error",a),u?u.parentNode.insertBefore(n,u.nextSibling):(l=l.nodeType===9?l.head:l,l.insertBefore(n,l.firstChild)),e.state.loading|=4}}var bn={$$typeof:Z,Provider:null,Consumer:null,_currentValue:V,_currentValue2:V,_threadCount:0};function ly(l,e,t,a,n,u,i,s,o){this.tag=1,this.containerInfo=l,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=$u(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=$u(0),this.hiddenUpdates=$u(null),this.identifierPrefix=a,this.onUncaughtError=n,this.onCaughtError=u,this.onRecoverableError=i,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=o,this.incompleteTransitions=new Map}function id(l,e,t,a,n,u,i,s,o,g,S,z){return l=new ly(l,e,t,i,o,g,S,z,s),e=1,u===!0&&(e|=24),u=ce(3,null,null,e),l.current=u,u.stateNode=l,e=Ri(),e.refCount++,l.pooledCache=e,e.refCount++,u.memoizedState={element:a,isDehydrated:t,cache:e},Yi(u),l}function cd(l){return l?(l=aa,l):aa}function fd(l,e,t,a,n,u){n=cd(n),a.context===null?a.context=n:a.pendingContext=n,a=it(e),a.payload={element:t},u=u===void 0?null:u,u!==null&&(a.callback=u),t=ct(l,a,e),t!==null&&(te(t,l,e),$a(t,l,e))}function sd(l,e){if(l=l.memoizedState,l!==null&&l.dehydrated!==null){var t=l.retryLane;l.retryLane=t!==0&&t<e?t:e}}function tf(l,e){sd(l,e),(l=l.alternate)&&sd(l,e)}function od(l){if(l.tag===13||l.tag===31){var e=Dt(l,67108864);e!==null&&te(e,l,67108864),tf(l,67108864)}}function rd(l){if(l.tag===13||l.tag===31){var e=de();e=Fu(e);var t=Dt(l,e);t!==null&&te(t,l,e),tf(l,e)}}var Bu=!0;function ey(l,e,t,a){var n=x.T;x.T=null;var u=U.p;try{U.p=2,af(l,e,t,a)}finally{U.p=u,x.T=n}}function ty(l,e,t,a){var n=x.T;x.T=null;var u=U.p;try{U.p=8,af(l,e,t,a)}finally{U.p=u,x.T=n}}function af(l,e,t,a){if(Bu){var n=nf(a);if(n===null)Lc(l,e,a,qu,t),hd(l,a);else if(ny(n,l,e,t,a))a.stopPropagation();else if(hd(l,a),e&4&&-1<ay.indexOf(l)){for(;n!==null;){var u=Jt(n);if(u!==null)switch(u.tag){case 3:if(u=u.stateNode,u.current.memoizedState.isDehydrated){var i=At(u.pendingLanes);if(i!==0){var s=u;for(s.pendingLanes|=2,s.entangledLanes|=2;i;){var o=1<<31-ue(i);s.entanglements[1]|=o,i&=~o}Ce(u),(sl&6)===0&&(bu=ae()+500,hn(0))}}break;case 31:case 13:s=Dt(u,2),s!==null&&te(s,u,2),xu(),tf(u,2)}if(u=nf(a),u===null&&Lc(l,e,a,qu,t),u===n)break;n=u}n!==null&&a.stopPropagation()}else Lc(l,e,a,null,t)}}function nf(l){return l=ii(l),uf(l)}var qu=null;function uf(l){if(qu=null,l=Kt(l),l!==null){var e=_(l);if(e===null)l=null;else{var t=e.tag;if(t===13){if(l=H(e),l!==null)return l;l=null}else if(t===31){if(l=G(e),l!==null)return l;l=null}else if(t===3){if(e.stateNode.current.memoizedState.isDehydrated)return e.tag===3?e.stateNode.containerInfo:null;l=null}else e!==l&&(l=null)}}return qu=l,null}function dd(l){switch(l){case"beforetoggle":case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(Zd()){case bf:return 2;case Sf:return 8;case En:case Ld:return 32;case xf:return 268435456;default:return 32}default:return 32}}var cf=!1,pt=null,bt=null,St=null,Sn=new Map,xn=new Map,xt=[],ay="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function hd(l,e){switch(l){case"focusin":case"focusout":pt=null;break;case"dragenter":case"dragleave":bt=null;break;case"mouseover":case"mouseout":St=null;break;case"pointerover":case"pointerout":Sn.delete(e.pointerId);break;case"gotpointercapture":case"lostpointercapture":xn.delete(e.pointerId)}}function jn(l,e,t,a,n,u){return l===null||l.nativeEvent!==u?(l={blockedOn:e,domEventName:t,eventSystemFlags:a,nativeEvent:u,targetContainers:[n]},e!==null&&(e=Jt(e),e!==null&&od(e)),l):(l.eventSystemFlags|=a,e=l.targetContainers,n!==null&&e.indexOf(n)===-1&&e.push(n),l)}function ny(l,e,t,a,n){switch(e){case"focusin":return pt=jn(pt,l,e,t,a,n),!0;case"dragenter":return bt=jn(bt,l,e,t,a,n),!0;case"mouseover":return St=jn(St,l,e,t,a,n),!0;case"pointerover":var u=n.pointerId;return Sn.set(u,jn(Sn.get(u)||null,l,e,t,a,n)),!0;case"gotpointercapture":return u=n.pointerId,xn.set(u,jn(xn.get(u)||null,l,e,t,a,n)),!0}return!1}function md(l){var e=Kt(l.target);if(e!==null){var t=_(e);if(t!==null){if(e=t.tag,e===13){if(e=H(t),e!==null){l.blockedOn=e,_f(l.priority,function(){rd(t)});return}}else if(e===31){if(e=G(t),e!==null){l.blockedOn=e,_f(l.priority,function(){rd(t)});return}}else if(e===3&&t.stateNode.current.memoizedState.isDehydrated){l.blockedOn=t.tag===3?t.stateNode.containerInfo:null;return}}}l.blockedOn=null}function Yu(l){if(l.blockedOn!==null)return!1;for(var e=l.targetContainers;0<e.length;){var t=nf(l.nativeEvent);if(t===null){t=l.nativeEvent;var a=new t.constructor(t.type,t);ui=a,t.target.dispatchEvent(a),ui=null}else return e=Jt(t),e!==null&&od(e),l.blockedOn=t,!1;e.shift()}return!0}function yd(l,e,t){Yu(l)&&t.delete(e)}function uy(){cf=!1,pt!==null&&Yu(pt)&&(pt=null),bt!==null&&Yu(bt)&&(bt=null),St!==null&&Yu(St)&&(St=null),Sn.forEach(yd),xn.forEach(yd)}function Gu(l,e){l.blockedOn===e&&(l.blockedOn=null,cf||(cf=!0,f.unstable_scheduleCallback(f.unstable_NormalPriority,uy)))}var Xu=null;function vd(l){Xu!==l&&(Xu=l,f.unstable_scheduleCallback(f.unstable_NormalPriority,function(){Xu===l&&(Xu=null);for(var e=0;e<l.length;e+=3){var t=l[e],a=l[e+1],n=l[e+2];if(typeof a!="function"){if(uf(a||t)===null)continue;break}var u=Jt(t);u!==null&&(l.splice(e,3),e-=3,nc(u,{pending:!0,data:n,method:t.method,action:a},a,n))}}))}function _a(l){function e(o){return Gu(o,l)}pt!==null&&Gu(pt,l),bt!==null&&Gu(bt,l),St!==null&&Gu(St,l),Sn.forEach(e),xn.forEach(e);for(var t=0;t<xt.length;t++){var a=xt[t];a.blockedOn===l&&(a.blockedOn=null)}for(;0<xt.length&&(t=xt[0],t.blockedOn===null);)md(t),t.blockedOn===null&&xt.shift();if(t=(l.ownerDocument||l).$$reactFormReplay,t!=null)for(a=0;a<t.length;a+=3){var n=t[a],u=t[a+1],i=n[$l]||null;if(typeof u=="function")i||vd(t);else if(i){var s=null;if(u&&u.hasAttribute("formAction")){if(n=u,i=u[$l]||null)s=i.formAction;else if(uf(n)!==null)continue}else s=i.action;typeof s=="function"?t[a+1]=s:(t.splice(a,3),a-=3),vd(t)}}}function gd(){function l(u){u.canIntercept&&u.info==="react-transition"&&u.intercept({handler:function(){return new Promise(function(i){return n=i})},focusReset:"manual",scroll:"manual"})}function e(){n!==null&&(n(),n=null),a||setTimeout(t,20)}function t(){if(!a&&!navigation.transition){var u=navigation.currentEntry;u&&u.url!=null&&navigation.navigate(u.url,{state:u.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var a=!1,n=null;return navigation.addEventListener("navigate",l),navigation.addEventListener("navigatesuccess",e),navigation.addEventListener("navigateerror",e),setTimeout(t,100),function(){a=!0,navigation.removeEventListener("navigate",l),navigation.removeEventListener("navigatesuccess",e),navigation.removeEventListener("navigateerror",e),n!==null&&(n(),n=null)}}}function ff(l){this._internalRoot=l}Qu.prototype.render=ff.prototype.render=function(l){var e=this._internalRoot;if(e===null)throw Error(r(409));var t=e.current,a=de();fd(t,a,l,e,null,null)},Qu.prototype.unmount=ff.prototype.unmount=function(){var l=this._internalRoot;if(l!==null){this._internalRoot=null;var e=l.containerInfo;fd(l.current,2,null,l,null,null),xu(),e[Vt]=null}};function Qu(l){this._internalRoot=l}Qu.prototype.unstable_scheduleHydration=function(l){if(l){var e=Ef();l={blockedOn:null,target:l,priority:e};for(var t=0;t<xt.length&&e!==0&&e<xt[t].priority;t++);xt.splice(t,0,l),t===0&&md(l)}};var pd=E.version;if(pd!=="19.2.5")throw Error(r(527,pd,"19.2.5"));U.findDOMNode=function(l){var e=l._reactInternals;if(e===void 0)throw typeof l.render=="function"?Error(r(188)):(l=Object.keys(l).join(","),Error(r(268,l)));return l=h(e),l=l!==null?C(l):null,l=l===null?null:l.stateNode,l};var iy={bundleType:0,version:"19.2.5",rendererPackageName:"react-dom",currentDispatcherRef:x,reconcilerVersion:"19.2.5"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Zu=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Zu.isDisabled&&Zu.supportsFiber)try{Da=Zu.inject(iy),ne=Zu}catch{}}return Tn.createRoot=function(l,e){if(!D(l))throw Error(r(299));var t=!1,a="",n=Ao,u=Eo,i=_o;return e!=null&&(e.unstable_strictMode===!0&&(t=!0),e.identifierPrefix!==void 0&&(a=e.identifierPrefix),e.onUncaughtError!==void 0&&(n=e.onUncaughtError),e.onCaughtError!==void 0&&(u=e.onCaughtError),e.onRecoverableError!==void 0&&(i=e.onRecoverableError)),e=id(l,1,!1,null,null,t,a,null,n,u,i,gd),l[Vt]=e.current,Zc(l),new ff(e)},Tn.hydrateRoot=function(l,e,t){if(!D(l))throw Error(r(299));var a=!1,n="",u=Ao,i=Eo,s=_o,o=null;return t!=null&&(t.unstable_strictMode===!0&&(a=!0),t.identifierPrefix!==void 0&&(n=t.identifierPrefix),t.onUncaughtError!==void 0&&(u=t.onUncaughtError),t.onCaughtError!==void 0&&(i=t.onCaughtError),t.onRecoverableError!==void 0&&(s=t.onRecoverableError),t.formState!==void 0&&(o=t.formState)),e=id(l,1,!0,e,t??null,a,n,o,u,i,s,gd),e.context=cd(null),t=e.current,a=de(),a=Fu(a),n=it(a),n.callback=null,ct(t,n,a),t=a,e.current.lanes=t,Ca(e,t),Ce(e),l[Vt]=e.current,Zc(l),new Qu(e)},Tn.version="19.2.5",Tn}var Od;function vy(){if(Od)return rf.exports;Od=1;function f(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(f)}catch(E){console.error(E)}}return f(),rf.exports=yy(),rf.exports}var gy=vy();const py=Cd(gy),Rd="";async function Dl(f,E){const T=await fetch(`${Rd}${f}`,{...E,credentials:"same-origin",headers:{"Content-Type":"application/json",...E==null?void 0:E.headers}});if(T.status===401)throw window.location.hash="#login",new Error("Unauthorized");if(!T.ok){const r=await T.json().catch(()=>({}));throw new Error(r.message||r.error||`HTTP ${T.status}`)}return T.json()}async function by(f){const E=await fetch(`${Rd}${f}`,{credentials:"same-origin"});if(E.status===401)throw window.location.hash="#login",new Error("Unauthorized");if(!E.ok)throw new Error(`HTTP ${E.status}`);return E.text()}const xl={login:f=>Dl("/admin/login",{method:"POST",body:JSON.stringify({token:f})}),signOutEverywhere:()=>Dl("/admin/api/sign-out-everywhere",{method:"POST"}),stats:()=>Dl("/admin/api/stats"),health:()=>Dl("/admin/api/health-indicators"),agents:()=>Dl("/admin/api/agents"),agentsSpend:()=>Dl("/admin/api/agents/spend"),sources:()=>Dl("/admin/api/sources"),grantCatalog:()=>Dl("/admin/api/grant-catalog"),clientGrant:f=>Dl(`/admin/api/grants/${encodeURIComponent(f)}`),registerClient:f=>Dl("/admin/api/register-client",{method:"POST",body:JSON.stringify(f)}),recoverClient:f=>Dl("/admin/api/recover-client",{method:"POST",body:JSON.stringify({clientId:f})}),updateClientGrant:(f,E)=>Dl("/admin/api/rescope-client",{method:"POST",body:JSON.stringify({...E,clientId:f})}),requests:(f=1,E="")=>Dl(`/admin/api/requests?page=${f}${E}`),apiKeys:()=>Dl("/admin/api/api-keys"),createApiKey(f){return Dl("/admin/api/api-keys",{method:"POST",body:JSON.stringify({name:f})})},revokeApiKey(f){return Dl("/admin/api/api-keys/revoke",{method:"POST",body:JSON.stringify({name:f})})},updateClientTtl:(f,E)=>Dl("/admin/api/update-client-ttl",{method:"POST",body:JSON.stringify({clientId:f,tokenTtl:E})}),rescopeClient:(f,E,T)=>Dl("/admin/api/rescope-client",{method:"POST",body:JSON.stringify({clientId:f,sourceId:E,federatedRead:T})}),revokeClient:f=>Dl("/admin/api/revoke-client",{method:"POST",body:JSON.stringify({clientId:f})}),calibrationProfile:f=>Dl(`/admin/api/calibration/profile${f?`?holder=${encodeURIComponent(f)}`:""}`),calibrationChart:(f,E)=>by(`/admin/api/calibration/charts/${encodeURIComponent(f)}${E?`?holder=${encodeURIComponent(E)}`:""}`),jobsWatch:()=>Dl("/admin/api/jobs/watch")};function Sy({onLogin:f}){const[E,T]=Y.useState(""),[r,D]=Y.useState(""),[_,H]=Y.useState(!1),G=async O=>{O.preventDefault(),D(""),H(!0);try{await xl.login(E),T(""),f()}catch{D("Invalid token.")}finally{H(!1)}};return c.jsx("div",{className:"login-page",children:c.jsxs("div",{className:"login-box",children:[c.jsx("div",{className:"login-logo",children:"GBrain"}),c.jsxs("div",{style:{background:"rgba(136, 170, 255, 0.08)",border:"1px solid rgba(136, 170, 255, 0.2)",borderRadius:8,padding:"14px 16px",marginBottom:20,fontSize:13,lineHeight:1.5,color:"var(--text-secondary)"},children:[c.jsx("div",{style:{fontWeight:600,color:"var(--text-primary)",marginBottom:6},children:"🔒 This is a protected dashboard"}),"Ask your AI agent for the admin login link:",c.jsx("div",{style:{background:"rgba(0,0,0,0.3)",borderRadius:6,padding:"8px 12px",marginTop:8,fontFamily:"var(--font-mono)",fontSize:12,color:"#88aaff",wordBreak:"break-all"},children:'"Give me the GBrain admin login link"'}),c.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--text-muted)"},children:"Each link is single-use. Your agent generates a fresh one each time."})]}),c.jsxs("details",{style:{marginBottom:16},children:[c.jsx("summary",{style:{cursor:"pointer",fontSize:13,color:"var(--text-muted)"},children:"Or paste bootstrap token manually"}),c.jsxs("form",{onSubmit:G,style:{marginTop:12},children:[c.jsx("div",{style:{marginBottom:12},children:c.jsx("input",{type:"password",placeholder:"Admin Token",value:E,onChange:O=>T(O.target.value)})}),c.jsx("button",{className:"btn btn-primary",style:{width:"100%"},disabled:_,children:_?"Authenticating...":"Submit"}),r&&c.jsx("div",{className:"login-error",children:r})]})]})]})})}function xy(){const[f,E]=Y.useState({connected_agents:0,requests_today:0,active_tokens:0}),[T,r]=Y.useState({expiring_soon:0,error_rate:"0%"}),[D,_]=Y.useState([]),[H,G]=Y.useState("connecting"),O=Y.useRef(null);Y.useEffect(()=>{xl.stats().then(E).catch(()=>{}),xl.health().then(r).catch(()=>{});const C=new EventSource("/admin/events",{withCredentials:!0});O.current=C,C.onopen=()=>G("connected"),C.onmessage=N=>{try{const w=JSON.parse(N.data);_(J=>[w,...J].slice(0,50))}catch{}},C.onerror=()=>{G("disconnected"),setTimeout(()=>{G("connecting"),C.close()},3e3)};const M=setInterval(()=>{xl.stats().then(E).catch(()=>{}),xl.health().then(r).catch(()=>{})},3e4);return()=>{C.close(),clearInterval(M)}},[]);const h=C=>{const M=Date.now()-new Date(C).getTime();return M<6e4?`${Math.floor(M/1e3)}s ago`:M<36e5?`${Math.floor(M/6e4)} min ago`:`${Math.floor(M/36e5)}h ago`};return c.jsxs(c.Fragment,{children:[c.jsx("h1",{className:"page-title",children:"Dashboard"}),c.jsxs("div",{style:{display:"flex",gap:24},children:[c.jsxs("div",{style:{flex:1},children:[c.jsxs("div",{className:"metrics",children:[c.jsxs("div",{className:"metric",children:[c.jsx("div",{className:"metric-value",children:f.connected_agents}),c.jsx("div",{className:"metric-label",children:"Connected Agents"})]}),c.jsxs("div",{className:"metric",children:[c.jsx("div",{className:"metric-value",children:f.requests_today}),c.jsx("div",{className:"metric-label",children:"Requests Today"})]}),c.jsxs("div",{className:"metric",children:[c.jsx("div",{className:"metric-value",children:f.active_tokens}),c.jsx("div",{className:"metric-label",children:"Active Tokens"})]})]}),c.jsxs("h2",{className:"section-title",children:["Live Activity",c.jsx("span",{style:{marginLeft:8,fontSize:10,color:H==="connected"?"var(--success)":H==="connecting"?"var(--warning)":"var(--error)"},children:H==="connected"?"● connected":H==="connecting"?"● connecting...":"● disconnected"})]}),c.jsx("div",{className:"feed",children:D.length===0?c.jsx("div",{className:"feed-empty",children:H==="connected"?"No requests yet. Agents will appear when they connect.":"Connecting..."}):c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Agent"}),c.jsx("th",{children:"Operation"}),c.jsx("th",{children:"Scopes"}),c.jsx("th",{children:"Latency"}),c.jsx("th",{children:"Status"}),c.jsx("th",{children:"Time"})]})}),c.jsx("tbody",{children:D.map((C,M)=>c.jsxs("tr",{children:[c.jsx("td",{className:"mono",children:C.agent}),c.jsx("td",{className:"mono",children:C.operation}),c.jsx("td",{children:C.scopes.split(",").map(N=>c.jsx("span",{className:`badge badge-${N.trim()}`,style:{marginRight:4},children:N.trim()},N))}),c.jsxs("td",{className:"mono",children:[C.latency_ms," ms"]}),c.jsx("td",{children:c.jsx("span",{className:`badge badge-${C.status}`,children:C.status})}),c.jsx("td",{style:{color:"var(--text-secondary)"},children:h(C.timestamp)})]},M))})]})})]}),c.jsxs("div",{style:{width:220},children:[c.jsx("h2",{className:"section-title",children:"Token Health"}),c.jsxs("div",{className:"health-panel",children:[c.jsxs("div",{className:"health-row",children:[c.jsx("span",{style:{color:"var(--warning)"},children:"Expiring Soon"}),c.jsx("span",{className:"mono",children:T.expiring_soon})]}),c.jsxs("div",{className:"health-row",children:[c.jsx("span",{style:{color:"var(--error)"},children:"Error Rate"}),c.jsx("span",{className:"mono",children:T.error_rate})]})]})]})]})]})}const Oa=f=>f.split(/[\s,]+/).filter(Boolean);function yf(f){var E,T,r;return{profile:(f==null?void 0:f.profile)??"memory-writer",applyProfile:!f,source:(f==null?void 0:f.sourceId)??"default",reads:(f==null?void 0:f.federatedRead)??["default"],scopes:(f==null?void 0:f.scopes.join(" "))??"",directPrefixes:((E=f==null?void 0:f.boundSlugPrefixes)==null?void 0:E.join(`-`))??"",tools:(f==null?void 0:f.boundTools)??[],namespace:(f==null?void 0:f.delegatedNamespace)??"job",delegatedPrefixes:((T=f==null?void 0:f.delegatedSlugPrefixes)==null?void 0:T.join(`-`))??"",concurrency:String((f==null?void 0:f.boundMaxConcurrent)??1),budget:(f==null?void 0:f.budgetUsdPerDay)??"unlimited",ttl:f?String(f.tokenTtlSeconds??0):"3600",surface:(f==null?void 0:f.surface)??"starter",operationSnapshot:((r=f==null?void 0:f.allowedOperations)==null?void 0:r.join(`-`))??"",editOperations:!1}}function Hd(f){const E=f.scopes?Oa(f.scopes).includes("agent"):["full","delegating-agent"].includes(f.profile);return{...f.applyProfile?{profile:f.profile}:{},sourceId:f.source,federatedRead:f.reads,boundSlugPrefixes:f.directPrefixes.trim()?Oa(f.directPrefixes):null,...f.scopes.trim()?{scopes:Oa(f.scopes)}:{},...f.editOperations?{allowedOperations:Oa(f.operationSnapshot)}:{},...E?{boundTools:f.tools,boundSourceId:f.source,delegatedNamespace:f.namespace,delegatedSlugPrefixes:f.namespace==="job"?null:Oa(f.delegatedPrefixes)}:{},boundMaxConcurrent:Number(f.concurrency),budgetUsdPerDay:f.budget==="unlimited"?null:f.budget,tokenTtl:f.ttl==="0"?null:Number(f.ttl),surface:f.surface==="default"?null:f.surface}}function Bd(f){return{...f.profile?{profile:f.profile}:{},scopes:f.scopes,sourceId:f.sourceId,federatedRead:f.federatedRead,boundSlugPrefixes:f.boundSlugPrefixes,allowedOperations:f.allowedOperations,boundTools:f.boundTools,boundSourceId:f.boundSourceId,boundBrainId:f.boundBrainId,delegatedNamespace:f.delegatedNamespace,delegatedSlugPrefixes:f.delegatedSlugPrefixes,boundMaxConcurrent:f.boundMaxConcurrent,budgetUsdPerDay:f.budgetUsdPerDay,tokenTtlSeconds:f.tokenTtlSeconds,surface:f.surface}}function qd({draft:f,setDraft:E,sources:T,catalog:r,existing:D=!1}){const _=(h,C)=>E({...f,[h]:C}),H=new Set(T.map(h=>h.id)),G=f.scopes?Oa(f.scopes).includes("agent"):["full","delegating-agent"].includes(f.profile),O={marginBottom:14};return c.jsxs(c.Fragment,{children:[c.jsxs("div",{style:O,children:[c.jsx("label",{htmlFor:"grant-profile",children:"Permission profile"}),c.jsx("select",{id:"grant-profile",value:f.profile,onChange:h=>E({...f,profile:h.target.value,applyProfile:!0,scopes:"",editOperations:!1,surface:["operator","full"].includes(h.target.value)?"full":"starter"}),children:r.profiles.map(h=>c.jsx("option",{children:h},h))}),c.jsx("p",{className:"grant-help",children:"Memory writer lets this agent recall, save, correct, and withdraw memory. Delegating profiles also allow selected server tools to run jobs."}),D&&c.jsxs("label",{className:"checkbox-label",children:[c.jsx("input",{type:"checkbox",checked:f.applyProfile,onChange:h=>_("applyProfile",h.target.checked)}),"Apply this profile's current operation snapshot"]})]}),c.jsxs("div",{style:O,children:[c.jsx("label",{htmlFor:"grant-source",children:"Primary / write source"}),c.jsxs("select",{id:"grant-source",value:f.source,onChange:h=>_("source",h.target.value),children:[!H.has(f.source)&&c.jsxs("option",{value:f.source,children:[f.source," · unavailable"]}),T.map(h=>c.jsxs("option",{value:h.id,children:[h.name," (",h.id,")"]},h.id))]})]}),c.jsxs("fieldset",{style:{border:0,padding:0,margin:"0 0 14px"},children:[c.jsx("legend",{children:"Readable sources"}),[...T,...f.reads.filter(h=>!H.has(h)).map(h=>({id:h,name:`${h} · unavailable`}))].map(h=>c.jsxs("label",{className:"checkbox-label",children:[c.jsx("input",{type:"checkbox",checked:f.reads.includes(h.id),onChange:C=>_("reads",C.target.checked?[...f.reads,h.id]:f.reads.filter(M=>M!==h.id))}),h.name]},h.id))]}),c.jsxs("div",{style:O,children:[c.jsx("label",{htmlFor:"grant-direct-prefixes",children:"Direct write prefixes (one per line)"}),c.jsx("textarea",{id:"grant-direct-prefixes",rows:2,value:f.directPrefixes,onChange:h=>_("directPrefixes",h.target.value),placeholder:"work-example/"}),c.jsx("p",{className:"grant-help",children:"Blank grants the whole primary source. Coding agent requires an explicit prefix."})]}),G&&c.jsxs("fieldset",{style:{border:"1px solid var(--border)",padding:12,marginBottom:14},children:[c.jsx("legend",{children:"Delegated jobs"}),c.jsx("p",{className:"grant-help",children:"Choose every tool explicitly. Jobs stay in the primary source; existing jobs retain their original limits."}),c.jsx("div",{className:"checkbox-group",style:{maxHeight:180,overflowY:"auto"},children:[...new Set([...r.delegatedTools,...f.tools])].map(h=>c.jsxs("label",{className:"checkbox-label",children:[c.jsx("input",{type:"checkbox",checked:f.tools.includes(h),onChange:C=>_("tools",C.target.checked?[...f.tools,h]:f.tools.filter(M=>M!==h))}),h,r.delegatedTools.includes(h)?"":" · unavailable"]},h))}),c.jsx("label",{htmlFor:"grant-namespace",children:"Delegated write namespace"}),c.jsxs("select",{id:"grant-namespace",value:f.namespace,onChange:h=>_("namespace",h.target.value),children:[c.jsx("option",{value:"job",children:"Each job's own wiki/agents/ directory"}),c.jsx("option",{value:"prefixes",children:"Explicit prefixes"})]}),f.namespace==="prefixes"&&c.jsx("textarea",{"aria-label":"Delegated prefixes",rows:2,value:f.delegatedPrefixes,onChange:h=>_("delegatedPrefixes",h.target.value),placeholder:"work-example/"})]}),c.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,...O},children:[c.jsxs("div",{children:[c.jsx("label",{htmlFor:"grant-concurrency",children:"Concurrent jobs"}),c.jsx("input",{id:"grant-concurrency",type:"number",min:1,step:1,value:f.concurrency,onChange:h=>_("concurrency",h.target.value)})]}),c.jsxs("div",{children:[c.jsx("label",{htmlFor:"grant-budget",children:"Daily delegated spend (USD)"}),c.jsx("input",{id:"grant-budget",value:f.budget,onChange:h=>_("budget",h.target.value),placeholder:"unlimited"}),c.jsx("p",{className:"grant-help",children:"Use unlimited for no spending cap, or an amount such as 2.50."})]})]}),c.jsxs("div",{style:O,children:[c.jsx("label",{htmlFor:"grant-ttl",children:"Future access token lifetime (seconds)"}),c.jsx("input",{id:"grant-ttl",type:"number",min:0,max:7776e3,step:1,value:f.ttl,onChange:h=>_("ttl",h.target.value)}),c.jsx("p",{className:"grant-help",children:"Renewable: 3600 (1 hour). Static bearer: 2592000 (30 days). 0 uses the server default. Existing tokens keep their expiry."})]}),c.jsxs("details",{style:O,children:[c.jsx("summary",{children:"Advanced permissions"}),c.jsx("label",{htmlFor:"grant-scopes",children:"Scope override"}),c.jsx("input",{id:"grant-scopes",value:f.scopes,onChange:h=>_("scopes",h.target.value),placeholder:"Use profile scopes"}),c.jsx("p",{className:"grant-help",children:"read, write, admin, and agent are distinct grants. Admin does not authorize delegation."}),c.jsx("label",{htmlFor:"grant-surface",children:"Visible tool catalog"}),c.jsx("select",{id:"grant-surface",value:f.surface,onChange:h=>_("surface",h.target.value),children:["verbs","starter","full","default"].map(h=>c.jsx("option",{children:h},h))}),c.jsx("p",{className:"grant-help",children:"Full shows all eligible tools; it does not grant additional authority."}),c.jsxs("label",{className:"checkbox-label",children:[c.jsx("input",{type:"checkbox",checked:f.editOperations,onChange:h=>_("editOperations",h.target.checked)}),"Replace operation authority snapshot"]}),f.editOperations&&c.jsxs(c.Fragment,{children:[c.jsx("textarea",{"aria-label":"Allowed operations",rows:5,value:f.operationSnapshot,onChange:h=>_("operationSnapshot",h.target.value)}),c.jsx("p",{className:"grant-help",children:"One operation name per line. An empty list denies every operation, including delegated tools."})]})]})]})}const jy=[["Profile","profile"],["Scopes","scopes"],["Write source","sourceId"],["Readable sources","federatedRead"],["Direct prefixes","boundSlugPrefixes"],["Visible catalog","surface"],["Operation authority","allowedOperations"],["Delegated tools","boundTools"],["Delegated source","boundSourceId"],["Delegated brain","boundBrainId"],["Delegated namespace","delegatedNamespace"],["Delegated prefixes","delegatedSlugPrefixes"],["Concurrent jobs","boundMaxConcurrent"],["Daily USD cap","budgetUsdPerDay"],["Future token TTL","tokenTtlSeconds"]];function zy(f,E){return f===null?E==="budgetUsdPerDay"?"Unlimited":E==="allowedOperations"?"Legacy scope-based catalog":"Unset":Array.isArray(f)?f.join(", ")||"(none)":String(f)}function Nd({grant:f,field:E}){const T=f[E];return E==="allowedOperations"&&Array.isArray(T)&&T.length>8?c.jsxs("details",{children:[c.jsxs("summary",{children:[T.length," operations · inspect list"]}),c.jsx("div",{style:{maxHeight:160,overflowY:"auto",marginTop:8},children:T.join(", ")})]}):c.jsx(c.Fragment,{children:zy(T,E)})}function Yd({preview:f}){return c.jsxs("div",{"aria-live":"polite",style:{margin:"16px 0"},children:[c.jsx("h3",{children:"Review permissions"}),c.jsx("div",{style:{overflowX:"auto"},children:c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Permission"}),f.before&&c.jsx("th",{children:"Current"}),c.jsx("th",{children:"Proposed"})]})}),c.jsx("tbody",{children:jy.filter(([,E])=>!f.before||JSON.stringify(f.before[E])!==JSON.stringify(f.after[E])).map(([E,T])=>c.jsxs("tr",{children:[c.jsx("th",{children:E}),f.before&&c.jsx("td",{style:{overflowWrap:"anywhere",maxWidth:200},children:c.jsx(Nd,{grant:f.before,field:T})}),c.jsx("td",{style:{overflowWrap:"anywhere",maxWidth:280},children:c.jsx(Nd,{grant:f.after,field:T})})]},T))})]})}),c.jsx("p",{className:"grant-help",children:f.tokenImplications})]})}function Ty({clientId:f,sources:E,onRescoped:T}){const[r,D]=Y.useState(),[_,H]=Y.useState(),[G,O]=Y.useState(),[h,C]=Y.useState(),[M,N]=Y.useState(""),[w,J]=Y.useState(!1),[il,jl]=Y.useState(!1),ul=async()=>{const[Z,Tl]=await Promise.all([xl.clientGrant(f),xl.grantCatalog()]);D(Z.grant),H(yf(Z.grant)),O(Tl),C(void 0),N("")};Y.useEffect(()=>{ul().catch(Z=>N(Z.message))},[f]);const k=async()=>{if(!(!_||!r)){J(!0),N(""),jl(!1);try{const Z=await xl.updateClientGrant(f,{...h?Bd(h.after):Hd(_),expectedRevision:r.revision,dryRun:!h});h?(D(Z.after),H(yf(Z.after)),C(void 0),jl(!0),T(Z.after)):C(Z)}catch(Z){C(void 0),N(Z instanceof Error?Z.message:"Grant update failed")}finally{J(!1)}}};return c.jsxs("section",{children:[c.jsx("div",{className:"section-title",children:"Permissions"}),r&&c.jsxs("p",{className:"grant-help",children:["Revision ",r.revision,". Review source access, direct tools, and delegated work independently."]}),r&&c.jsx(Ay,{clientId:f,revision:r.revision}),!!(r!=null&&r.repairReasons.length)&&c.jsxs("p",{role:"status",style:{color:"var(--warning)"},children:["Delegation needs repair: ",r.repairReasons.join(", "),". Review and explicitly grant the missing bindings below."]}),_&&G&&c.jsx(qd,{draft:_,catalog:G,sources:E,existing:!0,setDraft:Z=>{H(Z),C(void 0),jl(!1)}}),M&&c.jsxs("p",{role:"alert",style:{color:"var(--error)"},children:[M," ",c.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>void ul().catch(Z=>N(Z.message)),children:"Reload current grant"})]}),h&&c.jsx(Yd,{preview:h}),il&&c.jsx("p",{role:"status",children:"Permissions saved. Credentials are unchanged."}),c.jsx("button",{type:"button",className:"btn btn-primary",disabled:w||!_||!G,onClick:()=>void k(),children:w?"Checking…":h?"Apply reviewed changes":"Preview changes"})]})}function Ay({clientId:f,revision:E}){const[T,r]=Y.useState(),[D,_]=Y.useState(!1);return Y.useEffect(()=>{let H=!0;const G=()=>void xl.agentsSpend().then(h=>{H&&(r(h.find(C=>C.client_id===f)),_(!1))}).catch(()=>{H&&_(!0)});G();const O=setInterval(G,2e4);return()=>{H=!1,clearInterval(O)}},[f,E]),D?c.jsx("p",{role:"status",children:"Delegated spend is unavailable. Reload to check before starting more work."}):T?c.jsxs("div",{style:{border:"1px solid var(--border)",padding:12,marginBottom:14},children:[c.jsx("strong",{children:"Delegated work"}),c.jsxs("p",{children:[T.inflight_count," unfinished jobs · Daily cap: ",T.cap_usd_per_day===null?"Unlimited":`$${T.cap_usd_per_day.toFixed(2)}`]}),c.jsxs("p",{className:"grant-help",children:["Recorded today: $",(T.spent_cents_today/100).toFixed(2),". Known outstanding reservations: $",(T.pending_cents/100).toFixed(2),", including overdue calls from earlier days."]}),T.unknown_count>0&&c.jsxs("p",{role:"status",style:{color:"var(--warning)"},children:[T.unknown_count," unresolved calls have an unknown cost. The known amounts above do not bound total liability; a finite cap refuses further calls until reconciliation."]})]}):null}function Ey({serverUrl:f,clientId:E,credentialFile:T=!0}){const[r,D]=Y.useState();return Y.useEffect(()=>{xl.grantCatalog().then(D).catch(()=>{})},[]),c.jsxs("section",{children:[c.jsx("div",{className:"section-title",children:"Connect this agent"}),c.jsx("p",{children:"Follow your harness guide for the supported connection and reload steps. Grok Bot and Muse can use GBrain inside their own computer when its prerequisites pass."}),c.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:12},children:r==null?void 0:r.harnesses.map(_=>c.jsx("a",{href:_.documentation,target:"_blank",rel:"noreferrer",children:_.label},_.id))}),T?c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"grant-help",children:"Use the credential file saved at registration in the target environment. Restrict its file permissions to the owner before connecting."}),c.jsx("div",{className:"code-block",children:c.jsx("pre",{style:{whiteSpace:"pre-wrap"},children:`gbrain connect ${f}/mcp --credentials-file /absolute/private/credentials.json --harness YOUR_HARNESS --install`})})]}):c.jsx("p",{className:"grant-help",children:"Follow your harness guide for this credential type. The thin CLI used by Grok Bot and Muse requires a renewable OAuth client with client_credentials; register one above to use that connection."}),c.jsxs("p",{className:"grant-help",children:["Client ID: ",E,". Installing on the server host does not configure a different agent's computer."]})]})}function _y(f){const E=Math.floor((Date.now()-f.getTime())/1e3);return E<60?"just now":E<3600?`${Math.floor(E/60)}m ago`:E<86400?`${Math.floor(E/3600)}h ago`:`${Math.floor(E/86400)}d ago`}function Oy(){const[f,E]=Y.useState([]),[T,r]=Y.useState([]),[D,_]=Y.useState(!0),[H,G]=Y.useState(!1),[O,h]=Y.useState(null),[C,M]=Y.useState(!1),[N,w]=Y.useState(null),[J,il]=Y.useState(null);Y.useEffect(()=>{jl(),xl.sources().then(r).catch(()=>{})},[]);const jl=()=>{xl.agents().then(E).catch(()=>{})};return c.jsxs(c.Fragment,{children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:24},children:[c.jsx("h1",{className:"page-title",style:{marginBottom:0},children:"Agents"}),c.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[c.jsxs("label",{style:{fontSize:13,color:"var(--text-secondary)",display:"flex",alignItems:"center",gap:6,cursor:"pointer"},children:[c.jsx("input",{type:"checkbox",checked:D,onChange:ul=>_(ul.target.checked)})," Hide revoked"]}),c.jsx("button",{className:"btn btn-secondary",onClick:()=>M(!0),children:"+ API Key"}),c.jsx("button",{className:"btn btn-primary",onClick:()=>G(!0),children:"+ OAuth Client"})]})]}),(()=>{const ul=f.filter(k=>!D||k.status!=="revoked");return f.length===0?c.jsx("div",{style:{textAlign:"center",padding:48,color:"var(--text-muted)"},children:"No agents registered. Register your first agent to get started."}):ul.length===0?c.jsx("div",{style:{textAlign:"center",padding:48,color:"var(--text-muted)"},children:'All agents are revoked. Uncheck "Hide revoked" to view them.'}):c.jsxs(c.Fragment,{children:[c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Name"}),c.jsx("th",{children:"Type"}),c.jsx("th",{children:"Scopes"}),c.jsx("th",{children:"Sources"}),c.jsx("th",{children:"Status"}),c.jsx("th",{children:"Requests"}),c.jsx("th",{children:"Last Used"})]})}),c.jsx("tbody",{children:ul.map(k=>c.jsxs("tr",{onClick:()=>il(k),style:{cursor:"pointer"},children:[c.jsx("td",{style:{fontWeight:500},children:k.name||k.client_name}),c.jsx("td",{children:c.jsx("span",{className:`badge ${k.auth_type==="oauth"?"badge-read":"badge-write"}`,style:{fontSize:11},children:k.auth_type==="oauth"?"OAuth":"API Key"})}),c.jsx("td",{children:(k.scope||"").split(" ").filter(Boolean).map(Z=>c.jsx("span",{className:`badge badge-${Z}`,style:{marginRight:4},children:Z},Z))}),c.jsx("td",{style:{color:"var(--text-secondary)",fontSize:12},children:k.auth_type==="oauth"?`${k.source_id||"none"} · ${(k.federated_read||[]).length} readable`:"Unscoped"}),c.jsx("td",{children:c.jsx("span",{className:`badge ${k.status==="active"?"badge-success":"badge-danger"}`,children:k.status})}),c.jsxs("td",{children:[c.jsx("span",{style:{fontWeight:500},children:k.requests_today||0}),c.jsxs("span",{style:{color:"var(--text-muted)",fontSize:12},children:[" / ",k.total_requests||0]})]}),c.jsx("td",{style:{color:"var(--text-secondary)"},children:k.last_used_at?_y(new Date(k.last_used_at)):"Never"})]},k.id))})]}),c.jsxs("div",{style:{color:"var(--text-muted)",fontSize:13,marginTop:12},children:[f.filter(k=>k.status==="active").length," active / ",f.length," total"]})]})})(),H&&c.jsx(My,{sources:T,onClose:()=>G(!1),onRegistered:ul=>{G(!1),h(ul),jl()}}),O&&c.jsx(Cy,{credentials:O,onClose:()=>h(null)}),J&&c.jsx(Uy,{agent:J,sources:T,onClose:()=>il(null),onRevoked:jl,onRecovered:ul=>{il(null),h(ul)},onRescoped:({sourceId:ul,federatedRead:k})=>{il(Z=>Z&&{...Z,source_id:ul,federated_read:k}),jl()}},J.id),C&&c.jsx(Ny,{onClose:()=>M(!1),onCreated:ul=>{M(!1),w(ul),jl()}}),N&&c.jsx(Dy,{token:N,onClose:()=>w(null)})]})}function Ny({onClose:f,onCreated:E}){const[T,r]=Y.useState(""),[D,_]=Y.useState(!1),[H,G]=Y.useState(""),O=async h=>{if(h.preventDefault(),!T.trim()){G("Name required");return}_(!0);try{const C=await xl.createApiKey(T.trim());E({name:C.name,token:C.token})}catch(C){G(C instanceof Error?C.message:"Failed")}finally{_(!1)}};return c.jsx("div",{className:"modal-overlay",onClick:f,children:c.jsxs("form",{className:"modal",onClick:h=>h.stopPropagation(),onSubmit:O,children:[c.jsx("div",{className:"modal-title",children:"Create API Key"}),c.jsx("p",{style:{color:"var(--text-secondary)",fontSize:13,marginBottom:16},children:"API keys use simple bearer token auth. They grant full read+write+admin access. For scoped access, use OAuth clients instead."}),c.jsxs("div",{style:{marginBottom:16},children:[c.jsx("label",{children:"Key Name"}),c.jsx("input",{placeholder:"e.g. claude-code-local",value:T,onChange:h=>r(h.target.value),autoFocus:!0})]}),H&&c.jsx("div",{style:{color:"var(--error)",fontSize:13,marginBottom:12},children:H}),c.jsxs("div",{style:{display:"flex",gap:12,justifyContent:"flex-end"},children:[c.jsx("button",{type:"button",className:"btn btn-secondary",onClick:f,children:"Cancel"}),c.jsx("button",{type:"submit",className:"btn btn-primary",disabled:D,children:D?"Creating...":"Create Key"})]})]})})}function Dy({token:f,onClose:E}){const T=r=>navigator.clipboard.writeText(r);return c.jsx("div",{className:"modal-overlay",children:c.jsxs("div",{className:"modal",style:{maxWidth:560},children:[c.jsxs("div",{style:{textAlign:"center",marginBottom:16},children:[c.jsx("div",{style:{fontSize:36,color:"var(--success)",marginBottom:8},children:"✓"}),c.jsx("div",{style:{fontSize:20,fontWeight:600},children:"API Key Created"})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Name"}),c.jsx("div",{className:"code-block",children:c.jsx("span",{children:f.name})})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Bearer Token"}),c.jsxs("div",{className:"code-block",children:[c.jsx("span",{children:f.token}),c.jsx("button",{className:"copy-btn",onClick:()=>T(f.token),children:"Copy"})]})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Usage"}),c.jsxs("div",{className:"code-block",children:[c.jsx("pre",{style:{whiteSpace:"pre-wrap",margin:0,fontSize:12},children:`Authorization: Bearer ${f.token}`}),c.jsx("button",{className:"copy-btn",onClick:()=>T(`Authorization: Bearer ${f.token}`),children:"Copy"})]})]}),c.jsx("div",{className:"warning-bar",children:"Save this token now. It will not be shown again."}),c.jsx("div",{style:{display:"flex",gap:12,justifyContent:"flex-end",marginTop:20},children:c.jsx("button",{className:"btn btn-primary",onClick:E,children:"Done"})})]})})}function My({sources:f,onClose:E,onRegistered:T}){const[r,D]=Y.useState(""),[_,H]=Y.useState(()=>yf()),[G,O]=Y.useState(),[h,C]=Y.useState(),[M,N]=Y.useState(!1),[w,J]=Y.useState(""),[il,jl]=Y.useState();Y.useEffect(()=>{xl.grantCatalog().then(O).catch(Z=>J(Z.message))},[]);const ul=async Z=>{if(Z.preventDefault(),!r.trim()){J("Name required");return}N(!0),J("");try{const Tl=await xl.registerClient({...h?Bd(h.after):Hd(_),name:r.trim(),dryRun:!h});h?T({clientId:Tl.clientId,clientSecret:Tl.clientSecret,name:r.trim(),credentials:Tl.credentials}):C(Tl)}catch(Tl){if(C(void 0),J(Tl instanceof Error?Tl.message:"Registration failed"),h)try{const wl=(await xl.agents()).filter(Hl=>Hl.auth_type==="oauth"&&Hl.status==="active"&&(Hl.name||Hl.client_name)===r.trim());wl.length===1&&jl({clientId:wl[0].id||wl[0].client_id,name:r.trim()})}catch{}}finally{N(!1)}},k=async()=>{if(il){N(!0),J("");try{T(await xl.recoverClient(il.clientId))}catch(Z){J(Z instanceof Error?Z.message:"Credential recovery failed")}finally{N(!1)}}};return c.jsx("div",{className:"modal-overlay",onClick:E,children:c.jsxs("form",{className:"modal",style:{maxWidth:700,width:"90vw",minWidth:0,maxHeight:"90vh",overflowY:"auto"},onClick:Z=>Z.stopPropagation(),onSubmit:ul,children:[c.jsx("div",{className:"modal-title",children:"Register agent"}),c.jsxs("fieldset",{disabled:M||!!il,style:{border:0,padding:0,margin:0},children:[c.jsxs("div",{style:{marginBottom:16},children:[c.jsx("label",{htmlFor:"agent-name",children:"Agent name"}),c.jsx("input",{id:"agent-name",placeholder:"muse-personal-example",value:r,onChange:Z=>{D(Z.target.value),C(void 0)},autoFocus:!0})]}),G&&c.jsx(qd,{draft:_,setDraft:Z=>{H(Z),C(void 0)},catalog:G,sources:f})]}),h&&c.jsx(Yd,{preview:h}),w&&c.jsx("p",{role:"alert",style:{color:"var(--error)"},children:w}),il&&c.jsxs("div",{role:"status",children:[c.jsxs("p",{children:["A registered client named ",il.name," exists. Recover its saved credential delivery before retrying registration. This preserves its permissions and secret."]}),c.jsx("button",{type:"button",className:"btn btn-secondary",disabled:M,onClick:()=>void k(),children:"Recover credentials"})]}),c.jsxs("div",{style:{display:"flex",gap:12,justifyContent:"flex-end"},children:[c.jsx("button",{type:"button",className:"btn btn-secondary",onClick:E,children:"Cancel"}),c.jsx("button",{type:"submit",className:"btn btn-primary",disabled:M||!G||!!il,children:M?"Checking…":h?"Register with reviewed permissions":"Preview permissions"})]})]})})}function Cy({credentials:f,onClose:E}){const T=D=>navigator.clipboard.writeText(D),r=()=>{const D=f.credentials??{version:1,mcp_url:`${window.location.origin}/mcp`,issuer_url:window.location.origin,client_id:f.clientId,client_secret:f.clientSecret},_=new Blob([JSON.stringify(D,null,2)],{type:"application/json"}),H=URL.createObjectURL(_),G=document.createElement("a");G.href=H,G.download=`${f.name}-credentials.json`,G.click(),URL.revokeObjectURL(H)};return c.jsx("div",{className:"modal-overlay",children:c.jsxs("div",{className:"modal",style:{maxWidth:560},children:[c.jsxs("div",{style:{textAlign:"center",marginBottom:16},children:[c.jsx("div",{style:{fontSize:36,color:"var(--success)",marginBottom:8},children:"✓"}),c.jsx("div",{style:{fontSize:20,fontWeight:600},children:"Agent Registered"})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Client ID"}),c.jsxs("div",{className:"code-block",children:[c.jsx("span",{children:f.clientId}),c.jsx("button",{className:"copy-btn",onClick:()=>T(f.clientId),children:"Copy"})]})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Client Secret"}),c.jsxs("div",{className:"code-block",children:[c.jsx("span",{children:f.clientSecret}),c.jsx("button",{className:"copy-btn",onClick:()=>T(f.clientSecret),children:"Copy"})]})]}),c.jsx("div",{className:"warning-bar",children:"Download the credential file now. Keep it private, set its permissions to 0600 on the target computer, and use it with gbrain connect. If delivery is lost, use Recover credentials in this client's Agents entry."}),c.jsxs("div",{style:{display:"flex",gap:12,justifyContent:"flex-end",marginTop:20},children:[c.jsx("button",{className:"btn btn-secondary",onClick:r,children:"Download as JSON"}),c.jsx("button",{className:"btn btn-primary",onClick:E,children:"Done"})]})]})})}function Uy({agent:f,sources:E,onClose:T,onRevoked:r,onRescoped:D,onRecovered:_}){const H=window.location.origin,G=f.id||f.client_id||"",O=f.auth_type==="oauth",[h,C]=Y.useState(!1),[M,N]=Y.useState(""),w=async()=>{C(!0),N("");try{_(await xl.recoverClient(G))}catch(J){N(J instanceof Error?J.message:"Credential recovery failed")}finally{C(!1)}};return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"drawer-overlay",onClick:T}),c.jsxs("div",{className:"drawer",children:[c.jsx("button",{className:"drawer-close",onClick:T,children:"✕"}),c.jsx("div",{style:{fontSize:18,fontWeight:600,marginBottom:4},children:f.name||f.client_name}),c.jsx("span",{className:`badge ${f.status==="active"?"badge-success":"badge-danger"}`,children:f.status}),c.jsx("div",{className:"section-title",children:"Details"}),c.jsxs("div",{style:{display:"grid",gridTemplateColumns:"100px 1fr",gap:"6px 12px",fontSize:13},children:[c.jsx("span",{style:{color:"var(--text-secondary)"},children:"Client ID"}),c.jsxs("span",{className:"mono",children:[(f.id||f.id||f.client_id||"").substring(0,24),"..."]}),c.jsx("span",{style:{color:"var(--text-secondary)"},children:"Scopes"}),c.jsx("span",{children:(f.scope||"").split(" ").filter(Boolean).map(J=>c.jsx("span",{className:`badge badge-${J}`,style:{marginRight:4},children:J},J))}),c.jsx("span",{style:{color:"var(--text-secondary)"},children:"Registered"}),c.jsx("span",{children:new Date(f.created_at).toLocaleDateString()}),c.jsx("span",{style:{color:"var(--text-secondary)"},children:"Token TTL"}),c.jsx("span",{children:f.token_ttl?f.token_ttl>=86400?`${Math.floor(f.token_ttl/86400)}d`:f.token_ttl>=3600?`${Math.floor(f.token_ttl/3600)}h`:`${f.token_ttl}s`:"1h (default)"})]}),O&&c.jsx(Ty,{clientId:G,sources:E,onRescoped:D}),c.jsx(Ey,{serverUrl:H,clientId:G,credentialFile:O&&f.grant_types.includes("client_credentials")}),O&&f.status==="active"&&f.grant_types.includes("client_credentials")&&c.jsxs("div",{children:[c.jsx("p",{className:"grant-help",children:"If registration finished but its download was lost, recover the saved credential delivery. Existing permissions and credentials stay unchanged."}),c.jsx("button",{type:"button",className:"btn btn-secondary",disabled:h,onClick:()=>void w(),children:h?"Recovering…":"Recover credentials"}),M&&c.jsx("p",{role:"alert",style:{color:"var(--error)"},children:M})]}),c.jsxs("div",{style:{marginTop:32},children:[f.status==="active"&&c.jsx("button",{className:"btn btn-danger",onClick:async()=>{if(confirm(`Revoke ${f.name||f.client_name}? All active tokens will be invalidated.`))try{f.auth_type==="oauth"?await xl.revokeClient(f.id||f.client_id||""):await xl.revokeApiKey(f.name||""),r(),T()}catch(J){alert("Revoke failed: "+(J instanceof Error?J.message:"unknown error"))}},children:"Revoke Agent"}),f.status==="revoked"&&c.jsx("span",{style:{color:"var(--text-muted)",fontSize:13},children:"This agent has been revoked."})]})]})]})}function Ry(){const[f,E]=Y.useState({rows:[],total:0,page:1,pages:1}),[T,r]=Y.useState(1),[D,_]=Y.useState("all"),[H,G]=Y.useState(null);Y.useEffect(()=>{O(T)},[T,D]);const O=N=>{const w=D!=="all"?`&agent=${encodeURIComponent(D)}`:"";xl.requests(N,w).then(E).catch(()=>{})},h=N=>{const w=Date.now()-new Date(N).getTime();return w<6e4?`${Math.floor(w/1e3)}s ago`:w<36e5?`${Math.floor(w/6e4)} min ago`:w<864e5?`${Math.floor(w/36e5)}h ago`:new Date(N).toLocaleDateString()},C=N=>{if(!N)return null;const{query:w,slug:J,partial:il,limit:jl,...ul}=N,k=[];return w&&k.push(`"${w}"`),J&&k.push(J),il&&k.push(`~${il}`),jl&&k.push(`limit=${jl}`),Object.keys(ul).length>0&&k.push(`+${Object.keys(ul).length} params`),k.join(" ")},M=new Map;return f.rows.forEach(N=>{N.token_name&&M.set(N.token_name,N.agent_name||N.token_name)}),c.jsxs(c.Fragment,{children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:24},children:[c.jsx("h1",{className:"page-title",style:{marginBottom:0},children:"Request Log"}),c.jsxs("select",{value:D,onChange:N=>{_(N.target.value),r(1)},style:{background:"var(--bg-secondary)",color:"var(--text-primary)",border:"1px solid var(--border)",borderRadius:6,padding:"4px 8px",fontSize:13},children:[c.jsx("option",{value:"all",children:"All agents"}),[...M.entries()].map(([N,w])=>c.jsx("option",{value:N,children:w},N))]})]}),f.rows.length===0?c.jsx("div",{style:{textAlign:"center",padding:48,color:"var(--text-muted)"},children:"No requests yet."}):c.jsxs(c.Fragment,{children:[c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Time"}),c.jsx("th",{children:"Agent"}),c.jsx("th",{children:"Operation"}),c.jsx("th",{children:"Params"}),c.jsx("th",{children:"Latency"}),c.jsx("th",{children:"Status"})]})}),c.jsx("tbody",{children:f.rows.map(N=>c.jsxs(Ud.Fragment,{children:[c.jsxs("tr",{onClick:()=>G(H===N.id?null:N.id),style:{cursor:"pointer"},children:[c.jsx("td",{style:{color:"var(--text-secondary)",whiteSpace:"nowrap"},children:h(N.created_at)}),c.jsx("td",{children:c.jsx("a",{style:{color:"var(--text-link, #88aaff)",cursor:"pointer",textDecoration:"none",fontWeight:500},onClick:w=>{w.stopPropagation(),_(N.token_name),r(1)},children:N.agent_name||N.token_name})}),c.jsx("td",{className:"mono",children:N.operation}),c.jsx("td",{style:{color:"var(--text-secondary)",fontSize:12,maxWidth:200,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:C(N.params)}),c.jsxs("td",{className:"mono",children:[N.latency_ms,"ms"]}),c.jsx("td",{children:c.jsx("span",{className:`badge badge-${N.status}`,children:N.status})})]}),H===N.id&&c.jsx("tr",{children:c.jsx("td",{colSpan:6,style:{background:"var(--bg-secondary, #0f0f1a)",padding:16},children:c.jsxs("div",{style:{display:"grid",gridTemplateColumns:"100px 1fr",gap:"6px 12px",fontSize:13},children:[c.jsx("span",{style:{color:"var(--text-muted)"},children:"Time"}),c.jsx("span",{children:new Date(N.created_at).toLocaleString()}),c.jsx("span",{style:{color:"var(--text-muted)"},children:"Agent"}),c.jsx("span",{className:"mono",children:N.token_name}),c.jsx("span",{style:{color:"var(--text-muted)"},children:"Operation"}),c.jsx("span",{className:"mono",children:N.operation}),c.jsx("span",{style:{color:"var(--text-muted)"},children:"Latency"}),c.jsxs("span",{children:[N.latency_ms,"ms"]}),N.params&&c.jsxs(c.Fragment,{children:[c.jsx("span",{style:{color:"var(--text-muted)"},children:"Params"}),c.jsx("pre",{className:"mono",style:{margin:0,whiteSpace:"pre-wrap",fontSize:12},children:JSON.stringify(N.params,null,2)})]}),N.error_message&&c.jsxs(c.Fragment,{children:[c.jsx("span",{style:{color:"var(--error, #ff6b6b)"},children:"Error"}),c.jsx("span",{style:{color:"var(--error, #ff6b6b)"},children:N.error_message})]})]})})})]},N.id))})]}),c.jsxs("div",{className:"pagination",children:[c.jsxs("span",{children:["Page ",f.page," of ",f.pages," (",f.total," total)"]}),c.jsxs("div",{style:{display:"flex",gap:8},children:[c.jsx("button",{disabled:f.page<=1,onClick:()=>r(N=>N-1),children:"Previous"}),c.jsx("button",{disabled:f.page>=f.pages,onClick:()=>r(N=>N+1),children:"Next"})]})]})]})]})}function Hy({markup:f}){return c.jsx("div",{style:{width:"100%",overflow:"auto"},dangerouslySetInnerHTML:{__html:f}})}function Lu({type:f,ariaLabel:E}){const[T,r]=Y.useState(""),[D,_]=Y.useState("");return Y.useEffect(()=>{let H=!1;return xl.calibrationChart(f).then(G=>{H||r(G)}).catch(G=>{H||_(G.message??"fetch failed")}),()=>{H=!0}},[f]),D?c.jsxs("div",{style:{padding:16,color:"var(--error)"},role:"alert",children:[E,": ",D]}):T?c.jsx(Hy,{markup:T}):c.jsxs("div",{style:{padding:16,color:"var(--text-muted)"},children:[E," loading..."]})}function By(){const[f,E]=Y.useState(null),[T,r]=Y.useState(!0),[D,_]=Y.useState("");if(Y.useEffect(()=>{xl.calibrationProfile().then(O=>{E(O),r(!1)}).catch(O=>{_(O.message??"fetch failed"),r(!1)})},[]),T)return c.jsx("div",{style:{padding:24,color:"var(--text-secondary)"},children:"Loading calibration profile…"});if(D)return c.jsxs("div",{style:{padding:24,color:"var(--error)"},role:"alert",children:["Could not load calibration profile: ",D]});if(!f)return c.jsxs("div",{style:{padding:24,maxWidth:700},children:[c.jsx("h1",{style:{marginBottom:16},children:"Calibration"}),c.jsx("p",{style:{color:"var(--text-secondary)"},children:"No calibration profile yet. Builds after 5+ resolved takes."}),c.jsx("pre",{style:{background:"var(--bg-secondary)",padding:12,borderRadius:4,color:"var(--text-primary)",marginTop:12,fontFamily:"var(--font-mono)"},children:"gbrain dream --phase calibration_profile"})]});const H=new Date(f.generated_at),G=Math.floor((Date.now()-H.getTime())/(1e3*60*60*24));return c.jsxs("div",{style:{padding:32,maxWidth:720},children:[c.jsx("h1",{style:{marginBottom:8},children:"Calibration"}),c.jsxs("div",{style:{color:"var(--text-muted)",fontSize:13,marginBottom:24},children:["Holder: ",f.holder," · ","Updated ",G===0?"today":`${G}d ago`,f.published&&" · published",f.grade_completion<.9&&` · ~${Math.round(f.grade_completion*100)}% graded`,!f.voice_gate_passed&&" · voice gate fell back to template"]}),c.jsx("section",{style:{marginBottom:32},children:c.jsx(Lu,{type:"brier-trend",ariaLabel:"Brier trend"})}),c.jsxs("section",{style:{marginBottom:32},children:[c.jsx("h2",{style:{fontSize:14,color:"var(--text-secondary)",marginBottom:12,fontWeight:400},children:"Pattern statements"}),c.jsx(Lu,{type:"pattern-statements",ariaLabel:"Pattern statements"})]}),c.jsx("section",{style:{marginBottom:32},children:c.jsx(Lu,{type:"domain-bars",ariaLabel:"Per-domain accuracy"})}),c.jsx("section",{style:{marginBottom:32},children:c.jsx(Lu,{type:"abandoned-threads",ariaLabel:"Abandoned threads"})}),f.active_bias_tags.length>0&&c.jsxs("section",{style:{marginBottom:32,color:"var(--text-muted)",fontSize:13},children:["Active bias tags: ",f.active_bias_tags.join(", ")]})]})}function qy(f){return f===0?"var(--accent-success, #2ea043)":f>=100?"var(--accent-danger, #f85149)":"var(--accent-warn, #d29922)"}function Dd(f){return`$${(f/100).toFixed(2)}`}function Yy(){const[f,E]=Y.useState(null),[T,r]=Y.useState(null);if(Y.useEffect(()=>{let _=!0,H=null;const G=async()=>{try{const O=await xl.jobsWatch();_&&(E(O),r(null))}catch(O){_&&r(O instanceof Error?O.message:String(O))}_&&(H=setTimeout(G,1e3))};return G(),()=>{_=!1,H&&clearTimeout(H)}},[]),T)return c.jsxs("div",{style:{padding:24,color:"var(--accent-danger, #f85149)"},children:[c.jsx("h2",{children:"Jobs Watch — error"}),c.jsx("pre",{style:{whiteSpace:"pre-wrap"},children:T})]});if(!f)return c.jsx("div",{style:{padding:24,color:"var(--text-muted, #777)"},children:"Loading jobs watch…"});const D=new Date(f.ts_ms).toLocaleTimeString();return c.jsxs("div",{style:{padding:24,fontFamily:'var(--font-mono, "JetBrains Mono", monospace)'},children:[c.jsxs("h1",{style:{fontSize:18,marginBottom:4},children:["Jobs Watch",c.jsxs("span",{style:{marginLeft:12,color:"var(--text-muted, #777)",fontSize:12,fontWeight:"normal"},children:["updated ",D]})]}),c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Queue"}),c.jsxs("div",{children:["waiting=",c.jsx("b",{children:f.queue_health.waiting})," ","active=",c.jsx("b",{children:f.queue_health.active})," ","stalled=",c.jsx("b",{style:{color:f.queue_health.stalled>0?"var(--accent-warn, #d29922)":void 0},children:f.queue_health.stalled})]})]}),f.by_type.length>0&&c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"By type (24h)"}),c.jsxs("table",{style:{borderCollapse:"collapse"},children:[c.jsx("thead",{children:c.jsxs("tr",{style:{color:"var(--text-muted, #777)",fontSize:12},children:[c.jsx("th",{style:{textAlign:"left",padding:"4px 12px 4px 0"},children:"name"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"total"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"done"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"fail"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"dead"})]})}),c.jsx("tbody",{children:f.by_type.slice(0,6).map(_=>c.jsxs("tr",{children:[c.jsx("td",{style:{padding:"4px 12px 4px 0"},children:_.name}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.total}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.completed}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.failed}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.dead})]},_.name))})]})]}),c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Lease pressure (1h)"}),c.jsxs("div",{style:{color:qy(f.lease_pressure_1h)},children:[f.lease_pressure_1h," bounce",f.lease_pressure_1h===1?"":"s"]})]}),f.top_errors.length>0&&c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Top errors (24h)"}),c.jsx("table",{style:{borderCollapse:"collapse"},children:c.jsx("tbody",{children:f.top_errors.slice(0,5).map(_=>c.jsxs("tr",{children:[c.jsxs("td",{style:{textAlign:"right",padding:"4px 12px 4px 0",color:"var(--text-muted, #777)"},children:[_.count,"×"]}),c.jsx("td",{style:{padding:"4px 12px 4px 0"},children:_.cluster})]},_.cluster))})})]}),f.budget_owners.length>0&&c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Budget owners"}),c.jsxs("table",{style:{borderCollapse:"collapse"},children:[c.jsx("thead",{children:c.jsxs("tr",{style:{color:"var(--text-muted, #777)",fontSize:12},children:[c.jsx("th",{style:{textAlign:"left",padding:"4px 12px 4px 0"},children:"owner"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"spent"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"remaining"})]})}),c.jsx("tbody",{children:f.budget_owners.slice(0,5).map(_=>c.jsxs("tr",{children:[c.jsx("td",{style:{padding:"4px 12px 4px 0"},children:_.owner_id}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:Dd(_.total_spent_cents)}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:Dd(_.remaining_cents)})]},_.owner_id))})]})]})]})}function Md(){const f=window.location.hash.replace("#","")||"dashboard";return["login","dashboard","agents","log","calibration","jobs"].includes(f)?f:"dashboard"}function Gy(){const[f,E]=Y.useState(Md);Y.useEffect(()=>{const D=()=>E(Md());return window.addEventListener("hashchange",D),()=>window.removeEventListener("hashchange",D)},[]);const T=D=>{window.location.hash=D,E(D)};if(f==="login")return c.jsx(Sy,{onLogin:()=>T("dashboard")});const r=async()=>{if(confirm("Sign out every active admin session, including other browsers and tabs? Each one will need to re-authenticate via a fresh magic link.")){try{await xl.signOutEverywhere()}catch{}T("login")}};return c.jsxs("div",{className:"app",children:[c.jsxs("nav",{className:"sidebar",children:[c.jsx("div",{className:"sidebar-logo",children:"GBrain"}),c.jsxs("div",{className:"sidebar-nav",children:[c.jsx("a",{className:`nav-item ${f==="dashboard"?"active":""}`,onClick:()=>T("dashboard"),children:"Dashboard"}),c.jsx("a",{className:`nav-item ${f==="agents"?"active":""}`,onClick:()=>T("agents"),children:"Agents"}),c.jsx("a",{className:`nav-item ${f==="log"?"active":""}`,onClick:()=>T("log"),children:"Request Log"}),c.jsx("a",{className:`nav-item ${f==="calibration"?"active":""}`,onClick:()=>T("calibration"),children:"Calibration"}),c.jsx("a",{className:`nav-item ${f==="jobs"?"active":""}`,onClick:()=>T("jobs"),children:"Jobs Watch"})]}),c.jsx("div",{style:{marginTop:"auto",padding:"16px 12px",borderTop:"1px solid var(--border)"},children:c.jsx("button",{onClick:r,style:{background:"transparent",border:"1px solid var(--border)",color:"var(--text-secondary)",padding:"6px 10px",borderRadius:6,fontSize:12,cursor:"pointer",width:"100%"},title:"Revoke every active admin session — every browser, every tab",children:"Sign out everywhere"})})]}),c.jsxs("main",{className:"main",children:[f==="dashboard"&&c.jsx(xy,{}),f==="agents"&&c.jsx(Oy,{}),f==="log"&&c.jsx(Ry,{}),f==="calibration"&&c.jsx(By,{}),f==="jobs"&&c.jsx(Yy,{})]})]})}py.createRoot(document.getElementById("root")).render(c.jsx(Ud.StrictMode,{children:c.jsx(Gy,{})}));diff --git a/admin/dist/assets/index-CLnyXRh0.css b/admin/dist/assets/index-DECOlanw.csssimilarity index 95%rename from admin/dist/assets/index-CLnyXRh0.cssrename to admin/dist/assets/index-DECOlanw.cssindex a270151c0d..768c5ba784 100644--- a/admin/dist/assets/index-CLnyXRh0.css+++ b/admin/dist/assets/index-DECOlanw.css@@ -1 +1 @@-:root{--bg-primary: #0a0a0f;--bg-secondary: #14141f;--bg-tertiary: #1e1e2e;--text-primary: #e0e0e0;--text-secondary: #888;--text-muted: #777;--accent: #3b82f6;--success: #22c55e;--warning: #f59e0b;--error: #ef4444;--font-mono: "JetBrains Mono", monospace;--font-sans: "Inter", system-ui, sans-serif}*{margin:0;padding:0;box-sizing:border-box}body{font-family:var(--font-sans);background:var(--bg-primary);color:var(--text-primary);font-size:14px;line-height:1.5}.app{display:flex;min-height:100vh}.sidebar{width:200px;background:var(--bg-secondary);border-right:1px solid #1e1e2e;padding:16px 0;flex-shrink:0;display:flex;flex-direction:column}.sidebar-logo{font-size:18px;font-weight:600;padding:0 16px 24px;color:var(--text-primary)}.sidebar-nav{display:flex;flex-direction:column;gap:2px}.nav-item{display:flex;align-items:center;gap:8px;padding:8px 16px;color:var(--text-secondary);text-decoration:none;font-size:13px;cursor:pointer;border-left:3px solid transparent;transition:all .15s}.nav-item:hover{background:var(--bg-tertiary);color:var(--text-primary)}.nav-item.active{border-left-color:var(--accent);background:var(--bg-tertiary);color:var(--text-primary)}.main{flex:1;padding:24px 32px;overflow-y:auto}.page-title{font-size:24px;font-weight:600;margin-bottom:24px}.metrics{display:flex;gap:16px;margin-bottom:24px}.metric{background:var(--bg-secondary);padding:16px 20px;border-radius:6px;min-width:140px}.metric-value{font-family:var(--font-mono);font-size:28px;font-weight:500}.metric-label{font-size:12px;color:var(--text-secondary);margin-top:4px}table{width:100%;border-collapse:collapse}th{text-align:left;font-size:11px;text-transform:uppercase;color:var(--text-muted);padding:8px 12px;font-weight:500;letter-spacing:.5px}td{padding:10px 12px;font-size:13px;border-top:1px solid #1a1a2a}tr:hover td{background:var(--bg-tertiary)}.badge{display:inline-block;padding:2px 8px;border-radius:10px;font-size:11px;font-weight:500}.badge-read{background:#3b82f626;color:var(--accent)}.badge-write{background:#f59e0b26;color:var(--warning)}.badge-admin{background:#ef444426;color:var(--error)}.badge-success{background:#22c55e26;color:var(--success)}.badge-error{background:#ef444426;color:var(--error)}.status-dot{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:6px}.status-active{background:var(--success)}.status-warning{background:var(--warning)}.status-inactive{background:var(--text-muted)}.btn{padding:8px 16px;border-radius:6px;font-size:13px;font-weight:500;cursor:pointer;border:none;transition:all .15s}.btn-primary{background:var(--accent);color:#fff}.btn-primary:hover{background:#2563eb}.btn-secondary{background:transparent;color:var(--text-secondary);border:1px solid #333}.btn-secondary:hover{border-color:var(--text-secondary);color:var(--text-primary)}.btn-danger{background:transparent;color:var(--error);border:1px solid var(--error)}.btn-danger:hover{background:#ef44441a}input,select,textarea{background:var(--bg-primary);border:1px solid #333;color:var(--text-primary);padding:8px 12px;border-radius:6px;font-size:13px;font-family:var(--font-sans);width:100%}input:focus,select:focus,textarea:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 2px #3b82f633}input::placeholder{color:var(--text-muted)}label{display:block;font-size:13px;font-weight:500;margin-bottom:6px}.grant-help{color:var(--text-secondary);font-size:12px;line-height:1.5;margin:6px 0 12px}.modal-overlay{position:fixed;top:0;right:0;bottom:0;left:0;background:#000000b3;display:flex;align-items:center;justify-content:center;z-index:100}.modal{background:var(--bg-secondary);border-radius:8px;padding:24px;min-width:420px;max-width:520px}.modal-title{font-size:18px;font-weight:600;margin-bottom:20px}.drawer-overlay{position:fixed;top:0;right:0;bottom:0;left:0;background:#00000080;z-index:90}.drawer{position:fixed;right:0;top:0;bottom:0;width:420px;background:var(--bg-secondary);border-left:1px solid var(--accent);padding:24px;z-index:91;overflow-y:auto}.drawer-close{position:absolute;top:16px;right:16px;background:none;border:none;color:var(--text-muted);font-size:18px;cursor:pointer}.section-title{font-size:11px;text-transform:uppercase;color:var(--text-muted);letter-spacing:.5px;margin:20px 0 12px;font-weight:500}.health-panel{background:var(--bg-secondary);border-radius:6px;padding:16px}.health-row{display:flex;justify-content:space-between;padding:6px 0;font-size:13px}.code-block{background:var(--bg-primary);border-radius:6px;padding:12px;font-family:var(--font-mono);font-size:12px;overflow-x:auto;position:relative}.code-block .copy-btn{position:absolute;top:8px;right:8px;background:var(--accent);color:#fff;border:none;padding:4px 10px;border-radius:4px;font-size:11px;cursor:pointer}.feed{max-height:400px;overflow-y:auto}.feed-empty{color:var(--text-muted);text-align:center;padding:32px;font-size:13px}.sparkline{display:inline-block;vertical-align:middle}.filter-bar{display:flex;gap:12px;margin-bottom:16px;align-items:center}.filter-bar select{width:auto;min-width:140px}.pagination{display:flex;justify-content:space-between;align-items:center;padding:12px 0;font-size:13px;color:var(--text-secondary)}.pagination button{background:var(--bg-secondary);border:1px solid #333;color:var(--text-primary);padding:6px 12px;border-radius:4px;cursor:pointer;font-size:12px}.pagination button:disabled{opacity:.3;cursor:default}.warning-bar{background:#f59e0b26;border:1px solid var(--warning);color:var(--warning);padding:10px 16px;border-radius:6px;font-size:13px;margin:12px 0}.checkbox-group{display:flex;gap:16px;flex-wrap:wrap}.checkbox-label{display:flex;align-items:center;gap:6px;font-size:13px;cursor:pointer}.checkbox-label input[type=checkbox]{width:auto;flex-shrink:0}.tabs{display:flex;gap:0;margin-bottom:12px}.tab{padding:6px 12px;font-size:13px;color:var(--text-secondary);cursor:pointer;border-bottom:2px solid transparent}.tab.active{color:var(--accent);border-bottom-color:var(--accent)}.login-page{display:flex;align-items:center;justify-content:center;min-height:100vh;background:var(--bg-primary)}.login-box{text-align:left;width:340px}.login-logo{font-size:32px;font-weight:600;margin-bottom:32px}.login-hint{color:var(--text-muted);font-size:12px;margin-top:12px}.login-error{color:var(--error);font-size:13px;margin-top:8px}.mono{font-family:var(--font-mono);font-size:12px}@media(max-width:768px){.sidebar{display:none}.main{padding:16px}.metrics{flex-wrap:wrap}.drawer{width:100%}}+:root{--bg-primary: #0a0a0f;--bg-secondary: #14141f;--bg-tertiary: #1e1e2e;--text-primary: #e0e0e0;--text-secondary: #888;--text-muted: #777;--accent: #3b82f6;--success: #22c55e;--warning: #f59e0b;--error: #ef4444;--font-mono: "JetBrains Mono", monospace;--font-sans: "Inter", system-ui, sans-serif}*{margin:0;padding:0;box-sizing:border-box}body{font-family:var(--font-sans);background:var(--bg-primary);color:var(--text-primary);font-size:14px;line-height:1.5}.app{display:flex;min-height:100vh}.sidebar{width:200px;background:var(--bg-secondary);border-right:1px solid #1e1e2e;padding:16px 0;flex-shrink:0;display:flex;flex-direction:column}.sidebar-logo{font-size:18px;font-weight:600;padding:0 16px 24px;color:var(--text-primary)}.sidebar-nav{display:flex;flex-direction:column;gap:2px}.nav-item{display:flex;align-items:center;gap:8px;padding:8px 16px;color:var(--text-secondary);text-decoration:none;font-size:13px;cursor:pointer;border-left:3px solid transparent;transition:all .15s}.nav-item:hover{background:var(--bg-tertiary);color:var(--text-primary)}.nav-item.active{border-left-color:var(--accent);background:var(--bg-tertiary);color:var(--text-primary)}.main{flex:1;padding:24px 32px;overflow-y:auto}.page-title{font-size:24px;font-weight:600;margin-bottom:24px}.metrics{display:flex;gap:16px;margin-bottom:24px}.metric{background:var(--bg-secondary);padding:16px 20px;border-radius:6px;min-width:140px}.metric-value{font-family:var(--font-mono);font-size:28px;font-weight:500}.metric-label{font-size:12px;color:var(--text-secondary);margin-top:4px}table{width:100%;border-collapse:collapse}th{text-align:left;font-size:11px;text-transform:uppercase;color:var(--text-muted);padding:8px 12px;font-weight:500;letter-spacing:.5px}td{padding:10px 12px;font-size:13px;border-top:1px solid #1a1a2a}tr:hover td{background:var(--bg-tertiary)}.badge{display:inline-block;padding:2px 8px;border-radius:10px;font-size:11px;font-weight:500}.badge-read{background:#3b82f626;color:var(--accent)}.badge-write{background:#f59e0b26;color:var(--warning)}.badge-admin{background:#ef444426;color:var(--error)}.badge-success{background:#22c55e26;color:var(--success)}.badge-error{background:#ef444426;color:var(--error)}.status-dot{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:6px}.status-active{background:var(--success)}.status-warning{background:var(--warning)}.status-inactive{background:var(--text-muted)}.btn{padding:8px 16px;border-radius:6px;font-size:13px;font-weight:500;cursor:pointer;border:none;transition:all .15s}.btn-primary{background:var(--accent);color:#fff}.btn-primary:hover{background:#2563eb}.btn-secondary{background:transparent;color:var(--text-secondary);border:1px solid #333}.btn-secondary:hover{border-color:var(--text-secondary);color:var(--text-primary)}.btn-danger{background:transparent;color:var(--error);border:1px solid var(--error)}.btn-danger:hover{background:#ef44441a}input,select,textarea{background:var(--bg-primary);border:1px solid #333;color:var(--text-primary);padding:8px 12px;border-radius:6px;font-size:13px;font-family:var(--font-sans);width:100%}input:focus,select:focus,textarea:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 2px #3b82f633}input::placeholder{color:var(--text-muted)}label{display:block;font-size:13px;font-weight:500;margin-bottom:6px}.grant-help{color:var(--text-secondary);font-size:12px;line-height:1.5;margin:6px 0 12px}.modal-overlay{position:fixed;top:0;right:0;bottom:0;left:0;background:#000000b3;display:flex;align-items:center;justify-content:center;z-index:100}.modal{background:var(--bg-secondary);border-radius:8px;padding:24px;min-width:420px;max-width:520px}.modal-title{font-size:18px;font-weight:600;margin-bottom:20px}.drawer-overlay{position:fixed;top:0;right:0;bottom:0;left:0;background:#00000080;z-index:90}.drawer{position:fixed;right:0;top:0;bottom:0;width:420px;background:var(--bg-secondary);border-left:1px solid var(--accent);padding:24px;z-index:91;overflow-y:auto}.drawer-close{position:absolute;top:16px;right:16px;background:none;border:none;color:var(--text-muted);font-size:18px;cursor:pointer}.section-title{font-size:11px;text-transform:uppercase;color:var(--text-muted);letter-spacing:.5px;margin:20px 0 12px;font-weight:500}.health-panel{background:var(--bg-secondary);border-radius:6px;padding:16px}.health-row{display:flex;justify-content:space-between;padding:6px 0;font-size:13px}.code-block{background:var(--bg-primary);border-radius:6px;padding:12px;font-family:var(--font-mono);font-size:12px;overflow-x:auto;position:relative}.code-block .copy-btn{position:absolute;top:8px;right:8px;background:var(--accent);color:#fff;border:none;padding:4px 10px;border-radius:4px;font-size:11px;cursor:pointer}.feed{max-height:400px;overflow-y:auto}.feed-empty{color:var(--text-muted);text-align:center;padding:32px;font-size:13px}.sparkline{display:inline-block;vertical-align:middle}.filter-bar{display:flex;gap:12px;margin-bottom:16px;align-items:center}.filter-bar select{width:auto;min-width:140px}.pagination{display:flex;justify-content:space-between;align-items:center;padding:12px 0;font-size:13px;color:var(--text-secondary)}.pagination button{background:var(--bg-secondary);border:1px solid #333;color:var(--text-primary);padding:6px 12px;border-radius:4px;cursor:pointer;font-size:12px}.pagination button:disabled{opacity:.3;cursor:default}.warning-bar{background:#f59e0b26;border:1px solid var(--warning);color:var(--warning);padding:10px 16px;border-radius:6px;font-size:13px;margin:12px 0}.checkbox-group{display:flex;gap:16px;flex-wrap:wrap}.checkbox-label{display:flex;align-items:center;gap:6px;font-size:13px;cursor:pointer}.checkbox-label input[type=checkbox]{width:auto;flex-shrink:0}.tabs{display:flex;gap:0;margin-bottom:12px}.tab{padding:6px 12px;font-size:13px;color:var(--text-secondary);cursor:pointer;border-bottom:2px solid transparent}.tab.active{color:var(--accent);border-bottom-color:var(--accent)}.login-page{display:flex;align-items:center;justify-content:center;min-height:100vh;background:var(--bg-primary)}.login-box{text-align:left;width:340px}.login-logo{font-size:32px;font-weight:600;margin-bottom:32px}.login-hint{color:var(--text-muted);font-size:12px;margin-top:12px}.login-error{color:var(--error);font-size:13px;margin-top:8px}.mono{font-family:var(--font-mono);font-size:12px}@media(max-width:768px){.sidebar{display:none}.main{padding:16px}.metrics{flex-wrap:wrap}.drawer{width:100%}}.oauth-consent-details{display:grid;grid-template-columns:160px minmax(0,1fr);gap:16px}.oauth-consent-details dt{color:var(--text-secondary)}.oauth-consent-details dd{margin:0;overflow-wrap:anywhere}@media(max-width:640px){.oauth-consent-details{grid-template-columns:1fr;gap:8px}.oauth-consent-details dd{margin-bottom:12px}}diff --git a/admin/dist/assets/index-DfSDTH-v.js b/admin/dist/assets/index-DfSDTH-v.jsnew file mode 100644index 0000000000..4212a2d0c9--- /dev/null+++ b/admin/dist/assets/index-DfSDTH-v.js@@ -0,0 +1,52 @@+(function(){const A=document.createElement("link").relList;if(A&&A.supports&&A.supports("modulepreload"))return;for(const D of document.querySelectorAll('link[rel="modulepreload"]'))r(D);new MutationObserver(D=>{for(const _ of D)if(_.type==="childList")for(const H of _.addedNodes)H.tagName==="LINK"&&H.rel==="modulepreload"&&r(H)}).observe(document,{childList:!0,subtree:!0});function T(D){const _={};return D.integrity&&(_.integrity=D.integrity),D.referrerPolicy&&(_.referrerPolicy=D.referrerPolicy),D.crossOrigin==="use-credentials"?_.credentials="include":D.crossOrigin==="anonymous"?_.credentials="omit":_.credentials="same-origin",_}function r(D){if(D.ep)return;D.ep=!0;const _=T(D);fetch(D.href,_)}})();function Bd(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var ss={exports:{}},Tn={};/**+ * @license React+ * react-jsx-runtime.production.js+ *+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */var xd;function dy(){if(xd)return Tn;xd=1;var s=Symbol.for("react.transitional.element"),A=Symbol.for("react.fragment");function T(r,D,_){var H=null;if(_!==void 0&&(H=""+_),D.key!==void 0&&(H=""+D.key),"key"in D){_={};for(var Y in D)Y!=="key"&&(_[Y]=D[Y])}else _=D;return D=_.ref,{$$typeof:s,type:r,key:H,ref:D!==void 0?D:null,props:_}}return Tn.Fragment=A,Tn.jsx=T,Tn.jsxs=T,Tn}var jd;function hy(){return jd||(jd=1,ss.exports=dy()),ss.exports}var c=hy(),fs={exports:{}},w={};/**+ * @license React+ * react.production.js+ *+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */var Td;function my(){if(Td)return w;Td=1;var s=Symbol.for("react.transitional.element"),A=Symbol.for("react.portal"),T=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),D=Symbol.for("react.profiler"),_=Symbol.for("react.consumer"),H=Symbol.for("react.context"),Y=Symbol.for("react.forward_ref"),O=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),M=Symbol.for("react.lazy"),C=Symbol.for("react.activity"),N=Symbol.iterator;function J(m){return m===null||typeof m!="object"?null:(m=N&&m[N]||m["@@iterator"],typeof m=="function"?m:null)}var K={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},ie=Object.assign,je={};function ue(m,E,R){this.props=m,this.context=E,this.refs=je,this.updater=R||K}ue.prototype.isReactComponent={},ue.prototype.setState=function(m,E){if(typeof m!="object"&&typeof m!="function"&&m!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,m,E,"setState")},ue.prototype.forceUpdate=function(m){this.updater.enqueueForceUpdate(this,m,"forceUpdate")};function k(){}k.prototype=ue.prototype;function Z(m,E,R){this.props=m,this.context=E,this.refs=je,this.updater=R||K}var Ae=Z.prototype=new k;Ae.constructor=Z,ie(Ae,ue.prototype),Ae.isPureReactComponent=!0;var Je=Array.isArray;function He(){}var ae={H:null,A:null,T:null,S:null},ke=Object.prototype.hasOwnProperty;function _l(m,E,R){var G=R.ref;return{$$typeof:s,type:m,key:E,ref:G!==void 0?G:null,props:R}}function Lt(m,E){return _l(m.type,E,m.props)}function Ol(m){return typeof m=="object"&&m!==null&&m.$$typeof===s}function We(m){var E={"=":"=0",":":"=2"};return"$"+m.replace(/[=:]/g,function(R){return E[R]})}var Tt=/\/+/g;function Ul(m,E){return typeof m=="object"&&m!==null&&m.key!=null?We(""+m.key):E.toString(36)}function Tl(m){switch(m.status){case"fulfilled":return m.value;case"rejected":throw m.reason;default:switch(typeof m.status=="string"?m.then(He,He):(m.status="pending",m.then(function(E){m.status==="pending"&&(m.status="fulfilled",m.value=E)},function(E){m.status==="pending"&&(m.status="rejected",m.reason=E)})),m.status){case"fulfilled":return m.value;case"rejected":throw m.reason}}throw m}function x(m,E,R,G,W){var I=typeof m;(I==="undefined"||I==="boolean")&&(m=null);var oe=!1;if(m===null)oe=!0;else switch(I){case"bigint":case"string":case"number":oe=!0;break;case"object":switch(m.$$typeof){case s:case A:oe=!0;break;case M:return oe=m._init,x(oe(m._payload),E,R,G,W)}}if(oe)return W=W(m),oe=G===""?"."+Ul(m,0):G,Je(W)?(R="",oe!=null&&(R=oe.replace(Tt,"$&/")+"/"),x(W,E,R,"",function(Na){return Na})):W!=null&&(Ol(W)&&(W=Lt(W,R+(W.key==null||m&&m.key===W.key?"":(""+W.key).replace(Tt,"$&/")+"/")+oe)),E.push(W)),1;oe=0;var we=G===""?".":G+":";if(Je(m))for(var Oe=0;Oe<m.length;Oe++)G=m[Oe],I=we+Ul(G,Oe),oe+=x(G,E,R,I,W);else if(Oe=J(m),typeof Oe=="function")for(m=Oe.call(m),Oe=0;!(G=m.next()).done;)G=G.value,I=we+Ul(G,Oe++),oe+=x(G,E,R,I,W);else if(I==="object"){if(typeof m.then=="function")return x(Tl(m),E,R,G,W);throw E=String(m),Error("Objects are not valid as a React child (found: "+(E==="[object Object]"?"object with keys {"+Object.keys(m).join(", ")+"}":E)+"). If you meant to render a collection of children, use an array instead.")}return oe}function U(m,E,R){if(m==null)return m;var G=[],W=0;return x(m,G,"","",function(I){return E.call(R,I,W++)}),G}function V(m){if(m._status===-1){var E=m._result;E=E(),E.then(function(R){(m._status===0||m._status===-1)&&(m._status=1,m._result=R)},function(R){(m._status===0||m._status===-1)&&(m._status=2,m._result=R)}),m._status===-1&&(m._status=0,m._result=E)}if(m._status===1)return m._result.default;throw m._result}var he=typeof reportError=="function"?reportError:function(m){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var E=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof m=="object"&&m!==null&&typeof m.message=="string"?String(m.message):String(m),error:m});if(!window.dispatchEvent(E))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",m);return}console.error(m)},ge={map:U,forEach:function(m,E,R){U(m,function(){E.apply(this,arguments)},R)},count:function(m){var E=0;return U(m,function(){E++}),E},toArray:function(m){return U(m,function(E){return E})||[]},only:function(m){if(!Ol(m))throw Error("React.Children.only expected to receive a single React element child.");return m}};return w.Activity=C,w.Children=ge,w.Component=ue,w.Fragment=T,w.Profiler=D,w.PureComponent=Z,w.StrictMode=r,w.Suspense=O,w.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=ae,w.__COMPILER_RUNTIME={__proto__:null,c:function(m){return ae.H.useMemoCache(m)}},w.cache=function(m){return function(){return m.apply(null,arguments)}},w.cacheSignal=function(){return null},w.cloneElement=function(m,E,R){if(m==null)throw Error("The argument must be a React element, but you passed "+m+".");var G=ie({},m.props),W=m.key;if(E!=null)for(I in E.key!==void 0&&(W=""+E.key),E)!ke.call(E,I)||I==="key"||I==="__self"||I==="__source"||I==="ref"&&E.ref===void 0||(G[I]=E[I]);var I=arguments.length-2;if(I===1)G.children=R;else if(1<I){for(var oe=Array(I),we=0;we<I;we++)oe[we]=arguments[we+2];G.children=oe}return _l(m.type,W,G)},w.createContext=function(m){return m={$$typeof:H,_currentValue:m,_currentValue2:m,_threadCount:0,Provider:null,Consumer:null},m.Provider=m,m.Consumer={$$typeof:_,_context:m},m},w.createElement=function(m,E,R){var G,W={},I=null;if(E!=null)for(G in E.key!==void 0&&(I=""+E.key),E)ke.call(E,G)&&G!=="key"&&G!=="__self"&&G!=="__source"&&(W[G]=E[G]);var oe=arguments.length-2;if(oe===1)W.children=R;else if(1<oe){for(var we=Array(oe),Oe=0;Oe<oe;Oe++)we[Oe]=arguments[Oe+2];W.children=we}if(m&&m.defaultProps)for(G in oe=m.defaultProps,oe)W[G]===void 0&&(W[G]=oe[G]);return _l(m,I,W)},w.createRef=function(){return{current:null}},w.forwardRef=function(m){return{$$typeof:Y,render:m}},w.isValidElement=Ol,w.lazy=function(m){return{$$typeof:M,_payload:{_status:-1,_result:m},_init:V}},w.memo=function(m,E){return{$$typeof:d,type:m,compare:E===void 0?null:E}},w.startTransition=function(m){var E=ae.T,R={};ae.T=R;try{var G=m(),W=ae.S;W!==null&&W(R,G),typeof G=="object"&&G!==null&&typeof G.then=="function"&&G.then(He,he)}catch(I){he(I)}finally{E!==null&&R.types!==null&&(E.types=R.types),ae.T=E}},w.unstable_useCacheRefresh=function(){return ae.H.useCacheRefresh()},w.use=function(m){return ae.H.use(m)},w.useActionState=function(m,E,R){return ae.H.useActionState(m,E,R)},w.useCallback=function(m,E){return ae.H.useCallback(m,E)},w.useContext=function(m){return ae.H.useContext(m)},w.useDebugValue=function(){},w.useDeferredValue=function(m,E){return ae.H.useDeferredValue(m,E)},w.useEffect=function(m,E){return ae.H.useEffect(m,E)},w.useEffectEvent=function(m){return ae.H.useEffectEvent(m)},w.useId=function(){return ae.H.useId()},w.useImperativeHandle=function(m,E,R){return ae.H.useImperativeHandle(m,E,R)},w.useInsertionEffect=function(m,E){return ae.H.useInsertionEffect(m,E)},w.useLayoutEffect=function(m,E){return ae.H.useLayoutEffect(m,E)},w.useMemo=function(m,E){return ae.H.useMemo(m,E)},w.useOptimistic=function(m,E){return ae.H.useOptimistic(m,E)},w.useReducer=function(m,E,R){return ae.H.useReducer(m,E,R)},w.useRef=function(m){return ae.H.useRef(m)},w.useState=function(m){return ae.H.useState(m)},w.useSyncExternalStore=function(m,E,R){return ae.H.useSyncExternalStore(m,E,R)},w.useTransition=function(){return ae.H.useTransition()},w.version="19.2.5",w}var zd;function vs(){return zd||(zd=1,fs.exports=my()),fs.exports}var B=vs();const qd=Bd(B);var os={exports:{}},zn={},rs={exports:{}},ds={};/**+ * @license React+ * scheduler.production.js+ *+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */var Ad;function yy(){return Ad||(Ad=1,(function(s){function A(x,U){var V=x.length;x.push(U);e:for(;0<V;){var he=V-1>>>1,ge=x[he];if(0<D(ge,U))x[he]=U,x[V]=ge,V=he;else break e}}function T(x){return x.length===0?null:x[0]}function r(x){if(x.length===0)return null;var U=x[0],V=x.pop();if(V!==U){x[0]=V;e:for(var he=0,ge=x.length,m=ge>>>1;he<m;){var E=2*(he+1)-1,R=x[E],G=E+1,W=x[G];if(0>D(R,V))G<ge&&0>D(W,R)?(x[he]=W,x[G]=V,he=G):(x[he]=R,x[E]=V,he=E);else if(G<ge&&0>D(W,V))x[he]=W,x[G]=V,he=G;else break e}}return U}function D(x,U){var V=x.sortIndex-U.sortIndex;return V!==0?V:x.id-U.id}if(s.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var _=performance;s.unstable_now=function(){return _.now()}}else{var H=Date,Y=H.now();s.unstable_now=function(){return H.now()-Y}}var O=[],d=[],M=1,C=null,N=3,J=!1,K=!1,ie=!1,je=!1,ue=typeof setTimeout=="function"?setTimeout:null,k=typeof clearTimeout=="function"?clearTimeout:null,Z=typeof setImmediate<"u"?setImmediate:null;function Ae(x){for(var U=T(d);U!==null;){if(U.callback===null)r(d);else if(U.startTime<=x)r(d),U.sortIndex=U.expirationTime,A(O,U);else break;U=T(d)}}function Je(x){if(ie=!1,Ae(x),!K)if(T(O)!==null)K=!0,He||(He=!0,We());else{var U=T(d);U!==null&&Tl(Je,U.startTime-x)}}var He=!1,ae=-1,ke=5,_l=-1;function Lt(){return je?!0:!(s.unstable_now()-_l<ke)}function Ol(){if(je=!1,He){var x=s.unstable_now();_l=x;var U=!0;try{e:{K=!1,ie&&(ie=!1,k(ae),ae=-1),J=!0;var V=N;try{l:{for(Ae(x),C=T(O);C!==null&&!(C.expirationTime>x&&Lt());){var he=C.callback;if(typeof he=="function"){C.callback=null,N=C.priorityLevel;var ge=he(C.expirationTime<=x);if(x=s.unstable_now(),typeof ge=="function"){C.callback=ge,Ae(x),U=!0;break l}C===T(O)&&r(O),Ae(x)}else r(O);C=T(O)}if(C!==null)U=!0;else{var m=T(d);m!==null&&Tl(Je,m.startTime-x),U=!1}}break e}finally{C=null,N=V,J=!1}U=void 0}}finally{U?We():He=!1}}}var We;if(typeof Z=="function")We=function(){Z(Ol)};else if(typeof MessageChannel<"u"){var Tt=new MessageChannel,Ul=Tt.port2;Tt.port1.onmessage=Ol,We=function(){Ul.postMessage(null)}}else We=function(){ue(Ol,0)};function Tl(x,U){ae=ue(function(){x(s.unstable_now())},U)}s.unstable_IdlePriority=5,s.unstable_ImmediatePriority=1,s.unstable_LowPriority=4,s.unstable_NormalPriority=3,s.unstable_Profiling=null,s.unstable_UserBlockingPriority=2,s.unstable_cancelCallback=function(x){x.callback=null},s.unstable_forceFrameRate=function(x){0>x||125<x?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):ke=0<x?Math.floor(1e3/x):5},s.unstable_getCurrentPriorityLevel=function(){return N},s.unstable_next=function(x){switch(N){case 1:case 2:case 3:var U=3;break;default:U=N}var V=N;N=U;try{return x()}finally{N=V}},s.unstable_requestPaint=function(){je=!0},s.unstable_runWithPriority=function(x,U){switch(x){case 1:case 2:case 3:case 4:case 5:break;default:x=3}var V=N;N=x;try{return U()}finally{N=V}},s.unstable_scheduleCallback=function(x,U,V){var he=s.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0<V?he+V:he):V=he,x){case 1:var ge=-1;break;case 2:ge=250;break;case 5:ge=1073741823;break;case 4:ge=1e4;break;default:ge=5e3}return ge=V+ge,x={id:M++,callback:U,priorityLevel:x,startTime:V,expirationTime:ge,sortIndex:-1},V>he?(x.sortIndex=V,A(d,x),T(O)===null&&x===T(d)&&(ie?(k(ae),ae=-1):ie=!0,Tl(Je,V-he))):(x.sortIndex=ge,A(O,x),K||J||(K=!0,He||(He=!0,We()))),x},s.unstable_shouldYield=Lt,s.unstable_wrapCallback=function(x){var U=N;return function(){var V=N;N=U;try{return x.apply(this,arguments)}finally{N=V}}}})(ds)),ds}var Ed;function vy(){return Ed||(Ed=1,rs.exports=yy()),rs.exports}var hs={exports:{}},Ve={};/**+ * @license React+ * react-dom.production.js+ *+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */var _d;function gy(){if(_d)return Ve;_d=1;var s=vs();function A(O){var d="https://react.dev/errors/"+O;if(1<arguments.length){d+="?args[]="+encodeURIComponent(arguments[1]);for(var M=2;M<arguments.length;M++)d+="&args[]="+encodeURIComponent(arguments[M])}return"Minified React error #"+O+"; visit "+d+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function T(){}var r={d:{f:T,r:function(){throw Error(A(522))},D:T,C:T,L:T,m:T,X:T,S:T,M:T},p:0,findDOMNode:null},D=Symbol.for("react.portal");function _(O,d,M){var C=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:D,key:C==null?null:""+C,children:O,containerInfo:d,implementation:M}}var H=s.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function Y(O,d){if(O==="font")return"";if(typeof d=="string")return d==="use-credentials"?d:""}return Ve.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,Ve.createPortal=function(O,d){var M=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!d||d.nodeType!==1&&d.nodeType!==9&&d.nodeType!==11)throw Error(A(299));return _(O,d,null,M)},Ve.flushSync=function(O){var d=H.T,M=r.p;try{if(H.T=null,r.p=2,O)return O()}finally{H.T=d,r.p=M,r.d.f()}},Ve.preconnect=function(O,d){typeof O=="string"&&(d?(d=d.crossOrigin,d=typeof d=="string"?d==="use-credentials"?d:"":void 0):d=null,r.d.C(O,d))},Ve.prefetchDNS=function(O){typeof O=="string"&&r.d.D(O)},Ve.preinit=function(O,d){if(typeof O=="string"&&d&&typeof d.as=="string"){var M=d.as,C=Y(M,d.crossOrigin),N=typeof d.integrity=="string"?d.integrity:void 0,J=typeof d.fetchPriority=="string"?d.fetchPriority:void 0;M==="style"?r.d.S(O,typeof d.precedence=="string"?d.precedence:void 0,{crossOrigin:C,integrity:N,fetchPriority:J}):M==="script"&&r.d.X(O,{crossOrigin:C,integrity:N,fetchPriority:J,nonce:typeof d.nonce=="string"?d.nonce:void 0})}},Ve.preinitModule=function(O,d){if(typeof O=="string")if(typeof d=="object"&&d!==null){if(d.as==null||d.as==="script"){var M=Y(d.as,d.crossOrigin);r.d.M(O,{crossOrigin:M,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0})}}else d==null&&r.d.M(O)},Ve.preload=function(O,d){if(typeof O=="string"&&typeof d=="object"&&d!==null&&typeof d.as=="string"){var M=d.as,C=Y(M,d.crossOrigin);r.d.L(O,M,{crossOrigin:C,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0,type:typeof d.type=="string"?d.type:void 0,fetchPriority:typeof d.fetchPriority=="string"?d.fetchPriority:void 0,referrerPolicy:typeof d.referrerPolicy=="string"?d.referrerPolicy:void 0,imageSrcSet:typeof d.imageSrcSet=="string"?d.imageSrcSet:void 0,imageSizes:typeof d.imageSizes=="string"?d.imageSizes:void 0,media:typeof d.media=="string"?d.media:void 0})}},Ve.preloadModule=function(O,d){if(typeof O=="string")if(d){var M=Y(d.as,d.crossOrigin);r.d.m(O,{as:typeof d.as=="string"&&d.as!=="script"?d.as:void 0,crossOrigin:M,integrity:typeof d.integrity=="string"?d.integrity:void 0})}else r.d.m(O)},Ve.requestFormReset=function(O){r.d.r(O)},Ve.unstable_batchedUpdates=function(O,d){return O(d)},Ve.useFormState=function(O,d,M){return H.H.useFormState(O,d,M)},Ve.useFormStatus=function(){return H.H.useHostTransitionStatus()},Ve.version="19.2.5",Ve}var Od;function py(){if(Od)return hs.exports;Od=1;function s(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(A){console.error(A)}}return s(),hs.exports=gy(),hs.exports}/**+ * @license React+ * react-dom-client.production.js+ *+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */var Nd;function by(){if(Nd)return zn;Nd=1;var s=vy(),A=vs(),T=py();function r(e){var l="https://react.dev/errors/"+e;if(1<arguments.length){l+="?args[]="+encodeURIComponent(arguments[1]);for(var t=2;t<arguments.length;t++)l+="&args[]="+encodeURIComponent(arguments[t])}return"Minified React error #"+e+"; visit "+l+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function D(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function _(e){var l=e,t=e;if(e.alternate)for(;l.return;)l=l.return;else{e=l;do l=e,(l.flags&4098)!==0&&(t=l.return),e=l.return;while(e)}return l.tag===3?t:null}function H(e){if(e.tag===13){var l=e.memoizedState;if(l===null&&(e=e.alternate,e!==null&&(l=e.memoizedState)),l!==null)return l.dehydrated}return null}function Y(e){if(e.tag===31){var l=e.memoizedState;if(l===null&&(e=e.alternate,e!==null&&(l=e.memoizedState)),l!==null)return l.dehydrated}return null}function O(e){if(_(e)!==e)throw Error(r(188))}function d(e){var l=e.alternate;if(!l){if(l=_(e),l===null)throw Error(r(188));return l!==e?null:e}for(var t=e,a=l;;){var n=t.return;if(n===null)break;var u=n.alternate;if(u===null){if(a=n.return,a!==null){t=a;continue}break}if(n.child===u.child){for(u=n.child;u;){if(u===t)return O(n),e;if(u===a)return O(n),l;u=u.sibling}throw Error(r(188))}if(t.return!==a.return)t=n,a=u;else{for(var i=!1,f=n.child;f;){if(f===t){i=!0,t=n,a=u;break}if(f===a){i=!0,a=n,t=u;break}f=f.sibling}if(!i){for(f=u.child;f;){if(f===t){i=!0,t=u,a=n;break}if(f===a){i=!0,a=u,t=n;break}f=f.sibling}if(!i)throw Error(r(189))}}if(t.alternate!==a)throw Error(r(190))}if(t.tag!==3)throw Error(r(188));return t.stateNode.current===t?e:l}function M(e){var l=e.tag;if(l===5||l===26||l===27||l===6)return e;for(e=e.child;e!==null;){if(l=M(e),l!==null)return l;e=e.sibling}return null}var C=Object.assign,N=Symbol.for("react.element"),J=Symbol.for("react.transitional.element"),K=Symbol.for("react.portal"),ie=Symbol.for("react.fragment"),je=Symbol.for("react.strict_mode"),ue=Symbol.for("react.profiler"),k=Symbol.for("react.consumer"),Z=Symbol.for("react.context"),Ae=Symbol.for("react.forward_ref"),Je=Symbol.for("react.suspense"),He=Symbol.for("react.suspense_list"),ae=Symbol.for("react.memo"),ke=Symbol.for("react.lazy"),_l=Symbol.for("react.activity"),Lt=Symbol.for("react.memo_cache_sentinel"),Ol=Symbol.iterator;function We(e){return e===null||typeof e!="object"?null:(e=Ol&&e[Ol]||e["@@iterator"],typeof e=="function"?e:null)}var Tt=Symbol.for("react.client.reference");function Ul(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===Tt?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case ie:return"Fragment";case ue:return"Profiler";case je:return"StrictMode";case Je:return"Suspense";case He:return"SuspenseList";case _l:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case K:return"Portal";case Z:return e.displayName||"Context";case k:return(e._context.displayName||"Context")+".Consumer";case Ae:var l=e.render;return e=e.displayName,e||(e=l.displayName||l.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case ae:return l=e.displayName||null,l!==null?l:Ul(e.type)||"Memo";case ke:l=e._payload,e=e._init;try{return Ul(e(l))}catch{}}return null}var Tl=Array.isArray,x=A.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,U=T.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,V={pending:!1,data:null,method:null,action:null},he=[],ge=-1;function m(e){return{current:e}}function E(e){0>ge||(e.current=he[ge],he[ge]=null,ge--)}function R(e,l){ge++,he[ge]=e.current,e.current=l}var G=m(null),W=m(null),I=m(null),oe=m(null);function we(e,l){switch(R(I,l),R(W,e),R(G,null),l.nodeType){case 9:case 11:e=(e=l.documentElement)&&(e=e.namespaceURI)?Vr(e):0;break;default:if(e=l.tagName,l=l.namespaceURI)l=Vr(l),e=wr(l,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}E(G),R(G,e)}function Oe(){E(G),E(W),E(I)}function Na(e){e.memoizedState!==null&&R(oe,e);var l=G.current,t=wr(l,e.type);l!==t&&(R(W,e),R(G,t))}function An(e){W.current===e&&(E(G),E(W)),oe.current===e&&(E(oe),bn._currentValue=V)}var Vu,ps;function zt(e){if(Vu===void 0)try{throw Error()}catch(t){var l=t.stack.trim().match(/\n( *(at )?)/);Vu=l&&l[1]||"",ps=-1<t.stack.indexOf(`+ at`)?" (<anonymous>)":-1<t.stack.indexOf("@")?"@unknown:0:0":""}return`+`+Vu+e+ps}var wu=!1;function Ku(e,l){if(!e||wu)return"";wu=!0;var t=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var a={DetermineComponentFrameRoot:function(){try{if(l){var z=function(){throw Error()};if(Object.defineProperty(z.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(z,[])}catch(b){var p=b}Reflect.construct(e,[],z)}else{try{z.call()}catch(b){p=b}e.call(z.prototype)}}else{try{throw Error()}catch(b){p=b}(z=e())&&typeof z.catch=="function"&&z.catch(function(){})}}catch(b){if(b&&p&&typeof b.stack=="string")return[b.stack,p.stack]}return[null,null]}};a.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var n=Object.getOwnPropertyDescriptor(a.DetermineComponentFrameRoot,"name");n&&n.configurable&&Object.defineProperty(a.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var u=a.DetermineComponentFrameRoot(),i=u[0],f=u[1];if(i&&f){var o=i.split(`+`),g=f.split(`+`);for(n=a=0;a<o.length&&!o[a].includes("DetermineComponentFrameRoot");)a++;for(;n<g.length&&!g[n].includes("DetermineComponentFrameRoot");)n++;if(a===o.length||n===g.length)for(a=o.length-1,n=g.length-1;1<=a&&0<=n&&o[a]!==g[n];)n--;for(;1<=a&&0<=n;a--,n--)if(o[a]!==g[n]){if(a!==1||n!==1)do if(a--,n--,0>n||o[a]!==g[n]){var S=`+`+o[a].replace(" at new "," at ");return e.displayName&&S.includes("<anonymous>")&&(S=S.replace("<anonymous>",e.displayName)),S}while(1<=a&&0<=n);break}}}finally{wu=!1,Error.prepareStackTrace=t}return(t=e?e.displayName||e.name:"")?zt(t):""}function Ld(e,l){switch(e.tag){case 26:case 27:case 5:return zt(e.type);case 16:return zt("Lazy");case 13:return e.child!==l&&l!==null?zt("Suspense Fallback"):zt("Suspense");case 19:return zt("SuspenseList");case 0:case 15:return Ku(e.type,!1);case 11:return Ku(e.type.render,!1);case 1:return Ku(e.type,!0);case 31:return zt("Activity");default:return""}}function bs(e){try{var l="",t=null;do l+=Ld(e,t),t=e,e=e.return;while(e);return l}catch(a){return`+Error generating stack: `+a.message+`+`+a.stack}}var Ju=Object.prototype.hasOwnProperty,ku=s.unstable_scheduleCallback,Wu=s.unstable_cancelCallback,Vd=s.unstable_shouldYield,wd=s.unstable_requestPaint,al=s.unstable_now,Kd=s.unstable_getCurrentPriorityLevel,Ss=s.unstable_ImmediatePriority,xs=s.unstable_UserBlockingPriority,En=s.unstable_NormalPriority,Jd=s.unstable_LowPriority,js=s.unstable_IdlePriority,kd=s.log,Wd=s.unstable_setDisableYieldValue,Da=null,nl=null;function Il(e){if(typeof kd=="function"&&Wd(e),nl&&typeof nl.setStrictMode=="function")try{nl.setStrictMode(Da,e)}catch{}}var ul=Math.clz32?Math.clz32:Id,$d=Math.log,Fd=Math.LN2;function Id(e){return e>>>=0,e===0?32:31-($d(e)/Fd|0)|0}var _n=256,On=262144,Nn=4194304;function At(e){var l=e&42;if(l!==0)return l;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Dn(e,l,t){var a=e.pendingLanes;if(a===0)return 0;var n=0,u=e.suspendedLanes,i=e.pingedLanes;e=e.warmLanes;var f=a&134217727;return f!==0?(a=f&~u,a!==0?n=At(a):(i&=f,i!==0?n=At(i):t||(t=f&~e,t!==0&&(n=At(t))))):(f=a&~u,f!==0?n=At(f):i!==0?n=At(i):t||(t=a&~e,t!==0&&(n=At(t)))),n===0?0:l!==0&&l!==n&&(l&u)===0&&(u=n&-n,t=l&-l,u>=t||u===32&&(t&4194048)!==0)?l:n}function Ma(e,l){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&l)===0}function Pd(e,l){switch(e){case 1:case 2:case 4:case 8:case 64:return l+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return l+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Ts(){var e=Nn;return Nn<<=1,(Nn&62914560)===0&&(Nn=4194304),e}function $u(e){for(var l=[],t=0;31>t;t++)l.push(e);return l}function Ca(e,l){e.pendingLanes|=l,l!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function eh(e,l,t,a,n,u){var i=e.pendingLanes;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=t,e.entangledLanes&=t,e.errorRecoveryDisabledLanes&=t,e.shellSuspendCounter=0;var f=e.entanglements,o=e.expirationTimes,g=e.hiddenUpdates;for(t=i&~t;0<t;){var S=31-ul(t),z=1<<S;f[S]=0,o[S]=-1;var p=g[S];if(p!==null)for(g[S]=null,S=0;S<p.length;S++){var b=p[S];b!==null&&(b.lane&=-536870913)}t&=~z}a!==0&&zs(e,a,0),u!==0&&n===0&&e.tag!==0&&(e.suspendedLanes|=u&~(i&~l))}function zs(e,l,t){e.pendingLanes|=l,e.suspendedLanes&=~l;var a=31-ul(l);e.entangledLanes|=l,e.entanglements[a]=e.entanglements[a]|1073741824|t&261930}function As(e,l){var t=e.entangledLanes|=l;for(e=e.entanglements;t;){var a=31-ul(t),n=1<<a;n&l|e[a]&l&&(e[a]|=l),t&=~n}}function Es(e,l){var t=l&-l;return t=(t&42)!==0?1:Fu(t),(t&(e.suspendedLanes|l))!==0?0:t}function Fu(e){switch(e){case 2:e=1;break;case 8:e=4;break;case 32:e=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:e=128;break;case 268435456:e=134217728;break;default:e=0}return e}function Iu(e){return e&=-e,2<e?8<e?(e&134217727)!==0?32:268435456:8:2}function _s(){var e=U.p;return e!==0?e:(e=window.event,e===void 0?32:md(e.type))}function Os(e,l){var t=U.p;try{return U.p=e,l()}finally{U.p=t}}var Pl=Math.random().toString(36).slice(2),Ge="__reactFiber$"+Pl,$e="__reactProps$"+Pl,Vt="__reactContainer$"+Pl,Pu="__reactEvents$"+Pl,lh="__reactListeners$"+Pl,th="__reactHandles$"+Pl,Ns="__reactResources$"+Pl,Ua="__reactMarker$"+Pl;function ei(e){delete e[Ge],delete e[$e],delete e[Pu],delete e[lh],delete e[th]}function wt(e){var l=e[Ge];if(l)return l;for(var t=e.parentNode;t;){if(l=t[Vt]||t[Ge]){if(t=l.alternate,l.child!==null||t!==null&&t.child!==null)for(e=Ir(e);e!==null;){if(t=e[Ge])return t;e=Ir(e)}return l}e=t,t=e.parentNode}return null}function Kt(e){if(e=e[Ge]||e[Vt]){var l=e.tag;if(l===5||l===6||l===13||l===31||l===26||l===27||l===3)return e}return null}function Ra(e){var l=e.tag;if(l===5||l===26||l===27||l===6)return e.stateNode;throw Error(r(33))}function Jt(e){var l=e[Ns];return l||(l=e[Ns]={hoistableStyles:new Map,hoistableScripts:new Map}),l}function qe(e){e[Ua]=!0}var Ds=new Set,Ms={};function Et(e,l){kt(e,l),kt(e+"Capture",l)}function kt(e,l){for(Ms[e]=l,e=0;e<l.length;e++)Ds.add(l[e])}var ah=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),Cs={},Us={};function nh(e){return Ju.call(Us,e)?!0:Ju.call(Cs,e)?!1:ah.test(e)?Us[e]=!0:(Cs[e]=!0,!1)}function Mn(e,l,t){if(nh(l))if(t===null)e.removeAttribute(l);else{switch(typeof t){case"undefined":case"function":case"symbol":e.removeAttribute(l);return;case"boolean":var a=l.toLowerCase().slice(0,5);if(a!=="data-"&&a!=="aria-"){e.removeAttribute(l);return}}e.setAttribute(l,""+t)}}function Cn(e,l,t){if(t===null)e.removeAttribute(l);else{switch(typeof t){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(l);return}e.setAttribute(l,""+t)}}function Rl(e,l,t,a){if(a===null)e.removeAttribute(t);else{switch(typeof a){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(t);return}e.setAttributeNS(l,t,""+a)}}function hl(e){switch(typeof e){case"bigint":case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Rs(e){var l=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(l==="checkbox"||l==="radio")}function uh(e,l,t){var a=Object.getOwnPropertyDescriptor(e.constructor.prototype,l);if(!e.hasOwnProperty(l)&&typeof a<"u"&&typeof a.get=="function"&&typeof a.set=="function"){var n=a.get,u=a.set;return Object.defineProperty(e,l,{configurable:!0,get:function(){return n.call(this)},set:function(i){t=""+i,u.call(this,i)}}),Object.defineProperty(e,l,{enumerable:a.enumerable}),{getValue:function(){return t},setValue:function(i){t=""+i},stopTracking:function(){e._valueTracker=null,delete e[l]}}}}function li(e){if(!e._valueTracker){var l=Rs(e)?"checked":"value";e._valueTracker=uh(e,l,""+e[l])}}function Hs(e){if(!e)return!1;var l=e._valueTracker;if(!l)return!0;var t=l.getValue(),a="";return e&&(a=Rs(e)?e.checked?"true":"false":e.value),e=a,e!==t?(l.setValue(e),!0):!1}function Un(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}var ih=/[\n"\\]/g;function ml(e){return e.replace(ih,function(l){return"\\"+l.charCodeAt(0).toString(16)+" "})}function ti(e,l,t,a,n,u,i,f){e.name="",i!=null&&typeof i!="function"&&typeof i!="symbol"&&typeof i!="boolean"?e.type=i:e.removeAttribute("type"),l!=null?i==="number"?(l===0&&e.value===""||e.value!=l)&&(e.value=""+hl(l)):e.value!==""+hl(l)&&(e.value=""+hl(l)):i!=="submit"&&i!=="reset"||e.removeAttribute("value"),l!=null?ai(e,i,hl(l)):t!=null?ai(e,i,hl(t)):a!=null&&e.removeAttribute("value"),n==null&&u!=null&&(e.defaultChecked=!!u),n!=null&&(e.checked=n&&typeof n!="function"&&typeof n!="symbol"),f!=null&&typeof f!="function"&&typeof f!="symbol"&&typeof f!="boolean"?e.name=""+hl(f):e.removeAttribute("name")}function Bs(e,l,t,a,n,u,i,f){if(u!=null&&typeof u!="function"&&typeof u!="symbol"&&typeof u!="boolean"&&(e.type=u),l!=null||t!=null){if(!(u!=="submit"&&u!=="reset"||l!=null)){li(e);return}t=t!=null?""+hl(t):"",l=l!=null?""+hl(l):t,f||l===e.value||(e.value=l),e.defaultValue=l}a=a??n,a=typeof a!="function"&&typeof a!="symbol"&&!!a,e.checked=f?e.checked:!!a,e.defaultChecked=!!a,i!=null&&typeof i!="function"&&typeof i!="symbol"&&typeof i!="boolean"&&(e.name=i),li(e)}function ai(e,l,t){l==="number"&&Un(e.ownerDocument)===e||e.defaultValue===""+t||(e.defaultValue=""+t)}function Wt(e,l,t,a){if(e=e.options,l){l={};for(var n=0;n<t.length;n++)l["$"+t[n]]=!0;for(t=0;t<e.length;t++)n=l.hasOwnProperty("$"+e[t].value),e[t].selected!==n&&(e[t].selected=n),n&&a&&(e[t].defaultSelected=!0)}else{for(t=""+hl(t),l=null,n=0;n<e.length;n++){if(e[n].value===t){e[n].selected=!0,a&&(e[n].defaultSelected=!0);return}l!==null||e[n].disabled||(l=e[n])}l!==null&&(l.selected=!0)}}function qs(e,l,t){if(l!=null&&(l=""+hl(l),l!==e.value&&(e.value=l),t==null)){e.defaultValue!==l&&(e.defaultValue=l);return}e.defaultValue=t!=null?""+hl(t):""}function Ys(e,l,t,a){if(l==null){if(a!=null){if(t!=null)throw Error(r(92));if(Tl(a)){if(1<a.length)throw Error(r(93));a=a[0]}t=a}t==null&&(t=""),l=t}t=hl(l),e.defaultValue=t,a=e.textContent,a===t&&a!==""&&a!==null&&(e.value=a),li(e)}function $t(e,l){if(l){var t=e.firstChild;if(t&&t===e.lastChild&&t.nodeType===3){t.nodeValue=l;return}}e.textContent=l}var ch=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function Gs(e,l,t){var a=l.indexOf("--")===0;t==null||typeof t=="boolean"||t===""?a?e.setProperty(l,""):l==="float"?e.cssFloat="":e[l]="":a?e.setProperty(l,t):typeof t!="number"||t===0||ch.has(l)?l==="float"?e.cssFloat=t:e[l]=(""+t).trim():e[l]=t+"px"}function Xs(e,l,t){if(l!=null&&typeof l!="object")throw Error(r(62));if(e=e.style,t!=null){for(var a in t)!t.hasOwnProperty(a)||l!=null&&l.hasOwnProperty(a)||(a.indexOf("--")===0?e.setProperty(a,""):a==="float"?e.cssFloat="":e[a]="");for(var n in l)a=l[n],l.hasOwnProperty(n)&&t[n]!==a&&Gs(e,n,a)}else for(var u in l)l.hasOwnProperty(u)&&Gs(e,u,l[u])}function ni(e){if(e.indexOf("-")===-1)return!1;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var sh=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),fh=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function Rn(e){return fh.test(""+e)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":e}function Hl(){}var ui=null;function ii(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Ft=null,It=null;function Qs(e){var l=Kt(e);if(l&&(e=l.stateNode)){var t=e[$e]||null;e:switch(e=l.stateNode,l.type){case"input":if(ti(e,t.value,t.defaultValue,t.defaultValue,t.checked,t.defaultChecked,t.type,t.name),l=t.name,t.type==="radio"&&l!=null){for(t=e;t.parentNode;)t=t.parentNode;for(t=t.querySelectorAll('input[name="'+ml(""+l)+'"][type="radio"]'),l=0;l<t.length;l++){var a=t[l];if(a!==e&&a.form===e.form){var n=a[$e]||null;if(!n)throw Error(r(90));ti(a,n.value,n.defaultValue,n.defaultValue,n.checked,n.defaultChecked,n.type,n.name)}}for(l=0;l<t.length;l++)a=t[l],a.form===e.form&&Hs(a)}break e;case"textarea":qs(e,t.value,t.defaultValue);break e;case"select":l=t.value,l!=null&&Wt(e,!!t.multiple,l,!1)}}}var ci=!1;function Zs(e,l,t){if(ci)return e(l,t);ci=!0;try{var a=e(l);return a}finally{if(ci=!1,(Ft!==null||It!==null)&&(xu(),Ft&&(l=Ft,e=It,It=Ft=null,Qs(l),e)))for(l=0;l<e.length;l++)Qs(e[l])}}function Ha(e,l){var t=e.stateNode;if(t===null)return null;var a=t[$e]||null;if(a===null)return null;t=a[l];e:switch(l){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(a=!a.disabled)||(e=e.type,a=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!a;break e;default:e=!1}if(e)return null;if(t&&typeof t!="function")throw Error(r(231,l,typeof t));return t}var Bl=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),si=!1;if(Bl)try{var Ba={};Object.defineProperty(Ba,"passive",{get:function(){si=!0}}),window.addEventListener("test",Ba,Ba),window.removeEventListener("test",Ba,Ba)}catch{si=!1}var et=null,fi=null,Hn=null;function Ls(){if(Hn)return Hn;var e,l=fi,t=l.length,a,n="value"in et?et.value:et.textContent,u=n.length;for(e=0;e<t&&l[e]===n[e];e++);var i=t-e;for(a=1;a<=i&&l[t-a]===n[u-a];a++);return Hn=n.slice(e,1<a?1-a:void 0)}function Bn(e){var l=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&l===13&&(e=13)):e=l,e===10&&(e=13),32<=e||e===13?e:0}function qn(){return!0}function Vs(){return!1}function Fe(e){function l(t,a,n,u,i){this._reactName=t,this._targetInst=n,this.type=a,this.nativeEvent=u,this.target=i,this.currentTarget=null;for(var f in e)e.hasOwnProperty(f)&&(t=e[f],this[f]=t?t(u):u[f]);return this.isDefaultPrevented=(u.defaultPrevented!=null?u.defaultPrevented:u.returnValue===!1)?qn:Vs,this.isPropagationStopped=Vs,this}return C(l.prototype,{preventDefault:function(){this.defaultPrevented=!0;var t=this.nativeEvent;t&&(t.preventDefault?t.preventDefault():typeof t.returnValue!="unknown"&&(t.returnValue=!1),this.isDefaultPrevented=qn)},stopPropagation:function(){var t=this.nativeEvent;t&&(t.stopPropagation?t.stopPropagation():typeof t.cancelBubble!="unknown"&&(t.cancelBubble=!0),this.isPropagationStopped=qn)},persist:function(){},isPersistent:qn}),l}var _t={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Yn=Fe(_t),qa=C({},_t,{view:0,detail:0}),oh=Fe(qa),oi,ri,Ya,Gn=C({},qa,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:hi,button:0,buttons:0,relatedTarget:function(e){return e.relatedTarget===void 0?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==Ya&&(Ya&&e.type==="mousemove"?(oi=e.screenX-Ya.screenX,ri=e.screenY-Ya.screenY):ri=oi=0,Ya=e),oi)},movementY:function(e){return"movementY"in e?e.movementY:ri}}),ws=Fe(Gn),rh=C({},Gn,{dataTransfer:0}),dh=Fe(rh),hh=C({},qa,{relatedTarget:0}),di=Fe(hh),mh=C({},_t,{animationName:0,elapsedTime:0,pseudoElement:0}),yh=Fe(mh),vh=C({},_t,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),gh=Fe(vh),ph=C({},_t,{data:0}),Ks=Fe(ph),bh={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Sh={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},xh={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function jh(e){var l=this.nativeEvent;return l.getModifierState?l.getModifierState(e):(e=xh[e])?!!l[e]:!1}function hi(){return jh}var Th=C({},qa,{key:function(e){if(e.key){var l=bh[e.key]||e.key;if(l!=="Unidentified")return l}return e.type==="keypress"?(e=Bn(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?Sh[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:hi,charCode:function(e){return e.type==="keypress"?Bn(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?Bn(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),zh=Fe(Th),Ah=C({},Gn,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Js=Fe(Ah),Eh=C({},qa,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:hi}),_h=Fe(Eh),Oh=C({},_t,{propertyName:0,elapsedTime:0,pseudoElement:0}),Nh=Fe(Oh),Dh=C({},Gn,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),Mh=Fe(Dh),Ch=C({},_t,{newState:0,oldState:0}),Uh=Fe(Ch),Rh=[9,13,27,32],mi=Bl&&"CompositionEvent"in window,Ga=null;Bl&&"documentMode"in document&&(Ga=document.documentMode);var Hh=Bl&&"TextEvent"in window&&!Ga,ks=Bl&&(!mi||Ga&&8<Ga&&11>=Ga),Ws=" ",$s=!1;function Fs(e,l){switch(e){case"keyup":return Rh.indexOf(l.keyCode)!==-1;case"keydown":return l.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Is(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Pt=!1;function Bh(e,l){switch(e){case"compositionend":return Is(l);case"keypress":return l.which!==32?null:($s=!0,Ws);case"textInput":return e=l.data,e===Ws&&$s?null:e;default:return null}}function qh(e,l){if(Pt)return e==="compositionend"||!mi&&Fs(e,l)?(e=Ls(),Hn=fi=et=null,Pt=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(l.ctrlKey||l.altKey||l.metaKey)||l.ctrlKey&&l.altKey){if(l.char&&1<l.char.length)return l.char;if(l.which)return String.fromCharCode(l.which)}return null;case"compositionend":return ks&&l.locale!=="ko"?null:l.data;default:return null}}var Yh={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Ps(e){var l=e&&e.nodeName&&e.nodeName.toLowerCase();return l==="input"?!!Yh[e.type]:l==="textarea"}function ef(e,l,t,a){Ft?It?It.push(a):It=[a]:Ft=a,l=Ou(l,"onChange"),0<l.length&&(t=new Yn("onChange","change",null,t,a),e.push({event:t,listeners:l}))}var Xa=null,Qa=null;function Gh(e){Yr(e,0)}function Xn(e){var l=Ra(e);if(Hs(l))return e}function lf(e,l){if(e==="change")return l}var tf=!1;if(Bl){var yi;if(Bl){var vi="oninput"in document;if(!vi){var af=document.createElement("div");af.setAttribute("oninput","return;"),vi=typeof af.oninput=="function"}yi=vi}else yi=!1;tf=yi&&(!document.documentMode||9<document.documentMode)}function nf(){Xa&&(Xa.detachEvent("onpropertychange",uf),Qa=Xa=null)}function uf(e){if(e.propertyName==="value"&&Xn(Qa)){var l=[];ef(l,Qa,e,ii(e)),Zs(Gh,l)}}function Xh(e,l,t){e==="focusin"?(nf(),Xa=l,Qa=t,Xa.attachEvent("onpropertychange",uf)):e==="focusout"&&nf()}function Qh(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return Xn(Qa)}function Zh(e,l){if(e==="click")return Xn(l)}function Lh(e,l){if(e==="input"||e==="change")return Xn(l)}function Vh(e,l){return e===l&&(e!==0||1/e===1/l)||e!==e&&l!==l}var il=typeof Object.is=="function"?Object.is:Vh;function Za(e,l){if(il(e,l))return!0;if(typeof e!="object"||e===null||typeof l!="object"||l===null)return!1;var t=Object.keys(e),a=Object.keys(l);if(t.length!==a.length)return!1;for(a=0;a<t.length;a++){var n=t[a];if(!Ju.call(l,n)||!il(e[n],l[n]))return!1}return!0}function cf(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function sf(e,l){var t=cf(e);e=0;for(var a;t;){if(t.nodeType===3){if(a=e+t.textContent.length,e<=l&&a>=l)return{node:t,offset:l-e};e=a}e:{for(;t;){if(t.nextSibling){t=t.nextSibling;break e}t=t.parentNode}t=void 0}t=cf(t)}}function ff(e,l){return e&&l?e===l?!0:e&&e.nodeType===3?!1:l&&l.nodeType===3?ff(e,l.parentNode):"contains"in e?e.contains(l):e.compareDocumentPosition?!!(e.compareDocumentPosition(l)&16):!1:!1}function of(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var l=Un(e.document);l instanceof e.HTMLIFrameElement;){try{var t=typeof l.contentWindow.location.href=="string"}catch{t=!1}if(t)e=l.contentWindow;else break;l=Un(e.document)}return l}function gi(e){var l=e&&e.nodeName&&e.nodeName.toLowerCase();return l&&(l==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||l==="textarea"||e.contentEditable==="true")}var wh=Bl&&"documentMode"in document&&11>=document.documentMode,ea=null,pi=null,La=null,bi=!1;function rf(e,l,t){var a=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;bi||ea==null||ea!==Un(a)||(a=ea,"selectionStart"in a&&gi(a)?a={start:a.selectionStart,end:a.selectionEnd}:(a=(a.ownerDocument&&a.ownerDocument.defaultView||window).getSelection(),a={anchorNode:a.anchorNode,anchorOffset:a.anchorOffset,focusNode:a.focusNode,focusOffset:a.focusOffset}),La&&Za(La,a)||(La=a,a=Ou(pi,"onSelect"),0<a.length&&(l=new Yn("onSelect","select",null,l,t),e.push({event:l,listeners:a}),l.target=ea)))}function Ot(e,l){var t={};return t[e.toLowerCase()]=l.toLowerCase(),t["Webkit"+e]="webkit"+l,t["Moz"+e]="moz"+l,t}var la={animationend:Ot("Animation","AnimationEnd"),animationiteration:Ot("Animation","AnimationIteration"),animationstart:Ot("Animation","AnimationStart"),transitionrun:Ot("Transition","TransitionRun"),transitionstart:Ot("Transition","TransitionStart"),transitioncancel:Ot("Transition","TransitionCancel"),transitionend:Ot("Transition","TransitionEnd")},Si={},df={};Bl&&(df=document.createElement("div").style,"AnimationEvent"in window||(delete la.animationend.animation,delete la.animationiteration.animation,delete la.animationstart.animation),"TransitionEvent"in window||delete la.transitionend.transition);function Nt(e){if(Si[e])return Si[e];if(!la[e])return e;var l=la[e],t;for(t in l)if(l.hasOwnProperty(t)&&t in df)return Si[e]=l[t];return e}var hf=Nt("animationend"),mf=Nt("animationiteration"),yf=Nt("animationstart"),Kh=Nt("transitionrun"),Jh=Nt("transitionstart"),kh=Nt("transitioncancel"),vf=Nt("transitionend"),gf=new Map,xi="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");xi.push("scrollEnd");function zl(e,l){gf.set(e,l),Et(l,[e])}var Qn=typeof reportError=="function"?reportError:function(e){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var l=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof e=="object"&&e!==null&&typeof e.message=="string"?String(e.message):String(e),error:e});if(!window.dispatchEvent(l))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)},yl=[],ta=0,ji=0;function Zn(){for(var e=ta,l=ji=ta=0;l<e;){var t=yl[l];yl[l++]=null;var a=yl[l];yl[l++]=null;var n=yl[l];yl[l++]=null;var u=yl[l];if(yl[l++]=null,a!==null&&n!==null){var i=a.pending;i===null?n.next=n:(n.next=i.next,i.next=n),a.pending=n}u!==0&&pf(t,n,u)}}function Ln(e,l,t,a){yl[ta++]=e,yl[ta++]=l,yl[ta++]=t,yl[ta++]=a,ji|=a,e.lanes|=a,e=e.alternate,e!==null&&(e.lanes|=a)}function Ti(e,l,t,a){return Ln(e,l,t,a),Vn(e)}function Dt(e,l){return Ln(e,null,null,l),Vn(e)}function pf(e,l,t){e.lanes|=t;var a=e.alternate;a!==null&&(a.lanes|=t);for(var n=!1,u=e.return;u!==null;)u.childLanes|=t,a=u.alternate,a!==null&&(a.childLanes|=t),u.tag===22&&(e=u.stateNode,e===null||e._visibility&1||(n=!0)),e=u,u=u.return;return e.tag===3?(u=e.stateNode,n&&l!==null&&(n=31-ul(t),e=u.hiddenUpdates,a=e[n],a===null?e[n]=[l]:a.push(l),l.lane=t|536870912),u):null}function Vn(e){if(50<dn)throw dn=0,Cc=null,Error(r(185));for(var l=e.return;l!==null;)e=l,l=e.return;return e.tag===3?e.stateNode:null}var aa={};function Wh(e,l,t,a){this.tag=e,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=l,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=a,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function cl(e,l,t,a){return new Wh(e,l,t,a)}function zi(e){return e=e.prototype,!(!e||!e.isReactComponent)}function ql(e,l){var t=e.alternate;return t===null?(t=cl(e.tag,l,e.key,e.mode),t.elementType=e.elementType,t.type=e.type,t.stateNode=e.stateNode,t.alternate=e,e.alternate=t):(t.pendingProps=l,t.type=e.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=e.flags&65011712,t.childLanes=e.childLanes,t.lanes=e.lanes,t.child=e.child,t.memoizedProps=e.memoizedProps,t.memoizedState=e.memoizedState,t.updateQueue=e.updateQueue,l=e.dependencies,t.dependencies=l===null?null:{lanes:l.lanes,firstContext:l.firstContext},t.sibling=e.sibling,t.index=e.index,t.ref=e.ref,t.refCleanup=e.refCleanup,t}function bf(e,l){e.flags&=65011714;var t=e.alternate;return t===null?(e.childLanes=0,e.lanes=l,e.child=null,e.subtreeFlags=0,e.memoizedProps=null,e.memoizedState=null,e.updateQueue=null,e.dependencies=null,e.stateNode=null):(e.childLanes=t.childLanes,e.lanes=t.lanes,e.child=t.child,e.subtreeFlags=0,e.deletions=null,e.memoizedProps=t.memoizedProps,e.memoizedState=t.memoizedState,e.updateQueue=t.updateQueue,e.type=t.type,l=t.dependencies,e.dependencies=l===null?null:{lanes:l.lanes,firstContext:l.firstContext}),e}function wn(e,l,t,a,n,u){var i=0;if(a=e,typeof e=="function")zi(e)&&(i=1);else if(typeof e=="string")i=ey(e,t,G.current)?26:e==="html"||e==="head"||e==="body"?27:5;else e:switch(e){case _l:return e=cl(31,t,l,n),e.elementType=_l,e.lanes=u,e;case ie:return Mt(t.children,n,u,l);case je:i=8,n|=24;break;case ue:return e=cl(12,t,l,n|2),e.elementType=ue,e.lanes=u,e;case Je:return e=cl(13,t,l,n),e.elementType=Je,e.lanes=u,e;case He:return e=cl(19,t,l,n),e.elementType=He,e.lanes=u,e;default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Z:i=10;break e;case k:i=9;break e;case Ae:i=11;break e;case ae:i=14;break e;case ke:i=16,a=null;break e}i=29,t=Error(r(130,e===null?"null":typeof e,"")),a=null}return l=cl(i,t,l,n),l.elementType=e,l.type=a,l.lanes=u,l}function Mt(e,l,t,a){return e=cl(7,e,a,l),e.lanes=t,e}function Ai(e,l,t){return e=cl(6,e,null,l),e.lanes=t,e}function Sf(e){var l=cl(18,null,null,0);return l.stateNode=e,l}function Ei(e,l,t){return l=cl(4,e.children!==null?e.children:[],e.key,l),l.lanes=t,l.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},l}var xf=new WeakMap;function vl(e,l){if(typeof e=="object"&&e!==null){var t=xf.get(e);return t!==void 0?t:(l={value:e,source:l,stack:bs(l)},xf.set(e,l),l)}return{value:e,source:l,stack:bs(l)}}var na=[],ua=0,Kn=null,Va=0,gl=[],pl=0,lt=null,Nl=1,Dl="";function Yl(e,l){na[ua++]=Va,na[ua++]=Kn,Kn=e,Va=l}function jf(e,l,t){gl[pl++]=Nl,gl[pl++]=Dl,gl[pl++]=lt,lt=e;var a=Nl;e=Dl;var n=32-ul(a)-1;a&=~(1<<n),t+=1;var u=32-ul(l)+n;if(30<u){var i=n-n%5;u=(a&(1<<i)-1).toString(32),a>>=i,n-=i,Nl=1<<32-ul(l)+n|t<<n|a,Dl=u+e}else Nl=1<<u|t<<n|a,Dl=e}function _i(e){e.return!==null&&(Yl(e,1),jf(e,1,0))}function Oi(e){for(;e===Kn;)Kn=na[--ua],na[ua]=null,Va=na[--ua],na[ua]=null;for(;e===lt;)lt=gl[--pl],gl[pl]=null,Dl=gl[--pl],gl[pl]=null,Nl=gl[--pl],gl[pl]=null}function Tf(e,l){gl[pl++]=Nl,gl[pl++]=Dl,gl[pl++]=lt,Nl=l.id,Dl=l.overflow,lt=e}var Xe=null,Se=null,ne=!1,tt=null,bl=!1,Ni=Error(r(519));function at(e){var l=Error(r(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw wa(vl(l,e)),Ni}function zf(e){var l=e.stateNode,t=e.type,a=e.memoizedProps;switch(l[Ge]=e,l[$e]=a,t){case"dialog":ee("cancel",l),ee("close",l);break;case"iframe":case"object":case"embed":ee("load",l);break;case"video":case"audio":for(t=0;t<mn.length;t++)ee(mn[t],l);break;case"source":ee("error",l);break;case"img":case"image":case"link":ee("error",l),ee("load",l);break;case"details":ee("toggle",l);break;case"input":ee("invalid",l),Bs(l,a.value,a.defaultValue,a.checked,a.defaultChecked,a.type,a.name,!0);break;case"select":ee("invalid",l);break;case"textarea":ee("invalid",l),Ys(l,a.value,a.defaultValue,a.children)}t=a.children,typeof t!="string"&&typeof t!="number"&&typeof t!="bigint"||l.textContent===""+t||a.suppressHydrationWarning===!0||Zr(l.textContent,t)?(a.popover!=null&&(ee("beforetoggle",l),ee("toggle",l)),a.onScroll!=null&&ee("scroll",l),a.onScrollEnd!=null&&ee("scrollend",l),a.onClick!=null&&(l.onclick=Hl),l=!0):l=!1,l||at(e,!0)}function Af(e){for(Xe=e.return;Xe;)switch(Xe.tag){case 5:case 31:case 13:bl=!1;return;case 27:case 3:bl=!0;return;default:Xe=Xe.return}}function ia(e){if(e!==Xe)return!1;if(!ne)return Af(e),ne=!0,!1;var l=e.tag,t;if((t=l!==3&&l!==27)&&((t=l===5)&&(t=e.type,t=!(t!=="form"&&t!=="button")||Jc(e.type,e.memoizedProps)),t=!t),t&&Se&&at(e),Af(e),l===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(r(317));Se=Fr(e)}else if(l===31){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(r(317));Se=Fr(e)}else l===27?(l=Se,gt(e.type)?(e=Ic,Ic=null,Se=e):Se=l):Se=Xe?xl(e.stateNode.nextSibling):null;return!0}function Ct(){Se=Xe=null,ne=!1}function Di(){var e=tt;return e!==null&&(ll===null?ll=e:ll.push.apply(ll,e),tt=null),e}function wa(e){tt===null?tt=[e]:tt.push(e)}var Mi=m(null),Ut=null,Gl=null;function nt(e,l,t){R(Mi,l._currentValue),l._currentValue=t}function Xl(e){e._currentValue=Mi.current,E(Mi)}function Ci(e,l,t){for(;e!==null;){var a=e.alternate;if((e.childLanes&l)!==l?(e.childLanes|=l,a!==null&&(a.childLanes|=l)):a!==null&&(a.childLanes&l)!==l&&(a.childLanes|=l),e===t)break;e=e.return}}function Ui(e,l,t,a){var n=e.child;for(n!==null&&(n.return=e);n!==null;){var u=n.dependencies;if(u!==null){var i=n.child;u=u.firstContext;e:for(;u!==null;){var f=u;u=n;for(var o=0;o<l.length;o++)if(f.context===l[o]){u.lanes|=t,f=u.alternate,f!==null&&(f.lanes|=t),Ci(u.return,t,e),a||(i=null);break e}u=f.next}}else if(n.tag===18){if(i=n.return,i===null)throw Error(r(341));i.lanes|=t,u=i.alternate,u!==null&&(u.lanes|=t),Ci(i,t,e),i=null}else i=n.child;if(i!==null)i.return=n;else for(i=n;i!==null;){if(i===e){i=null;break}if(n=i.sibling,n!==null){n.return=i.return,i=n;break}i=i.return}n=i}}function ca(e,l,t,a){e=null;for(var n=l,u=!1;n!==null;){if(!u){if((n.flags&524288)!==0)u=!0;else if((n.flags&262144)!==0)break}if(n.tag===10){var i=n.alternate;if(i===null)throw Error(r(387));if(i=i.memoizedProps,i!==null){var f=n.type;il(n.pendingProps.value,i.value)||(e!==null?e.push(f):e=[f])}}else if(n===oe.current){if(i=n.alternate,i===null)throw Error(r(387));i.memoizedState.memoizedState!==n.memoizedState.memoizedState&&(e!==null?e.push(bn):e=[bn])}n=n.return}e!==null&&Ui(l,e,t,a),l.flags|=262144}function Jn(e){for(e=e.firstContext;e!==null;){if(!il(e.context._currentValue,e.memoizedValue))return!0;e=e.next}return!1}function Rt(e){Ut=e,Gl=null,e=e.dependencies,e!==null&&(e.firstContext=null)}function Qe(e){return Ef(Ut,e)}function kn(e,l){return Ut===null&&Rt(e),Ef(e,l)}function Ef(e,l){var t=l._currentValue;if(l={context:l,memoizedValue:t,next:null},Gl===null){if(e===null)throw Error(r(308));Gl=l,e.dependencies={lanes:0,firstContext:l},e.flags|=524288}else Gl=Gl.next=l;return t}var $h=typeof AbortController<"u"?AbortController:function(){var e=[],l=this.signal={aborted:!1,addEventListener:function(t,a){e.push(a)}};this.abort=function(){l.aborted=!0,e.forEach(function(t){return t()})}},Fh=s.unstable_scheduleCallback,Ih=s.unstable_NormalPriority,Me={$$typeof:Z,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Ri(){return{controller:new $h,data:new Map,refCount:0}}function Ka(e){e.refCount--,e.refCount===0&&Fh(Ih,function(){e.controller.abort()})}var Ja=null,Hi=0,sa=0,fa=null;function Ph(e,l){if(Ja===null){var t=Ja=[];Hi=0,sa=Yc(),fa={status:"pending",value:void 0,then:function(a){t.push(a)}}}return Hi++,l.then(_f,_f),l}function _f(){if(--Hi===0&&Ja!==null){fa!==null&&(fa.status="fulfilled");var e=Ja;Ja=null,sa=0,fa=null;for(var l=0;l<e.length;l++)(0,e[l])()}}function em(e,l){var t=[],a={status:"pending",value:null,reason:null,then:function(n){t.push(n)}};return e.then(function(){a.status="fulfilled",a.value=l;for(var n=0;n<t.length;n++)(0,t[n])(l)},function(n){for(a.status="rejected",a.reason=n,n=0;n<t.length;n++)(0,t[n])(void 0)}),a}var Of=x.S;x.S=function(e,l){dr=al(),typeof l=="object"&&l!==null&&typeof l.then=="function"&&Ph(e,l),Of!==null&&Of(e,l)};var Ht=m(null);function Bi(){var e=Ht.current;return e!==null?e:pe.pooledCache}function Wn(e,l){l===null?R(Ht,Ht.current):R(Ht,l.pool)}function Nf(){var e=Bi();return e===null?null:{parent:Me._currentValue,pool:e}}var oa=Error(r(460)),qi=Error(r(474)),$n=Error(r(542)),Fn={then:function(){}};function Df(e){return e=e.status,e==="fulfilled"||e==="rejected"}function Mf(e,l,t){switch(t=e[t],t===void 0?e.push(l):t!==l&&(l.then(Hl,Hl),l=t),l.status){case"fulfilled":return l.value;case"rejected":throw e=l.reason,Uf(e),e;default:if(typeof l.status=="string")l.then(Hl,Hl);else{if(e=pe,e!==null&&100<e.shellSuspendCounter)throw Error(r(482));e=l,e.status="pending",e.then(function(a){if(l.status==="pending"){var n=l;n.status="fulfilled",n.value=a}},function(a){if(l.status==="pending"){var n=l;n.status="rejected",n.reason=a}})}switch(l.status){case"fulfilled":return l.value;case"rejected":throw e=l.reason,Uf(e),e}throw qt=l,oa}}function Bt(e){try{var l=e._init;return l(e._payload)}catch(t){throw t!==null&&typeof t=="object"&&typeof t.then=="function"?(qt=t,oa):t}}var qt=null;function Cf(){if(qt===null)throw Error(r(459));var e=qt;return qt=null,e}function Uf(e){if(e===oa||e===$n)throw Error(r(483))}var ra=null,ka=0;function In(e){var l=ka;return ka+=1,ra===null&&(ra=[]),Mf(ra,e,l)}function Wa(e,l){l=l.props.ref,e.ref=l!==void 0?l:null}function Pn(e,l){throw l.$$typeof===N?Error(r(525)):(e=Object.prototype.toString.call(l),Error(r(31,e==="[object Object]"?"object with keys {"+Object.keys(l).join(", ")+"}":e)))}function Rf(e){function l(y,h){if(e){var v=y.deletions;v===null?(y.deletions=[h],y.flags|=16):v.push(h)}}function t(y,h){if(!e)return null;for(;h!==null;)l(y,h),h=h.sibling;return null}function a(y){for(var h=new Map;y!==null;)y.key!==null?h.set(y.key,y):h.set(y.index,y),y=y.sibling;return h}function n(y,h){return y=ql(y,h),y.index=0,y.sibling=null,y}function u(y,h,v){return y.index=v,e?(v=y.alternate,v!==null?(v=v.index,v<h?(y.flags|=67108866,h):v):(y.flags|=67108866,h)):(y.flags|=1048576,h)}function i(y){return e&&y.alternate===null&&(y.flags|=67108866),y}function f(y,h,v,j){return h===null||h.tag!==6?(h=Ai(v,y.mode,j),h.return=y,h):(h=n(h,v),h.return=y,h)}function o(y,h,v,j){var Q=v.type;return Q===ie?S(y,h,v.props.children,j,v.key):h!==null&&(h.elementType===Q||typeof Q=="object"&&Q!==null&&Q.$$typeof===ke&&Bt(Q)===h.type)?(h=n(h,v.props),Wa(h,v),h.return=y,h):(h=wn(v.type,v.key,v.props,null,y.mode,j),Wa(h,v),h.return=y,h)}function g(y,h,v,j){return h===null||h.tag!==4||h.stateNode.containerInfo!==v.containerInfo||h.stateNode.implementation!==v.implementation?(h=Ei(v,y.mode,j),h.return=y,h):(h=n(h,v.children||[]),h.return=y,h)}function S(y,h,v,j,Q){return h===null||h.tag!==7?(h=Mt(v,y.mode,j,Q),h.return=y,h):(h=n(h,v),h.return=y,h)}function z(y,h,v){if(typeof h=="string"&&h!==""||typeof h=="number"||typeof h=="bigint")return h=Ai(""+h,y.mode,v),h.return=y,h;if(typeof h=="object"&&h!==null){switch(h.$$typeof){case J:return v=wn(h.type,h.key,h.props,null,y.mode,v),Wa(v,h),v.return=y,v;case K:return h=Ei(h,y.mode,v),h.return=y,h;case ke:return h=Bt(h),z(y,h,v)}if(Tl(h)||We(h))return h=Mt(h,y.mode,v,null),h.return=y,h;if(typeof h.then=="function")return z(y,In(h),v);if(h.$$typeof===Z)return z(y,kn(y,h),v);Pn(y,h)}return null}function p(y,h,v,j){var Q=h!==null?h.key:null;if(typeof v=="string"&&v!==""||typeof v=="number"||typeof v=="bigint")return Q!==null?null:f(y,h,""+v,j);if(typeof v=="object"&&v!==null){switch(v.$$typeof){case J:return v.key===Q?o(y,h,v,j):null;case K:return v.key===Q?g(y,h,v,j):null;case ke:return v=Bt(v),p(y,h,v,j)}if(Tl(v)||We(v))return Q!==null?null:S(y,h,v,j,null);if(typeof v.then=="function")return p(y,h,In(v),j);if(v.$$typeof===Z)return p(y,h,kn(y,v),j);Pn(y,v)}return null}function b(y,h,v,j,Q){if(typeof j=="string"&&j!==""||typeof j=="number"||typeof j=="bigint")return y=y.get(v)||null,f(h,y,""+j,Q);if(typeof j=="object"&&j!==null){switch(j.$$typeof){case J:return y=y.get(j.key===null?v:j.key)||null,o(h,y,j,Q);case K:return y=y.get(j.key===null?v:j.key)||null,g(h,y,j,Q);case ke:return j=Bt(j),b(y,h,v,j,Q)}if(Tl(j)||We(j))return y=y.get(v)||null,S(h,y,j,Q,null);if(typeof j.then=="function")return b(y,h,v,In(j),Q);if(j.$$typeof===Z)return b(y,h,v,kn(h,j),Q);Pn(h,j)}return null}function q(y,h,v,j){for(var Q=null,ce=null,X=h,F=h=0,te=null;X!==null&&F<v.length;F++){X.index>F?(te=X,X=null):te=X.sibling;var se=p(y,X,v[F],j);if(se===null){X===null&&(X=te);break}e&&X&&se.alternate===null&&l(y,X),h=u(se,h,F),ce===null?Q=se:ce.sibling=se,ce=se,X=te}if(F===v.length)return t(y,X),ne&&Yl(y,F),Q;if(X===null){for(;F<v.length;F++)X=z(y,v[F],j),X!==null&&(h=u(X,h,F),ce===null?Q=X:ce.sibling=X,ce=X);return ne&&Yl(y,F),Q}for(X=a(X);F<v.length;F++)te=b(X,y,F,v[F],j),te!==null&&(e&&te.alternate!==null&&X.delete(te.key===null?F:te.key),h=u(te,h,F),ce===null?Q=te:ce.sibling=te,ce=te);return e&&X.forEach(function(jt){return l(y,jt)}),ne&&Yl(y,F),Q}function L(y,h,v,j){if(v==null)throw Error(r(151));for(var Q=null,ce=null,X=h,F=h=0,te=null,se=v.next();X!==null&&!se.done;F++,se=v.next()){X.index>F?(te=X,X=null):te=X.sibling;var jt=p(y,X,se.value,j);if(jt===null){X===null&&(X=te);break}e&&X&&jt.alternate===null&&l(y,X),h=u(jt,h,F),ce===null?Q=jt:ce.sibling=jt,ce=jt,X=te}if(se.done)return t(y,X),ne&&Yl(y,F),Q;if(X===null){for(;!se.done;F++,se=v.next())se=z(y,se.value,j),se!==null&&(h=u(se,h,F),ce===null?Q=se:ce.sibling=se,ce=se);return ne&&Yl(y,F),Q}for(X=a(X);!se.done;F++,se=v.next())se=b(X,y,F,se.value,j),se!==null&&(e&&se.alternate!==null&&X.delete(se.key===null?F:se.key),h=u(se,h,F),ce===null?Q=se:ce.sibling=se,ce=se);return e&&X.forEach(function(ry){return l(y,ry)}),ne&&Yl(y,F),Q}function ve(y,h,v,j){if(typeof v=="object"&&v!==null&&v.type===ie&&v.key===null&&(v=v.props.children),typeof v=="object"&&v!==null){switch(v.$$typeof){case J:e:{for(var Q=v.key;h!==null;){if(h.key===Q){if(Q=v.type,Q===ie){if(h.tag===7){t(y,h.sibling),j=n(h,v.props.children),j.return=y,y=j;break e}}else if(h.elementType===Q||typeof Q=="object"&&Q!==null&&Q.$$typeof===ke&&Bt(Q)===h.type){t(y,h.sibling),j=n(h,v.props),Wa(j,v),j.return=y,y=j;break e}t(y,h);break}else l(y,h);h=h.sibling}v.type===ie?(j=Mt(v.props.children,y.mode,j,v.key),j.return=y,y=j):(j=wn(v.type,v.key,v.props,null,y.mode,j),Wa(j,v),j.return=y,y=j)}return i(y);case K:e:{for(Q=v.key;h!==null;){if(h.key===Q)if(h.tag===4&&h.stateNode.containerInfo===v.containerInfo&&h.stateNode.implementation===v.implementation){t(y,h.sibling),j=n(h,v.children||[]),j.return=y,y=j;break e}else{t(y,h);break}else l(y,h);h=h.sibling}j=Ei(v,y.mode,j),j.return=y,y=j}return i(y);case ke:return v=Bt(v),ve(y,h,v,j)}if(Tl(v))return q(y,h,v,j);if(We(v)){if(Q=We(v),typeof Q!="function")throw Error(r(150));return v=Q.call(v),L(y,h,v,j)}if(typeof v.then=="function")return ve(y,h,In(v),j);if(v.$$typeof===Z)return ve(y,h,kn(y,v),j);Pn(y,v)}return typeof v=="string"&&v!==""||typeof v=="number"||typeof v=="bigint"?(v=""+v,h!==null&&h.tag===6?(t(y,h.sibling),j=n(h,v),j.return=y,y=j):(t(y,h),j=Ai(v,y.mode,j),j.return=y,y=j),i(y)):t(y,h)}return function(y,h,v,j){try{ka=0;var Q=ve(y,h,v,j);return ra=null,Q}catch(X){if(X===oa||X===$n)throw X;var ce=cl(29,X,null,y.mode);return ce.lanes=j,ce.return=y,ce}finally{}}}var Yt=Rf(!0),Hf=Rf(!1),ut=!1;function Yi(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Gi(e,l){e=e.updateQueue,l.updateQueue===e&&(l.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function it(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function ct(e,l,t){var a=e.updateQueue;if(a===null)return null;if(a=a.shared,(fe&2)!==0){var n=a.pending;return n===null?l.next=l:(l.next=n.next,n.next=l),a.pending=l,l=Vn(e),pf(e,null,t),l}return Ln(e,a,l,t),Vn(e)}function $a(e,l,t){if(l=l.updateQueue,l!==null&&(l=l.shared,(t&4194048)!==0)){var a=l.lanes;a&=e.pendingLanes,t|=a,l.lanes=t,As(e,t)}}function Xi(e,l){var t=e.updateQueue,a=e.alternate;if(a!==null&&(a=a.updateQueue,t===a)){var n=null,u=null;if(t=t.firstBaseUpdate,t!==null){do{var i={lane:t.lane,tag:t.tag,payload:t.payload,callback:null,next:null};u===null?n=u=i:u=u.next=i,t=t.next}while(t!==null);u===null?n=u=l:u=u.next=l}else n=u=l;t={baseState:a.baseState,firstBaseUpdate:n,lastBaseUpdate:u,shared:a.shared,callbacks:a.callbacks},e.updateQueue=t;return}e=t.lastBaseUpdate,e===null?t.firstBaseUpdate=l:e.next=l,t.lastBaseUpdate=l}var Qi=!1;function Fa(){if(Qi){var e=fa;if(e!==null)throw e}}function Ia(e,l,t,a){Qi=!1;var n=e.updateQueue;ut=!1;var u=n.firstBaseUpdate,i=n.lastBaseUpdate,f=n.shared.pending;if(f!==null){n.shared.pending=null;var o=f,g=o.next;o.next=null,i===null?u=g:i.next=g,i=o;var S=e.alternate;S!==null&&(S=S.updateQueue,f=S.lastBaseUpdate,f!==i&&(f===null?S.firstBaseUpdate=g:f.next=g,S.lastBaseUpdate=o))}if(u!==null){var z=n.baseState;i=0,S=g=o=null,f=u;do{var p=f.lane&-536870913,b=p!==f.lane;if(b?(le&p)===p:(a&p)===p){p!==0&&p===sa&&(Qi=!0),S!==null&&(S=S.next={lane:0,tag:f.tag,payload:f.payload,callback:null,next:null});e:{var q=e,L=f;p=l;var ve=t;switch(L.tag){case 1:if(q=L.payload,typeof q=="function"){z=q.call(ve,z,p);break e}z=q;break e;case 3:q.flags=q.flags&-65537|128;case 0:if(q=L.payload,p=typeof q=="function"?q.call(ve,z,p):q,p==null)break e;z=C({},z,p);break e;case 2:ut=!0}}p=f.callback,p!==null&&(e.flags|=64,b&&(e.flags|=8192),b=n.callbacks,b===null?n.callbacks=[p]:b.push(p))}else b={lane:p,tag:f.tag,payload:f.payload,callback:f.callback,next:null},S===null?(g=S=b,o=z):S=S.next=b,i|=p;if(f=f.next,f===null){if(f=n.shared.pending,f===null)break;b=f,f=b.next,b.next=null,n.lastBaseUpdate=b,n.shared.pending=null}}while(!0);S===null&&(o=z),n.baseState=o,n.firstBaseUpdate=g,n.lastBaseUpdate=S,u===null&&(n.shared.lanes=0),dt|=i,e.lanes=i,e.memoizedState=z}}function Bf(e,l){if(typeof e!="function")throw Error(r(191,e));e.call(l)}function qf(e,l){var t=e.callbacks;if(t!==null)for(e.callbacks=null,e=0;e<t.length;e++)Bf(t[e],l)}var da=m(null),eu=m(0);function Yf(e,l){e=Wl,R(eu,e),R(da,l),Wl=e|l.baseLanes}function Zi(){R(eu,Wl),R(da,da.current)}function Li(){Wl=eu.current,E(da),E(eu)}var sl=m(null),Sl=null;function st(e){var l=e.alternate;R(Ne,Ne.current&1),R(sl,e),Sl===null&&(l===null||da.current!==null||l.memoizedState!==null)&&(Sl=e)}function Vi(e){R(Ne,Ne.current),R(sl,e),Sl===null&&(Sl=e)}function Gf(e){e.tag===22?(R(Ne,Ne.current),R(sl,e),Sl===null&&(Sl=e)):ft()}function ft(){R(Ne,Ne.current),R(sl,sl.current)}function fl(e){E(sl),Sl===e&&(Sl=null),E(Ne)}var Ne=m(0);function lu(e){for(var l=e;l!==null;){if(l.tag===13){var t=l.memoizedState;if(t!==null&&(t=t.dehydrated,t===null||$c(t)||Fc(t)))return l}else if(l.tag===19&&(l.memoizedProps.revealOrder==="forwards"||l.memoizedProps.revealOrder==="backwards"||l.memoizedProps.revealOrder==="unstable_legacy-backwards"||l.memoizedProps.revealOrder==="together")){if((l.flags&128)!==0)return l}else if(l.child!==null){l.child.return=l,l=l.child;continue}if(l===e)break;for(;l.sibling===null;){if(l.return===null||l.return===e)return null;l=l.return}l.sibling.return=l.return,l=l.sibling}return null}var Ql=0,$=null,me=null,Ce=null,tu=!1,ha=!1,Gt=!1,au=0,Pa=0,ma=null,lm=0;function Ee(){throw Error(r(321))}function wi(e,l){if(l===null)return!1;for(var t=0;t<l.length&&t<e.length;t++)if(!il(e[t],l[t]))return!1;return!0}function Ki(e,l,t,a,n,u){return Ql=u,$=l,l.memoizedState=null,l.updateQueue=null,l.lanes=0,x.H=e===null||e.memoizedState===null?To:cc,Gt=!1,u=t(a,n),Gt=!1,ha&&(u=Qf(l,t,a,n)),Xf(e),u}function Xf(e){x.H=tn;var l=me!==null&&me.next!==null;if(Ql=0,Ce=me=$=null,tu=!1,Pa=0,ma=null,l)throw Error(r(300));e===null||Ue||(e=e.dependencies,e!==null&&Jn(e)&&(Ue=!0))}function Qf(e,l,t,a){$=e;var n=0;do{if(ha&&(ma=null),Pa=0,ha=!1,25<=n)throw Error(r(301));if(n+=1,Ce=me=null,e.updateQueue!=null){var u=e.updateQueue;u.lastEffect=null,u.events=null,u.stores=null,u.memoCache!=null&&(u.memoCache.index=0)}x.H=zo,u=l(t,a)}while(ha);return u}function tm(){var e=x.H,l=e.useState()[0];return l=typeof l.then=="function"?en(l):l,e=e.useState()[0],(me!==null?me.memoizedState:null)!==e&&($.flags|=1024),l}function Ji(){var e=au!==0;return au=0,e}function ki(e,l,t){l.updateQueue=e.updateQueue,l.flags&=-2053,e.lanes&=~t}function Wi(e){if(tu){for(e=e.memoizedState;e!==null;){var l=e.queue;l!==null&&(l.pending=null),e=e.next}tu=!1}Ql=0,Ce=me=$=null,ha=!1,Pa=au=0,ma=null}function Ke(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Ce===null?$.memoizedState=Ce=e:Ce=Ce.next=e,Ce}function De(){if(me===null){var e=$.alternate;e=e!==null?e.memoizedState:null}else e=me.next;var l=Ce===null?$.memoizedState:Ce.next;if(l!==null)Ce=l,me=e;else{if(e===null)throw $.alternate===null?Error(r(467)):Error(r(310));me=e,e={memoizedState:me.memoizedState,baseState:me.baseState,baseQueue:me.baseQueue,queue:me.queue,next:null},Ce===null?$.memoizedState=Ce=e:Ce=Ce.next=e}return Ce}function nu(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function en(e){var l=Pa;return Pa+=1,ma===null&&(ma=[]),e=Mf(ma,e,l),l=$,(Ce===null?l.memoizedState:Ce.next)===null&&(l=l.alternate,x.H=l===null||l.memoizedState===null?To:cc),e}function uu(e){if(e!==null&&typeof e=="object"){if(typeof e.then=="function")return en(e);if(e.$$typeof===Z)return Qe(e)}throw Error(r(438,String(e)))}function $i(e){var l=null,t=$.updateQueue;if(t!==null&&(l=t.memoCache),l==null){var a=$.alternate;a!==null&&(a=a.updateQueue,a!==null&&(a=a.memoCache,a!=null&&(l={data:a.data.map(function(n){return n.slice()}),index:0})))}if(l==null&&(l={data:[],index:0}),t===null&&(t=nu(),$.updateQueue=t),t.memoCache=l,t=l.data[l.index],t===void 0)for(t=l.data[l.index]=Array(e),a=0;a<e;a++)t[a]=Lt;return l.index++,t}function Zl(e,l){return typeof l=="function"?l(e):l}function iu(e){var l=De();return Fi(l,me,e)}function Fi(e,l,t){var a=e.queue;if(a===null)throw Error(r(311));a.lastRenderedReducer=t;var n=e.baseQueue,u=a.pending;if(u!==null){if(n!==null){var i=n.next;n.next=u.next,u.next=i}l.baseQueue=n=u,a.pending=null}if(u=e.baseState,n===null)e.memoizedState=u;else{l=n.next;var f=i=null,o=null,g=l,S=!1;do{var z=g.lane&-536870913;if(z!==g.lane?(le&z)===z:(Ql&z)===z){var p=g.revertLane;if(p===0)o!==null&&(o=o.next={lane:0,revertLane:0,gesture:null,action:g.action,hasEagerState:g.hasEagerState,eagerState:g.eagerState,next:null}),z===sa&&(S=!0);else if((Ql&p)===p){g=g.next,p===sa&&(S=!0);continue}else z={lane:0,revertLane:g.revertLane,gesture:null,action:g.action,hasEagerState:g.hasEagerState,eagerState:g.eagerState,next:null},o===null?(f=o=z,i=u):o=o.next=z,$.lanes|=p,dt|=p;z=g.action,Gt&&t(u,z),u=g.hasEagerState?g.eagerState:t(u,z)}else p={lane:z,revertLane:g.revertLane,gesture:g.gesture,action:g.action,hasEagerState:g.hasEagerState,eagerState:g.eagerState,next:null},o===null?(f=o=p,i=u):o=o.next=p,$.lanes|=z,dt|=z;g=g.next}while(g!==null&&g!==l);if(o===null?i=u:o.next=f,!il(u,e.memoizedState)&&(Ue=!0,S&&(t=fa,t!==null)))throw t;e.memoizedState=u,e.baseState=i,e.baseQueue=o,a.lastRenderedState=u}return n===null&&(a.lanes=0),[e.memoizedState,a.dispatch]}function Ii(e){var l=De(),t=l.queue;if(t===null)throw Error(r(311));t.lastRenderedReducer=e;var a=t.dispatch,n=t.pending,u=l.memoizedState;if(n!==null){t.pending=null;var i=n=n.next;do u=e(u,i.action),i=i.next;while(i!==n);il(u,l.memoizedState)||(Ue=!0),l.memoizedState=u,l.baseQueue===null&&(l.baseState=u),t.lastRenderedState=u}return[u,a]}function Zf(e,l,t){var a=$,n=De(),u=ne;if(u){if(t===void 0)throw Error(r(407));t=t()}else t=l();var i=!il((me||n).memoizedState,t);if(i&&(n.memoizedState=t,Ue=!0),n=n.queue,lc(wf.bind(null,a,n,e),[e]),n.getSnapshot!==l||i||Ce!==null&&Ce.memoizedState.tag&1){if(a.flags|=2048,ya(9,{destroy:void 0},Vf.bind(null,a,n,t,l),null),pe===null)throw Error(r(349));u||(Ql&127)!==0||Lf(a,l,t)}return t}function Lf(e,l,t){e.flags|=16384,e={getSnapshot:l,value:t},l=$.updateQueue,l===null?(l=nu(),$.updateQueue=l,l.stores=[e]):(t=l.stores,t===null?l.stores=[e]:t.push(e))}function Vf(e,l,t,a){l.value=t,l.getSnapshot=a,Kf(l)&&Jf(e)}function wf(e,l,t){return t(function(){Kf(l)&&Jf(e)})}function Kf(e){var l=e.getSnapshot;e=e.value;try{var t=l();return!il(e,t)}catch{return!0}}function Jf(e){var l=Dt(e,2);l!==null&&tl(l,e,2)}function Pi(e){var l=Ke();if(typeof e=="function"){var t=e;if(e=t(),Gt){Il(!0);try{t()}finally{Il(!1)}}}return l.memoizedState=l.baseState=e,l.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Zl,lastRenderedState:e},l}function kf(e,l,t,a){return e.baseState=t,Fi(e,me,typeof a=="function"?a:Zl)}function am(e,l,t,a,n){if(fu(e))throw Error(r(485));if(e=l.action,e!==null){var u={payload:n,action:e,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(i){u.listeners.push(i)}};x.T!==null?t(!0):u.isTransition=!1,a(u),t=l.pending,t===null?(u.next=l.pending=u,Wf(l,u)):(u.next=t.next,l.pending=t.next=u)}}function Wf(e,l){var t=l.action,a=l.payload,n=e.state;if(l.isTransition){var u=x.T,i={};x.T=i;try{var f=t(n,a),o=x.S;o!==null&&o(i,f),$f(e,l,f)}catch(g){ec(e,l,g)}finally{u!==null&&i.types!==null&&(u.types=i.types),x.T=u}}else try{u=t(n,a),$f(e,l,u)}catch(g){ec(e,l,g)}}function $f(e,l,t){t!==null&&typeof t=="object"&&typeof t.then=="function"?t.then(function(a){Ff(e,l,a)},function(a){return ec(e,l,a)}):Ff(e,l,t)}function Ff(e,l,t){l.status="fulfilled",l.value=t,If(l),e.state=t,l=e.pending,l!==null&&(t=l.next,t===l?e.pending=null:(t=t.next,l.next=t,Wf(e,t)))}function ec(e,l,t){var a=e.pending;if(e.pending=null,a!==null){a=a.next;do l.status="rejected",l.reason=t,If(l),l=l.next;while(l!==a)}e.action=null}function If(e){e=e.listeners;for(var l=0;l<e.length;l++)(0,e[l])()}function Pf(e,l){return l}function eo(e,l){if(ne){var t=pe.formState;if(t!==null){e:{var a=$;if(ne){if(Se){l:{for(var n=Se,u=bl;n.nodeType!==8;){if(!u){n=null;break l}if(n=xl(n.nextSibling),n===null){n=null;break l}}u=n.data,n=u==="F!"||u==="F"?n:null}if(n){Se=xl(n.nextSibling),a=n.data==="F!";break e}}at(a)}a=!1}a&&(l=t[0])}}return t=Ke(),t.memoizedState=t.baseState=l,a={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Pf,lastRenderedState:l},t.queue=a,t=So.bind(null,$,a),a.dispatch=t,a=Pi(!1),u=ic.bind(null,$,!1,a.queue),a=Ke(),n={state:l,dispatch:null,action:e,pending:null},a.queue=n,t=am.bind(null,$,n,u,t),n.dispatch=t,a.memoizedState=e,[l,t,!1]}function lo(e){var l=De();return to(l,me,e)}function to(e,l,t){if(l=Fi(e,l,Pf)[0],e=iu(Zl)[0],typeof l=="object"&&l!==null&&typeof l.then=="function")try{var a=en(l)}catch(i){throw i===oa?$n:i}else a=l;l=De();var n=l.queue,u=n.dispatch;return t!==l.memoizedState&&($.flags|=2048,ya(9,{destroy:void 0},nm.bind(null,n,t),null)),[a,u,e]}function nm(e,l){e.action=l}function ao(e){var l=De(),t=me;if(t!==null)return to(l,t,e);De(),l=l.memoizedState,t=De();var a=t.queue.dispatch;return t.memoizedState=e,[l,a,!1]}function ya(e,l,t,a){return e={tag:e,create:t,deps:a,inst:l,next:null},l=$.updateQueue,l===null&&(l=nu(),$.updateQueue=l),t=l.lastEffect,t===null?l.lastEffect=e.next=e:(a=t.next,t.next=e,e.next=a,l.lastEffect=e),e}function no(){return De().memoizedState}function cu(e,l,t,a){var n=Ke();$.flags|=e,n.memoizedState=ya(1|l,{destroy:void 0},t,a===void 0?null:a)}function su(e,l,t,a){var n=De();a=a===void 0?null:a;var u=n.memoizedState.inst;me!==null&&a!==null&&wi(a,me.memoizedState.deps)?n.memoizedState=ya(l,u,t,a):($.flags|=e,n.memoizedState=ya(1|l,u,t,a))}function uo(e,l){cu(8390656,8,e,l)}function lc(e,l){su(2048,8,e,l)}function um(e){$.flags|=4;var l=$.updateQueue;if(l===null)l=nu(),$.updateQueue=l,l.events=[e];else{var t=l.events;t===null?l.events=[e]:t.push(e)}}function io(e){var l=De().memoizedState;return um({ref:l,nextImpl:e}),function(){if((fe&2)!==0)throw Error(r(440));return l.impl.apply(void 0,arguments)}}function co(e,l){return su(4,2,e,l)}function so(e,l){return su(4,4,e,l)}function fo(e,l){if(typeof l=="function"){e=e();var t=l(e);return function(){typeof t=="function"?t():l(null)}}if(l!=null)return e=e(),l.current=e,function(){l.current=null}}function oo(e,l,t){t=t!=null?t.concat([e]):null,su(4,4,fo.bind(null,l,e),t)}function tc(){}function ro(e,l){var t=De();l=l===void 0?null:l;var a=t.memoizedState;return l!==null&&wi(l,a[1])?a[0]:(t.memoizedState=[e,l],e)}function ho(e,l){var t=De();l=l===void 0?null:l;var a=t.memoizedState;if(l!==null&&wi(l,a[1]))return a[0];if(a=e(),Gt){Il(!0);try{e()}finally{Il(!1)}}return t.memoizedState=[a,l],a}function ac(e,l,t){return t===void 0||(Ql&1073741824)!==0&&(le&261930)===0?e.memoizedState=l:(e.memoizedState=t,e=mr(),$.lanes|=e,dt|=e,t)}function mo(e,l,t,a){return il(t,l)?t:da.current!==null?(e=ac(e,t,a),il(e,l)||(Ue=!0),e):(Ql&42)===0||(Ql&1073741824)!==0&&(le&261930)===0?(Ue=!0,e.memoizedState=t):(e=mr(),$.lanes|=e,dt|=e,l)}function yo(e,l,t,a,n){var u=U.p;U.p=u!==0&&8>u?u:8;var i=x.T,f={};x.T=f,ic(e,!1,l,t);try{var o=n(),g=x.S;if(g!==null&&g(f,o),o!==null&&typeof o=="object"&&typeof o.then=="function"){var S=em(o,a);ln(e,l,S,dl(e))}else ln(e,l,a,dl(e))}catch(z){ln(e,l,{then:function(){},status:"rejected",reason:z},dl())}finally{U.p=u,i!==null&&f.types!==null&&(i.types=f.types),x.T=i}}function im(){}function nc(e,l,t,a){if(e.tag!==5)throw Error(r(476));var n=vo(e).queue;yo(e,n,l,V,t===null?im:function(){return go(e),t(a)})}function vo(e){var l=e.memoizedState;if(l!==null)return l;l={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Zl,lastRenderedState:V},next:null};var t={};return l.next={memoizedState:t,baseState:t,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Zl,lastRenderedState:t},next:null},e.memoizedState=l,e=e.alternate,e!==null&&(e.memoizedState=l),l}function go(e){var l=vo(e);l.next===null&&(l=e.alternate.memoizedState),ln(e,l.next.queue,{},dl())}function uc(){return Qe(bn)}function po(){return De().memoizedState}function bo(){return De().memoizedState}function cm(e){for(var l=e.return;l!==null;){switch(l.tag){case 24:case 3:var t=dl();e=it(t);var a=ct(l,e,t);a!==null&&(tl(a,l,t),$a(a,l,t)),l={cache:Ri()},e.payload=l;return}l=l.return}}function sm(e,l,t){var a=dl();t={lane:a,revertLane:0,gesture:null,action:t,hasEagerState:!1,eagerState:null,next:null},fu(e)?xo(l,t):(t=Ti(e,l,t,a),t!==null&&(tl(t,e,a),jo(t,l,a)))}function So(e,l,t){var a=dl();ln(e,l,t,a)}function ln(e,l,t,a){var n={lane:a,revertLane:0,gesture:null,action:t,hasEagerState:!1,eagerState:null,next:null};if(fu(e))xo(l,n);else{var u=e.alternate;if(e.lanes===0&&(u===null||u.lanes===0)&&(u=l.lastRenderedReducer,u!==null))try{var i=l.lastRenderedState,f=u(i,t);if(n.hasEagerState=!0,n.eagerState=f,il(f,i))return Ln(e,l,n,0),pe===null&&Zn(),!1}catch{}finally{}if(t=Ti(e,l,n,a),t!==null)return tl(t,e,a),jo(t,l,a),!0}return!1}function ic(e,l,t,a){if(a={lane:2,revertLane:Yc(),gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null},fu(e)){if(l)throw Error(r(479))}else l=Ti(e,t,a,2),l!==null&&tl(l,e,2)}function fu(e){var l=e.alternate;return e===$||l!==null&&l===$}function xo(e,l){ha=tu=!0;var t=e.pending;t===null?l.next=l:(l.next=t.next,t.next=l),e.pending=l}function jo(e,l,t){if((t&4194048)!==0){var a=l.lanes;a&=e.pendingLanes,t|=a,l.lanes=t,As(e,t)}}var tn={readContext:Qe,use:uu,useCallback:Ee,useContext:Ee,useEffect:Ee,useImperativeHandle:Ee,useLayoutEffect:Ee,useInsertionEffect:Ee,useMemo:Ee,useReducer:Ee,useRef:Ee,useState:Ee,useDebugValue:Ee,useDeferredValue:Ee,useTransition:Ee,useSyncExternalStore:Ee,useId:Ee,useHostTransitionStatus:Ee,useFormState:Ee,useActionState:Ee,useOptimistic:Ee,useMemoCache:Ee,useCacheRefresh:Ee};tn.useEffectEvent=Ee;var To={readContext:Qe,use:uu,useCallback:function(e,l){return Ke().memoizedState=[e,l===void 0?null:l],e},useContext:Qe,useEffect:uo,useImperativeHandle:function(e,l,t){t=t!=null?t.concat([e]):null,cu(4194308,4,fo.bind(null,l,e),t)},useLayoutEffect:function(e,l){return cu(4194308,4,e,l)},useInsertionEffect:function(e,l){cu(4,2,e,l)},useMemo:function(e,l){var t=Ke();l=l===void 0?null:l;var a=e();if(Gt){Il(!0);try{e()}finally{Il(!1)}}return t.memoizedState=[a,l],a},useReducer:function(e,l,t){var a=Ke();if(t!==void 0){var n=t(l);if(Gt){Il(!0);try{t(l)}finally{Il(!1)}}}else n=l;return a.memoizedState=a.baseState=n,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},a.queue=e,e=e.dispatch=sm.bind(null,$,e),[a.memoizedState,e]},useRef:function(e){var l=Ke();return e={current:e},l.memoizedState=e},useState:function(e){e=Pi(e);var l=e.queue,t=So.bind(null,$,l);return l.dispatch=t,[e.memoizedState,t]},useDebugValue:tc,useDeferredValue:function(e,l){var t=Ke();return ac(t,e,l)},useTransition:function(){var e=Pi(!1);return e=yo.bind(null,$,e.queue,!0,!1),Ke().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,l,t){var a=$,n=Ke();if(ne){if(t===void 0)throw Error(r(407));t=t()}else{if(t=l(),pe===null)throw Error(r(349));(le&127)!==0||Lf(a,l,t)}n.memoizedState=t;var u={value:t,getSnapshot:l};return n.queue=u,uo(wf.bind(null,a,u,e),[e]),a.flags|=2048,ya(9,{destroy:void 0},Vf.bind(null,a,u,t,l),null),t},useId:function(){var e=Ke(),l=pe.identifierPrefix;if(ne){var t=Dl,a=Nl;t=(a&~(1<<32-ul(a)-1)).toString(32)+t,l="_"+l+"R_"+t,t=au++,0<t&&(l+="H"+t.toString(32)),l+="_"}else t=lm++,l="_"+l+"r_"+t.toString(32)+"_";return e.memoizedState=l},useHostTransitionStatus:uc,useFormState:eo,useActionState:eo,useOptimistic:function(e){var l=Ke();l.memoizedState=l.baseState=e;var t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return l.queue=t,l=ic.bind(null,$,!0,t),t.dispatch=l,[e,l]},useMemoCache:$i,useCacheRefresh:function(){return Ke().memoizedState=cm.bind(null,$)},useEffectEvent:function(e){var l=Ke(),t={impl:e};return l.memoizedState=t,function(){if((fe&2)!==0)throw Error(r(440));return t.impl.apply(void 0,arguments)}}},cc={readContext:Qe,use:uu,useCallback:ro,useContext:Qe,useEffect:lc,useImperativeHandle:oo,useInsertionEffect:co,useLayoutEffect:so,useMemo:ho,useReducer:iu,useRef:no,useState:function(){return iu(Zl)},useDebugValue:tc,useDeferredValue:function(e,l){var t=De();return mo(t,me.memoizedState,e,l)},useTransition:function(){var e=iu(Zl)[0],l=De().memoizedState;return[typeof e=="boolean"?e:en(e),l]},useSyncExternalStore:Zf,useId:po,useHostTransitionStatus:uc,useFormState:lo,useActionState:lo,useOptimistic:function(e,l){var t=De();return kf(t,me,e,l)},useMemoCache:$i,useCacheRefresh:bo};cc.useEffectEvent=io;var zo={readContext:Qe,use:uu,useCallback:ro,useContext:Qe,useEffect:lc,useImperativeHandle:oo,useInsertionEffect:co,useLayoutEffect:so,useMemo:ho,useReducer:Ii,useRef:no,useState:function(){return Ii(Zl)},useDebugValue:tc,useDeferredValue:function(e,l){var t=De();return me===null?ac(t,e,l):mo(t,me.memoizedState,e,l)},useTransition:function(){var e=Ii(Zl)[0],l=De().memoizedState;return[typeof e=="boolean"?e:en(e),l]},useSyncExternalStore:Zf,useId:po,useHostTransitionStatus:uc,useFormState:ao,useActionState:ao,useOptimistic:function(e,l){var t=De();return me!==null?kf(t,me,e,l):(t.baseState=e,[e,t.queue.dispatch])},useMemoCache:$i,useCacheRefresh:bo};zo.useEffectEvent=io;function sc(e,l,t,a){l=e.memoizedState,t=t(a,l),t=t==null?l:C({},l,t),e.memoizedState=t,e.lanes===0&&(e.updateQueue.baseState=t)}var fc={enqueueSetState:function(e,l,t){e=e._reactInternals;var a=dl(),n=it(a);n.payload=l,t!=null&&(n.callback=t),l=ct(e,n,a),l!==null&&(tl(l,e,a),$a(l,e,a))},enqueueReplaceState:function(e,l,t){e=e._reactInternals;var a=dl(),n=it(a);n.tag=1,n.payload=l,t!=null&&(n.callback=t),l=ct(e,n,a),l!==null&&(tl(l,e,a),$a(l,e,a))},enqueueForceUpdate:function(e,l){e=e._reactInternals;var t=dl(),a=it(t);a.tag=2,l!=null&&(a.callback=l),l=ct(e,a,t),l!==null&&(tl(l,e,t),$a(l,e,t))}};function Ao(e,l,t,a,n,u,i){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(a,u,i):l.prototype&&l.prototype.isPureReactComponent?!Za(t,a)||!Za(n,u):!0}function Eo(e,l,t,a){e=l.state,typeof l.componentWillReceiveProps=="function"&&l.componentWillReceiveProps(t,a),typeof l.UNSAFE_componentWillReceiveProps=="function"&&l.UNSAFE_componentWillReceiveProps(t,a),l.state!==e&&fc.enqueueReplaceState(l,l.state,null)}function Xt(e,l){var t=l;if("ref"in l){t={};for(var a in l)a!=="ref"&&(t[a]=l[a])}if(e=e.defaultProps){t===l&&(t=C({},t));for(var n in e)t[n]===void 0&&(t[n]=e[n])}return t}function _o(e){Qn(e)}function Oo(e){console.error(e)}function No(e){Qn(e)}function ou(e,l){try{var t=e.onUncaughtError;t(l.value,{componentStack:l.stack})}catch(a){setTimeout(function(){throw a})}}function Do(e,l,t){try{var a=e.onCaughtError;a(t.value,{componentStack:t.stack,errorBoundary:l.tag===1?l.stateNode:null})}catch(n){setTimeout(function(){throw n})}}function oc(e,l,t){return t=it(t),t.tag=3,t.payload={element:null},t.callback=function(){ou(e,l)},t}function Mo(e){return e=it(e),e.tag=3,e}function Co(e,l,t,a){var n=t.type.getDerivedStateFromError;if(typeof n=="function"){var u=a.value;e.payload=function(){return n(u)},e.callback=function(){Do(l,t,a)}}var i=t.stateNode;i!==null&&typeof i.componentDidCatch=="function"&&(e.callback=function(){Do(l,t,a),typeof n!="function"&&(ht===null?ht=new Set([this]):ht.add(this));var f=a.stack;this.componentDidCatch(a.value,{componentStack:f!==null?f:""})})}function fm(e,l,t,a,n){if(t.flags|=32768,a!==null&&typeof a=="object"&&typeof a.then=="function"){if(l=t.alternate,l!==null&&ca(l,t,n,!0),t=sl.current,t!==null){switch(t.tag){case 31:case 13:return Sl===null?ju():t.alternate===null&&_e===0&&(_e=3),t.flags&=-257,t.flags|=65536,t.lanes=n,a===Fn?t.flags|=16384:(l=t.updateQueue,l===null?t.updateQueue=new Set([a]):l.add(a),Hc(e,a,n)),!1;case 22:return t.flags|=65536,a===Fn?t.flags|=16384:(l=t.updateQueue,l===null?(l={transitions:null,markerInstances:null,retryQueue:new Set([a])},t.updateQueue=l):(t=l.retryQueue,t===null?l.retryQueue=new Set([a]):t.add(a)),Hc(e,a,n)),!1}throw Error(r(435,t.tag))}return Hc(e,a,n),ju(),!1}if(ne)return l=sl.current,l!==null?((l.flags&65536)===0&&(l.flags|=256),l.flags|=65536,l.lanes=n,a!==Ni&&(e=Error(r(422),{cause:a}),wa(vl(e,t)))):(a!==Ni&&(l=Error(r(423),{cause:a}),wa(vl(l,t))),e=e.current.alternate,e.flags|=65536,n&=-n,e.lanes|=n,a=vl(a,t),n=oc(e.stateNode,a,n),Xi(e,n),_e!==4&&(_e=2)),!1;var u=Error(r(520),{cause:a});if(u=vl(u,t),rn===null?rn=[u]:rn.push(u),_e!==4&&(_e=2),l===null)return!0;a=vl(a,t),t=l;do{switch(t.tag){case 3:return t.flags|=65536,e=n&-n,t.lanes|=e,e=oc(t.stateNode,a,e),Xi(t,e),!1;case 1:if(l=t.type,u=t.stateNode,(t.flags&128)===0&&(typeof l.getDerivedStateFromError=="function"||u!==null&&typeof u.componentDidCatch=="function"&&(ht===null||!ht.has(u))))return t.flags|=65536,n&=-n,t.lanes|=n,n=Mo(n),Co(n,e,t,a),Xi(t,n),!1}t=t.return}while(t!==null);return!1}var rc=Error(r(461)),Ue=!1;function Ze(e,l,t,a){l.child=e===null?Hf(l,null,t,a):Yt(l,e.child,t,a)}function Uo(e,l,t,a,n){t=t.render;var u=l.ref;if("ref"in a){var i={};for(var f in a)f!=="ref"&&(i[f]=a[f])}else i=a;return Rt(l),a=Ki(e,l,t,i,u,n),f=Ji(),e!==null&&!Ue?(ki(e,l,n),Ll(e,l,n)):(ne&&f&&_i(l),l.flags|=1,Ze(e,l,a,n),l.child)}function Ro(e,l,t,a,n){if(e===null){var u=t.type;return typeof u=="function"&&!zi(u)&&u.defaultProps===void 0&&t.compare===null?(l.tag=15,l.type=u,Ho(e,l,u,a,n)):(e=wn(t.type,null,a,l,l.mode,n),e.ref=l.ref,e.return=l,l.child=e)}if(u=e.child,!bc(e,n)){var i=u.memoizedProps;if(t=t.compare,t=t!==null?t:Za,t(i,a)&&e.ref===l.ref)return Ll(e,l,n)}return l.flags|=1,e=ql(u,a),e.ref=l.ref,e.return=l,l.child=e}function Ho(e,l,t,a,n){if(e!==null){var u=e.memoizedProps;if(Za(u,a)&&e.ref===l.ref)if(Ue=!1,l.pendingProps=a=u,bc(e,n))(e.flags&131072)!==0&&(Ue=!0);else return l.lanes=e.lanes,Ll(e,l,n)}return dc(e,l,t,a,n)}function Bo(e,l,t,a){var n=a.children,u=e!==null?e.memoizedState:null;if(e===null&&l.stateNode===null&&(l.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),a.mode==="hidden"){if((l.flags&128)!==0){if(u=u!==null?u.baseLanes|t:t,e!==null){for(a=l.child=e.child,n=0;a!==null;)n=n|a.lanes|a.childLanes,a=a.sibling;a=n&~u}else a=0,l.child=null;return qo(e,l,u,t,a)}if((t&536870912)!==0)l.memoizedState={baseLanes:0,cachePool:null},e!==null&&Wn(l,u!==null?u.cachePool:null),u!==null?Yf(l,u):Zi(),Gf(l);else return a=l.lanes=536870912,qo(e,l,u!==null?u.baseLanes|t:t,t,a)}else u!==null?(Wn(l,u.cachePool),Yf(l,u),ft(),l.memoizedState=null):(e!==null&&Wn(l,null),Zi(),ft());return Ze(e,l,n,t),l.child}function an(e,l){return e!==null&&e.tag===22||l.stateNode!==null||(l.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),l.sibling}function qo(e,l,t,a,n){var u=Bi();return u=u===null?null:{parent:Me._currentValue,pool:u},l.memoizedState={baseLanes:t,cachePool:u},e!==null&&Wn(l,null),Zi(),Gf(l),e!==null&&ca(e,l,a,!0),l.childLanes=n,null}function ru(e,l){return l=hu({mode:l.mode,children:l.children},e.mode),l.ref=e.ref,e.child=l,l.return=e,l}function Yo(e,l,t){return Yt(l,e.child,null,t),e=ru(l,l.pendingProps),e.flags|=2,fl(l),l.memoizedState=null,e}function om(e,l,t){var a=l.pendingProps,n=(l.flags&128)!==0;if(l.flags&=-129,e===null){if(ne){if(a.mode==="hidden")return e=ru(l,a),l.lanes=536870912,an(null,e);if(Vi(l),(e=Se)?(e=$r(e,bl),e=e!==null&&e.data==="&"?e:null,e!==null&&(l.memoizedState={dehydrated:e,treeContext:lt!==null?{id:Nl,overflow:Dl}:null,retryLane:536870912,hydrationErrors:null},t=Sf(e),t.return=l,l.child=t,Xe=l,Se=null)):e=null,e===null)throw at(l);return l.lanes=536870912,null}return ru(l,a)}var u=e.memoizedState;if(u!==null){var i=u.dehydrated;if(Vi(l),n)if(l.flags&256)l.flags&=-257,l=Yo(e,l,t);else if(l.memoizedState!==null)l.child=e.child,l.flags|=128,l=null;else throw Error(r(558));else if(Ue||ca(e,l,t,!1),n=(t&e.childLanes)!==0,Ue||n){if(a=pe,a!==null&&(i=Es(a,t),i!==0&&i!==u.retryLane))throw u.retryLane=i,Dt(e,i),tl(a,e,i),rc;ju(),l=Yo(e,l,t)}else e=u.treeContext,Se=xl(i.nextSibling),Xe=l,ne=!0,tt=null,bl=!1,e!==null&&Tf(l,e),l=ru(l,a),l.flags|=4096;return l}return e=ql(e.child,{mode:a.mode,children:a.children}),e.ref=l.ref,l.child=e,e.return=l,e}function du(e,l){var t=l.ref;if(t===null)e!==null&&e.ref!==null&&(l.flags|=4194816);else{if(typeof t!="function"&&typeof t!="object")throw Error(r(284));(e===null||e.ref!==t)&&(l.flags|=4194816)}}function dc(e,l,t,a,n){return Rt(l),t=Ki(e,l,t,a,void 0,n),a=Ji(),e!==null&&!Ue?(ki(e,l,n),Ll(e,l,n)):(ne&&a&&_i(l),l.flags|=1,Ze(e,l,t,n),l.child)}function Go(e,l,t,a,n,u){return Rt(l),l.updateQueue=null,t=Qf(l,a,t,n),Xf(e),a=Ji(),e!==null&&!Ue?(ki(e,l,u),Ll(e,l,u)):(ne&&a&&_i(l),l.flags|=1,Ze(e,l,t,u),l.child)}function Xo(e,l,t,a,n){if(Rt(l),l.stateNode===null){var u=aa,i=t.contextType;typeof i=="object"&&i!==null&&(u=Qe(i)),u=new t(a,u),l.memoizedState=u.state!==null&&u.state!==void 0?u.state:null,u.updater=fc,l.stateNode=u,u._reactInternals=l,u=l.stateNode,u.props=a,u.state=l.memoizedState,u.refs={},Yi(l),i=t.contextType,u.context=typeof i=="object"&&i!==null?Qe(i):aa,u.state=l.memoizedState,i=t.getDerivedStateFromProps,typeof i=="function"&&(sc(l,t,i,a),u.state=l.memoizedState),typeof t.getDerivedStateFromProps=="function"||typeof u.getSnapshotBeforeUpdate=="function"||typeof u.UNSAFE_componentWillMount!="function"&&typeof u.componentWillMount!="function"||(i=u.state,typeof u.componentWillMount=="function"&&u.componentWillMount(),typeof u.UNSAFE_componentWillMount=="function"&&u.UNSAFE_componentWillMount(),i!==u.state&&fc.enqueueReplaceState(u,u.state,null),Ia(l,a,u,n),Fa(),u.state=l.memoizedState),typeof u.componentDidMount=="function"&&(l.flags|=4194308),a=!0}else if(e===null){u=l.stateNode;var f=l.memoizedProps,o=Xt(t,f);u.props=o;var g=u.context,S=t.contextType;i=aa,typeof S=="object"&&S!==null&&(i=Qe(S));var z=t.getDerivedStateFromProps;S=typeof z=="function"||typeof u.getSnapshotBeforeUpdate=="function",f=l.pendingProps!==f,S||typeof u.UNSAFE_componentWillReceiveProps!="function"&&typeof u.componentWillReceiveProps!="function"||(f||g!==i)&&Eo(l,u,a,i),ut=!1;var p=l.memoizedState;u.state=p,Ia(l,a,u,n),Fa(),g=l.memoizedState,f||p!==g||ut?(typeof z=="function"&&(sc(l,t,z,a),g=l.memoizedState),(o=ut||Ao(l,t,o,a,p,g,i))?(S||typeof u.UNSAFE_componentWillMount!="function"&&typeof u.componentWillMount!="function"||(typeof u.componentWillMount=="function"&&u.componentWillMount(),typeof u.UNSAFE_componentWillMount=="function"&&u.UNSAFE_componentWillMount()),typeof u.componentDidMount=="function"&&(l.flags|=4194308)):(typeof u.componentDidMount=="function"&&(l.flags|=4194308),l.memoizedProps=a,l.memoizedState=g),u.props=a,u.state=g,u.context=i,a=o):(typeof u.componentDidMount=="function"&&(l.flags|=4194308),a=!1)}else{u=l.stateNode,Gi(e,l),i=l.memoizedProps,S=Xt(t,i),u.props=S,z=l.pendingProps,p=u.context,g=t.contextType,o=aa,typeof g=="object"&&g!==null&&(o=Qe(g)),f=t.getDerivedStateFromProps,(g=typeof f=="function"||typeof u.getSnapshotBeforeUpdate=="function")||typeof u.UNSAFE_componentWillReceiveProps!="function"&&typeof u.componentWillReceiveProps!="function"||(i!==z||p!==o)&&Eo(l,u,a,o),ut=!1,p=l.memoizedState,u.state=p,Ia(l,a,u,n),Fa();var b=l.memoizedState;i!==z||p!==b||ut||e!==null&&e.dependencies!==null&&Jn(e.dependencies)?(typeof f=="function"&&(sc(l,t,f,a),b=l.memoizedState),(S=ut||Ao(l,t,S,a,p,b,o)||e!==null&&e.dependencies!==null&&Jn(e.dependencies))?(g||typeof u.UNSAFE_componentWillUpdate!="function"&&typeof u.componentWillUpdate!="function"||(typeof u.componentWillUpdate=="function"&&u.componentWillUpdate(a,b,o),typeof u.UNSAFE_componentWillUpdate=="function"&&u.UNSAFE_componentWillUpdate(a,b,o)),typeof u.componentDidUpdate=="function"&&(l.flags|=4),typeof u.getSnapshotBeforeUpdate=="function"&&(l.flags|=1024)):(typeof u.componentDidUpdate!="function"||i===e.memoizedProps&&p===e.memoizedState||(l.flags|=4),typeof u.getSnapshotBeforeUpdate!="function"||i===e.memoizedProps&&p===e.memoizedState||(l.flags|=1024),l.memoizedProps=a,l.memoizedState=b),u.props=a,u.state=b,u.context=o,a=S):(typeof u.componentDidUpdate!="function"||i===e.memoizedProps&&p===e.memoizedState||(l.flags|=4),typeof u.getSnapshotBeforeUpdate!="function"||i===e.memoizedProps&&p===e.memoizedState||(l.flags|=1024),a=!1)}return u=a,du(e,l),a=(l.flags&128)!==0,u||a?(u=l.stateNode,t=a&&typeof t.getDerivedStateFromError!="function"?null:u.render(),l.flags|=1,e!==null&&a?(l.child=Yt(l,e.child,null,n),l.child=Yt(l,null,t,n)):Ze(e,l,t,n),l.memoizedState=u.state,e=l.child):e=Ll(e,l,n),e}function Qo(e,l,t,a){return Ct(),l.flags|=256,Ze(e,l,t,a),l.child}var hc={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function mc(e){return{baseLanes:e,cachePool:Nf()}}function yc(e,l,t){return e=e!==null?e.childLanes&~t:0,l&&(e|=rl),e}function Zo(e,l,t){var a=l.pendingProps,n=!1,u=(l.flags&128)!==0,i;if((i=u)||(i=e!==null&&e.memoizedState===null?!1:(Ne.current&2)!==0),i&&(n=!0,l.flags&=-129),i=(l.flags&32)!==0,l.flags&=-33,e===null){if(ne){if(n?st(l):ft(),(e=Se)?(e=$r(e,bl),e=e!==null&&e.data!=="&"?e:null,e!==null&&(l.memoizedState={dehydrated:e,treeContext:lt!==null?{id:Nl,overflow:Dl}:null,retryLane:536870912,hydrationErrors:null},t=Sf(e),t.return=l,l.child=t,Xe=l,Se=null)):e=null,e===null)throw at(l);return Fc(e)?l.lanes=32:l.lanes=536870912,null}var f=a.children;return a=a.fallback,n?(ft(),n=l.mode,f=hu({mode:"hidden",children:f},n),a=Mt(a,n,t,null),f.return=l,a.return=l,f.sibling=a,l.child=f,a=l.child,a.memoizedState=mc(t),a.childLanes=yc(e,i,t),l.memoizedState=hc,an(null,a)):(st(l),vc(l,f))}var o=e.memoizedState;if(o!==null&&(f=o.dehydrated,f!==null)){if(u)l.flags&256?(st(l),l.flags&=-257,l=gc(e,l,t)):l.memoizedState!==null?(ft(),l.child=e.child,l.flags|=128,l=null):(ft(),f=a.fallback,n=l.mode,a=hu({mode:"visible",children:a.children},n),f=Mt(f,n,t,null),f.flags|=2,a.return=l,f.return=l,a.sibling=f,l.child=a,Yt(l,e.child,null,t),a=l.child,a.memoizedState=mc(t),a.childLanes=yc(e,i,t),l.memoizedState=hc,l=an(null,a));else if(st(l),Fc(f)){if(i=f.nextSibling&&f.nextSibling.dataset,i)var g=i.dgst;i=g,a=Error(r(419)),a.stack="",a.digest=i,wa({value:a,source:null,stack:null}),l=gc(e,l,t)}else if(Ue||ca(e,l,t,!1),i=(t&e.childLanes)!==0,Ue||i){if(i=pe,i!==null&&(a=Es(i,t),a!==0&&a!==o.retryLane))throw o.retryLane=a,Dt(e,a),tl(i,e,a),rc;$c(f)||ju(),l=gc(e,l,t)}else $c(f)?(l.flags|=192,l.child=e.child,l=null):(e=o.treeContext,Se=xl(f.nextSibling),Xe=l,ne=!0,tt=null,bl=!1,e!==null&&Tf(l,e),l=vc(l,a.children),l.flags|=4096);return l}return n?(ft(),f=a.fallback,n=l.mode,o=e.child,g=o.sibling,a=ql(o,{mode:"hidden",children:a.children}),a.subtreeFlags=o.subtreeFlags&65011712,g!==null?f=ql(g,f):(f=Mt(f,n,t,null),f.flags|=2),f.return=l,a.return=l,a.sibling=f,l.child=a,an(null,a),a=l.child,f=e.child.memoizedState,f===null?f=mc(t):(n=f.cachePool,n!==null?(o=Me._currentValue,n=n.parent!==o?{parent:o,pool:o}:n):n=Nf(),f={baseLanes:f.baseLanes|t,cachePool:n}),a.memoizedState=f,a.childLanes=yc(e,i,t),l.memoizedState=hc,an(e.child,a)):(st(l),t=e.child,e=t.sibling,t=ql(t,{mode:"visible",children:a.children}),t.return=l,t.sibling=null,e!==null&&(i=l.deletions,i===null?(l.deletions=[e],l.flags|=16):i.push(e)),l.child=t,l.memoizedState=null,t)}function vc(e,l){return l=hu({mode:"visible",children:l},e.mode),l.return=e,e.child=l}function hu(e,l){return e=cl(22,e,null,l),e.lanes=0,e}function gc(e,l,t){return Yt(l,e.child,null,t),e=vc(l,l.pendingProps.children),e.flags|=2,l.memoizedState=null,e}function Lo(e,l,t){e.lanes|=l;var a=e.alternate;a!==null&&(a.lanes|=l),Ci(e.return,l,t)}function pc(e,l,t,a,n,u){var i=e.memoizedState;i===null?e.memoizedState={isBackwards:l,rendering:null,renderingStartTime:0,last:a,tail:t,tailMode:n,treeForkCount:u}:(i.isBackwards=l,i.rendering=null,i.renderingStartTime=0,i.last=a,i.tail=t,i.tailMode=n,i.treeForkCount=u)}function Vo(e,l,t){var a=l.pendingProps,n=a.revealOrder,u=a.tail;a=a.children;var i=Ne.current,f=(i&2)!==0;if(f?(i=i&1|2,l.flags|=128):i&=1,R(Ne,i),Ze(e,l,a,t),a=ne?Va:0,!f&&e!==null&&(e.flags&128)!==0)e:for(e=l.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&Lo(e,t,l);else if(e.tag===19)Lo(e,t,l);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===l)break e;for(;e.sibling===null;){if(e.return===null||e.return===l)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}switch(n){case"forwards":for(t=l.child,n=null;t!==null;)e=t.alternate,e!==null&&lu(e)===null&&(n=t),t=t.sibling;t=n,t===null?(n=l.child,l.child=null):(n=t.sibling,t.sibling=null),pc(l,!1,n,t,u,a);break;case"backwards":case"unstable_legacy-backwards":for(t=null,n=l.child,l.child=null;n!==null;){if(e=n.alternate,e!==null&&lu(e)===null){l.child=n;break}e=n.sibling,n.sibling=t,t=n,n=e}pc(l,!0,t,null,u,a);break;case"together":pc(l,!1,null,null,void 0,a);break;default:l.memoizedState=null}return l.child}function Ll(e,l,t){if(e!==null&&(l.dependencies=e.dependencies),dt|=l.lanes,(t&l.childLanes)===0)if(e!==null){if(ca(e,l,t,!1),(t&l.childLanes)===0)return null}else return null;if(e!==null&&l.child!==e.child)throw Error(r(153));if(l.child!==null){for(e=l.child,t=ql(e,e.pendingProps),l.child=t,t.return=l;e.sibling!==null;)e=e.sibling,t=t.sibling=ql(e,e.pendingProps),t.return=l;t.sibling=null}return l.child}function bc(e,l){return(e.lanes&l)!==0?!0:(e=e.dependencies,!!(e!==null&&Jn(e)))}function rm(e,l,t){switch(l.tag){case 3:we(l,l.stateNode.containerInfo),nt(l,Me,e.memoizedState.cache),Ct();break;case 27:case 5:Na(l);break;case 4:we(l,l.stateNode.containerInfo);break;case 10:nt(l,l.type,l.memoizedProps.value);break;case 31:if(l.memoizedState!==null)return l.flags|=128,Vi(l),null;break;case 13:var a=l.memoizedState;if(a!==null)return a.dehydrated!==null?(st(l),l.flags|=128,null):(t&l.child.childLanes)!==0?Zo(e,l,t):(st(l),e=Ll(e,l,t),e!==null?e.sibling:null);st(l);break;case 19:var n=(e.flags&128)!==0;if(a=(t&l.childLanes)!==0,a||(ca(e,l,t,!1),a=(t&l.childLanes)!==0),n){if(a)return Vo(e,l,t);l.flags|=128}if(n=l.memoizedState,n!==null&&(n.rendering=null,n.tail=null,n.lastEffect=null),R(Ne,Ne.current),a)break;return null;case 22:return l.lanes=0,Bo(e,l,t,l.pendingProps);case 24:nt(l,Me,e.memoizedState.cache)}return Ll(e,l,t)}function wo(e,l,t){if(e!==null)if(e.memoizedProps!==l.pendingProps)Ue=!0;else{if(!bc(e,t)&&(l.flags&128)===0)return Ue=!1,rm(e,l,t);Ue=(e.flags&131072)!==0}else Ue=!1,ne&&(l.flags&1048576)!==0&&jf(l,Va,l.index);switch(l.lanes=0,l.tag){case 16:e:{var a=l.pendingProps;if(e=Bt(l.elementType),l.type=e,typeof e=="function")zi(e)?(a=Xt(e,a),l.tag=1,l=Xo(null,l,e,a,t)):(l.tag=0,l=dc(null,l,e,a,t));else{if(e!=null){var n=e.$$typeof;if(n===Ae){l.tag=11,l=Uo(null,l,e,a,t);break e}else if(n===ae){l.tag=14,l=Ro(null,l,e,a,t);break e}}throw l=Ul(e)||e,Error(r(306,l,""))}}return l;case 0:return dc(e,l,l.type,l.pendingProps,t);case 1:return a=l.type,n=Xt(a,l.pendingProps),Xo(e,l,a,n,t);case 3:e:{if(we(l,l.stateNode.containerInfo),e===null)throw Error(r(387));a=l.pendingProps;var u=l.memoizedState;n=u.element,Gi(e,l),Ia(l,a,null,t);var i=l.memoizedState;if(a=i.cache,nt(l,Me,a),a!==u.cache&&Ui(l,[Me],t,!0),Fa(),a=i.element,u.isDehydrated)if(u={element:a,isDehydrated:!1,cache:i.cache},l.updateQueue.baseState=u,l.memoizedState=u,l.flags&256){l=Qo(e,l,a,t);break e}else if(a!==n){n=vl(Error(r(424)),l),wa(n),l=Qo(e,l,a,t);break e}else{switch(e=l.stateNode.containerInfo,e.nodeType){case 9:e=e.body;break;default:e=e.nodeName==="HTML"?e.ownerDocument.body:e}for(Se=xl(e.firstChild),Xe=l,ne=!0,tt=null,bl=!0,t=Hf(l,null,a,t),l.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling}else{if(Ct(),a===n){l=Ll(e,l,t);break e}Ze(e,l,a,t)}l=l.child}return l;case 26:return du(e,l),e===null?(t=td(l.type,null,l.pendingProps,null))?l.memoizedState=t:ne||(t=l.type,e=l.pendingProps,a=Nu(I.current).createElement(t),a[Ge]=l,a[$e]=e,Le(a,t,e),qe(a),l.stateNode=a):l.memoizedState=td(l.type,e.memoizedProps,l.pendingProps,e.memoizedState),null;case 27:return Na(l),e===null&&ne&&(a=l.stateNode=Pr(l.type,l.pendingProps,I.current),Xe=l,bl=!0,n=Se,gt(l.type)?(Ic=n,Se=xl(a.firstChild)):Se=n),Ze(e,l,l.pendingProps.children,t),du(e,l),e===null&&(l.flags|=4194304),l.child;case 5:return e===null&&ne&&((n=a=Se)&&(a=Qm(a,l.type,l.pendingProps,bl),a!==null?(l.stateNode=a,Xe=l,Se=xl(a.firstChild),bl=!1,n=!0):n=!1),n||at(l)),Na(l),n=l.type,u=l.pendingProps,i=e!==null?e.memoizedProps:null,a=u.children,Jc(n,u)?a=null:i!==null&&Jc(n,i)&&(l.flags|=32),l.memoizedState!==null&&(n=Ki(e,l,tm,null,null,t),bn._currentValue=n),du(e,l),Ze(e,l,a,t),l.child;case 6:return e===null&&ne&&((e=t=Se)&&(t=Zm(t,l.pendingProps,bl),t!==null?(l.stateNode=t,Xe=l,Se=null,e=!0):e=!1),e||at(l)),null;case 13:return Zo(e,l,t);case 4:return we(l,l.stateNode.containerInfo),a=l.pendingProps,e===null?l.child=Yt(l,null,a,t):Ze(e,l,a,t),l.child;case 11:return Uo(e,l,l.type,l.pendingProps,t);case 7:return Ze(e,l,l.pendingProps,t),l.child;case 8:return Ze(e,l,l.pendingProps.children,t),l.child;case 12:return Ze(e,l,l.pendingProps.children,t),l.child;case 10:return a=l.pendingProps,nt(l,l.type,a.value),Ze(e,l,a.children,t),l.child;case 9:return n=l.type._context,a=l.pendingProps.children,Rt(l),n=Qe(n),a=a(n),l.flags|=1,Ze(e,l,a,t),l.child;case 14:return Ro(e,l,l.type,l.pendingProps,t);case 15:return Ho(e,l,l.type,l.pendingProps,t);case 19:return Vo(e,l,t);case 31:return om(e,l,t);case 22:return Bo(e,l,t,l.pendingProps);case 24:return Rt(l),a=Qe(Me),e===null?(n=Bi(),n===null&&(n=pe,u=Ri(),n.pooledCache=u,u.refCount++,u!==null&&(n.pooledCacheLanes|=t),n=u),l.memoizedState={parent:a,cache:n},Yi(l),nt(l,Me,n)):((e.lanes&t)!==0&&(Gi(e,l),Ia(l,null,null,t),Fa()),n=e.memoizedState,u=l.memoizedState,n.parent!==a?(n={parent:a,cache:a},l.memoizedState=n,l.lanes===0&&(l.memoizedState=l.updateQueue.baseState=n),nt(l,Me,a)):(a=u.cache,nt(l,Me,a),a!==n.cache&&Ui(l,[Me],t,!0))),Ze(e,l,l.pendingProps.children,t),l.child;case 29:throw l.pendingProps}throw Error(r(156,l.tag))}function Vl(e){e.flags|=4}function Sc(e,l,t,a,n){if((l=(e.mode&32)!==0)&&(l=!1),l){if(e.flags|=16777216,(n&335544128)===n)if(e.stateNode.complete)e.flags|=8192;else if(pr())e.flags|=8192;else throw qt=Fn,qi}else e.flags&=-16777217}function Ko(e,l){if(l.type!=="stylesheet"||(l.state.loading&4)!==0)e.flags&=-16777217;else if(e.flags|=16777216,!cd(l))if(pr())e.flags|=8192;else throw qt=Fn,qi}function mu(e,l){l!==null&&(e.flags|=4),e.flags&16384&&(l=e.tag!==22?Ts():536870912,e.lanes|=l,ba|=l)}function nn(e,l){if(!ne)switch(e.tailMode){case"hidden":l=e.tail;for(var t=null;l!==null;)l.alternate!==null&&(t=l),l=l.sibling;t===null?e.tail=null:t.sibling=null;break;case"collapsed":t=e.tail;for(var a=null;t!==null;)t.alternate!==null&&(a=t),t=t.sibling;a===null?l||e.tail===null?e.tail=null:e.tail.sibling=null:a.sibling=null}}function xe(e){var l=e.alternate!==null&&e.alternate.child===e.child,t=0,a=0;if(l)for(var n=e.child;n!==null;)t|=n.lanes|n.childLanes,a|=n.subtreeFlags&65011712,a|=n.flags&65011712,n.return=e,n=n.sibling;else for(n=e.child;n!==null;)t|=n.lanes|n.childLanes,a|=n.subtreeFlags,a|=n.flags,n.return=e,n=n.sibling;return e.subtreeFlags|=a,e.childLanes=t,l}function dm(e,l,t){var a=l.pendingProps;switch(Oi(l),l.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return xe(l),null;case 1:return xe(l),null;case 3:return t=l.stateNode,a=null,e!==null&&(a=e.memoizedState.cache),l.memoizedState.cache!==a&&(l.flags|=2048),Xl(Me),Oe(),t.pendingContext&&(t.context=t.pendingContext,t.pendingContext=null),(e===null||e.child===null)&&(ia(l)?Vl(l):e===null||e.memoizedState.isDehydrated&&(l.flags&256)===0||(l.flags|=1024,Di())),xe(l),null;case 26:var n=l.type,u=l.memoizedState;return e===null?(Vl(l),u!==null?(xe(l),Ko(l,u)):(xe(l),Sc(l,n,null,a,t))):u?u!==e.memoizedState?(Vl(l),xe(l),Ko(l,u)):(xe(l),l.flags&=-16777217):(e=e.memoizedProps,e!==a&&Vl(l),xe(l),Sc(l,n,e,a,t)),null;case 27:if(An(l),t=I.current,n=l.type,e!==null&&l.stateNode!=null)e.memoizedProps!==a&&Vl(l);else{if(!a){if(l.stateNode===null)throw Error(r(166));return xe(l),null}e=G.current,ia(l)?zf(l):(e=Pr(n,a,t),l.stateNode=e,Vl(l))}return xe(l),null;case 5:if(An(l),n=l.type,e!==null&&l.stateNode!=null)e.memoizedProps!==a&&Vl(l);else{if(!a){if(l.stateNode===null)throw Error(r(166));return xe(l),null}if(u=G.current,ia(l))zf(l);else{var i=Nu(I.current);switch(u){case 1:u=i.createElementNS("http://www.w3.org/2000/svg",n);break;case 2:u=i.createElementNS("http://www.w3.org/1998/Math/MathML",n);break;default:switch(n){case"svg":u=i.createElementNS("http://www.w3.org/2000/svg",n);break;case"math":u=i.createElementNS("http://www.w3.org/1998/Math/MathML",n);break;case"script":u=i.createElement("div"),u.innerHTML="<script><\/script>",u=u.removeChild(u.firstChild);break;case"select":u=typeof a.is=="string"?i.createElement("select",{is:a.is}):i.createElement("select"),a.multiple?u.multiple=!0:a.size&&(u.size=a.size);break;default:u=typeof a.is=="string"?i.createElement(n,{is:a.is}):i.createElement(n)}}u[Ge]=l,u[$e]=a;e:for(i=l.child;i!==null;){if(i.tag===5||i.tag===6)u.appendChild(i.stateNode);else if(i.tag!==4&&i.tag!==27&&i.child!==null){i.child.return=i,i=i.child;continue}if(i===l)break e;for(;i.sibling===null;){if(i.return===null||i.return===l)break e;i=i.return}i.sibling.return=i.return,i=i.sibling}l.stateNode=u;e:switch(Le(u,n,a),n){case"button":case"input":case"select":case"textarea":a=!!a.autoFocus;break e;case"img":a=!0;break e;default:a=!1}a&&Vl(l)}}return xe(l),Sc(l,l.type,e===null?null:e.memoizedProps,l.pendingProps,t),null;case 6:if(e&&l.stateNode!=null)e.memoizedProps!==a&&Vl(l);else{if(typeof a!="string"&&l.stateNode===null)throw Error(r(166));if(e=I.current,ia(l)){if(e=l.stateNode,t=l.memoizedProps,a=null,n=Xe,n!==null)switch(n.tag){case 27:case 5:a=n.memoizedProps}e[Ge]=l,e=!!(e.nodeValue===t||a!==null&&a.suppressHydrationWarning===!0||Zr(e.nodeValue,t)),e||at(l,!0)}else e=Nu(e).createTextNode(a),e[Ge]=l,l.stateNode=e}return xe(l),null;case 31:if(t=l.memoizedState,e===null||e.memoizedState!==null){if(a=ia(l),t!==null){if(e===null){if(!a)throw Error(r(318));if(e=l.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(r(557));e[Ge]=l}else Ct(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;xe(l),e=!1}else t=Di(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=t),e=!0;if(!e)return l.flags&256?(fl(l),l):(fl(l),null);if((l.flags&128)!==0)throw Error(r(558))}return xe(l),null;case 13:if(a=l.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(n=ia(l),a!==null&&a.dehydrated!==null){if(e===null){if(!n)throw Error(r(318));if(n=l.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(r(317));n[Ge]=l}else Ct(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;xe(l),n=!1}else n=Di(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),n=!0;if(!n)return l.flags&256?(fl(l),l):(fl(l),null)}return fl(l),(l.flags&128)!==0?(l.lanes=t,l):(t=a!==null,e=e!==null&&e.memoizedState!==null,t&&(a=l.child,n=null,a.alternate!==null&&a.alternate.memoizedState!==null&&a.alternate.memoizedState.cachePool!==null&&(n=a.alternate.memoizedState.cachePool.pool),u=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(u=a.memoizedState.cachePool.pool),u!==n&&(a.flags|=2048)),t!==e&&t&&(l.child.flags|=8192),mu(l,l.updateQueue),xe(l),null);case 4:return Oe(),e===null&&Zc(l.stateNode.containerInfo),xe(l),null;case 10:return Xl(l.type),xe(l),null;case 19:if(E(Ne),a=l.memoizedState,a===null)return xe(l),null;if(n=(l.flags&128)!==0,u=a.rendering,u===null)if(n)nn(a,!1);else{if(_e!==0||e!==null&&(e.flags&128)!==0)for(e=l.child;e!==null;){if(u=lu(e),u!==null){for(l.flags|=128,nn(a,!1),e=u.updateQueue,l.updateQueue=e,mu(l,e),l.subtreeFlags=0,e=t,t=l.child;t!==null;)bf(t,e),t=t.sibling;return R(Ne,Ne.current&1|2),ne&&Yl(l,a.treeForkCount),l.child}e=e.sibling}a.tail!==null&&al()>bu&&(l.flags|=128,n=!0,nn(a,!1),l.lanes=4194304)}else{if(!n)if(e=lu(u),e!==null){if(l.flags|=128,n=!0,e=e.updateQueue,l.updateQueue=e,mu(l,e),nn(a,!0),a.tail===null&&a.tailMode==="hidden"&&!u.alternate&&!ne)return xe(l),null}else 2*al()-a.renderingStartTime>bu&&t!==536870912&&(l.flags|=128,n=!0,nn(a,!1),l.lanes=4194304);a.isBackwards?(u.sibling=l.child,l.child=u):(e=a.last,e!==null?e.sibling=u:l.child=u,a.last=u)}return a.tail!==null?(e=a.tail,a.rendering=e,a.tail=e.sibling,a.renderingStartTime=al(),e.sibling=null,t=Ne.current,R(Ne,n?t&1|2:t&1),ne&&Yl(l,a.treeForkCount),e):(xe(l),null);case 22:case 23:return fl(l),Li(),a=l.memoizedState!==null,e!==null?e.memoizedState!==null!==a&&(l.flags|=8192):a&&(l.flags|=8192),a?(t&536870912)!==0&&(l.flags&128)===0&&(xe(l),l.subtreeFlags&6&&(l.flags|=8192)):xe(l),t=l.updateQueue,t!==null&&mu(l,t.retryQueue),t=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(t=e.memoizedState.cachePool.pool),a=null,l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(a=l.memoizedState.cachePool.pool),a!==t&&(l.flags|=2048),e!==null&&E(Ht),null;case 24:return t=null,e!==null&&(t=e.memoizedState.cache),l.memoizedState.cache!==t&&(l.flags|=2048),Xl(Me),xe(l),null;case 25:return null;case 30:return null}throw Error(r(156,l.tag))}function hm(e,l){switch(Oi(l),l.tag){case 1:return e=l.flags,e&65536?(l.flags=e&-65537|128,l):null;case 3:return Xl(Me),Oe(),e=l.flags,(e&65536)!==0&&(e&128)===0?(l.flags=e&-65537|128,l):null;case 26:case 27:case 5:return An(l),null;case 31:if(l.memoizedState!==null){if(fl(l),l.alternate===null)throw Error(r(340));Ct()}return e=l.flags,e&65536?(l.flags=e&-65537|128,l):null;case 13:if(fl(l),e=l.memoizedState,e!==null&&e.dehydrated!==null){if(l.alternate===null)throw Error(r(340));Ct()}return e=l.flags,e&65536?(l.flags=e&-65537|128,l):null;case 19:return E(Ne),null;case 4:return Oe(),null;case 10:return Xl(l.type),null;case 22:case 23:return fl(l),Li(),e!==null&&E(Ht),e=l.flags,e&65536?(l.flags=e&-65537|128,l):null;case 24:return Xl(Me),null;case 25:return null;default:return null}}function Jo(e,l){switch(Oi(l),l.tag){case 3:Xl(Me),Oe();break;case 26:case 27:case 5:An(l);break;case 4:Oe();break;case 31:l.memoizedState!==null&&fl(l);break;case 13:fl(l);break;case 19:E(Ne);break;case 10:Xl(l.type);break;case 22:case 23:fl(l),Li(),e!==null&&E(Ht);break;case 24:Xl(Me)}}function un(e,l){try{var t=l.updateQueue,a=t!==null?t.lastEffect:null;if(a!==null){var n=a.next;t=n;do{if((t.tag&e)===e){a=void 0;var u=t.create,i=t.inst;a=u(),i.destroy=a}t=t.next}while(t!==n)}}catch(f){de(l,l.return,f)}}function ot(e,l,t){try{var a=l.updateQueue,n=a!==null?a.lastEffect:null;if(n!==null){var u=n.next;a=u;do{if((a.tag&e)===e){var i=a.inst,f=i.destroy;if(f!==void 0){i.destroy=void 0,n=l;var o=t,g=f;try{g()}catch(S){de(n,o,S)}}}a=a.next}while(a!==u)}}catch(S){de(l,l.return,S)}}function ko(e){var l=e.updateQueue;if(l!==null){var t=e.stateNode;try{qf(l,t)}catch(a){de(e,e.return,a)}}}function Wo(e,l,t){t.props=Xt(e.type,e.memoizedProps),t.state=e.memoizedState;try{t.componentWillUnmount()}catch(a){de(e,l,a)}}function cn(e,l){try{var t=e.ref;if(t!==null){switch(e.tag){case 26:case 27:case 5:var a=e.stateNode;break;case 30:a=e.stateNode;break;default:a=e.stateNode}typeof t=="function"?e.refCleanup=t(a):t.current=a}}catch(n){de(e,l,n)}}function Ml(e,l){var t=e.ref,a=e.refCleanup;if(t!==null)if(typeof a=="function")try{a()}catch(n){de(e,l,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof t=="function")try{t(null)}catch(n){de(e,l,n)}else t.current=null}function $o(e){var l=e.type,t=e.memoizedProps,a=e.stateNode;try{e:switch(l){case"button":case"input":case"select":case"textarea":t.autoFocus&&a.focus();break e;case"img":t.src?a.src=t.src:t.srcSet&&(a.srcset=t.srcSet)}}catch(n){de(e,e.return,n)}}function xc(e,l,t){try{var a=e.stateNode;Hm(a,e.type,t,l),a[$e]=l}catch(n){de(e,e.return,n)}}function Fo(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&>(e.type)||e.tag===4}function jc(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Fo(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&>(e.type)||e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Tc(e,l,t){var a=e.tag;if(a===5||a===6)e=e.stateNode,l?(t.nodeType===9?t.body:t.nodeName==="HTML"?t.ownerDocument.body:t).insertBefore(e,l):(l=t.nodeType===9?t.body:t.nodeName==="HTML"?t.ownerDocument.body:t,l.appendChild(e),t=t._reactRootContainer,t!=null||l.onclick!==null||(l.onclick=Hl));else if(a!==4&&(a===27&>(e.type)&&(t=e.stateNode,l=null),e=e.child,e!==null))for(Tc(e,l,t),e=e.sibling;e!==null;)Tc(e,l,t),e=e.sibling}function yu(e,l,t){var a=e.tag;if(a===5||a===6)e=e.stateNode,l?t.insertBefore(e,l):t.appendChild(e);else if(a!==4&&(a===27&>(e.type)&&(t=e.stateNode),e=e.child,e!==null))for(yu(e,l,t),e=e.sibling;e!==null;)yu(e,l,t),e=e.sibling}function Io(e){var l=e.stateNode,t=e.memoizedProps;try{for(var a=e.type,n=l.attributes;n.length;)l.removeAttributeNode(n[0]);Le(l,a,t),l[Ge]=e,l[$e]=t}catch(u){de(e,e.return,u)}}var wl=!1,Re=!1,zc=!1,Po=typeof WeakSet=="function"?WeakSet:Set,Ye=null;function mm(e,l){if(e=e.containerInfo,wc=Bu,e=of(e),gi(e)){if("selectionStart"in e)var t={start:e.selectionStart,end:e.selectionEnd};else e:{t=(t=e.ownerDocument)&&t.defaultView||window;var a=t.getSelection&&t.getSelection();if(a&&a.rangeCount!==0){t=a.anchorNode;var n=a.anchorOffset,u=a.focusNode;a=a.focusOffset;try{t.nodeType,u.nodeType}catch{t=null;break e}var i=0,f=-1,o=-1,g=0,S=0,z=e,p=null;l:for(;;){for(var b;z!==t||n!==0&&z.nodeType!==3||(f=i+n),z!==u||a!==0&&z.nodeType!==3||(o=i+a),z.nodeType===3&&(i+=z.nodeValue.length),(b=z.firstChild)!==null;)p=z,z=b;for(;;){if(z===e)break l;if(p===t&&++g===n&&(f=i),p===u&&++S===a&&(o=i),(b=z.nextSibling)!==null)break;z=p,p=z.parentNode}z=b}t=f===-1||o===-1?null:{start:f,end:o}}else t=null}t=t||{start:0,end:0}}else t=null;for(Kc={focusedElem:e,selectionRange:t},Bu=!1,Ye=l;Ye!==null;)if(l=Ye,e=l.child,(l.subtreeFlags&1028)!==0&&e!==null)e.return=l,Ye=e;else for(;Ye!==null;){switch(l=Ye,u=l.alternate,e=l.flags,l.tag){case 0:if((e&4)!==0&&(e=l.updateQueue,e=e!==null?e.events:null,e!==null))for(t=0;t<e.length;t++)n=e[t],n.ref.impl=n.nextImpl;break;case 11:case 15:break;case 1:if((e&1024)!==0&&u!==null){e=void 0,t=l,n=u.memoizedProps,u=u.memoizedState,a=t.stateNode;try{var q=Xt(t.type,n);e=a.getSnapshotBeforeUpdate(q,u),a.__reactInternalSnapshotBeforeUpdate=e}catch(L){de(t,t.return,L)}}break;case 3:if((e&1024)!==0){if(e=l.stateNode.containerInfo,t=e.nodeType,t===9)Wc(e);else if(t===1)switch(e.nodeName){case"HEAD":case"HTML":case"BODY":Wc(e);break;default:e.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((e&1024)!==0)throw Error(r(163))}if(e=l.sibling,e!==null){e.return=l.return,Ye=e;break}Ye=l.return}}function er(e,l,t){var a=t.flags;switch(t.tag){case 0:case 11:case 15:Jl(e,t),a&4&&un(5,t);break;case 1:if(Jl(e,t),a&4)if(e=t.stateNode,l===null)try{e.componentDidMount()}catch(i){de(t,t.return,i)}else{var n=Xt(t.type,l.memoizedProps);l=l.memoizedState;try{e.componentDidUpdate(n,l,e.__reactInternalSnapshotBeforeUpdate)}catch(i){de(t,t.return,i)}}a&64&&ko(t),a&512&&cn(t,t.return);break;case 3:if(Jl(e,t),a&64&&(e=t.updateQueue,e!==null)){if(l=null,t.child!==null)switch(t.child.tag){case 27:case 5:l=t.child.stateNode;break;case 1:l=t.child.stateNode}try{qf(e,l)}catch(i){de(t,t.return,i)}}break;case 27:l===null&&a&4&&Io(t);case 26:case 5:Jl(e,t),l===null&&a&4&&$o(t),a&512&&cn(t,t.return);break;case 12:Jl(e,t);break;case 31:Jl(e,t),a&4&&ar(e,t);break;case 13:Jl(e,t),a&4&&nr(e,t),a&64&&(e=t.memoizedState,e!==null&&(e=e.dehydrated,e!==null&&(t=Tm.bind(null,t),Lm(e,t))));break;case 22:if(a=t.memoizedState!==null||wl,!a){l=l!==null&&l.memoizedState!==null||Re,n=wl;var u=Re;wl=a,(Re=l)&&!u?kl(e,t,(t.subtreeFlags&8772)!==0):Jl(e,t),wl=n,Re=u}break;case 30:break;default:Jl(e,t)}}function lr(e){var l=e.alternate;l!==null&&(e.alternate=null,lr(l)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(l=e.stateNode,l!==null&&ei(l)),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}var Te=null,Ie=!1;function Kl(e,l,t){for(t=t.child;t!==null;)tr(e,l,t),t=t.sibling}function tr(e,l,t){if(nl&&typeof nl.onCommitFiberUnmount=="function")try{nl.onCommitFiberUnmount(Da,t)}catch{}switch(t.tag){case 26:Re||Ml(t,l),Kl(e,l,t),t.memoizedState?t.memoizedState.count--:t.stateNode&&(t=t.stateNode,t.parentNode.removeChild(t));break;case 27:Re||Ml(t,l);var a=Te,n=Ie;gt(t.type)&&(Te=t.stateNode,Ie=!1),Kl(e,l,t),vn(t.stateNode),Te=a,Ie=n;break;case 5:Re||Ml(t,l);case 6:if(a=Te,n=Ie,Te=null,Kl(e,l,t),Te=a,Ie=n,Te!==null)if(Ie)try{(Te.nodeType===9?Te.body:Te.nodeName==="HTML"?Te.ownerDocument.body:Te).removeChild(t.stateNode)}catch(u){de(t,l,u)}else try{Te.removeChild(t.stateNode)}catch(u){de(t,l,u)}break;case 18:Te!==null&&(Ie?(e=Te,kr(e.nodeType===9?e.body:e.nodeName==="HTML"?e.ownerDocument.body:e,t.stateNode),_a(e)):kr(Te,t.stateNode));break;case 4:a=Te,n=Ie,Te=t.stateNode.containerInfo,Ie=!0,Kl(e,l,t),Te=a,Ie=n;break;case 0:case 11:case 14:case 15:ot(2,t,l),Re||ot(4,t,l),Kl(e,l,t);break;case 1:Re||(Ml(t,l),a=t.stateNode,typeof a.componentWillUnmount=="function"&&Wo(t,l,a)),Kl(e,l,t);break;case 21:Kl(e,l,t);break;case 22:Re=(a=Re)||t.memoizedState!==null,Kl(e,l,t),Re=a;break;default:Kl(e,l,t)}}function ar(e,l){if(l.memoizedState===null&&(e=l.alternate,e!==null&&(e=e.memoizedState,e!==null))){e=e.dehydrated;try{_a(e)}catch(t){de(l,l.return,t)}}}function nr(e,l){if(l.memoizedState===null&&(e=l.alternate,e!==null&&(e=e.memoizedState,e!==null&&(e=e.dehydrated,e!==null))))try{_a(e)}catch(t){de(l,l.return,t)}}function ym(e){switch(e.tag){case 31:case 13:case 19:var l=e.stateNode;return l===null&&(l=e.stateNode=new Po),l;case 22:return e=e.stateNode,l=e._retryCache,l===null&&(l=e._retryCache=new Po),l;default:throw Error(r(435,e.tag))}}function vu(e,l){var t=ym(e);l.forEach(function(a){if(!t.has(a)){t.add(a);var n=zm.bind(null,e,a);a.then(n,n)}})}function Pe(e,l){var t=l.deletions;if(t!==null)for(var a=0;a<t.length;a++){var n=t[a],u=e,i=l,f=i;e:for(;f!==null;){switch(f.tag){case 27:if(gt(f.type)){Te=f.stateNode,Ie=!1;break e}break;case 5:Te=f.stateNode,Ie=!1;break e;case 3:case 4:Te=f.stateNode.containerInfo,Ie=!0;break e}f=f.return}if(Te===null)throw Error(r(160));tr(u,i,n),Te=null,Ie=!1,u=n.alternate,u!==null&&(u.return=null),n.return=null}if(l.subtreeFlags&13886)for(l=l.child;l!==null;)ur(l,e),l=l.sibling}var Al=null;function ur(e,l){var t=e.alternate,a=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:Pe(l,e),el(e),a&4&&(ot(3,e,e.return),un(3,e),ot(5,e,e.return));break;case 1:Pe(l,e),el(e),a&512&&(Re||t===null||Ml(t,t.return)),a&64&&wl&&(e=e.updateQueue,e!==null&&(a=e.callbacks,a!==null&&(t=e.shared.hiddenCallbacks,e.shared.hiddenCallbacks=t===null?a:t.concat(a))));break;case 26:var n=Al;if(Pe(l,e),el(e),a&512&&(Re||t===null||Ml(t,t.return)),a&4){var u=t!==null?t.memoizedState:null;if(a=e.memoizedState,t===null)if(a===null)if(e.stateNode===null){e:{a=e.type,t=e.memoizedProps,n=n.ownerDocument||n;l:switch(a){case"title":u=n.getElementsByTagName("title")[0],(!u||u[Ua]||u[Ge]||u.namespaceURI==="http://www.w3.org/2000/svg"||u.hasAttribute("itemprop"))&&(u=n.createElement(a),n.head.insertBefore(u,n.querySelector("head > title"))),Le(u,a,t),u[Ge]=e,qe(u),a=u;break e;case"link":var i=ud("link","href",n).get(a+(t.href||""));if(i){for(var f=0;f<i.length;f++)if(u=i[f],u.getAttribute("href")===(t.href==null||t.href===""?null:t.href)&&u.getAttribute("rel")===(t.rel==null?null:t.rel)&&u.getAttribute("title")===(t.title==null?null:t.title)&&u.getAttribute("crossorigin")===(t.crossOrigin==null?null:t.crossOrigin)){i.splice(f,1);break l}}u=n.createElement(a),Le(u,a,t),n.head.appendChild(u);break;case"meta":if(i=ud("meta","content",n).get(a+(t.content||""))){for(f=0;f<i.length;f++)if(u=i[f],u.getAttribute("content")===(t.content==null?null:""+t.content)&&u.getAttribute("name")===(t.name==null?null:t.name)&&u.getAttribute("property")===(t.property==null?null:t.property)&&u.getAttribute("http-equiv")===(t.httpEquiv==null?null:t.httpEquiv)&&u.getAttribute("charset")===(t.charSet==null?null:t.charSet)){i.splice(f,1);break l}}u=n.createElement(a),Le(u,a,t),n.head.appendChild(u);break;default:throw Error(r(468,a))}u[Ge]=e,qe(u),a=u}e.stateNode=a}else id(n,e.type,e.stateNode);else e.stateNode=nd(n,a,e.memoizedProps);else u!==a?(u===null?t.stateNode!==null&&(t=t.stateNode,t.parentNode.removeChild(t)):u.count--,a===null?id(n,e.type,e.stateNode):nd(n,a,e.memoizedProps)):a===null&&e.stateNode!==null&&xc(e,e.memoizedProps,t.memoizedProps)}break;case 27:Pe(l,e),el(e),a&512&&(Re||t===null||Ml(t,t.return)),t!==null&&a&4&&xc(e,e.memoizedProps,t.memoizedProps);break;case 5:if(Pe(l,e),el(e),a&512&&(Re||t===null||Ml(t,t.return)),e.flags&32){n=e.stateNode;try{$t(n,"")}catch(q){de(e,e.return,q)}}a&4&&e.stateNode!=null&&(n=e.memoizedProps,xc(e,n,t!==null?t.memoizedProps:n)),a&1024&&(zc=!0);break;case 6:if(Pe(l,e),el(e),a&4){if(e.stateNode===null)throw Error(r(162));a=e.memoizedProps,t=e.stateNode;try{t.nodeValue=a}catch(q){de(e,e.return,q)}}break;case 3:if(Cu=null,n=Al,Al=Du(l.containerInfo),Pe(l,e),Al=n,el(e),a&4&&t!==null&&t.memoizedState.isDehydrated)try{_a(l.containerInfo)}catch(q){de(e,e.return,q)}zc&&(zc=!1,ir(e));break;case 4:a=Al,Al=Du(e.stateNode.containerInfo),Pe(l,e),el(e),Al=a;break;case 12:Pe(l,e),el(e);break;case 31:Pe(l,e),el(e),a&4&&(a=e.updateQueue,a!==null&&(e.updateQueue=null,vu(e,a)));break;case 13:Pe(l,e),el(e),e.child.flags&8192&&e.memoizedState!==null!=(t!==null&&t.memoizedState!==null)&&(pu=al()),a&4&&(a=e.updateQueue,a!==null&&(e.updateQueue=null,vu(e,a)));break;case 22:n=e.memoizedState!==null;var o=t!==null&&t.memoizedState!==null,g=wl,S=Re;if(wl=g||n,Re=S||o,Pe(l,e),Re=S,wl=g,el(e),a&8192)e:for(l=e.stateNode,l._visibility=n?l._visibility&-2:l._visibility|1,n&&(t===null||o||wl||Re||Qt(e)),t=null,l=e;;){if(l.tag===5||l.tag===26){if(t===null){o=t=l;try{if(u=o.stateNode,n)i=u.style,typeof i.setProperty=="function"?i.setProperty("display","none","important"):i.display="none";else{f=o.stateNode;var z=o.memoizedProps.style,p=z!=null&&z.hasOwnProperty("display")?z.display:null;f.style.display=p==null||typeof p=="boolean"?"":(""+p).trim()}}catch(q){de(o,o.return,q)}}}else if(l.tag===6){if(t===null){o=l;try{o.stateNode.nodeValue=n?"":o.memoizedProps}catch(q){de(o,o.return,q)}}}else if(l.tag===18){if(t===null){o=l;try{var b=o.stateNode;n?Wr(b,!0):Wr(o.stateNode,!1)}catch(q){de(o,o.return,q)}}}else if((l.tag!==22&&l.tag!==23||l.memoizedState===null||l===e)&&l.child!==null){l.child.return=l,l=l.child;continue}if(l===e)break e;for(;l.sibling===null;){if(l.return===null||l.return===e)break e;t===l&&(t=null),l=l.return}t===l&&(t=null),l.sibling.return=l.return,l=l.sibling}a&4&&(a=e.updateQueue,a!==null&&(t=a.retryQueue,t!==null&&(a.retryQueue=null,vu(e,t))));break;case 19:Pe(l,e),el(e),a&4&&(a=e.updateQueue,a!==null&&(e.updateQueue=null,vu(e,a)));break;case 30:break;case 21:break;default:Pe(l,e),el(e)}}function el(e){var l=e.flags;if(l&2){try{for(var t,a=e.return;a!==null;){if(Fo(a)){t=a;break}a=a.return}if(t==null)throw Error(r(160));switch(t.tag){case 27:var n=t.stateNode,u=jc(e);yu(e,u,n);break;case 5:var i=t.stateNode;t.flags&32&&($t(i,""),t.flags&=-33);var f=jc(e);yu(e,f,i);break;case 3:case 4:var o=t.stateNode.containerInfo,g=jc(e);Tc(e,g,o);break;default:throw Error(r(161))}}catch(S){de(e,e.return,S)}e.flags&=-3}l&4096&&(e.flags&=-4097)}function ir(e){if(e.subtreeFlags&1024)for(e=e.child;e!==null;){var l=e;ir(l),l.tag===5&&l.flags&1024&&l.stateNode.reset(),e=e.sibling}}function Jl(e,l){if(l.subtreeFlags&8772)for(l=l.child;l!==null;)er(e,l.alternate,l),l=l.sibling}function Qt(e){for(e=e.child;e!==null;){var l=e;switch(l.tag){case 0:case 11:case 14:case 15:ot(4,l,l.return),Qt(l);break;case 1:Ml(l,l.return);var t=l.stateNode;typeof t.componentWillUnmount=="function"&&Wo(l,l.return,t),Qt(l);break;case 27:vn(l.stateNode);case 26:case 5:Ml(l,l.return),Qt(l);break;case 22:l.memoizedState===null&&Qt(l);break;case 30:Qt(l);break;default:Qt(l)}e=e.sibling}}function kl(e,l,t){for(t=t&&(l.subtreeFlags&8772)!==0,l=l.child;l!==null;){var a=l.alternate,n=e,u=l,i=u.flags;switch(u.tag){case 0:case 11:case 15:kl(n,u,t),un(4,u);break;case 1:if(kl(n,u,t),a=u,n=a.stateNode,typeof n.componentDidMount=="function")try{n.componentDidMount()}catch(g){de(a,a.return,g)}if(a=u,n=a.updateQueue,n!==null){var f=a.stateNode;try{var o=n.shared.hiddenCallbacks;if(o!==null)for(n.shared.hiddenCallbacks=null,n=0;n<o.length;n++)Bf(o[n],f)}catch(g){de(a,a.return,g)}}t&&i&64&&ko(u),cn(u,u.return);break;case 27:Io(u);case 26:case 5:kl(n,u,t),t&&a===null&&i&4&&$o(u),cn(u,u.return);break;case 12:kl(n,u,t);break;case 31:kl(n,u,t),t&&i&4&&ar(n,u);break;case 13:kl(n,u,t),t&&i&4&&nr(n,u);break;case 22:u.memoizedState===null&&kl(n,u,t),cn(u,u.return);break;case 30:break;default:kl(n,u,t)}l=l.sibling}}function Ac(e,l){var t=null;e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(t=e.memoizedState.cachePool.pool),e=null,l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(e=l.memoizedState.cachePool.pool),e!==t&&(e!=null&&e.refCount++,t!=null&&Ka(t))}function Ec(e,l){e=null,l.alternate!==null&&(e=l.alternate.memoizedState.cache),l=l.memoizedState.cache,l!==e&&(l.refCount++,e!=null&&Ka(e))}function El(e,l,t,a){if(l.subtreeFlags&10256)for(l=l.child;l!==null;)cr(e,l,t,a),l=l.sibling}function cr(e,l,t,a){var n=l.flags;switch(l.tag){case 0:case 11:case 15:El(e,l,t,a),n&2048&&un(9,l);break;case 1:El(e,l,t,a);break;case 3:El(e,l,t,a),n&2048&&(e=null,l.alternate!==null&&(e=l.alternate.memoizedState.cache),l=l.memoizedState.cache,l!==e&&(l.refCount++,e!=null&&Ka(e)));break;case 12:if(n&2048){El(e,l,t,a),e=l.stateNode;try{var u=l.memoizedProps,i=u.id,f=u.onPostCommit;typeof f=="function"&&f(i,l.alternate===null?"mount":"update",e.passiveEffectDuration,-0)}catch(o){de(l,l.return,o)}}else El(e,l,t,a);break;case 31:El(e,l,t,a);break;case 13:El(e,l,t,a);break;case 23:break;case 22:u=l.stateNode,i=l.alternate,l.memoizedState!==null?u._visibility&2?El(e,l,t,a):sn(e,l):u._visibility&2?El(e,l,t,a):(u._visibility|=2,va(e,l,t,a,(l.subtreeFlags&10256)!==0||!1)),n&2048&&Ac(i,l);break;case 24:El(e,l,t,a),n&2048&&Ec(l.alternate,l);break;default:El(e,l,t,a)}}function va(e,l,t,a,n){for(n=n&&((l.subtreeFlags&10256)!==0||!1),l=l.child;l!==null;){var u=e,i=l,f=t,o=a,g=i.flags;switch(i.tag){case 0:case 11:case 15:va(u,i,f,o,n),un(8,i);break;case 23:break;case 22:var S=i.stateNode;i.memoizedState!==null?S._visibility&2?va(u,i,f,o,n):sn(u,i):(S._visibility|=2,va(u,i,f,o,n)),n&&g&2048&&Ac(i.alternate,i);break;case 24:va(u,i,f,o,n),n&&g&2048&&Ec(i.alternate,i);break;default:va(u,i,f,o,n)}l=l.sibling}}function sn(e,l){if(l.subtreeFlags&10256)for(l=l.child;l!==null;){var t=e,a=l,n=a.flags;switch(a.tag){case 22:sn(t,a),n&2048&&Ac(a.alternate,a);break;case 24:sn(t,a),n&2048&&Ec(a.alternate,a);break;default:sn(t,a)}l=l.sibling}}var fn=8192;function ga(e,l,t){if(e.subtreeFlags&fn)for(e=e.child;e!==null;)sr(e,l,t),e=e.sibling}function sr(e,l,t){switch(e.tag){case 26:ga(e,l,t),e.flags&fn&&e.memoizedState!==null&&ly(t,Al,e.memoizedState,e.memoizedProps);break;case 5:ga(e,l,t);break;case 3:case 4:var a=Al;Al=Du(e.stateNode.containerInfo),ga(e,l,t),Al=a;break;case 22:e.memoizedState===null&&(a=e.alternate,a!==null&&a.memoizedState!==null?(a=fn,fn=16777216,ga(e,l,t),fn=a):ga(e,l,t));break;default:ga(e,l,t)}}function fr(e){var l=e.alternate;if(l!==null&&(e=l.child,e!==null)){l.child=null;do l=e.sibling,e.sibling=null,e=l;while(e!==null)}}function on(e){var l=e.deletions;if((e.flags&16)!==0){if(l!==null)for(var t=0;t<l.length;t++){var a=l[t];Ye=a,rr(a,e)}fr(e)}if(e.subtreeFlags&10256)for(e=e.child;e!==null;)or(e),e=e.sibling}function or(e){switch(e.tag){case 0:case 11:case 15:on(e),e.flags&2048&&ot(9,e,e.return);break;case 3:on(e);break;case 12:on(e);break;case 22:var l=e.stateNode;e.memoizedState!==null&&l._visibility&2&&(e.return===null||e.return.tag!==13)?(l._visibility&=-3,gu(e)):on(e);break;default:on(e)}}function gu(e){var l=e.deletions;if((e.flags&16)!==0){if(l!==null)for(var t=0;t<l.length;t++){var a=l[t];Ye=a,rr(a,e)}fr(e)}for(e=e.child;e!==null;){switch(l=e,l.tag){case 0:case 11:case 15:ot(8,l,l.return),gu(l);break;case 22:t=l.stateNode,t._visibility&2&&(t._visibility&=-3,gu(l));break;default:gu(l)}e=e.sibling}}function rr(e,l){for(;Ye!==null;){var t=Ye;switch(t.tag){case 0:case 11:case 15:ot(8,t,l);break;case 23:case 22:if(t.memoizedState!==null&&t.memoizedState.cachePool!==null){var a=t.memoizedState.cachePool.pool;a!=null&&a.refCount++}break;case 24:Ka(t.memoizedState.cache)}if(a=t.child,a!==null)a.return=t,Ye=a;else e:for(t=e;Ye!==null;){a=Ye;var n=a.sibling,u=a.return;if(lr(a),a===t){Ye=null;break e}if(n!==null){n.return=u,Ye=n;break e}Ye=u}}}var vm={getCacheForType:function(e){var l=Qe(Me),t=l.data.get(e);return t===void 0&&(t=e(),l.data.set(e,t)),t},cacheSignal:function(){return Qe(Me).controller.signal}},gm=typeof WeakMap=="function"?WeakMap:Map,fe=0,pe=null,P=null,le=0,re=0,ol=null,rt=!1,pa=!1,_c=!1,Wl=0,_e=0,dt=0,Zt=0,Oc=0,rl=0,ba=0,rn=null,ll=null,Nc=!1,pu=0,dr=0,bu=1/0,Su=null,ht=null,Be=0,mt=null,Sa=null,$l=0,Dc=0,Mc=null,hr=null,dn=0,Cc=null;function dl(){return(fe&2)!==0&&le!==0?le&-le:x.T!==null?Yc():_s()}function mr(){if(rl===0)if((le&536870912)===0||ne){var e=On;On<<=1,(On&3932160)===0&&(On=262144),rl=e}else rl=536870912;return e=sl.current,e!==null&&(e.flags|=32),rl}function tl(e,l,t){(e===pe&&(re===2||re===9)||e.cancelPendingCommit!==null)&&(xa(e,0),yt(e,le,rl,!1)),Ca(e,t),((fe&2)===0||e!==pe)&&(e===pe&&((fe&2)===0&&(Zt|=t),_e===4&&yt(e,le,rl,!1)),Cl(e))}function yr(e,l,t){if((fe&6)!==0)throw Error(r(327));var a=!t&&(l&127)===0&&(l&e.expiredLanes)===0||Ma(e,l),n=a?Sm(e,l):Rc(e,l,!0),u=a;do{if(n===0){pa&&!a&&yt(e,l,0,!1);break}else{if(t=e.current.alternate,u&&!pm(t)){n=Rc(e,l,!1),u=!1;continue}if(n===2){if(u=l,e.errorRecoveryDisabledLanes&u)var i=0;else i=e.pendingLanes&-536870913,i=i!==0?i:i&536870912?536870912:0;if(i!==0){l=i;e:{var f=e;n=rn;var o=f.current.memoizedState.isDehydrated;if(o&&(xa(f,i).flags|=256),i=Rc(f,i,!1),i!==2){if(_c&&!o){f.errorRecoveryDisabledLanes|=u,Zt|=u,n=4;break e}u=ll,ll=n,u!==null&&(ll===null?ll=u:ll.push.apply(ll,u))}n=i}if(u=!1,n!==2)continue}}if(n===1){xa(e,0),yt(e,l,0,!0);break}e:{switch(a=e,u=n,u){case 0:case 1:throw Error(r(345));case 4:if((l&4194048)!==l)break;case 6:yt(a,l,rl,!rt);break e;case 2:ll=null;break;case 3:case 5:break;default:throw Error(r(329))}if((l&62914560)===l&&(n=pu+300-al(),10<n)){if(yt(a,l,rl,!rt),Dn(a,0,!0)!==0)break e;$l=l,a.timeoutHandle=Kr(vr.bind(null,a,t,ll,Su,Nc,l,rl,Zt,ba,rt,u,"Throttled",-0,0),n);break e}vr(a,t,ll,Su,Nc,l,rl,Zt,ba,rt,u,null,-0,0)}}break}while(!0);Cl(e)}function vr(e,l,t,a,n,u,i,f,o,g,S,z,p,b){if(e.timeoutHandle=-1,z=l.subtreeFlags,z&8192||(z&16785408)===16785408){z={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:Hl},sr(l,u,z);var q=(u&62914560)===u?pu-al():(u&4194048)===u?dr-al():0;if(q=ty(z,q),q!==null){$l=u,e.cancelPendingCommit=q(zr.bind(null,e,l,u,t,a,n,i,f,o,S,z,null,p,b)),yt(e,u,i,!g);return}}zr(e,l,u,t,a,n,i,f,o)}function pm(e){for(var l=e;;){var t=l.tag;if((t===0||t===11||t===15)&&l.flags&16384&&(t=l.updateQueue,t!==null&&(t=t.stores,t!==null)))for(var a=0;a<t.length;a++){var n=t[a],u=n.getSnapshot;n=n.value;try{if(!il(u(),n))return!1}catch{return!1}}if(t=l.child,l.subtreeFlags&16384&&t!==null)t.return=l,l=t;else{if(l===e)break;for(;l.sibling===null;){if(l.return===null||l.return===e)return!0;l=l.return}l.sibling.return=l.return,l=l.sibling}}return!0}function yt(e,l,t,a){l&=~Oc,l&=~Zt,e.suspendedLanes|=l,e.pingedLanes&=~l,a&&(e.warmLanes|=l),a=e.expirationTimes;for(var n=l;0<n;){var u=31-ul(n),i=1<<u;a[u]=-1,n&=~i}t!==0&&zs(e,t,l)}function xu(){return(fe&6)===0?(hn(0),!1):!0}function Uc(){if(P!==null){if(re===0)var e=P.return;else e=P,Gl=Ut=null,Wi(e),ra=null,ka=0,e=P;for(;e!==null;)Jo(e.alternate,e),e=e.return;P=null}}function xa(e,l){var t=e.timeoutHandle;t!==-1&&(e.timeoutHandle=-1,Ym(t)),t=e.cancelPendingCommit,t!==null&&(e.cancelPendingCommit=null,t()),$l=0,Uc(),pe=e,P=t=ql(e.current,null),le=l,re=0,ol=null,rt=!1,pa=Ma(e,l),_c=!1,ba=rl=Oc=Zt=dt=_e=0,ll=rn=null,Nc=!1,(l&8)!==0&&(l|=l&32);var a=e.entangledLanes;if(a!==0)for(e=e.entanglements,a&=l;0<a;){var n=31-ul(a),u=1<<n;l|=e[n],a&=~u}return Wl=l,Zn(),t}function gr(e,l){$=null,x.H=tn,l===oa||l===$n?(l=Cf(),re=3):l===qi?(l=Cf(),re=4):re=l===rc?8:l!==null&&typeof l=="object"&&typeof l.then=="function"?6:1,ol=l,P===null&&(_e=1,ou(e,vl(l,e.current)))}function pr(){var e=sl.current;return e===null?!0:(le&4194048)===le?Sl===null:(le&62914560)===le||(le&536870912)!==0?e===Sl:!1}function br(){var e=x.H;return x.H=tn,e===null?tn:e}function Sr(){var e=x.A;return x.A=vm,e}function ju(){_e=4,rt||(le&4194048)!==le&&sl.current!==null||(pa=!0),(dt&134217727)===0&&(Zt&134217727)===0||pe===null||yt(pe,le,rl,!1)}function Rc(e,l,t){var a=fe;fe|=2;var n=br(),u=Sr();(pe!==e||le!==l)&&(Su=null,xa(e,l)),l=!1;var i=_e;e:do try{if(re!==0&&P!==null){var f=P,o=ol;switch(re){case 8:Uc(),i=6;break e;case 3:case 2:case 9:case 6:sl.current===null&&(l=!0);var g=re;if(re=0,ol=null,ja(e,f,o,g),t&&pa){i=0;break e}break;default:g=re,re=0,ol=null,ja(e,f,o,g)}}bm(),i=_e;break}catch(S){gr(e,S)}while(!0);return l&&e.shellSuspendCounter++,Gl=Ut=null,fe=a,x.H=n,x.A=u,P===null&&(pe=null,le=0,Zn()),i}function bm(){for(;P!==null;)xr(P)}function Sm(e,l){var t=fe;fe|=2;var a=br(),n=Sr();pe!==e||le!==l?(Su=null,bu=al()+500,xa(e,l)):pa=Ma(e,l);e:do try{if(re!==0&&P!==null){l=P;var u=ol;l:switch(re){case 1:re=0,ol=null,ja(e,l,u,1);break;case 2:case 9:if(Df(u)){re=0,ol=null,jr(l);break}l=function(){re!==2&&re!==9||pe!==e||(re=7),Cl(e)},u.then(l,l);break e;case 3:re=7;break e;case 4:re=5;break e;case 7:Df(u)?(re=0,ol=null,jr(l)):(re=0,ol=null,ja(e,l,u,7));break;case 5:var i=null;switch(P.tag){case 26:i=P.memoizedState;case 5:case 27:var f=P;if(i?cd(i):f.stateNode.complete){re=0,ol=null;var o=f.sibling;if(o!==null)P=o;else{var g=f.return;g!==null?(P=g,Tu(g)):P=null}break l}}re=0,ol=null,ja(e,l,u,5);break;case 6:re=0,ol=null,ja(e,l,u,6);break;case 8:Uc(),_e=6;break e;default:throw Error(r(462))}}xm();break}catch(S){gr(e,S)}while(!0);return Gl=Ut=null,x.H=a,x.A=n,fe=t,P!==null?0:(pe=null,le=0,Zn(),_e)}function xm(){for(;P!==null&&!Vd();)xr(P)}function xr(e){var l=wo(e.alternate,e,Wl);e.memoizedProps=e.pendingProps,l===null?Tu(e):P=l}function jr(e){var l=e,t=l.alternate;switch(l.tag){case 15:case 0:l=Go(t,l,l.pendingProps,l.type,void 0,le);break;case 11:l=Go(t,l,l.pendingProps,l.type.render,l.ref,le);break;case 5:Wi(l);default:Jo(t,l),l=P=bf(l,Wl),l=wo(t,l,Wl)}e.memoizedProps=e.pendingProps,l===null?Tu(e):P=l}function ja(e,l,t,a){Gl=Ut=null,Wi(l),ra=null,ka=0;var n=l.return;try{if(fm(e,n,l,t,le)){_e=1,ou(e,vl(t,e.current)),P=null;return}}catch(u){if(n!==null)throw P=n,u;_e=1,ou(e,vl(t,e.current)),P=null;return}l.flags&32768?(ne||a===1?e=!0:pa||(le&536870912)!==0?e=!1:(rt=e=!0,(a===2||a===9||a===3||a===6)&&(a=sl.current,a!==null&&a.tag===13&&(a.flags|=16384))),Tr(l,e)):Tu(l)}function Tu(e){var l=e;do{if((l.flags&32768)!==0){Tr(l,rt);return}e=l.return;var t=dm(l.alternate,l,Wl);if(t!==null){P=t;return}if(l=l.sibling,l!==null){P=l;return}P=l=e}while(l!==null);_e===0&&(_e=5)}function Tr(e,l){do{var t=hm(e.alternate,e);if(t!==null){t.flags&=32767,P=t;return}if(t=e.return,t!==null&&(t.flags|=32768,t.subtreeFlags=0,t.deletions=null),!l&&(e=e.sibling,e!==null)){P=e;return}P=e=t}while(e!==null);_e=6,P=null}function zr(e,l,t,a,n,u,i,f,o){e.cancelPendingCommit=null;do zu();while(Be!==0);if((fe&6)!==0)throw Error(r(327));if(l!==null){if(l===e.current)throw Error(r(177));if(u=l.lanes|l.childLanes,u|=ji,eh(e,t,u,i,f,o),e===pe&&(P=pe=null,le=0),Sa=l,mt=e,$l=t,Dc=u,Mc=n,hr=a,(l.subtreeFlags&10256)!==0||(l.flags&10256)!==0?(e.callbackNode=null,e.callbackPriority=0,Am(En,function(){return Nr(),null})):(e.callbackNode=null,e.callbackPriority=0),a=(l.flags&13878)!==0,(l.subtreeFlags&13878)!==0||a){a=x.T,x.T=null,n=U.p,U.p=2,i=fe,fe|=4;try{mm(e,l,t)}finally{fe=i,U.p=n,x.T=a}}Be=1,Ar(),Er(),_r()}}function Ar(){if(Be===1){Be=0;var e=mt,l=Sa,t=(l.flags&13878)!==0;if((l.subtreeFlags&13878)!==0||t){t=x.T,x.T=null;var a=U.p;U.p=2;var n=fe;fe|=4;try{ur(l,e);var u=Kc,i=of(e.containerInfo),f=u.focusedElem,o=u.selectionRange;if(i!==f&&f&&f.ownerDocument&&ff(f.ownerDocument.documentElement,f)){if(o!==null&&gi(f)){var g=o.start,S=o.end;if(S===void 0&&(S=g),"selectionStart"in f)f.selectionStart=g,f.selectionEnd=Math.min(S,f.value.length);else{var z=f.ownerDocument||document,p=z&&z.defaultView||window;if(p.getSelection){var b=p.getSelection(),q=f.textContent.length,L=Math.min(o.start,q),ve=o.end===void 0?L:Math.min(o.end,q);!b.extend&&L>ve&&(i=ve,ve=L,L=i);var y=sf(f,L),h=sf(f,ve);if(y&&h&&(b.rangeCount!==1||b.anchorNode!==y.node||b.anchorOffset!==y.offset||b.focusNode!==h.node||b.focusOffset!==h.offset)){var v=z.createRange();v.setStart(y.node,y.offset),b.removeAllRanges(),L>ve?(b.addRange(v),b.extend(h.node,h.offset)):(v.setEnd(h.node,h.offset),b.addRange(v))}}}}for(z=[],b=f;b=b.parentNode;)b.nodeType===1&&z.push({element:b,left:b.scrollLeft,top:b.scrollTop});for(typeof f.focus=="function"&&f.focus(),f=0;f<z.length;f++){var j=z[f];j.element.scrollLeft=j.left,j.element.scrollTop=j.top}}Bu=!!wc,Kc=wc=null}finally{fe=n,U.p=a,x.T=t}}e.current=l,Be=2}}function Er(){if(Be===2){Be=0;var e=mt,l=Sa,t=(l.flags&8772)!==0;if((l.subtreeFlags&8772)!==0||t){t=x.T,x.T=null;var a=U.p;U.p=2;var n=fe;fe|=4;try{er(e,l.alternate,l)}finally{fe=n,U.p=a,x.T=t}}Be=3}}function _r(){if(Be===4||Be===3){Be=0,wd();var e=mt,l=Sa,t=$l,a=hr;(l.subtreeFlags&10256)!==0||(l.flags&10256)!==0?Be=5:(Be=0,Sa=mt=null,Or(e,e.pendingLanes));var n=e.pendingLanes;if(n===0&&(ht=null),Iu(t),l=l.stateNode,nl&&typeof nl.onCommitFiberRoot=="function")try{nl.onCommitFiberRoot(Da,l,void 0,(l.current.flags&128)===128)}catch{}if(a!==null){l=x.T,n=U.p,U.p=2,x.T=null;try{for(var u=e.onRecoverableError,i=0;i<a.length;i++){var f=a[i];u(f.value,{componentStack:f.stack})}}finally{x.T=l,U.p=n}}($l&3)!==0&&zu(),Cl(e),n=e.pendingLanes,(t&261930)!==0&&(n&42)!==0?e===Cc?dn++:(dn=0,Cc=e):dn=0,hn(0)}}function Or(e,l){(e.pooledCacheLanes&=l)===0&&(l=e.pooledCache,l!=null&&(e.pooledCache=null,Ka(l)))}function zu(){return Ar(),Er(),_r(),Nr()}function Nr(){if(Be!==5)return!1;var e=mt,l=Dc;Dc=0;var t=Iu($l),a=x.T,n=U.p;try{U.p=32>t?32:t,x.T=null,t=Mc,Mc=null;var u=mt,i=$l;if(Be=0,Sa=mt=null,$l=0,(fe&6)!==0)throw Error(r(331));var f=fe;if(fe|=4,or(u.current),cr(u,u.current,i,t),fe=f,hn(0,!1),nl&&typeof nl.onPostCommitFiberRoot=="function")try{nl.onPostCommitFiberRoot(Da,u)}catch{}return!0}finally{U.p=n,x.T=a,Or(e,l)}}function Dr(e,l,t){l=vl(t,l),l=oc(e.stateNode,l,2),e=ct(e,l,2),e!==null&&(Ca(e,2),Cl(e))}function de(e,l,t){if(e.tag===3)Dr(e,e,t);else for(;l!==null;){if(l.tag===3){Dr(l,e,t);break}else if(l.tag===1){var a=l.stateNode;if(typeof l.type.getDerivedStateFromError=="function"||typeof a.componentDidCatch=="function"&&(ht===null||!ht.has(a))){e=vl(t,e),t=Mo(2),a=ct(l,t,2),a!==null&&(Co(t,a,l,e),Ca(a,2),Cl(a));break}}l=l.return}}function Hc(e,l,t){var a=e.pingCache;if(a===null){a=e.pingCache=new gm;var n=new Set;a.set(l,n)}else n=a.get(l),n===void 0&&(n=new Set,a.set(l,n));n.has(t)||(_c=!0,n.add(t),e=jm.bind(null,e,l,t),l.then(e,e))}function jm(e,l,t){var a=e.pingCache;a!==null&&a.delete(l),e.pingedLanes|=e.suspendedLanes&t,e.warmLanes&=~t,pe===e&&(le&t)===t&&(_e===4||_e===3&&(le&62914560)===le&&300>al()-pu?(fe&2)===0&&xa(e,0):Oc|=t,ba===le&&(ba=0)),Cl(e)}function Mr(e,l){l===0&&(l=Ts()),e=Dt(e,l),e!==null&&(Ca(e,l),Cl(e))}function Tm(e){var l=e.memoizedState,t=0;l!==null&&(t=l.retryLane),Mr(e,t)}function zm(e,l){var t=0;switch(e.tag){case 31:case 13:var a=e.stateNode,n=e.memoizedState;n!==null&&(t=n.retryLane);break;case 19:a=e.stateNode;break;case 22:a=e.stateNode._retryCache;break;default:throw Error(r(314))}a!==null&&a.delete(l),Mr(e,t)}function Am(e,l){return ku(e,l)}var Au=null,Ta=null,Bc=!1,Eu=!1,qc=!1,vt=0;function Cl(e){e!==Ta&&e.next===null&&(Ta===null?Au=Ta=e:Ta=Ta.next=e),Eu=!0,Bc||(Bc=!0,_m())}function hn(e,l){if(!qc&&Eu){qc=!0;do for(var t=!1,a=Au;a!==null;){if(e!==0){var n=a.pendingLanes;if(n===0)var u=0;else{var i=a.suspendedLanes,f=a.pingedLanes;u=(1<<31-ul(42|e)+1)-1,u&=n&~(i&~f),u=u&201326741?u&201326741|1:u?u|2:0}u!==0&&(t=!0,Hr(a,u))}else u=le,u=Dn(a,a===pe?u:0,a.cancelPendingCommit!==null||a.timeoutHandle!==-1),(u&3)===0||Ma(a,u)||(t=!0,Hr(a,u));a=a.next}while(t);qc=!1}}function Em(){Cr()}function Cr(){Eu=Bc=!1;var e=0;vt!==0&&qm()&&(e=vt);for(var l=al(),t=null,a=Au;a!==null;){var n=a.next,u=Ur(a,l);u===0?(a.next=null,t===null?Au=n:t.next=n,n===null&&(Ta=t)):(t=a,(e!==0||(u&3)!==0)&&(Eu=!0)),a=n}Be!==0&&Be!==5||hn(e),vt!==0&&(vt=0)}function Ur(e,l){for(var t=e.suspendedLanes,a=e.pingedLanes,n=e.expirationTimes,u=e.pendingLanes&-62914561;0<u;){var i=31-ul(u),f=1<<i,o=n[i];o===-1?((f&t)===0||(f&a)!==0)&&(n[i]=Pd(f,l)):o<=l&&(e.expiredLanes|=f),u&=~f}if(l=pe,t=le,t=Dn(e,e===l?t:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),a=e.callbackNode,t===0||e===l&&(re===2||re===9)||e.cancelPendingCommit!==null)return a!==null&&a!==null&&Wu(a),e.callbackNode=null,e.callbackPriority=0;if((t&3)===0||Ma(e,t)){if(l=t&-t,l===e.callbackPriority)return l;switch(a!==null&&Wu(a),Iu(t)){case 2:case 8:t=xs;break;case 32:t=En;break;case 268435456:t=js;break;default:t=En}return a=Rr.bind(null,e),t=ku(t,a),e.callbackPriority=l,e.callbackNode=t,l}return a!==null&&a!==null&&Wu(a),e.callbackPriority=2,e.callbackNode=null,2}function Rr(e,l){if(Be!==0&&Be!==5)return e.callbackNode=null,e.callbackPriority=0,null;var t=e.callbackNode;if(zu()&&e.callbackNode!==t)return null;var a=le;return a=Dn(e,e===pe?a:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),a===0?null:(yr(e,a,l),Ur(e,al()),e.callbackNode!=null&&e.callbackNode===t?Rr.bind(null,e):null)}function Hr(e,l){if(zu())return null;yr(e,l,!0)}function _m(){Gm(function(){(fe&6)!==0?ku(Ss,Em):Cr()})}function Yc(){if(vt===0){var e=sa;e===0&&(e=_n,_n<<=1,(_n&261888)===0&&(_n=256)),vt=e}return vt}function Br(e){return e==null||typeof e=="symbol"||typeof e=="boolean"?null:typeof e=="function"?e:Rn(""+e)}function qr(e,l){var t=l.ownerDocument.createElement("input");return t.name=l.name,t.value=l.value,e.id&&t.setAttribute("form",e.id),l.parentNode.insertBefore(t,l),e=new FormData(e),t.parentNode.removeChild(t),e}function Om(e,l,t,a,n){if(l==="submit"&&t&&t.stateNode===n){var u=Br((n[$e]||null).action),i=a.submitter;i&&(l=(l=i[$e]||null)?Br(l.formAction):i.getAttribute("formAction"),l!==null&&(u=l,i=null));var f=new Yn("action","action",null,a,n);e.push({event:f,listeners:[{instance:null,listener:function(){if(a.defaultPrevented){if(vt!==0){var o=i?qr(n,i):new FormData(n);nc(t,{pending:!0,data:o,method:n.method,action:u},null,o)}}else typeof u=="function"&&(f.preventDefault(),o=i?qr(n,i):new FormData(n),nc(t,{pending:!0,data:o,method:n.method,action:u},u,o))},currentTarget:n}]})}}for(var Gc=0;Gc<xi.length;Gc++){var Xc=xi[Gc],Nm=Xc.toLowerCase(),Dm=Xc[0].toUpperCase()+Xc.slice(1);zl(Nm,"on"+Dm)}zl(hf,"onAnimationEnd"),zl(mf,"onAnimationIteration"),zl(yf,"onAnimationStart"),zl("dblclick","onDoubleClick"),zl("focusin","onFocus"),zl("focusout","onBlur"),zl(Kh,"onTransitionRun"),zl(Jh,"onTransitionStart"),zl(kh,"onTransitionCancel"),zl(vf,"onTransitionEnd"),kt("onMouseEnter",["mouseout","mouseover"]),kt("onMouseLeave",["mouseout","mouseover"]),kt("onPointerEnter",["pointerout","pointerover"]),kt("onPointerLeave",["pointerout","pointerover"]),Et("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),Et("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),Et("onBeforeInput",["compositionend","keypress","textInput","paste"]),Et("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),Et("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),Et("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var mn="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),Mm=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(mn));function Yr(e,l){l=(l&4)!==0;for(var t=0;t<e.length;t++){var a=e[t],n=a.event;a=a.listeners;e:{var u=void 0;if(l)for(var i=a.length-1;0<=i;i--){var f=a[i],o=f.instance,g=f.currentTarget;if(f=f.listener,o!==u&&n.isPropagationStopped())break e;u=f,n.currentTarget=g;try{u(n)}catch(S){Qn(S)}n.currentTarget=null,u=o}else for(i=0;i<a.length;i++){if(f=a[i],o=f.instance,g=f.currentTarget,f=f.listener,o!==u&&n.isPropagationStopped())break e;u=f,n.currentTarget=g;try{u(n)}catch(S){Qn(S)}n.currentTarget=null,u=o}}}}function ee(e,l){var t=l[Pu];t===void 0&&(t=l[Pu]=new Set);var a=e+"__bubble";t.has(a)||(Gr(l,e,2,!1),t.add(a))}function Qc(e,l,t){var a=0;l&&(a|=4),Gr(t,e,a,l)}var _u="_reactListening"+Math.random().toString(36).slice(2);function Zc(e){if(!e[_u]){e[_u]=!0,Ds.forEach(function(t){t!=="selectionchange"&&(Mm.has(t)||Qc(t,!1,e),Qc(t,!0,e))});var l=e.nodeType===9?e:e.ownerDocument;l===null||l[_u]||(l[_u]=!0,Qc("selectionchange",!1,l))}}function Gr(e,l,t,a){switch(md(l)){case 2:var n=uy;break;case 8:n=iy;break;default:n=as}t=n.bind(null,l,t,e),n=void 0,!si||l!=="touchstart"&&l!=="touchmove"&&l!=="wheel"||(n=!0),a?n!==void 0?e.addEventListener(l,t,{capture:!0,passive:n}):e.addEventListener(l,t,!0):n!==void 0?e.addEventListener(l,t,{passive:n}):e.addEventListener(l,t,!1)}function Lc(e,l,t,a,n){var u=a;if((l&1)===0&&(l&2)===0&&a!==null)e:for(;;){if(a===null)return;var i=a.tag;if(i===3||i===4){var f=a.stateNode.containerInfo;if(f===n)break;if(i===4)for(i=a.return;i!==null;){var o=i.tag;if((o===3||o===4)&&i.stateNode.containerInfo===n)return;i=i.return}for(;f!==null;){if(i=wt(f),i===null)return;if(o=i.tag,o===5||o===6||o===26||o===27){a=u=i;continue e}f=f.parentNode}}a=a.return}Zs(function(){var g=u,S=ii(t),z=[];e:{var p=gf.get(e);if(p!==void 0){var b=Yn,q=e;switch(e){case"keypress":if(Bn(t)===0)break e;case"keydown":case"keyup":b=zh;break;case"focusin":q="focus",b=di;break;case"focusout":q="blur",b=di;break;case"beforeblur":case"afterblur":b=di;break;case"click":if(t.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":b=ws;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":b=dh;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":b=_h;break;case hf:case mf:case yf:b=yh;break;case vf:b=Nh;break;case"scroll":case"scrollend":b=oh;break;case"wheel":b=Mh;break;case"copy":case"cut":case"paste":b=gh;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":b=Js;break;case"toggle":case"beforetoggle":b=Uh}var L=(l&4)!==0,ve=!L&&(e==="scroll"||e==="scrollend"),y=L?p!==null?p+"Capture":null:p;L=[];for(var h=g,v;h!==null;){var j=h;if(v=j.stateNode,j=j.tag,j!==5&&j!==26&&j!==27||v===null||y===null||(j=Ha(h,y),j!=null&&L.push(yn(h,j,v))),ve)break;h=h.return}0<L.length&&(p=new b(p,q,null,t,S),z.push({event:p,listeners:L}))}}if((l&7)===0){e:{if(p=e==="mouseover"||e==="pointerover",b=e==="mouseout"||e==="pointerout",p&&t!==ui&&(q=t.relatedTarget||t.fromElement)&&(wt(q)||q[Vt]))break e;if((b||p)&&(p=S.window===S?S:(p=S.ownerDocument)?p.defaultView||p.parentWindow:window,b?(q=t.relatedTarget||t.toElement,b=g,q=q?wt(q):null,q!==null&&(ve=_(q),L=q.tag,q!==ve||L!==5&&L!==27&&L!==6)&&(q=null)):(b=null,q=g),b!==q)){if(L=ws,j="onMouseLeave",y="onMouseEnter",h="mouse",(e==="pointerout"||e==="pointerover")&&(L=Js,j="onPointerLeave",y="onPointerEnter",h="pointer"),ve=b==null?p:Ra(b),v=q==null?p:Ra(q),p=new L(j,h+"leave",b,t,S),p.target=ve,p.relatedTarget=v,j=null,wt(S)===g&&(L=new L(y,h+"enter",q,t,S),L.target=v,L.relatedTarget=ve,j=L),ve=j,b&&q)l:{for(L=Cm,y=b,h=q,v=0,j=y;j;j=L(j))v++;j=0;for(var Q=h;Q;Q=L(Q))j++;for(;0<v-j;)y=L(y),v--;for(;0<j-v;)h=L(h),j--;for(;v--;){if(y===h||h!==null&&y===h.alternate){L=y;break l}y=L(y),h=L(h)}L=null}else L=null;b!==null&&Xr(z,p,b,L,!1),q!==null&&ve!==null&&Xr(z,ve,q,L,!0)}}e:{if(p=g?Ra(g):window,b=p.nodeName&&p.nodeName.toLowerCase(),b==="select"||b==="input"&&p.type==="file")var ce=lf;else if(Ps(p))if(tf)ce=Lh;else{ce=Qh;var X=Xh}else b=p.nodeName,!b||b.toLowerCase()!=="input"||p.type!=="checkbox"&&p.type!=="radio"?g&&ni(g.elementType)&&(ce=lf):ce=Zh;if(ce&&(ce=ce(e,g))){ef(z,ce,t,S);break e}X&&X(e,p,g),e==="focusout"&&g&&p.type==="number"&&g.memoizedProps.value!=null&&ai(p,"number",p.value)}switch(X=g?Ra(g):window,e){case"focusin":(Ps(X)||X.contentEditable==="true")&&(ea=X,pi=g,La=null);break;case"focusout":La=pi=ea=null;break;case"mousedown":bi=!0;break;case"contextmenu":case"mouseup":case"dragend":bi=!1,rf(z,t,S);break;case"selectionchange":if(wh)break;case"keydown":case"keyup":rf(z,t,S)}var F;if(mi)e:{switch(e){case"compositionstart":var te="onCompositionStart";break e;case"compositionend":te="onCompositionEnd";break e;case"compositionupdate":te="onCompositionUpdate";break e}te=void 0}else Pt?Fs(e,t)&&(te="onCompositionEnd"):e==="keydown"&&t.keyCode===229&&(te="onCompositionStart");te&&(ks&&t.locale!=="ko"&&(Pt||te!=="onCompositionStart"?te==="onCompositionEnd"&&Pt&&(F=Ls()):(et=S,fi="value"in et?et.value:et.textContent,Pt=!0)),X=Ou(g,te),0<X.length&&(te=new Ks(te,e,null,t,S),z.push({event:te,listeners:X}),F?te.data=F:(F=Is(t),F!==null&&(te.data=F)))),(F=Hh?Bh(e,t):qh(e,t))&&(te=Ou(g,"onBeforeInput"),0<te.length&&(X=new Ks("onBeforeInput","beforeinput",null,t,S),z.push({event:X,listeners:te}),X.data=F)),Om(z,e,g,t,S)}Yr(z,l)})}function yn(e,l,t){return{instance:e,listener:l,currentTarget:t}}function Ou(e,l){for(var t=l+"Capture",a=[];e!==null;){var n=e,u=n.stateNode;if(n=n.tag,n!==5&&n!==26&&n!==27||u===null||(n=Ha(e,t),n!=null&&a.unshift(yn(e,n,u)),n=Ha(e,l),n!=null&&a.push(yn(e,n,u))),e.tag===3)return a;e=e.return}return[]}function Cm(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5&&e.tag!==27);return e||null}function Xr(e,l,t,a,n){for(var u=l._reactName,i=[];t!==null&&t!==a;){var f=t,o=f.alternate,g=f.stateNode;if(f=f.tag,o!==null&&o===a)break;f!==5&&f!==26&&f!==27||g===null||(o=g,n?(g=Ha(t,u),g!=null&&i.unshift(yn(t,g,o))):n||(g=Ha(t,u),g!=null&&i.push(yn(t,g,o)))),t=t.return}i.length!==0&&e.push({event:l,listeners:i})}var Um=/\r\n?/g,Rm=/\u0000|\uFFFD/g;function Qr(e){return(typeof e=="string"?e:""+e).replace(Um,`+`).replace(Rm,"")}function Zr(e,l){return l=Qr(l),Qr(e)===l}function ye(e,l,t,a,n,u){switch(t){case"children":typeof a=="string"?l==="body"||l==="textarea"&&a===""||$t(e,a):(typeof a=="number"||typeof a=="bigint")&&l!=="body"&&$t(e,""+a);break;case"className":Cn(e,"class",a);break;case"tabIndex":Cn(e,"tabindex",a);break;case"dir":case"role":case"viewBox":case"width":case"height":Cn(e,t,a);break;case"style":Xs(e,a,u);break;case"data":if(l!=="object"){Cn(e,"data",a);break}case"src":case"href":if(a===""&&(l!=="a"||t!=="href")){e.removeAttribute(t);break}if(a==null||typeof a=="function"||typeof a=="symbol"||typeof a=="boolean"){e.removeAttribute(t);break}a=Rn(""+a),e.setAttribute(t,a);break;case"action":case"formAction":if(typeof a=="function"){e.setAttribute(t,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof u=="function"&&(t==="formAction"?(l!=="input"&&ye(e,l,"name",n.name,n,null),ye(e,l,"formEncType",n.formEncType,n,null),ye(e,l,"formMethod",n.formMethod,n,null),ye(e,l,"formTarget",n.formTarget,n,null)):(ye(e,l,"encType",n.encType,n,null),ye(e,l,"method",n.method,n,null),ye(e,l,"target",n.target,n,null)));if(a==null||typeof a=="symbol"||typeof a=="boolean"){e.removeAttribute(t);break}a=Rn(""+a),e.setAttribute(t,a);break;case"onClick":a!=null&&(e.onclick=Hl);break;case"onScroll":a!=null&&ee("scroll",e);break;case"onScrollEnd":a!=null&&ee("scrollend",e);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(r(61));if(t=a.__html,t!=null){if(n.children!=null)throw Error(r(60));e.innerHTML=t}}break;case"multiple":e.multiple=a&&typeof a!="function"&&typeof a!="symbol";break;case"muted":e.muted=a&&typeof a!="function"&&typeof a!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(a==null||typeof a=="function"||typeof a=="boolean"||typeof a=="symbol"){e.removeAttribute("xlink:href");break}t=Rn(""+a),e.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",t);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":a!=null&&typeof a!="function"&&typeof a!="symbol"?e.setAttribute(t,""+a):e.removeAttribute(t);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":a&&typeof a!="function"&&typeof a!="symbol"?e.setAttribute(t,""):e.removeAttribute(t);break;case"capture":case"download":a===!0?e.setAttribute(t,""):a!==!1&&a!=null&&typeof a!="function"&&typeof a!="symbol"?e.setAttribute(t,a):e.removeAttribute(t);break;case"cols":case"rows":case"size":case"span":a!=null&&typeof a!="function"&&typeof a!="symbol"&&!isNaN(a)&&1<=a?e.setAttribute(t,a):e.removeAttribute(t);break;case"rowSpan":case"start":a==null||typeof a=="function"||typeof a=="symbol"||isNaN(a)?e.removeAttribute(t):e.setAttribute(t,a);break;case"popover":ee("beforetoggle",e),ee("toggle",e),Mn(e,"popover",a);break;case"xlinkActuate":Rl(e,"http://www.w3.org/1999/xlink","xlink:actuate",a);break;case"xlinkArcrole":Rl(e,"http://www.w3.org/1999/xlink","xlink:arcrole",a);break;case"xlinkRole":Rl(e,"http://www.w3.org/1999/xlink","xlink:role",a);break;case"xlinkShow":Rl(e,"http://www.w3.org/1999/xlink","xlink:show",a);break;case"xlinkTitle":Rl(e,"http://www.w3.org/1999/xlink","xlink:title",a);break;case"xlinkType":Rl(e,"http://www.w3.org/1999/xlink","xlink:type",a);break;case"xmlBase":Rl(e,"http://www.w3.org/XML/1998/namespace","xml:base",a);break;case"xmlLang":Rl(e,"http://www.w3.org/XML/1998/namespace","xml:lang",a);break;case"xmlSpace":Rl(e,"http://www.w3.org/XML/1998/namespace","xml:space",a);break;case"is":Mn(e,"is",a);break;case"innerText":case"textContent":break;default:(!(2<t.length)||t[0]!=="o"&&t[0]!=="O"||t[1]!=="n"&&t[1]!=="N")&&(t=sh.get(t)||t,Mn(e,t,a))}}function Vc(e,l,t,a,n,u){switch(t){case"style":Xs(e,a,u);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(r(61));if(t=a.__html,t!=null){if(n.children!=null)throw Error(r(60));e.innerHTML=t}}break;case"children":typeof a=="string"?$t(e,a):(typeof a=="number"||typeof a=="bigint")&&$t(e,""+a);break;case"onScroll":a!=null&&ee("scroll",e);break;case"onScrollEnd":a!=null&&ee("scrollend",e);break;case"onClick":a!=null&&(e.onclick=Hl);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!Ms.hasOwnProperty(t))e:{if(t[0]==="o"&&t[1]==="n"&&(n=t.endsWith("Capture"),l=t.slice(2,n?t.length-7:void 0),u=e[$e]||null,u=u!=null?u[t]:null,typeof u=="function"&&e.removeEventListener(l,u,n),typeof a=="function")){typeof u!="function"&&u!==null&&(t in e?e[t]=null:e.hasAttribute(t)&&e.removeAttribute(t)),e.addEventListener(l,a,n);break e}t in e?e[t]=a:a===!0?e.setAttribute(t,""):Mn(e,t,a)}}}function Le(e,l,t){switch(l){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":ee("error",e),ee("load",e);var a=!1,n=!1,u;for(u in t)if(t.hasOwnProperty(u)){var i=t[u];if(i!=null)switch(u){case"src":a=!0;break;case"srcSet":n=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(r(137,l));default:ye(e,l,u,i,t,null)}}n&&ye(e,l,"srcSet",t.srcSet,t,null),a&&ye(e,l,"src",t.src,t,null);return;case"input":ee("invalid",e);var f=u=i=n=null,o=null,g=null;for(a in t)if(t.hasOwnProperty(a)){var S=t[a];if(S!=null)switch(a){case"name":n=S;break;case"type":i=S;break;case"checked":o=S;break;case"defaultChecked":g=S;break;case"value":u=S;break;case"defaultValue":f=S;break;case"children":case"dangerouslySetInnerHTML":if(S!=null)throw Error(r(137,l));break;default:ye(e,l,a,S,t,null)}}Bs(e,u,f,o,g,i,n,!1);return;case"select":ee("invalid",e),a=i=u=null;for(n in t)if(t.hasOwnProperty(n)&&(f=t[n],f!=null))switch(n){case"value":u=f;break;case"defaultValue":i=f;break;case"multiple":a=f;default:ye(e,l,n,f,t,null)}l=u,t=i,e.multiple=!!a,l!=null?Wt(e,!!a,l,!1):t!=null&&Wt(e,!!a,t,!0);return;case"textarea":ee("invalid",e),u=n=a=null;for(i in t)if(t.hasOwnProperty(i)&&(f=t[i],f!=null))switch(i){case"value":a=f;break;case"defaultValue":n=f;break;case"children":u=f;break;case"dangerouslySetInnerHTML":if(f!=null)throw Error(r(91));break;default:ye(e,l,i,f,t,null)}Ys(e,a,n,u);return;case"option":for(o in t)if(t.hasOwnProperty(o)&&(a=t[o],a!=null))switch(o){case"selected":e.selected=a&&typeof a!="function"&&typeof a!="symbol";break;default:ye(e,l,o,a,t,null)}return;case"dialog":ee("beforetoggle",e),ee("toggle",e),ee("cancel",e),ee("close",e);break;case"iframe":case"object":ee("load",e);break;case"video":case"audio":for(a=0;a<mn.length;a++)ee(mn[a],e);break;case"image":ee("error",e),ee("load",e);break;case"details":ee("toggle",e);break;case"embed":case"source":case"link":ee("error",e),ee("load",e);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(g in t)if(t.hasOwnProperty(g)&&(a=t[g],a!=null))switch(g){case"children":case"dangerouslySetInnerHTML":throw Error(r(137,l));default:ye(e,l,g,a,t,null)}return;default:if(ni(l)){for(S in t)t.hasOwnProperty(S)&&(a=t[S],a!==void 0&&Vc(e,l,S,a,t,void 0));return}}for(f in t)t.hasOwnProperty(f)&&(a=t[f],a!=null&&ye(e,l,f,a,t,null))}function Hm(e,l,t,a){switch(l){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var n=null,u=null,i=null,f=null,o=null,g=null,S=null;for(b in t){var z=t[b];if(t.hasOwnProperty(b)&&z!=null)switch(b){case"checked":break;case"value":break;case"defaultValue":o=z;default:a.hasOwnProperty(b)||ye(e,l,b,null,a,z)}}for(var p in a){var b=a[p];if(z=t[p],a.hasOwnProperty(p)&&(b!=null||z!=null))switch(p){case"type":u=b;break;case"name":n=b;break;case"checked":g=b;break;case"defaultChecked":S=b;break;case"value":i=b;break;case"defaultValue":f=b;break;case"children":case"dangerouslySetInnerHTML":if(b!=null)throw Error(r(137,l));break;default:b!==z&&ye(e,l,p,b,a,z)}}ti(e,i,f,o,g,S,u,n);return;case"select":b=i=f=p=null;for(u in t)if(o=t[u],t.hasOwnProperty(u)&&o!=null)switch(u){case"value":break;case"multiple":b=o;default:a.hasOwnProperty(u)||ye(e,l,u,null,a,o)}for(n in a)if(u=a[n],o=t[n],a.hasOwnProperty(n)&&(u!=null||o!=null))switch(n){case"value":p=u;break;case"defaultValue":f=u;break;case"multiple":i=u;default:u!==o&&ye(e,l,n,u,a,o)}l=f,t=i,a=b,p!=null?Wt(e,!!t,p,!1):!!a!=!!t&&(l!=null?Wt(e,!!t,l,!0):Wt(e,!!t,t?[]:"",!1));return;case"textarea":b=p=null;for(f in t)if(n=t[f],t.hasOwnProperty(f)&&n!=null&&!a.hasOwnProperty(f))switch(f){case"value":break;case"children":break;default:ye(e,l,f,null,a,n)}for(i in a)if(n=a[i],u=t[i],a.hasOwnProperty(i)&&(n!=null||u!=null))switch(i){case"value":p=n;break;case"defaultValue":b=n;break;case"children":break;case"dangerouslySetInnerHTML":if(n!=null)throw Error(r(91));break;default:n!==u&&ye(e,l,i,n,a,u)}qs(e,p,b);return;case"option":for(var q in t)if(p=t[q],t.hasOwnProperty(q)&&p!=null&&!a.hasOwnProperty(q))switch(q){case"selected":e.selected=!1;break;default:ye(e,l,q,null,a,p)}for(o in a)if(p=a[o],b=t[o],a.hasOwnProperty(o)&&p!==b&&(p!=null||b!=null))switch(o){case"selected":e.selected=p&&typeof p!="function"&&typeof p!="symbol";break;default:ye(e,l,o,p,a,b)}return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var L in t)p=t[L],t.hasOwnProperty(L)&&p!=null&&!a.hasOwnProperty(L)&&ye(e,l,L,null,a,p);for(g in a)if(p=a[g],b=t[g],a.hasOwnProperty(g)&&p!==b&&(p!=null||b!=null))switch(g){case"children":case"dangerouslySetInnerHTML":if(p!=null)throw Error(r(137,l));break;default:ye(e,l,g,p,a,b)}return;default:if(ni(l)){for(var ve in t)p=t[ve],t.hasOwnProperty(ve)&&p!==void 0&&!a.hasOwnProperty(ve)&&Vc(e,l,ve,void 0,a,p);for(S in a)p=a[S],b=t[S],!a.hasOwnProperty(S)||p===b||p===void 0&&b===void 0||Vc(e,l,S,p,a,b);return}}for(var y in t)p=t[y],t.hasOwnProperty(y)&&p!=null&&!a.hasOwnProperty(y)&&ye(e,l,y,null,a,p);for(z in a)p=a[z],b=t[z],!a.hasOwnProperty(z)||p===b||p==null&&b==null||ye(e,l,z,p,a,b)}function Lr(e){switch(e){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function Bm(){if(typeof performance.getEntriesByType=="function"){for(var e=0,l=0,t=performance.getEntriesByType("resource"),a=0;a<t.length;a++){var n=t[a],u=n.transferSize,i=n.initiatorType,f=n.duration;if(u&&f&&Lr(i)){for(i=0,f=n.responseEnd,a+=1;a<t.length;a++){var o=t[a],g=o.startTime;if(g>f)break;var S=o.transferSize,z=o.initiatorType;S&&Lr(z)&&(o=o.responseEnd,i+=S*(o<f?1:(f-g)/(o-g)))}if(--a,l+=8*(u+i)/(n.duration/1e3),e++,10<e)break}}if(0<e)return l/e/1e6}return navigator.connection&&(e=navigator.connection.downlink,typeof e=="number")?e:5}var wc=null,Kc=null;function Nu(e){return e.nodeType===9?e:e.ownerDocument}function Vr(e){switch(e){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function wr(e,l){if(e===0)switch(l){case"svg":return 1;case"math":return 2;default:return 0}return e===1&&l==="foreignObject"?0:e}function Jc(e,l){return e==="textarea"||e==="noscript"||typeof l.children=="string"||typeof l.children=="number"||typeof l.children=="bigint"||typeof l.dangerouslySetInnerHTML=="object"&&l.dangerouslySetInnerHTML!==null&&l.dangerouslySetInnerHTML.__html!=null}var kc=null;function qm(){var e=window.event;return e&&e.type==="popstate"?e===kc?!1:(kc=e,!0):(kc=null,!1)}var Kr=typeof setTimeout=="function"?setTimeout:void 0,Ym=typeof clearTimeout=="function"?clearTimeout:void 0,Jr=typeof Promise=="function"?Promise:void 0,Gm=typeof queueMicrotask=="function"?queueMicrotask:typeof Jr<"u"?function(e){return Jr.resolve(null).then(e).catch(Xm)}:Kr;function Xm(e){setTimeout(function(){throw e})}function gt(e){return e==="head"}function kr(e,l){var t=l,a=0;do{var n=t.nextSibling;if(e.removeChild(t),n&&n.nodeType===8)if(t=n.data,t==="/$"||t==="/&"){if(a===0){e.removeChild(n),_a(l);return}a--}else if(t==="$"||t==="$?"||t==="$~"||t==="$!"||t==="&")a++;else if(t==="html")vn(e.ownerDocument.documentElement);else if(t==="head"){t=e.ownerDocument.head,vn(t);for(var u=t.firstChild;u;){var i=u.nextSibling,f=u.nodeName;u[Ua]||f==="SCRIPT"||f==="STYLE"||f==="LINK"&&u.rel.toLowerCase()==="stylesheet"||t.removeChild(u),u=i}}else t==="body"&&vn(e.ownerDocument.body);t=n}while(t);_a(l)}function Wr(e,l){var t=e;e=0;do{var a=t.nextSibling;if(t.nodeType===1?l?(t._stashedDisplay=t.style.display,t.style.display="none"):(t.style.display=t._stashedDisplay||"",t.getAttribute("style")===""&&t.removeAttribute("style")):t.nodeType===3&&(l?(t._stashedText=t.nodeValue,t.nodeValue=""):t.nodeValue=t._stashedText||""),a&&a.nodeType===8)if(t=a.data,t==="/$"){if(e===0)break;e--}else t!=="$"&&t!=="$?"&&t!=="$~"&&t!=="$!"||e++;t=a}while(t)}function Wc(e){var l=e.firstChild;for(l&&l.nodeType===10&&(l=l.nextSibling);l;){var t=l;switch(l=l.nextSibling,t.nodeName){case"HTML":case"HEAD":case"BODY":Wc(t),ei(t);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(t.rel.toLowerCase()==="stylesheet")continue}e.removeChild(t)}}function Qm(e,l,t,a){for(;e.nodeType===1;){var n=t;if(e.nodeName.toLowerCase()!==l.toLowerCase()){if(!a&&(e.nodeName!=="INPUT"||e.type!=="hidden"))break}else if(a){if(!e[Ua])switch(l){case"meta":if(!e.hasAttribute("itemprop"))break;return e;case"link":if(u=e.getAttribute("rel"),u==="stylesheet"&&e.hasAttribute("data-precedence"))break;if(u!==n.rel||e.getAttribute("href")!==(n.href==null||n.href===""?null:n.href)||e.getAttribute("crossorigin")!==(n.crossOrigin==null?null:n.crossOrigin)||e.getAttribute("title")!==(n.title==null?null:n.title))break;return e;case"style":if(e.hasAttribute("data-precedence"))break;return e;case"script":if(u=e.getAttribute("src"),(u!==(n.src==null?null:n.src)||e.getAttribute("type")!==(n.type==null?null:n.type)||e.getAttribute("crossorigin")!==(n.crossOrigin==null?null:n.crossOrigin))&&u&&e.hasAttribute("async")&&!e.hasAttribute("itemprop"))break;return e;default:return e}}else if(l==="input"&&e.type==="hidden"){var u=n.name==null?null:""+n.name;if(n.type==="hidden"&&e.getAttribute("name")===u)return e}else return e;if(e=xl(e.nextSibling),e===null)break}return null}function Zm(e,l,t){if(l==="")return null;for(;e.nodeType!==3;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!t||(e=xl(e.nextSibling),e===null))return null;return e}function $r(e,l){for(;e.nodeType!==8;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!l||(e=xl(e.nextSibling),e===null))return null;return e}function $c(e){return e.data==="$?"||e.data==="$~"}function Fc(e){return e.data==="$!"||e.data==="$?"&&e.ownerDocument.readyState!=="loading"}function Lm(e,l){var t=e.ownerDocument;if(e.data==="$~")e._reactRetry=l;else if(e.data!=="$?"||t.readyState!=="loading")l();else{var a=function(){l(),t.removeEventListener("DOMContentLoaded",a)};t.addEventListener("DOMContentLoaded",a),e._reactRetry=a}}function xl(e){for(;e!=null;e=e.nextSibling){var l=e.nodeType;if(l===1||l===3)break;if(l===8){if(l=e.data,l==="$"||l==="$!"||l==="$?"||l==="$~"||l==="&"||l==="F!"||l==="F")break;if(l==="/$"||l==="/&")return null}}return e}var Ic=null;function Fr(e){e=e.nextSibling;for(var l=0;e;){if(e.nodeType===8){var t=e.data;if(t==="/$"||t==="/&"){if(l===0)return xl(e.nextSibling);l--}else t!=="$"&&t!=="$!"&&t!=="$?"&&t!=="$~"&&t!=="&"||l++}e=e.nextSibling}return null}function Ir(e){e=e.previousSibling;for(var l=0;e;){if(e.nodeType===8){var t=e.data;if(t==="$"||t==="$!"||t==="$?"||t==="$~"||t==="&"){if(l===0)return e;l--}else t!=="/$"&&t!=="/&"||l++}e=e.previousSibling}return null}function Pr(e,l,t){switch(l=Nu(t),e){case"html":if(e=l.documentElement,!e)throw Error(r(452));return e;case"head":if(e=l.head,!e)throw Error(r(453));return e;case"body":if(e=l.body,!e)throw Error(r(454));return e;default:throw Error(r(451))}}function vn(e){for(var l=e.attributes;l.length;)e.removeAttributeNode(l[0]);ei(e)}var jl=new Map,ed=new Set;function Du(e){return typeof e.getRootNode=="function"?e.getRootNode():e.nodeType===9?e:e.ownerDocument}var Fl=U.d;U.d={f:Vm,r:wm,D:Km,C:Jm,L:km,m:Wm,X:Fm,S:$m,M:Im};function Vm(){var e=Fl.f(),l=xu();return e||l}function wm(e){var l=Kt(e);l!==null&&l.tag===5&&l.type==="form"?go(l):Fl.r(e)}var za=typeof document>"u"?null:document;function ld(e,l,t){var a=za;if(a&&typeof l=="string"&&l){var n=ml(l);n='link[rel="'+e+'"][href="'+n+'"]',typeof t=="string"&&(n+='[crossorigin="'+t+'"]'),ed.has(n)||(ed.add(n),e={rel:e,crossOrigin:t,href:l},a.querySelector(n)===null&&(l=a.createElement("link"),Le(l,"link",e),qe(l),a.head.appendChild(l)))}}function Km(e){Fl.D(e),ld("dns-prefetch",e,null)}function Jm(e,l){Fl.C(e,l),ld("preconnect",e,l)}function km(e,l,t){Fl.L(e,l,t);var a=za;if(a&&e&&l){var n='link[rel="preload"][as="'+ml(l)+'"]';l==="image"&&t&&t.imageSrcSet?(n+='[imagesrcset="'+ml(t.imageSrcSet)+'"]',typeof t.imageSizes=="string"&&(n+='[imagesizes="'+ml(t.imageSizes)+'"]')):n+='[href="'+ml(e)+'"]';var u=n;switch(l){case"style":u=Aa(e);break;case"script":u=Ea(e)}jl.has(u)||(e=C({rel:"preload",href:l==="image"&&t&&t.imageSrcSet?void 0:e,as:l},t),jl.set(u,e),a.querySelector(n)!==null||l==="style"&&a.querySelector(gn(u))||l==="script"&&a.querySelector(pn(u))||(l=a.createElement("link"),Le(l,"link",e),qe(l),a.head.appendChild(l)))}}function Wm(e,l){Fl.m(e,l);var t=za;if(t&&e){var a=l&&typeof l.as=="string"?l.as:"script",n='link[rel="modulepreload"][as="'+ml(a)+'"][href="'+ml(e)+'"]',u=n;switch(a){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":u=Ea(e)}if(!jl.has(u)&&(e=C({rel:"modulepreload",href:e},l),jl.set(u,e),t.querySelector(n)===null)){switch(a){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(t.querySelector(pn(u)))return}a=t.createElement("link"),Le(a,"link",e),qe(a),t.head.appendChild(a)}}}function $m(e,l,t){Fl.S(e,l,t);var a=za;if(a&&e){var n=Jt(a).hoistableStyles,u=Aa(e);l=l||"default";var i=n.get(u);if(!i){var f={loading:0,preload:null};if(i=a.querySelector(gn(u)))f.loading=5;else{e=C({rel:"stylesheet",href:e,"data-precedence":l},t),(t=jl.get(u))&&Pc(e,t);var o=i=a.createElement("link");qe(o),Le(o,"link",e),o._p=new Promise(function(g,S){o.onload=g,o.onerror=S}),o.addEventListener("load",function(){f.loading|=1}),o.addEventListener("error",function(){f.loading|=2}),f.loading|=4,Mu(i,l,a)}i={type:"stylesheet",instance:i,count:1,state:f},n.set(u,i)}}}function Fm(e,l){Fl.X(e,l);var t=za;if(t&&e){var a=Jt(t).hoistableScripts,n=Ea(e),u=a.get(n);u||(u=t.querySelector(pn(n)),u||(e=C({src:e,async:!0},l),(l=jl.get(n))&&es(e,l),u=t.createElement("script"),qe(u),Le(u,"link",e),t.head.appendChild(u)),u={type:"script",instance:u,count:1,state:null},a.set(n,u))}}function Im(e,l){Fl.M(e,l);var t=za;if(t&&e){var a=Jt(t).hoistableScripts,n=Ea(e),u=a.get(n);u||(u=t.querySelector(pn(n)),u||(e=C({src:e,async:!0,type:"module"},l),(l=jl.get(n))&&es(e,l),u=t.createElement("script"),qe(u),Le(u,"link",e),t.head.appendChild(u)),u={type:"script",instance:u,count:1,state:null},a.set(n,u))}}function td(e,l,t,a){var n=(n=I.current)?Du(n):null;if(!n)throw Error(r(446));switch(e){case"meta":case"title":return null;case"style":return typeof t.precedence=="string"&&typeof t.href=="string"?(l=Aa(t.href),t=Jt(n).hoistableStyles,a=t.get(l),a||(a={type:"style",instance:null,count:0,state:null},t.set(l,a)),a):{type:"void",instance:null,count:0,state:null};case"link":if(t.rel==="stylesheet"&&typeof t.href=="string"&&typeof t.precedence=="string"){e=Aa(t.href);var u=Jt(n).hoistableStyles,i=u.get(e);if(i||(n=n.ownerDocument||n,i={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},u.set(e,i),(u=n.querySelector(gn(e)))&&!u._p&&(i.instance=u,i.state.loading=5),jl.has(e)||(t={rel:"preload",as:"style",href:t.href,crossOrigin:t.crossOrigin,integrity:t.integrity,media:t.media,hrefLang:t.hrefLang,referrerPolicy:t.referrerPolicy},jl.set(e,t),u||Pm(n,e,t,i.state))),l&&a===null)throw Error(r(528,""));return i}if(l&&a!==null)throw Error(r(529,""));return null;case"script":return l=t.async,t=t.src,typeof t=="string"&&l&&typeof l!="function"&&typeof l!="symbol"?(l=Ea(t),t=Jt(n).hoistableScripts,a=t.get(l),a||(a={type:"script",instance:null,count:0,state:null},t.set(l,a)),a):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,e))}}function Aa(e){return'href="'+ml(e)+'"'}function gn(e){return'link[rel="stylesheet"]['+e+"]"}function ad(e){return C({},e,{"data-precedence":e.precedence,precedence:null})}function Pm(e,l,t,a){e.querySelector('link[rel="preload"][as="style"]['+l+"]")?a.loading=1:(l=e.createElement("link"),a.preload=l,l.addEventListener("load",function(){return a.loading|=1}),l.addEventListener("error",function(){return a.loading|=2}),Le(l,"link",t),qe(l),e.head.appendChild(l))}function Ea(e){return'[src="'+ml(e)+'"]'}function pn(e){return"script[async]"+e}function nd(e,l,t){if(l.count++,l.instance===null)switch(l.type){case"style":var a=e.querySelector('style[data-href~="'+ml(t.href)+'"]');if(a)return l.instance=a,qe(a),a;var n=C({},t,{"data-href":t.href,"data-precedence":t.precedence,href:null,precedence:null});return a=(e.ownerDocument||e).createElement("style"),qe(a),Le(a,"style",n),Mu(a,t.precedence,e),l.instance=a;case"stylesheet":n=Aa(t.href);var u=e.querySelector(gn(n));if(u)return l.state.loading|=4,l.instance=u,qe(u),u;a=ad(t),(n=jl.get(n))&&Pc(a,n),u=(e.ownerDocument||e).createElement("link"),qe(u);var i=u;return i._p=new Promise(function(f,o){i.onload=f,i.onerror=o}),Le(u,"link",a),l.state.loading|=4,Mu(u,t.precedence,e),l.instance=u;case"script":return u=Ea(t.src),(n=e.querySelector(pn(u)))?(l.instance=n,qe(n),n):(a=t,(n=jl.get(u))&&(a=C({},t),es(a,n)),e=e.ownerDocument||e,n=e.createElement("script"),qe(n),Le(n,"link",a),e.head.appendChild(n),l.instance=n);case"void":return null;default:throw Error(r(443,l.type))}else l.type==="stylesheet"&&(l.state.loading&4)===0&&(a=l.instance,l.state.loading|=4,Mu(a,t.precedence,e));return l.instance}function Mu(e,l,t){for(var a=t.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),n=a.length?a[a.length-1]:null,u=n,i=0;i<a.length;i++){var f=a[i];if(f.dataset.precedence===l)u=f;else if(u!==n)break}u?u.parentNode.insertBefore(e,u.nextSibling):(l=t.nodeType===9?t.head:t,l.insertBefore(e,l.firstChild))}function Pc(e,l){e.crossOrigin==null&&(e.crossOrigin=l.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=l.referrerPolicy),e.title==null&&(e.title=l.title)}function es(e,l){e.crossOrigin==null&&(e.crossOrigin=l.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=l.referrerPolicy),e.integrity==null&&(e.integrity=l.integrity)}var Cu=null;function ud(e,l,t){if(Cu===null){var a=new Map,n=Cu=new Map;n.set(t,a)}else n=Cu,a=n.get(t),a||(a=new Map,n.set(t,a));if(a.has(e))return a;for(a.set(e,null),t=t.getElementsByTagName(e),n=0;n<t.length;n++){var u=t[n];if(!(u[Ua]||u[Ge]||e==="link"&&u.getAttribute("rel")==="stylesheet")&&u.namespaceURI!=="http://www.w3.org/2000/svg"){var i=u.getAttribute(l)||"";i=e+i;var f=a.get(i);f?f.push(u):a.set(i,[u])}}return a}function id(e,l,t){e=e.ownerDocument||e,e.head.insertBefore(t,l==="title"?e.querySelector("head > title"):null)}function ey(e,l,t){if(t===1||l.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof l.precedence!="string"||typeof l.href!="string"||l.href==="")break;return!0;case"link":if(typeof l.rel!="string"||typeof l.href!="string"||l.href===""||l.onLoad||l.onError)break;switch(l.rel){case"stylesheet":return e=l.disabled,typeof l.precedence=="string"&&e==null;default:return!0}case"script":if(l.async&&typeof l.async!="function"&&typeof l.async!="symbol"&&!l.onLoad&&!l.onError&&l.src&&typeof l.src=="string")return!0}return!1}function cd(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function ly(e,l,t,a){if(t.type==="stylesheet"&&(typeof a.media!="string"||matchMedia(a.media).matches!==!1)&&(t.state.loading&4)===0){if(t.instance===null){var n=Aa(a.href),u=l.querySelector(gn(n));if(u){l=u._p,l!==null&&typeof l=="object"&&typeof l.then=="function"&&(e.count++,e=Uu.bind(e),l.then(e,e)),t.state.loading|=4,t.instance=u,qe(u);return}u=l.ownerDocument||l,a=ad(a),(n=jl.get(n))&&Pc(a,n),u=u.createElement("link"),qe(u);var i=u;i._p=new Promise(function(f,o){i.onload=f,i.onerror=o}),Le(u,"link",a),t.instance=u}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(t,l),(l=t.state.preload)&&(t.state.loading&3)===0&&(e.count++,t=Uu.bind(e),l.addEventListener("load",t),l.addEventListener("error",t))}}var ls=0;function ty(e,l){return e.stylesheets&&e.count===0&&Hu(e,e.stylesheets),0<e.count||0<e.imgCount?function(t){var a=setTimeout(function(){if(e.stylesheets&&Hu(e,e.stylesheets),e.unsuspend){var u=e.unsuspend;e.unsuspend=null,u()}},6e4+l);0<e.imgBytes&&ls===0&&(ls=62500*Bm());var n=setTimeout(function(){if(e.waitingForImages=!1,e.count===0&&(e.stylesheets&&Hu(e,e.stylesheets),e.unsuspend)){var u=e.unsuspend;e.unsuspend=null,u()}},(e.imgBytes>ls?50:800)+l);return e.unsuspend=t,function(){e.unsuspend=null,clearTimeout(a),clearTimeout(n)}}:null}function Uu(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Hu(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Ru=null;function Hu(e,l){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Ru=new Map,l.forEach(ay,e),Ru=null,Uu.call(e))}function ay(e,l){if(!(l.state.loading&4)){var t=Ru.get(e);if(t)var a=t.get(null);else{t=new Map,Ru.set(e,t);for(var n=e.querySelectorAll("link[data-precedence],style[data-precedence]"),u=0;u<n.length;u++){var i=n[u];(i.nodeName==="LINK"||i.getAttribute("media")!=="not all")&&(t.set(i.dataset.precedence,i),a=i)}a&&t.set(null,a)}n=l.instance,i=n.getAttribute("data-precedence"),u=t.get(i)||a,u===a&&t.set(null,n),t.set(i,n),this.count++,a=Uu.bind(this),n.addEventListener("load",a),n.addEventListener("error",a),u?u.parentNode.insertBefore(n,u.nextSibling):(e=e.nodeType===9?e.head:e,e.insertBefore(n,e.firstChild)),l.state.loading|=4}}var bn={$$typeof:Z,Provider:null,Consumer:null,_currentValue:V,_currentValue2:V,_threadCount:0};function ny(e,l,t,a,n,u,i,f,o){this.tag=1,this.containerInfo=e,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=$u(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=$u(0),this.hiddenUpdates=$u(null),this.identifierPrefix=a,this.onUncaughtError=n,this.onCaughtError=u,this.onRecoverableError=i,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=o,this.incompleteTransitions=new Map}function sd(e,l,t,a,n,u,i,f,o,g,S,z){return e=new ny(e,l,t,i,o,g,S,z,f),l=1,u===!0&&(l|=24),u=cl(3,null,null,l),e.current=u,u.stateNode=e,l=Ri(),l.refCount++,e.pooledCache=l,l.refCount++,u.memoizedState={element:a,isDehydrated:t,cache:l},Yi(u),e}function fd(e){return e?(e=aa,e):aa}function od(e,l,t,a,n,u){n=fd(n),a.context===null?a.context=n:a.pendingContext=n,a=it(l),a.payload={element:t},u=u===void 0?null:u,u!==null&&(a.callback=u),t=ct(e,a,l),t!==null&&(tl(t,e,l),$a(t,e,l))}function rd(e,l){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var t=e.retryLane;e.retryLane=t!==0&&t<l?t:l}}function ts(e,l){rd(e,l),(e=e.alternate)&&rd(e,l)}function dd(e){if(e.tag===13||e.tag===31){var l=Dt(e,67108864);l!==null&&tl(l,e,67108864),ts(e,67108864)}}function hd(e){if(e.tag===13||e.tag===31){var l=dl();l=Fu(l);var t=Dt(e,l);t!==null&&tl(t,e,l),ts(e,l)}}var Bu=!0;function uy(e,l,t,a){var n=x.T;x.T=null;var u=U.p;try{U.p=2,as(e,l,t,a)}finally{U.p=u,x.T=n}}function iy(e,l,t,a){var n=x.T;x.T=null;var u=U.p;try{U.p=8,as(e,l,t,a)}finally{U.p=u,x.T=n}}function as(e,l,t,a){if(Bu){var n=ns(a);if(n===null)Lc(e,l,a,qu,t),yd(e,a);else if(sy(n,e,l,t,a))a.stopPropagation();else if(yd(e,a),l&4&&-1<cy.indexOf(e)){for(;n!==null;){var u=Kt(n);if(u!==null)switch(u.tag){case 3:if(u=u.stateNode,u.current.memoizedState.isDehydrated){var i=At(u.pendingLanes);if(i!==0){var f=u;for(f.pendingLanes|=2,f.entangledLanes|=2;i;){var o=1<<31-ul(i);f.entanglements[1]|=o,i&=~o}Cl(u),(fe&6)===0&&(bu=al()+500,hn(0))}}break;case 31:case 13:f=Dt(u,2),f!==null&&tl(f,u,2),xu(),ts(u,2)}if(u=ns(a),u===null&&Lc(e,l,a,qu,t),u===n)break;n=u}n!==null&&a.stopPropagation()}else Lc(e,l,a,null,t)}}function ns(e){return e=ii(e),us(e)}var qu=null;function us(e){if(qu=null,e=wt(e),e!==null){var l=_(e);if(l===null)e=null;else{var t=l.tag;if(t===13){if(e=H(l),e!==null)return e;e=null}else if(t===31){if(e=Y(l),e!==null)return e;e=null}else if(t===3){if(l.stateNode.current.memoizedState.isDehydrated)return l.tag===3?l.stateNode.containerInfo:null;e=null}else l!==e&&(e=null)}}return qu=e,null}function md(e){switch(e){case"beforetoggle":case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(Kd()){case Ss:return 2;case xs:return 8;case En:case Jd:return 32;case js:return 268435456;default:return 32}default:return 32}}var is=!1,pt=null,bt=null,St=null,Sn=new Map,xn=new Map,xt=[],cy="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function yd(e,l){switch(e){case"focusin":case"focusout":pt=null;break;case"dragenter":case"dragleave":bt=null;break;case"mouseover":case"mouseout":St=null;break;case"pointerover":case"pointerout":Sn.delete(l.pointerId);break;case"gotpointercapture":case"lostpointercapture":xn.delete(l.pointerId)}}function jn(e,l,t,a,n,u){return e===null||e.nativeEvent!==u?(e={blockedOn:l,domEventName:t,eventSystemFlags:a,nativeEvent:u,targetContainers:[n]},l!==null&&(l=Kt(l),l!==null&&dd(l)),e):(e.eventSystemFlags|=a,l=e.targetContainers,n!==null&&l.indexOf(n)===-1&&l.push(n),e)}function sy(e,l,t,a,n){switch(l){case"focusin":return pt=jn(pt,e,l,t,a,n),!0;case"dragenter":return bt=jn(bt,e,l,t,a,n),!0;case"mouseover":return St=jn(St,e,l,t,a,n),!0;case"pointerover":var u=n.pointerId;return Sn.set(u,jn(Sn.get(u)||null,e,l,t,a,n)),!0;case"gotpointercapture":return u=n.pointerId,xn.set(u,jn(xn.get(u)||null,e,l,t,a,n)),!0}return!1}function vd(e){var l=wt(e.target);if(l!==null){var t=_(l);if(t!==null){if(l=t.tag,l===13){if(l=H(t),l!==null){e.blockedOn=l,Os(e.priority,function(){hd(t)});return}}else if(l===31){if(l=Y(t),l!==null){e.blockedOn=l,Os(e.priority,function(){hd(t)});return}}else if(l===3&&t.stateNode.current.memoizedState.isDehydrated){e.blockedOn=t.tag===3?t.stateNode.containerInfo:null;return}}}e.blockedOn=null}function Yu(e){if(e.blockedOn!==null)return!1;for(var l=e.targetContainers;0<l.length;){var t=ns(e.nativeEvent);if(t===null){t=e.nativeEvent;var a=new t.constructor(t.type,t);ui=a,t.target.dispatchEvent(a),ui=null}else return l=Kt(t),l!==null&&dd(l),e.blockedOn=t,!1;l.shift()}return!0}function gd(e,l,t){Yu(e)&&t.delete(l)}function fy(){is=!1,pt!==null&&Yu(pt)&&(pt=null),bt!==null&&Yu(bt)&&(bt=null),St!==null&&Yu(St)&&(St=null),Sn.forEach(gd),xn.forEach(gd)}function Gu(e,l){e.blockedOn===l&&(e.blockedOn=null,is||(is=!0,s.unstable_scheduleCallback(s.unstable_NormalPriority,fy)))}var Xu=null;function pd(e){Xu!==e&&(Xu=e,s.unstable_scheduleCallback(s.unstable_NormalPriority,function(){Xu===e&&(Xu=null);for(var l=0;l<e.length;l+=3){var t=e[l],a=e[l+1],n=e[l+2];if(typeof a!="function"){if(us(a||t)===null)continue;break}var u=Kt(t);u!==null&&(e.splice(l,3),l-=3,nc(u,{pending:!0,data:n,method:t.method,action:a},a,n))}}))}function _a(e){function l(o){return Gu(o,e)}pt!==null&&Gu(pt,e),bt!==null&&Gu(bt,e),St!==null&&Gu(St,e),Sn.forEach(l),xn.forEach(l);for(var t=0;t<xt.length;t++){var a=xt[t];a.blockedOn===e&&(a.blockedOn=null)}for(;0<xt.length&&(t=xt[0],t.blockedOn===null);)vd(t),t.blockedOn===null&&xt.shift();if(t=(e.ownerDocument||e).$$reactFormReplay,t!=null)for(a=0;a<t.length;a+=3){var n=t[a],u=t[a+1],i=n[$e]||null;if(typeof u=="function")i||pd(t);else if(i){var f=null;if(u&&u.hasAttribute("formAction")){if(n=u,i=u[$e]||null)f=i.formAction;else if(us(n)!==null)continue}else f=i.action;typeof f=="function"?t[a+1]=f:(t.splice(a,3),a-=3),pd(t)}}}function bd(){function e(u){u.canIntercept&&u.info==="react-transition"&&u.intercept({handler:function(){return new Promise(function(i){return n=i})},focusReset:"manual",scroll:"manual"})}function l(){n!==null&&(n(),n=null),a||setTimeout(t,20)}function t(){if(!a&&!navigation.transition){var u=navigation.currentEntry;u&&u.url!=null&&navigation.navigate(u.url,{state:u.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var a=!1,n=null;return navigation.addEventListener("navigate",e),navigation.addEventListener("navigatesuccess",l),navigation.addEventListener("navigateerror",l),setTimeout(t,100),function(){a=!0,navigation.removeEventListener("navigate",e),navigation.removeEventListener("navigatesuccess",l),navigation.removeEventListener("navigateerror",l),n!==null&&(n(),n=null)}}}function cs(e){this._internalRoot=e}Qu.prototype.render=cs.prototype.render=function(e){var l=this._internalRoot;if(l===null)throw Error(r(409));var t=l.current,a=dl();od(t,a,e,l,null,null)},Qu.prototype.unmount=cs.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var l=e.containerInfo;od(e.current,2,null,e,null,null),xu(),l[Vt]=null}};function Qu(e){this._internalRoot=e}Qu.prototype.unstable_scheduleHydration=function(e){if(e){var l=_s();e={blockedOn:null,target:e,priority:l};for(var t=0;t<xt.length&&l!==0&&l<xt[t].priority;t++);xt.splice(t,0,e),t===0&&vd(e)}};var Sd=A.version;if(Sd!=="19.2.5")throw Error(r(527,Sd,"19.2.5"));U.findDOMNode=function(e){var l=e._reactInternals;if(l===void 0)throw typeof e.render=="function"?Error(r(188)):(e=Object.keys(e).join(","),Error(r(268,e)));return e=d(l),e=e!==null?M(e):null,e=e===null?null:e.stateNode,e};var oy={bundleType:0,version:"19.2.5",rendererPackageName:"react-dom",currentDispatcherRef:x,reconcilerVersion:"19.2.5"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Zu=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Zu.isDisabled&&Zu.supportsFiber)try{Da=Zu.inject(oy),nl=Zu}catch{}}return zn.createRoot=function(e,l){if(!D(e))throw Error(r(299));var t=!1,a="",n=_o,u=Oo,i=No;return l!=null&&(l.unstable_strictMode===!0&&(t=!0),l.identifierPrefix!==void 0&&(a=l.identifierPrefix),l.onUncaughtError!==void 0&&(n=l.onUncaughtError),l.onCaughtError!==void 0&&(u=l.onCaughtError),l.onRecoverableError!==void 0&&(i=l.onRecoverableError)),l=sd(e,1,!1,null,null,t,a,null,n,u,i,bd),e[Vt]=l.current,Zc(e),new cs(l)},zn.hydrateRoot=function(e,l,t){if(!D(e))throw Error(r(299));var a=!1,n="",u=_o,i=Oo,f=No,o=null;return t!=null&&(t.unstable_strictMode===!0&&(a=!0),t.identifierPrefix!==void 0&&(n=t.identifierPrefix),t.onUncaughtError!==void 0&&(u=t.onUncaughtError),t.onCaughtError!==void 0&&(i=t.onCaughtError),t.onRecoverableError!==void 0&&(f=t.onRecoverableError),t.formState!==void 0&&(o=t.formState)),l=sd(e,1,!0,l,t??null,a,n,o,u,i,f,bd),l.context=fd(null),t=l.current,a=dl(),a=Fu(a),n=it(a),n.callback=null,ct(t,n,a),t=a,l.current.lanes=t,Ca(l,t),Cl(l),e[Vt]=l.current,Zc(e),new Qu(l)},zn.version="19.2.5",zn}var Dd;function Sy(){if(Dd)return os.exports;Dd=1;function s(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(A){console.error(A)}}return s(),os.exports=by(),os.exports}var xy=Sy();const jy=Bd(xy),Yd="";async function ze(s,A){const T=await fetch(`${Yd}${s}`,{...A,credentials:"same-origin",headers:{"Content-Type":"application/json",...A==null?void 0:A.headers}});if(T.status===401)throw window.location.hash="#login",new Error("Unauthorized");if(!T.ok){const r=await T.json().catch(()=>({}));throw new Error(r.message||r.error||`HTTP ${T.status}`)}return T.json()}async function Ty(s){const A=await fetch(`${Yd}${s}`,{credentials:"same-origin"});if(A.status===401)throw window.location.hash="#login",new Error("Unauthorized");if(!A.ok)throw new Error(`HTTP ${A.status}`);return A.text()}const be={oauthRequest:s=>ze(`/admin/api/oauth-requests/${encodeURIComponent(s)}`),decideOAuthRequest:(s,A,T)=>ze(`/admin/api/oauth-requests/${encodeURIComponent(s)}`,{method:"POST",body:JSON.stringify({decision:A,csrf:T})}),login:s=>ze("/admin/login",{method:"POST",body:JSON.stringify({token:s})}),signOutEverywhere:()=>ze("/admin/api/sign-out-everywhere",{method:"POST"}),stats:()=>ze("/admin/api/stats"),health:()=>ze("/admin/api/health-indicators"),agents:()=>ze("/admin/api/agents"),agentsSpend:()=>ze("/admin/api/agents/spend"),sources:()=>ze("/admin/api/sources"),grantCatalog:()=>ze("/admin/api/grant-catalog"),clientGrant:s=>ze(`/admin/api/grants/${encodeURIComponent(s)}`),registerClient:s=>ze("/admin/api/register-client",{method:"POST",body:JSON.stringify(s)}),recoverClient:s=>ze("/admin/api/recover-client",{method:"POST",body:JSON.stringify({clientId:s})}),updateClientGrant:(s,A)=>ze("/admin/api/rescope-client",{method:"POST",body:JSON.stringify({...A,clientId:s})}),requests:(s=1,A="")=>ze(`/admin/api/requests?page=${s}${A}`),apiKeys:()=>ze("/admin/api/api-keys"),createApiKey(s){return ze("/admin/api/api-keys",{method:"POST",body:JSON.stringify({name:s})})},revokeApiKey(s){return ze("/admin/api/api-keys/revoke",{method:"POST",body:JSON.stringify({name:s})})},updateClientTtl:(s,A)=>ze("/admin/api/update-client-ttl",{method:"POST",body:JSON.stringify({clientId:s,tokenTtl:A})}),rescopeClient:(s,A,T)=>ze("/admin/api/rescope-client",{method:"POST",body:JSON.stringify({clientId:s,sourceId:A,federatedRead:T})}),revokeClient:s=>ze("/admin/api/revoke-client",{method:"POST",body:JSON.stringify({clientId:s})}),calibrationProfile:s=>ze(`/admin/api/calibration/profile${s?`?holder=${encodeURIComponent(s)}`:""}`),calibrationChart:(s,A)=>Ty(`/admin/api/calibration/charts/${encodeURIComponent(s)}${A?`?holder=${encodeURIComponent(A)}`:""}`),jobsWatch:()=>ze("/admin/api/jobs/watch")};function zy({onLogin:s}){const[A,T]=B.useState(""),[r,D]=B.useState(""),[_,H]=B.useState(!1),Y=async O=>{O.preventDefault(),D(""),H(!0);try{await be.login(A),T(""),s()}catch{D("Invalid token.")}finally{H(!1)}};return c.jsx("div",{className:"login-page",children:c.jsxs("div",{className:"login-box",children:[c.jsx("div",{className:"login-logo",children:"GBrain"}),c.jsxs("div",{style:{background:"rgba(136, 170, 255, 0.08)",border:"1px solid rgba(136, 170, 255, 0.2)",borderRadius:8,padding:"14px 16px",marginBottom:20,fontSize:13,lineHeight:1.5,color:"var(--text-secondary)"},children:[c.jsx("div",{style:{fontWeight:600,color:"var(--text-primary)",marginBottom:6},children:"🔒 This is a protected dashboard"}),"Ask your AI agent for the admin login link:",c.jsx("div",{style:{background:"rgba(0,0,0,0.3)",borderRadius:6,padding:"8px 12px",marginTop:8,fontFamily:"var(--font-mono)",fontSize:12,color:"#88aaff",wordBreak:"break-all"},children:'"Give me the GBrain admin login link"'}),c.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--text-muted)"},children:"Each link is single-use. Your agent generates a fresh one each time."})]}),c.jsxs("details",{style:{marginBottom:16},children:[c.jsx("summary",{style:{cursor:"pointer",fontSize:13,color:"var(--text-muted)"},children:"Or paste bootstrap token manually"}),c.jsxs("form",{onSubmit:Y,style:{marginTop:12},children:[c.jsx("div",{style:{marginBottom:12},children:c.jsx("input",{type:"password",placeholder:"Admin Token",value:A,onChange:O=>T(O.target.value)})}),c.jsx("button",{className:"btn btn-primary",style:{width:"100%"},disabled:_,children:_?"Authenticating...":"Submit"}),r&&c.jsx("div",{className:"login-error",children:r})]})]})]})})}function Ay(){const[s,A]=B.useState({connected_agents:0,requests_today:0,active_tokens:0}),[T,r]=B.useState({expiring_soon:0,error_rate:"0%"}),[D,_]=B.useState([]),[H,Y]=B.useState("connecting"),O=B.useRef(null);B.useEffect(()=>{be.stats().then(A).catch(()=>{}),be.health().then(r).catch(()=>{});const M=new EventSource("/admin/events",{withCredentials:!0});O.current=M,M.onopen=()=>Y("connected"),M.onmessage=N=>{try{const J=JSON.parse(N.data);_(K=>[J,...K].slice(0,50))}catch{}},M.onerror=()=>{Y("disconnected"),setTimeout(()=>{Y("connecting"),M.close()},3e3)};const C=setInterval(()=>{be.stats().then(A).catch(()=>{}),be.health().then(r).catch(()=>{})},3e4);return()=>{M.close(),clearInterval(C)}},[]);const d=M=>{const C=Date.now()-new Date(M).getTime();return C<6e4?`${Math.floor(C/1e3)}s ago`:C<36e5?`${Math.floor(C/6e4)} min ago`:`${Math.floor(C/36e5)}h ago`};return c.jsxs(c.Fragment,{children:[c.jsx("h1",{className:"page-title",children:"Dashboard"}),c.jsxs("div",{style:{display:"flex",gap:24},children:[c.jsxs("div",{style:{flex:1},children:[c.jsxs("div",{className:"metrics",children:[c.jsxs("div",{className:"metric",children:[c.jsx("div",{className:"metric-value",children:s.connected_agents}),c.jsx("div",{className:"metric-label",children:"Connected Agents"})]}),c.jsxs("div",{className:"metric",children:[c.jsx("div",{className:"metric-value",children:s.requests_today}),c.jsx("div",{className:"metric-label",children:"Requests Today"})]}),c.jsxs("div",{className:"metric",children:[c.jsx("div",{className:"metric-value",children:s.active_tokens}),c.jsx("div",{className:"metric-label",children:"Active Tokens"})]})]}),c.jsxs("h2",{className:"section-title",children:["Live Activity",c.jsx("span",{style:{marginLeft:8,fontSize:10,color:H==="connected"?"var(--success)":H==="connecting"?"var(--warning)":"var(--error)"},children:H==="connected"?"● connected":H==="connecting"?"● connecting...":"● disconnected"})]}),c.jsx("div",{className:"feed",children:D.length===0?c.jsx("div",{className:"feed-empty",children:H==="connected"?"No requests yet. Agents will appear when they connect.":"Connecting..."}):c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Agent"}),c.jsx("th",{children:"Operation"}),c.jsx("th",{children:"Scopes"}),c.jsx("th",{children:"Latency"}),c.jsx("th",{children:"Status"}),c.jsx("th",{children:"Time"})]})}),c.jsx("tbody",{children:D.map((M,C)=>c.jsxs("tr",{children:[c.jsx("td",{className:"mono",children:M.agent}),c.jsx("td",{className:"mono",children:M.operation}),c.jsx("td",{children:M.scopes.split(",").map(N=>c.jsx("span",{className:`badge badge-${N.trim()}`,style:{marginRight:4},children:N.trim()},N))}),c.jsxs("td",{className:"mono",children:[M.latency_ms," ms"]}),c.jsx("td",{children:c.jsx("span",{className:`badge badge-${M.status}`,children:M.status})}),c.jsx("td",{style:{color:"var(--text-secondary)"},children:d(M.timestamp)})]},C))})]})})]}),c.jsxs("div",{style:{width:220},children:[c.jsx("h2",{className:"section-title",children:"Token Health"}),c.jsxs("div",{className:"health-panel",children:[c.jsxs("div",{className:"health-row",children:[c.jsx("span",{style:{color:"var(--warning)"},children:"Expiring Soon"}),c.jsx("span",{className:"mono",children:T.expiring_soon})]}),c.jsxs("div",{className:"health-row",children:[c.jsx("span",{style:{color:"var(--error)"},children:"Error Rate"}),c.jsx("span",{className:"mono",children:T.error_rate})]})]})]})]})]})}const Oa=s=>s.split(/[\s,]+/).filter(Boolean);function ms(s){var A,T,r;return{profile:(s==null?void 0:s.profile)??"memory-writer",applyProfile:!s,source:(s==null?void 0:s.sourceId)??"default",reads:(s==null?void 0:s.federatedRead)??["default"],scopes:(s==null?void 0:s.scopes.join(" "))??"",directPrefixes:((A=s==null?void 0:s.boundSlugPrefixes)==null?void 0:A.join(`+`))??"",tools:(s==null?void 0:s.boundTools)??[],namespace:(s==null?void 0:s.delegatedNamespace)??"job",delegatedPrefixes:((T=s==null?void 0:s.delegatedSlugPrefixes)==null?void 0:T.join(`+`))??"",concurrency:String((s==null?void 0:s.boundMaxConcurrent)??1),budget:(s==null?void 0:s.budgetUsdPerDay)??"unlimited",ttl:s?String(s.tokenTtlSeconds??0):"3600",surface:(s==null?void 0:s.surface)??"starter",operationSnapshot:((r=s==null?void 0:s.allowedOperations)==null?void 0:r.join(`+`))??"",editOperations:!1}}function Gd(s){const A=s.scopes?Oa(s.scopes).includes("agent"):["full","delegating-agent"].includes(s.profile);return{...s.applyProfile?{profile:s.profile}:{},sourceId:s.source,federatedRead:s.reads,boundSlugPrefixes:s.directPrefixes.trim()?Oa(s.directPrefixes):null,...s.scopes.trim()?{scopes:Oa(s.scopes)}:{},...s.editOperations?{allowedOperations:Oa(s.operationSnapshot)}:{},...A?{boundTools:s.tools,boundSourceId:s.source,delegatedNamespace:s.namespace,delegatedSlugPrefixes:s.namespace==="job"?null:Oa(s.delegatedPrefixes)}:{},boundMaxConcurrent:Number(s.concurrency),budgetUsdPerDay:s.budget==="unlimited"?null:s.budget,tokenTtl:s.ttl==="0"?null:Number(s.ttl),surface:s.surface==="default"?null:s.surface}}function Xd(s){return{...s.profile?{profile:s.profile}:{},scopes:s.scopes,sourceId:s.sourceId,federatedRead:s.federatedRead,boundSlugPrefixes:s.boundSlugPrefixes,allowedOperations:s.allowedOperations,boundTools:s.boundTools,boundSourceId:s.boundSourceId,boundBrainId:s.boundBrainId,delegatedNamespace:s.delegatedNamespace,delegatedSlugPrefixes:s.delegatedSlugPrefixes,boundMaxConcurrent:s.boundMaxConcurrent,budgetUsdPerDay:s.budgetUsdPerDay,tokenTtlSeconds:s.tokenTtlSeconds,surface:s.surface}}function Qd({draft:s,setDraft:A,sources:T,catalog:r,existing:D=!1}){const _=(d,M)=>A({...s,[d]:M}),H=new Set(T.map(d=>d.id)),Y=s.scopes?Oa(s.scopes).includes("agent"):["full","delegating-agent"].includes(s.profile),O={marginBottom:14};return c.jsxs(c.Fragment,{children:[c.jsxs("div",{style:O,children:[c.jsx("label",{htmlFor:"grant-profile",children:"Permission profile"}),c.jsx("select",{id:"grant-profile",value:s.profile,onChange:d=>A({...s,profile:d.target.value,applyProfile:!0,scopes:"",editOperations:!1,surface:["operator","full"].includes(d.target.value)?"full":"starter"}),children:r.profiles.map(d=>c.jsx("option",{children:d},d))}),c.jsx("p",{className:"grant-help",children:"Memory writer lets this agent recall, save, correct, and withdraw memory. Delegating profiles also allow selected server tools to run jobs."}),D&&c.jsxs("label",{className:"checkbox-label",children:[c.jsx("input",{type:"checkbox",checked:s.applyProfile,onChange:d=>_("applyProfile",d.target.checked)}),"Apply this profile's current operation snapshot"]})]}),c.jsxs("div",{style:O,children:[c.jsx("label",{htmlFor:"grant-source",children:"Primary / write source"}),c.jsxs("select",{id:"grant-source",value:s.source,onChange:d=>_("source",d.target.value),children:[!H.has(s.source)&&c.jsxs("option",{value:s.source,children:[s.source," · unavailable"]}),T.map(d=>c.jsxs("option",{value:d.id,children:[d.name," (",d.id,")"]},d.id))]})]}),c.jsxs("fieldset",{style:{border:0,padding:0,margin:"0 0 14px"},children:[c.jsx("legend",{children:"Readable sources"}),[...T,...s.reads.filter(d=>!H.has(d)).map(d=>({id:d,name:`${d} · unavailable`}))].map(d=>c.jsxs("label",{className:"checkbox-label",children:[c.jsx("input",{type:"checkbox",checked:s.reads.includes(d.id),onChange:M=>_("reads",M.target.checked?[...s.reads,d.id]:s.reads.filter(C=>C!==d.id))}),d.name]},d.id))]}),c.jsxs("div",{style:O,children:[c.jsx("label",{htmlFor:"grant-direct-prefixes",children:"Direct write prefixes (one per line)"}),c.jsx("textarea",{id:"grant-direct-prefixes",rows:2,value:s.directPrefixes,onChange:d=>_("directPrefixes",d.target.value),placeholder:"work-example/"}),c.jsx("p",{className:"grant-help",children:"Blank grants the whole primary source. Coding agent requires an explicit prefix."})]}),Y&&c.jsxs("fieldset",{style:{border:"1px solid var(--border)",padding:12,marginBottom:14},children:[c.jsx("legend",{children:"Delegated jobs"}),c.jsx("p",{className:"grant-help",children:"Choose every tool explicitly. Jobs stay in the primary source; existing jobs retain their original limits."}),c.jsx("div",{className:"checkbox-group",style:{maxHeight:180,overflowY:"auto"},children:[...new Set([...r.delegatedTools,...s.tools])].map(d=>c.jsxs("label",{className:"checkbox-label",children:[c.jsx("input",{type:"checkbox",checked:s.tools.includes(d),onChange:M=>_("tools",M.target.checked?[...s.tools,d]:s.tools.filter(C=>C!==d))}),d,r.delegatedTools.includes(d)?"":" · unavailable"]},d))}),c.jsx("label",{htmlFor:"grant-namespace",children:"Delegated write namespace"}),c.jsxs("select",{id:"grant-namespace",value:s.namespace,onChange:d=>_("namespace",d.target.value),children:[c.jsx("option",{value:"job",children:"Each job's own wiki/agents/ directory"}),c.jsx("option",{value:"prefixes",children:"Explicit prefixes"})]}),s.namespace==="prefixes"&&c.jsx("textarea",{"aria-label":"Delegated prefixes",rows:2,value:s.delegatedPrefixes,onChange:d=>_("delegatedPrefixes",d.target.value),placeholder:"work-example/"})]}),c.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,...O},children:[c.jsxs("div",{children:[c.jsx("label",{htmlFor:"grant-concurrency",children:"Concurrent jobs"}),c.jsx("input",{id:"grant-concurrency",type:"number",min:1,step:1,value:s.concurrency,onChange:d=>_("concurrency",d.target.value)})]}),c.jsxs("div",{children:[c.jsx("label",{htmlFor:"grant-budget",children:"Daily delegated spend (USD)"}),c.jsx("input",{id:"grant-budget",value:s.budget,onChange:d=>_("budget",d.target.value),placeholder:"unlimited"}),c.jsx("p",{className:"grant-help",children:"Use unlimited for no spending cap, or an amount such as 2.50."})]})]}),c.jsxs("div",{style:O,children:[c.jsx("label",{htmlFor:"grant-ttl",children:"Future access token lifetime (seconds)"}),c.jsx("input",{id:"grant-ttl",type:"number",min:0,max:7776e3,step:1,value:s.ttl,onChange:d=>_("ttl",d.target.value)}),c.jsx("p",{className:"grant-help",children:"Renewable: 3600 (1 hour). Static bearer: 2592000 (30 days). 0 uses the server default. Existing tokens keep their expiry."})]}),c.jsxs("details",{style:O,children:[c.jsx("summary",{children:"Advanced permissions"}),c.jsx("label",{htmlFor:"grant-scopes",children:"Scope override"}),c.jsx("input",{id:"grant-scopes",value:s.scopes,onChange:d=>_("scopes",d.target.value),placeholder:"Use profile scopes"}),c.jsx("p",{className:"grant-help",children:"read, write, admin, and agent are distinct grants. Admin does not authorize delegation."}),c.jsx("label",{htmlFor:"grant-surface",children:"Visible tool catalog"}),c.jsx("select",{id:"grant-surface",value:s.surface,onChange:d=>_("surface",d.target.value),children:["verbs","starter","full","default"].map(d=>c.jsx("option",{children:d},d))}),c.jsx("p",{className:"grant-help",children:"Full shows all eligible tools; it does not grant additional authority."}),c.jsxs("label",{className:"checkbox-label",children:[c.jsx("input",{type:"checkbox",checked:s.editOperations,onChange:d=>_("editOperations",d.target.checked)}),"Replace operation authority snapshot"]}),s.editOperations&&c.jsxs(c.Fragment,{children:[c.jsx("textarea",{"aria-label":"Allowed operations",rows:5,value:s.operationSnapshot,onChange:d=>_("operationSnapshot",d.target.value)}),c.jsx("p",{className:"grant-help",children:"One operation name per line. An empty list denies every operation, including delegated tools."})]})]})]})}const Ey=[["Profile","profile"],["Scopes","scopes"],["Write source","sourceId"],["Readable sources","federatedRead"],["Direct prefixes","boundSlugPrefixes"],["Visible catalog","surface"],["Operation authority","allowedOperations"],["Delegated tools","boundTools"],["Delegated source","boundSourceId"],["Delegated brain","boundBrainId"],["Delegated namespace","delegatedNamespace"],["Delegated prefixes","delegatedSlugPrefixes"],["Concurrent jobs","boundMaxConcurrent"],["Daily USD cap","budgetUsdPerDay"],["Future token TTL","tokenTtlSeconds"]];function _y(s,A){return s===null?A==="budgetUsdPerDay"?"Unlimited":A==="allowedOperations"?"Legacy scope-based catalog":"Unset":Array.isArray(s)?s.join(", ")||"(none)":String(s)}function Md({grant:s,field:A}){const T=s[A];return A==="allowedOperations"&&Array.isArray(T)&&T.length>8?c.jsxs("details",{children:[c.jsxs("summary",{children:[T.length," operations · inspect list"]}),c.jsx("div",{style:{maxHeight:160,overflowY:"auto",marginTop:8},children:T.join(", ")})]}):c.jsx(c.Fragment,{children:_y(T,A)})}function Zd({preview:s}){return c.jsxs("div",{"aria-live":"polite",style:{margin:"16px 0"},children:[c.jsx("h3",{children:"Review permissions"}),c.jsx("div",{style:{overflowX:"auto"},children:c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Permission"}),s.before&&c.jsx("th",{children:"Current"}),c.jsx("th",{children:"Proposed"})]})}),c.jsx("tbody",{children:Ey.filter(([,A])=>!s.before||JSON.stringify(s.before[A])!==JSON.stringify(s.after[A])).map(([A,T])=>c.jsxs("tr",{children:[c.jsx("th",{children:A}),s.before&&c.jsx("td",{style:{overflowWrap:"anywhere",maxWidth:200},children:c.jsx(Md,{grant:s.before,field:T})}),c.jsx("td",{style:{overflowWrap:"anywhere",maxWidth:280},children:c.jsx(Md,{grant:s.after,field:T})})]},T))})]})}),c.jsx("p",{className:"grant-help",children:s.tokenImplications})]})}function Oy({clientId:s,sources:A,onRescoped:T}){const[r,D]=B.useState(),[_,H]=B.useState(),[Y,O]=B.useState(),[d,M]=B.useState(),[C,N]=B.useState(""),[J,K]=B.useState(!1),[ie,je]=B.useState(!1),ue=async()=>{const[Z,Ae]=await Promise.all([be.clientGrant(s),be.grantCatalog()]);D(Z.grant),H(ms(Z.grant)),O(Ae),M(void 0),N("")};B.useEffect(()=>{ue().catch(Z=>N(Z.message))},[s]);const k=async()=>{if(!(!_||!r)){K(!0),N(""),je(!1);try{const Z=await be.updateClientGrant(s,{...d?Xd(d.after):Gd(_),expectedRevision:r.revision,dryRun:!d});d?(D(Z.after),H(ms(Z.after)),M(void 0),je(!0),T(Z.after)):M(Z)}catch(Z){M(void 0),N(Z instanceof Error?Z.message:"Grant update failed")}finally{K(!1)}}};return c.jsxs("section",{children:[c.jsx("div",{className:"section-title",children:"Permissions"}),r&&c.jsxs("p",{className:"grant-help",children:["Revision ",r.revision,". Review source access, direct tools, and delegated work independently."]}),r&&c.jsx(Ny,{clientId:s,revision:r.revision}),!!(r!=null&&r.repairReasons.length)&&c.jsxs("p",{role:"status",style:{color:"var(--warning)"},children:["Delegation needs repair: ",r.repairReasons.join(", "),". Review and explicitly grant the missing bindings below."]}),_&&Y&&c.jsx(Qd,{draft:_,catalog:Y,sources:A,existing:!0,setDraft:Z=>{H(Z),M(void 0),je(!1)}}),C&&c.jsxs("p",{role:"alert",style:{color:"var(--error)"},children:[C," ",c.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>void ue().catch(Z=>N(Z.message)),children:"Reload current grant"})]}),d&&c.jsx(Zd,{preview:d}),ie&&c.jsx("p",{role:"status",children:"Permissions saved. Credentials are unchanged."}),c.jsx("button",{type:"button",className:"btn btn-primary",disabled:J||!_||!Y,onClick:()=>void k(),children:J?"Checking…":d?"Apply reviewed changes":"Preview changes"})]})}function Ny({clientId:s,revision:A}){const[T,r]=B.useState(),[D,_]=B.useState(!1);return B.useEffect(()=>{let H=!0;const Y=()=>void be.agentsSpend().then(d=>{H&&(r(d.find(M=>M.client_id===s)),_(!1))}).catch(()=>{H&&_(!0)});Y();const O=setInterval(Y,2e4);return()=>{H=!1,clearInterval(O)}},[s,A]),D?c.jsx("p",{role:"status",children:"Delegated spend is unavailable. Reload to check before starting more work."}):T?c.jsxs("div",{style:{border:"1px solid var(--border)",padding:12,marginBottom:14},children:[c.jsx("strong",{children:"Delegated work"}),c.jsxs("p",{children:[T.inflight_count," unfinished jobs · Daily cap: ",T.cap_usd_per_day===null?"Unlimited":`$${T.cap_usd_per_day.toFixed(2)}`]}),c.jsxs("p",{className:"grant-help",children:["Recorded today: $",(T.spent_cents_today/100).toFixed(2),". Known outstanding reservations: $",(T.pending_cents/100).toFixed(2),", including overdue calls from earlier days."]}),T.unknown_count>0&&c.jsxs("p",{role:"status",style:{color:"var(--warning)"},children:[T.unknown_count," unresolved calls have an unknown cost. The known amounts above do not bound total liability; a finite cap refuses further calls until reconciliation."]})]}):null}function Dy({serverUrl:s,clientId:A,credentialFile:T=!0}){const[r,D]=B.useState();return B.useEffect(()=>{be.grantCatalog().then(D).catch(()=>{})},[]),c.jsxs("section",{children:[c.jsx("div",{className:"section-title",children:"Connect this agent"}),c.jsx("p",{children:"Follow your harness guide for the supported connection and reload steps. Grok Bot and Muse can use GBrain inside their own computer when its prerequisites pass."}),c.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:12},children:r==null?void 0:r.harnesses.map(_=>c.jsx("a",{href:_.documentation,target:"_blank",rel:"noreferrer",children:_.label},_.id))}),T?c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"grant-help",children:"Use the credential file saved at registration in the target environment. Restrict its file permissions to the owner before connecting."}),c.jsx("div",{className:"code-block",children:c.jsx("pre",{style:{whiteSpace:"pre-wrap"},children:`gbrain connect ${s}/mcp --credentials-file /absolute/private/credentials.json --harness YOUR_HARNESS --install`})})]}):c.jsx("p",{className:"grant-help",children:"Follow your harness guide for this credential type. The thin CLI used by Grok Bot and Muse requires a renewable OAuth client with client_credentials; register one above to use that connection."}),c.jsxs("p",{className:"grant-help",children:["Client ID: ",A,". Installing on the server host does not configure a different agent's computer."]})]})}function My(s){const A=Math.floor((Date.now()-s.getTime())/1e3);return A<60?"just now":A<3600?`${Math.floor(A/60)}m ago`:A<86400?`${Math.floor(A/3600)}h ago`:`${Math.floor(A/86400)}d ago`}function Cy(){const[s,A]=B.useState([]),[T,r]=B.useState([]),[D,_]=B.useState(!0),[H,Y]=B.useState(!1),[O,d]=B.useState(null),[M,C]=B.useState(!1),[N,J]=B.useState(null),[K,ie]=B.useState(null);B.useEffect(()=>{je(),be.sources().then(r).catch(()=>{})},[]);const je=()=>{be.agents().then(A).catch(()=>{})};return c.jsxs(c.Fragment,{children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:24},children:[c.jsx("h1",{className:"page-title",style:{marginBottom:0},children:"Agents"}),c.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[c.jsxs("label",{style:{fontSize:13,color:"var(--text-secondary)",display:"flex",alignItems:"center",gap:6,cursor:"pointer"},children:[c.jsx("input",{type:"checkbox",checked:D,onChange:ue=>_(ue.target.checked)})," Hide revoked"]}),c.jsx("button",{className:"btn btn-secondary",onClick:()=>C(!0),children:"+ API Key"}),c.jsx("button",{className:"btn btn-primary",onClick:()=>Y(!0),children:"+ OAuth Client"})]})]}),(()=>{const ue=s.filter(k=>!D||k.status!=="revoked");return s.length===0?c.jsx("div",{style:{textAlign:"center",padding:48,color:"var(--text-muted)"},children:"No agents registered. Register your first agent to get started."}):ue.length===0?c.jsx("div",{style:{textAlign:"center",padding:48,color:"var(--text-muted)"},children:'All agents are revoked. Uncheck "Hide revoked" to view them.'}):c.jsxs(c.Fragment,{children:[c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Name"}),c.jsx("th",{children:"Type"}),c.jsx("th",{children:"Scopes"}),c.jsx("th",{children:"Sources"}),c.jsx("th",{children:"Status"}),c.jsx("th",{children:"Requests"}),c.jsx("th",{children:"Last Used"})]})}),c.jsx("tbody",{children:ue.map(k=>c.jsxs("tr",{onClick:()=>ie(k),style:{cursor:"pointer"},children:[c.jsx("td",{style:{fontWeight:500},children:k.name||k.client_name}),c.jsx("td",{children:c.jsx("span",{className:`badge ${k.auth_type==="oauth"?"badge-read":"badge-write"}`,style:{fontSize:11},children:k.auth_type==="oauth"?"OAuth":"API Key"})}),c.jsx("td",{children:(k.scope||"").split(" ").filter(Boolean).map(Z=>c.jsx("span",{className:`badge badge-${Z}`,style:{marginRight:4},children:Z},Z))}),c.jsx("td",{style:{color:"var(--text-secondary)",fontSize:12},children:k.auth_type==="oauth"?`${k.source_id||"none"} · ${(k.federated_read||[]).length} readable`:"Unscoped"}),c.jsx("td",{children:c.jsx("span",{className:`badge ${k.status==="active"?"badge-success":"badge-danger"}`,children:k.status})}),c.jsxs("td",{children:[c.jsx("span",{style:{fontWeight:500},children:k.requests_today||0}),c.jsxs("span",{style:{color:"var(--text-muted)",fontSize:12},children:[" / ",k.total_requests||0]})]}),c.jsx("td",{style:{color:"var(--text-secondary)"},children:k.last_used_at?My(new Date(k.last_used_at)):"Never"})]},k.id))})]}),c.jsxs("div",{style:{color:"var(--text-muted)",fontSize:13,marginTop:12},children:[s.filter(k=>k.status==="active").length," active / ",s.length," total"]})]})})(),H&&c.jsx(Hy,{sources:T,onClose:()=>Y(!1),onRegistered:ue=>{Y(!1),d(ue),je()}}),O&&c.jsx(By,{credentials:O,onClose:()=>d(null)}),K&&c.jsx(qy,{agent:K,sources:T,onClose:()=>ie(null),onRevoked:je,onRecovered:ue=>{ie(null),d(ue)},onRescoped:({sourceId:ue,federatedRead:k})=>{ie(Z=>Z&&{...Z,source_id:ue,federated_read:k}),je()}},K.id),M&&c.jsx(Uy,{onClose:()=>C(!1),onCreated:ue=>{C(!1),J(ue),je()}}),N&&c.jsx(Ry,{token:N,onClose:()=>J(null)})]})}function Uy({onClose:s,onCreated:A}){const[T,r]=B.useState(""),[D,_]=B.useState(!1),[H,Y]=B.useState(""),O=async d=>{if(d.preventDefault(),!T.trim()){Y("Name required");return}_(!0);try{const M=await be.createApiKey(T.trim());A({name:M.name,token:M.token})}catch(M){Y(M instanceof Error?M.message:"Failed")}finally{_(!1)}};return c.jsx("div",{className:"modal-overlay",onClick:s,children:c.jsxs("form",{className:"modal",onClick:d=>d.stopPropagation(),onSubmit:O,children:[c.jsx("div",{className:"modal-title",children:"Create API Key"}),c.jsx("p",{style:{color:"var(--text-secondary)",fontSize:13,marginBottom:16},children:"API keys use simple bearer token auth. They grant full read+write+admin access. For scoped access, use OAuth clients instead."}),c.jsxs("div",{style:{marginBottom:16},children:[c.jsx("label",{children:"Key Name"}),c.jsx("input",{placeholder:"e.g. claude-code-local",value:T,onChange:d=>r(d.target.value),autoFocus:!0})]}),H&&c.jsx("div",{style:{color:"var(--error)",fontSize:13,marginBottom:12},children:H}),c.jsxs("div",{style:{display:"flex",gap:12,justifyContent:"flex-end"},children:[c.jsx("button",{type:"button",className:"btn btn-secondary",onClick:s,children:"Cancel"}),c.jsx("button",{type:"submit",className:"btn btn-primary",disabled:D,children:D?"Creating...":"Create Key"})]})]})})}function Ry({token:s,onClose:A}){const T=r=>navigator.clipboard.writeText(r);return c.jsx("div",{className:"modal-overlay",children:c.jsxs("div",{className:"modal",style:{maxWidth:560},children:[c.jsxs("div",{style:{textAlign:"center",marginBottom:16},children:[c.jsx("div",{style:{fontSize:36,color:"var(--success)",marginBottom:8},children:"✓"}),c.jsx("div",{style:{fontSize:20,fontWeight:600},children:"API Key Created"})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Name"}),c.jsx("div",{className:"code-block",children:c.jsx("span",{children:s.name})})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Bearer Token"}),c.jsxs("div",{className:"code-block",children:[c.jsx("span",{children:s.token}),c.jsx("button",{className:"copy-btn",onClick:()=>T(s.token),children:"Copy"})]})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Usage"}),c.jsxs("div",{className:"code-block",children:[c.jsx("pre",{style:{whiteSpace:"pre-wrap",margin:0,fontSize:12},children:`Authorization: Bearer ${s.token}`}),c.jsx("button",{className:"copy-btn",onClick:()=>T(`Authorization: Bearer ${s.token}`),children:"Copy"})]})]}),c.jsx("div",{className:"warning-bar",children:"Save this token now. It will not be shown again."}),c.jsx("div",{style:{display:"flex",gap:12,justifyContent:"flex-end",marginTop:20},children:c.jsx("button",{className:"btn btn-primary",onClick:A,children:"Done"})})]})})}function Hy({sources:s,onClose:A,onRegistered:T}){const[r,D]=B.useState(""),[_,H]=B.useState(()=>ms()),[Y,O]=B.useState(),[d,M]=B.useState(),[C,N]=B.useState(!1),[J,K]=B.useState(""),[ie,je]=B.useState();B.useEffect(()=>{be.grantCatalog().then(O).catch(Z=>K(Z.message))},[]);const ue=async Z=>{if(Z.preventDefault(),!r.trim()){K("Name required");return}N(!0),K("");try{const Ae=await be.registerClient({...d?Xd(d.after):Gd(_),name:r.trim(),dryRun:!d});d?T({clientId:Ae.clientId,clientSecret:Ae.clientSecret,name:r.trim(),credentials:Ae.credentials}):M(Ae)}catch(Ae){if(M(void 0),K(Ae instanceof Error?Ae.message:"Registration failed"),d)try{const Je=(await be.agents()).filter(He=>He.auth_type==="oauth"&&He.status==="active"&&(He.name||He.client_name)===r.trim());Je.length===1&&je({clientId:Je[0].id||Je[0].client_id,name:r.trim()})}catch{}}finally{N(!1)}},k=async()=>{if(ie){N(!0),K("");try{T(await be.recoverClient(ie.clientId))}catch(Z){K(Z instanceof Error?Z.message:"Credential recovery failed")}finally{N(!1)}}};return c.jsx("div",{className:"modal-overlay",onClick:A,children:c.jsxs("form",{className:"modal",style:{maxWidth:700,width:"90vw",minWidth:0,maxHeight:"90vh",overflowY:"auto"},onClick:Z=>Z.stopPropagation(),onSubmit:ue,children:[c.jsx("div",{className:"modal-title",children:"Register agent"}),c.jsxs("fieldset",{disabled:C||!!ie,style:{border:0,padding:0,margin:0},children:[c.jsxs("div",{style:{marginBottom:16},children:[c.jsx("label",{htmlFor:"agent-name",children:"Agent name"}),c.jsx("input",{id:"agent-name",placeholder:"muse-personal-example",value:r,onChange:Z=>{D(Z.target.value),M(void 0)},autoFocus:!0})]}),Y&&c.jsx(Qd,{draft:_,setDraft:Z=>{H(Z),M(void 0)},catalog:Y,sources:s})]}),d&&c.jsx(Zd,{preview:d}),J&&c.jsx("p",{role:"alert",style:{color:"var(--error)"},children:J}),ie&&c.jsxs("div",{role:"status",children:[c.jsxs("p",{children:["A registered client named ",ie.name," exists. Recover its saved credential delivery before retrying registration. This preserves its permissions and secret."]}),c.jsx("button",{type:"button",className:"btn btn-secondary",disabled:C,onClick:()=>void k(),children:"Recover credentials"})]}),c.jsxs("div",{style:{display:"flex",gap:12,justifyContent:"flex-end"},children:[c.jsx("button",{type:"button",className:"btn btn-secondary",onClick:A,children:"Cancel"}),c.jsx("button",{type:"submit",className:"btn btn-primary",disabled:C||!Y||!!ie,children:C?"Checking…":d?"Register with reviewed permissions":"Preview permissions"})]})]})})}function By({credentials:s,onClose:A}){const T=D=>navigator.clipboard.writeText(D),r=()=>{const D=s.credentials??{version:1,mcp_url:`${window.location.origin}/mcp`,issuer_url:window.location.origin,client_id:s.clientId,client_secret:s.clientSecret},_=new Blob([JSON.stringify(D,null,2)],{type:"application/json"}),H=URL.createObjectURL(_),Y=document.createElement("a");Y.href=H,Y.download=`${s.name}-credentials.json`,Y.click(),URL.revokeObjectURL(H)};return c.jsx("div",{className:"modal-overlay",children:c.jsxs("div",{className:"modal",style:{maxWidth:560},children:[c.jsxs("div",{style:{textAlign:"center",marginBottom:16},children:[c.jsx("div",{style:{fontSize:36,color:"var(--success)",marginBottom:8},children:"✓"}),c.jsx("div",{style:{fontSize:20,fontWeight:600},children:"Agent Registered"})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Client ID"}),c.jsxs("div",{className:"code-block",children:[c.jsx("span",{children:s.clientId}),c.jsx("button",{className:"copy-btn",onClick:()=>T(s.clientId),children:"Copy"})]})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Client Secret"}),c.jsxs("div",{className:"code-block",children:[c.jsx("span",{children:s.clientSecret}),c.jsx("button",{className:"copy-btn",onClick:()=>T(s.clientSecret),children:"Copy"})]})]}),c.jsx("div",{className:"warning-bar",children:"Download the credential file now. Keep it private, set its permissions to 0600 on the target computer, and use it with gbrain connect. If delivery is lost, use Recover credentials in this client's Agents entry."}),c.jsxs("div",{style:{display:"flex",gap:12,justifyContent:"flex-end",marginTop:20},children:[c.jsx("button",{className:"btn btn-secondary",onClick:r,children:"Download as JSON"}),c.jsx("button",{className:"btn btn-primary",onClick:A,children:"Done"})]})]})})}function qy({agent:s,sources:A,onClose:T,onRevoked:r,onRescoped:D,onRecovered:_}){const H=window.location.origin,Y=s.id||s.client_id||"",O=s.auth_type==="oauth",[d,M]=B.useState(!1),[C,N]=B.useState(""),J=async()=>{M(!0),N("");try{_(await be.recoverClient(Y))}catch(K){N(K instanceof Error?K.message:"Credential recovery failed")}finally{M(!1)}};return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"drawer-overlay",onClick:T}),c.jsxs("div",{className:"drawer",children:[c.jsx("button",{className:"drawer-close",onClick:T,children:"✕"}),c.jsx("div",{style:{fontSize:18,fontWeight:600,marginBottom:4},children:s.name||s.client_name}),c.jsx("span",{className:`badge ${s.status==="active"?"badge-success":"badge-danger"}`,children:s.status}),c.jsx("div",{className:"section-title",children:"Details"}),c.jsxs("div",{style:{display:"grid",gridTemplateColumns:"100px 1fr",gap:"6px 12px",fontSize:13},children:[c.jsx("span",{style:{color:"var(--text-secondary)"},children:"Client ID"}),c.jsxs("span",{className:"mono",children:[(s.id||s.id||s.client_id||"").substring(0,24),"..."]}),c.jsx("span",{style:{color:"var(--text-secondary)"},children:"Scopes"}),c.jsx("span",{children:(s.scope||"").split(" ").filter(Boolean).map(K=>c.jsx("span",{className:`badge badge-${K}`,style:{marginRight:4},children:K},K))}),c.jsx("span",{style:{color:"var(--text-secondary)"},children:"Registered"}),c.jsx("span",{children:new Date(s.created_at).toLocaleDateString()}),c.jsx("span",{style:{color:"var(--text-secondary)"},children:"Token TTL"}),c.jsx("span",{children:s.token_ttl?s.token_ttl>=86400?`${Math.floor(s.token_ttl/86400)}d`:s.token_ttl>=3600?`${Math.floor(s.token_ttl/3600)}h`:`${s.token_ttl}s`:"1h (default)"})]}),O&&c.jsx(Oy,{clientId:Y,sources:A,onRescoped:D}),c.jsx(Dy,{serverUrl:H,clientId:Y,credentialFile:O&&s.grant_types.includes("client_credentials")}),O&&s.status==="active"&&s.grant_types.includes("client_credentials")&&c.jsxs("div",{children:[c.jsx("p",{className:"grant-help",children:"If registration finished but its download was lost, recover the saved credential delivery. Existing permissions and credentials stay unchanged."}),c.jsx("button",{type:"button",className:"btn btn-secondary",disabled:d,onClick:()=>void J(),children:d?"Recovering…":"Recover credentials"}),C&&c.jsx("p",{role:"alert",style:{color:"var(--error)"},children:C})]}),c.jsxs("div",{style:{marginTop:32},children:[s.status==="active"&&c.jsx("button",{className:"btn btn-danger",onClick:async()=>{if(confirm(`Revoke ${s.name||s.client_name}? All active tokens will be invalidated.`))try{s.auth_type==="oauth"?await be.revokeClient(s.id||s.client_id||""):await be.revokeApiKey(s.name||""),r(),T()}catch(K){alert("Revoke failed: "+(K instanceof Error?K.message:"unknown error"))}},children:"Revoke Agent"}),s.status==="revoked"&&c.jsx("span",{style:{color:"var(--text-muted)",fontSize:13},children:"This agent has been revoked."})]})]})]})}function Yy(){const[s,A]=B.useState({rows:[],total:0,page:1,pages:1}),[T,r]=B.useState(1),[D,_]=B.useState("all"),[H,Y]=B.useState(null);B.useEffect(()=>{O(T)},[T,D]);const O=N=>{const J=D!=="all"?`&agent=${encodeURIComponent(D)}`:"";be.requests(N,J).then(A).catch(()=>{})},d=N=>{const J=Date.now()-new Date(N).getTime();return J<6e4?`${Math.floor(J/1e3)}s ago`:J<36e5?`${Math.floor(J/6e4)} min ago`:J<864e5?`${Math.floor(J/36e5)}h ago`:new Date(N).toLocaleDateString()},M=N=>{if(!N)return null;const{query:J,slug:K,partial:ie,limit:je,...ue}=N,k=[];return J&&k.push(`"${J}"`),K&&k.push(K),ie&&k.push(`~${ie}`),je&&k.push(`limit=${je}`),Object.keys(ue).length>0&&k.push(`+${Object.keys(ue).length} params`),k.join(" ")},C=new Map;return s.rows.forEach(N=>{N.token_name&&C.set(N.token_name,N.agent_name||N.token_name)}),c.jsxs(c.Fragment,{children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:24},children:[c.jsx("h1",{className:"page-title",style:{marginBottom:0},children:"Request Log"}),c.jsxs("select",{value:D,onChange:N=>{_(N.target.value),r(1)},style:{background:"var(--bg-secondary)",color:"var(--text-primary)",border:"1px solid var(--border)",borderRadius:6,padding:"4px 8px",fontSize:13},children:[c.jsx("option",{value:"all",children:"All agents"}),[...C.entries()].map(([N,J])=>c.jsx("option",{value:N,children:J},N))]})]}),s.rows.length===0?c.jsx("div",{style:{textAlign:"center",padding:48,color:"var(--text-muted)"},children:"No requests yet."}):c.jsxs(c.Fragment,{children:[c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Time"}),c.jsx("th",{children:"Agent"}),c.jsx("th",{children:"Operation"}),c.jsx("th",{children:"Params"}),c.jsx("th",{children:"Latency"}),c.jsx("th",{children:"Status"})]})}),c.jsx("tbody",{children:s.rows.map(N=>c.jsxs(qd.Fragment,{children:[c.jsxs("tr",{onClick:()=>Y(H===N.id?null:N.id),style:{cursor:"pointer"},children:[c.jsx("td",{style:{color:"var(--text-secondary)",whiteSpace:"nowrap"},children:d(N.created_at)}),c.jsx("td",{children:c.jsx("a",{style:{color:"var(--text-link, #88aaff)",cursor:"pointer",textDecoration:"none",fontWeight:500},onClick:J=>{J.stopPropagation(),_(N.token_name),r(1)},children:N.agent_name||N.token_name})}),c.jsx("td",{className:"mono",children:N.operation}),c.jsx("td",{style:{color:"var(--text-secondary)",fontSize:12,maxWidth:200,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M(N.params)}),c.jsxs("td",{className:"mono",children:[N.latency_ms,"ms"]}),c.jsx("td",{children:c.jsx("span",{className:`badge badge-${N.status}`,children:N.status})})]}),H===N.id&&c.jsx("tr",{children:c.jsx("td",{colSpan:6,style:{background:"var(--bg-secondary, #0f0f1a)",padding:16},children:c.jsxs("div",{style:{display:"grid",gridTemplateColumns:"100px 1fr",gap:"6px 12px",fontSize:13},children:[c.jsx("span",{style:{color:"var(--text-muted)"},children:"Time"}),c.jsx("span",{children:new Date(N.created_at).toLocaleString()}),c.jsx("span",{style:{color:"var(--text-muted)"},children:"Agent"}),c.jsx("span",{className:"mono",children:N.token_name}),c.jsx("span",{style:{color:"var(--text-muted)"},children:"Operation"}),c.jsx("span",{className:"mono",children:N.operation}),c.jsx("span",{style:{color:"var(--text-muted)"},children:"Latency"}),c.jsxs("span",{children:[N.latency_ms,"ms"]}),N.params&&c.jsxs(c.Fragment,{children:[c.jsx("span",{style:{color:"var(--text-muted)"},children:"Params"}),c.jsx("pre",{className:"mono",style:{margin:0,whiteSpace:"pre-wrap",fontSize:12},children:JSON.stringify(N.params,null,2)})]}),N.error_message&&c.jsxs(c.Fragment,{children:[c.jsx("span",{style:{color:"var(--error, #ff6b6b)"},children:"Error"}),c.jsx("span",{style:{color:"var(--error, #ff6b6b)"},children:N.error_message})]})]})})})]},N.id))})]}),c.jsxs("div",{className:"pagination",children:[c.jsxs("span",{children:["Page ",s.page," of ",s.pages," (",s.total," total)"]}),c.jsxs("div",{style:{display:"flex",gap:8},children:[c.jsx("button",{disabled:s.page<=1,onClick:()=>r(N=>N-1),children:"Previous"}),c.jsx("button",{disabled:s.page>=s.pages,onClick:()=>r(N=>N+1),children:"Next"})]})]})]})]})}function Gy({markup:s}){return c.jsx("div",{style:{width:"100%",overflow:"auto"},dangerouslySetInnerHTML:{__html:s}})}function Lu({type:s,ariaLabel:A}){const[T,r]=B.useState(""),[D,_]=B.useState("");return B.useEffect(()=>{let H=!1;return be.calibrationChart(s).then(Y=>{H||r(Y)}).catch(Y=>{H||_(Y.message??"fetch failed")}),()=>{H=!0}},[s]),D?c.jsxs("div",{style:{padding:16,color:"var(--error)"},role:"alert",children:[A,": ",D]}):T?c.jsx(Gy,{markup:T}):c.jsxs("div",{style:{padding:16,color:"var(--text-muted)"},children:[A," loading..."]})}function Xy(){const[s,A]=B.useState(null),[T,r]=B.useState(!0),[D,_]=B.useState("");if(B.useEffect(()=>{be.calibrationProfile().then(O=>{A(O),r(!1)}).catch(O=>{_(O.message??"fetch failed"),r(!1)})},[]),T)return c.jsx("div",{style:{padding:24,color:"var(--text-secondary)"},children:"Loading calibration profile…"});if(D)return c.jsxs("div",{style:{padding:24,color:"var(--error)"},role:"alert",children:["Could not load calibration profile: ",D]});if(!s)return c.jsxs("div",{style:{padding:24,maxWidth:700},children:[c.jsx("h1",{style:{marginBottom:16},children:"Calibration"}),c.jsx("p",{style:{color:"var(--text-secondary)"},children:"No calibration profile yet. Builds after 5+ resolved takes."}),c.jsx("pre",{style:{background:"var(--bg-secondary)",padding:12,borderRadius:4,color:"var(--text-primary)",marginTop:12,fontFamily:"var(--font-mono)"},children:"gbrain dream --phase calibration_profile"})]});const H=new Date(s.generated_at),Y=Math.floor((Date.now()-H.getTime())/(1e3*60*60*24));return c.jsxs("div",{style:{padding:32,maxWidth:720},children:[c.jsx("h1",{style:{marginBottom:8},children:"Calibration"}),c.jsxs("div",{style:{color:"var(--text-muted)",fontSize:13,marginBottom:24},children:["Holder: ",s.holder," · ","Updated ",Y===0?"today":`${Y}d ago`,s.published&&" · published",s.grade_completion<.9&&` · ~${Math.round(s.grade_completion*100)}% graded`,!s.voice_gate_passed&&" · voice gate fell back to template"]}),c.jsx("section",{style:{marginBottom:32},children:c.jsx(Lu,{type:"brier-trend",ariaLabel:"Brier trend"})}),c.jsxs("section",{style:{marginBottom:32},children:[c.jsx("h2",{style:{fontSize:14,color:"var(--text-secondary)",marginBottom:12,fontWeight:400},children:"Pattern statements"}),c.jsx(Lu,{type:"pattern-statements",ariaLabel:"Pattern statements"})]}),c.jsx("section",{style:{marginBottom:32},children:c.jsx(Lu,{type:"domain-bars",ariaLabel:"Per-domain accuracy"})}),c.jsx("section",{style:{marginBottom:32},children:c.jsx(Lu,{type:"abandoned-threads",ariaLabel:"Abandoned threads"})}),s.active_bias_tags.length>0&&c.jsxs("section",{style:{marginBottom:32,color:"var(--text-muted)",fontSize:13},children:["Active bias tags: ",s.active_bias_tags.join(", ")]})]})}function Qy(s){return s===0?"var(--accent-success, #2ea043)":s>=100?"var(--accent-danger, #f85149)":"var(--accent-warn, #d29922)"}function Cd(s){return`$${(s/100).toFixed(2)}`}function Zy(){const[s,A]=B.useState(null),[T,r]=B.useState(null);if(B.useEffect(()=>{let _=!0,H=null;const Y=async()=>{try{const O=await be.jobsWatch();_&&(A(O),r(null))}catch(O){_&&r(O instanceof Error?O.message:String(O))}_&&(H=setTimeout(Y,1e3))};return Y(),()=>{_=!1,H&&clearTimeout(H)}},[]),T)return c.jsxs("div",{style:{padding:24,color:"var(--accent-danger, #f85149)"},children:[c.jsx("h2",{children:"Jobs Watch — error"}),c.jsx("pre",{style:{whiteSpace:"pre-wrap"},children:T})]});if(!s)return c.jsx("div",{style:{padding:24,color:"var(--text-muted, #777)"},children:"Loading jobs watch…"});const D=new Date(s.ts_ms).toLocaleTimeString();return c.jsxs("div",{style:{padding:24,fontFamily:'var(--font-mono, "JetBrains Mono", monospace)'},children:[c.jsxs("h1",{style:{fontSize:18,marginBottom:4},children:["Jobs Watch",c.jsxs("span",{style:{marginLeft:12,color:"var(--text-muted, #777)",fontSize:12,fontWeight:"normal"},children:["updated ",D]})]}),c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Queue"}),c.jsxs("div",{children:["waiting=",c.jsx("b",{children:s.queue_health.waiting})," ","active=",c.jsx("b",{children:s.queue_health.active})," ","stalled=",c.jsx("b",{style:{color:s.queue_health.stalled>0?"var(--accent-warn, #d29922)":void 0},children:s.queue_health.stalled})]})]}),s.by_type.length>0&&c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"By type (24h)"}),c.jsxs("table",{style:{borderCollapse:"collapse"},children:[c.jsx("thead",{children:c.jsxs("tr",{style:{color:"var(--text-muted, #777)",fontSize:12},children:[c.jsx("th",{style:{textAlign:"left",padding:"4px 12px 4px 0"},children:"name"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"total"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"done"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"fail"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"dead"})]})}),c.jsx("tbody",{children:s.by_type.slice(0,6).map(_=>c.jsxs("tr",{children:[c.jsx("td",{style:{padding:"4px 12px 4px 0"},children:_.name}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.total}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.completed}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.failed}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.dead})]},_.name))})]})]}),c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Lease pressure (1h)"}),c.jsxs("div",{style:{color:Qy(s.lease_pressure_1h)},children:[s.lease_pressure_1h," bounce",s.lease_pressure_1h===1?"":"s"]})]}),s.top_errors.length>0&&c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Top errors (24h)"}),c.jsx("table",{style:{borderCollapse:"collapse"},children:c.jsx("tbody",{children:s.top_errors.slice(0,5).map(_=>c.jsxs("tr",{children:[c.jsxs("td",{style:{textAlign:"right",padding:"4px 12px 4px 0",color:"var(--text-muted, #777)"},children:[_.count,"×"]}),c.jsx("td",{style:{padding:"4px 12px 4px 0"},children:_.cluster})]},_.cluster))})})]}),s.budget_owners.length>0&&c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Budget owners"}),c.jsxs("table",{style:{borderCollapse:"collapse"},children:[c.jsx("thead",{children:c.jsxs("tr",{style:{color:"var(--text-muted, #777)",fontSize:12},children:[c.jsx("th",{style:{textAlign:"left",padding:"4px 12px 4px 0"},children:"owner"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"spent"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"remaining"})]})}),c.jsx("tbody",{children:s.budget_owners.slice(0,5).map(_=>c.jsxs("tr",{children:[c.jsx("td",{style:{padding:"4px 12px 4px 0"},children:_.owner_id}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:Cd(_.total_spent_cents)}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:Cd(_.remaining_cents)})]},_.owner_id))})]})]})]})}const ys="gbrain.pending-oauth-request",Ud=s=>s!==null&&/^[a-f0-9]{64}$/.test(s);function gs(){const s=new URL(window.location.href).searchParams.get("oauth_request");if(Ud(s)){try{window.sessionStorage.setItem(ys,s)}catch{}return s}try{const A=window.sessionStorage.getItem(ys);if(Ud(A))return A}catch{}}function Rd(){try{window.sessionStorage.removeItem(ys)}catch{}const s=new URL(window.location.href);s.searchParams.delete("oauth_request"),window.history.replaceState(null,"",s)}function Ly(){var Y,O;const[s,A]=B.useState(),[T,r]=B.useState(""),[D,_]=B.useState(!1);B.useEffect(()=>{let d=!0;const M=gs();if(!M){r("No pending authorization request. Restart the connection from your client.");return}return be.oauthRequest(M).then(C=>{d&&A(C)}).catch(C=>{d&&r(C.message)}),()=>{d=!1}},[]);const H=async d=>{if(!(!s||D)){_(!0),r("");try{const M=await be.decideOAuthRequest(s.id,d,s.csrf);Rd(),window.location.assign(M.redirectUrl)}catch(M){r(M instanceof Error?M.message:"Approval failed. Restart the connection from your client."),A(void 0),_(!1)}}};return c.jsxs("section",{"aria-labelledby":"consent-title",style:{maxWidth:760},children:[c.jsx("h1",{id:"consent-title",children:"Approve client access"}),c.jsx("p",{style:{color:"var(--text-secondary)",margin:"16px 0"},children:"Only approve a connection you initiated. These permissions let the client act on your brain."}),T&&c.jsx("div",{role:"alert",className:"login-error",style:{marginBottom:16},children:T}),!s&&!T&&c.jsx("p",{role:"status",children:"Loading authorization request…"}),s&&c.jsxs(c.Fragment,{children:[c.jsxs("dl",{className:"oauth-consent-details",children:[c.jsx("dt",{children:"Client"}),c.jsx("dd",{children:s.clientName}),c.jsx("dt",{children:"Client ID"}),c.jsx("dd",{children:c.jsx("code",{children:s.clientId})}),c.jsx("dt",{children:"Redirect destination"}),c.jsx("dd",{children:c.jsx("code",{children:s.redirectUri})}),c.jsx("dt",{children:"Permissions"}),c.jsx("dd",{children:s.scopes.length?s.scopes.map(d=>c.jsx("span",{className:`badge ${d.includes("admin")?"badge-error":""}`,style:{marginRight:8},children:d},d)):"No permissions"}),c.jsx("dt",{children:"Administrative access"}),c.jsx("dd",{children:s.scopes.some(d=>d==="admin")?"Administration within the allowed operations shown below.":s.scopes.some(d=>d.endsWith("_admin"))?"Administrative capabilities are included in the permissions above.":"None"}),c.jsx("dt",{children:"Allowed operations"}),c.jsx("dd",{children:s.allowedOperations===null?"All operations permitted by these scopes and the server policy":s.allowedOperations.join(", ")||"None"}),c.jsx("dt",{children:"Write paths"}),c.jsx("dd",{children:s.boundSlugPrefixes===null?"Within the granted source":s.boundSlugPrefixes.join(", ")||"None"}),s.scopes.includes("agent")&&c.jsxs(c.Fragment,{children:[c.jsx("dt",{children:"Delegated tools"}),c.jsx("dd",{children:((Y=s.delegatedTools)==null?void 0:Y.join(", "))||"None"}),c.jsx("dt",{children:"Delegated write paths"}),c.jsx("dd",{children:s.delegatedNamespace==="job"?"A separate namespace for each job":((O=s.delegatedSlugPrefixes)==null?void 0:O.join(", "))||"None"})]}),c.jsx("dt",{children:"Write source"}),c.jsx("dd",{children:s.sourceId??"Not configured"}),c.jsx("dt",{children:"Read sources"}),c.jsx("dd",{children:s.allowedSources.length?s.allowedSources.join(", "):s.sourceId??"Not configured"}),c.jsx("dt",{children:"Resource"}),c.jsx("dd",{children:c.jsx("code",{children:s.resource??"No resource binding requested"})}),c.jsx("dt",{children:"Request expires"}),c.jsx("dd",{children:new Date(s.expiresAt).toLocaleTimeString()})]}),c.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:12,marginTop:24},children:[c.jsx("button",{className:"btn",disabled:D,onClick:()=>H("deny"),children:"Deny"}),c.jsx("button",{className:"btn btn-primary",disabled:D,onClick:()=>H("approve"),children:D?"Completing request…":"Approve access"})]})]}),T&&c.jsx("button",{className:"btn",onClick:()=>{Rd(),window.location.hash="agents"},children:"Return to agents"})]})}function Hd(){const s=window.location.hash.replace("#","")||"dashboard";return gs()&&s==="dashboard"?"oauth-consent":["login","dashboard","agents","log","calibration","jobs","oauth-consent"].includes(s)?s:"dashboard"}function Vy(){const[s,A]=B.useState(Hd);B.useEffect(()=>{const D=()=>A(Hd());return window.addEventListener("hashchange",D),()=>window.removeEventListener("hashchange",D)},[]);const T=D=>{window.location.hash=D,A(D)};if(s==="login")return c.jsx(zy,{onLogin:()=>T(gs()?"oauth-consent":"dashboard")});const r=async()=>{if(confirm("Sign out every active admin session, including other browsers and tabs? Each one will need to re-authenticate via a fresh magic link.")){try{await be.signOutEverywhere()}catch{}T("login")}};return c.jsxs("div",{className:"app",children:[c.jsxs("nav",{className:"sidebar",children:[c.jsx("div",{className:"sidebar-logo",children:"GBrain"}),c.jsxs("div",{className:"sidebar-nav",children:[c.jsx("a",{className:`nav-item ${s==="dashboard"?"active":""}`,onClick:()=>T("dashboard"),children:"Dashboard"}),c.jsx("a",{className:`nav-item ${s==="agents"?"active":""}`,onClick:()=>T("agents"),children:"Agents"}),c.jsx("a",{className:`nav-item ${s==="log"?"active":""}`,onClick:()=>T("log"),children:"Request Log"}),c.jsx("a",{className:`nav-item ${s==="calibration"?"active":""}`,onClick:()=>T("calibration"),children:"Calibration"}),c.jsx("a",{className:`nav-item ${s==="jobs"?"active":""}`,onClick:()=>T("jobs"),children:"Jobs Watch"})]}),c.jsx("div",{style:{marginTop:"auto",padding:"16px 12px",borderTop:"1px solid var(--border)"},children:c.jsx("button",{onClick:r,style:{background:"transparent",border:"1px solid var(--border)",color:"var(--text-secondary)",padding:"6px 10px",borderRadius:6,fontSize:12,cursor:"pointer",width:"100%"},title:"Revoke every active admin session — every browser, every tab",children:"Sign out everywhere"})})]}),c.jsxs("main",{className:"main",children:[s==="dashboard"&&c.jsx(Ay,{}),s==="agents"&&c.jsx(Cy,{}),s==="log"&&c.jsx(Yy,{}),s==="calibration"&&c.jsx(Xy,{}),s==="jobs"&&c.jsx(Zy,{}),s==="oauth-consent"&&c.jsx(Ly,{})]})]})}jy.createRoot(document.getElementById("root")).render(c.jsx(qd.StrictMode,{children:c.jsx(Vy,{})}));diff --git a/admin/dist/index.html b/admin/dist/index.htmlindex 8a8d946b88..c317f2618b 100644--- a/admin/dist/index.html+++ b/admin/dist/index.html@@ -7,8 +7,8 @@<link rel="preconnect" href="https://fonts.googleapis.com" /><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet" />- <script type="module" crossorigin src="/admin/assets/index-B5gNvpC1.js"></script>- <link rel="stylesheet" crossorigin href="/admin/assets/index-CLnyXRh0.css">+ <script type="module" crossorigin src="/admin/assets/index-DfSDTH-v.js"></script>+ <link rel="stylesheet" crossorigin href="/admin/assets/index-DECOlanw.css"></head><body><div id="root"></div>diff --git a/admin/src/App.tsx b/admin/src/App.tsxindex fd6c3ed90a..f2d81057cd 100644--- a/admin/src/App.tsx+++ b/admin/src/App.tsx@@ -5,13 +5,16 @@ import { AgentsPage } from './pages/Agents';import { RequestLogPage } from './pages/RequestLog';import { CalibrationPage } from './pages/Calibration';import { JobsWatchPage } from './pages/JobsWatch';+import { OAuthConsentPage } from './pages/OAuthConsent';+import { pendingOAuthRequest } from './lib/oauth-request';import { api } from './api';-type Page = 'login' | 'dashboard' | 'agents' | 'log' | 'calibration' | 'jobs';+type Page = 'login' | 'dashboard' | 'agents' | 'log' | 'calibration' | 'jobs' | 'oauth-consent';function getPage(): Page {const hash = window.location.hash.replace('#', '') || 'dashboard';- if (['login', 'dashboard', 'agents', 'log', 'calibration', 'jobs'].includes(hash)) return hash as Page;+ if (pendingOAuthRequest() && hash === 'dashboard') return 'oauth-consent';+ if (['login', 'dashboard', 'agents', 'log', 'calibration', 'jobs', 'oauth-consent'].includes(hash)) return hash as Page;return 'dashboard';}@@ -30,7 +33,7 @@ export function App() {};if (page === 'login') {- return <LoginPage onLogin={() => navigate('dashboard')} />;+ return <LoginPage onLogin={() => navigate(pendingOAuthRequest() ? 'oauth-consent' : 'dashboard')} />;}const handleSignOutEverywhere = async () => {@@ -86,6 +89,7 @@ export function App() {{page === 'log' && <RequestLogPage />}{page === 'calibration' && <CalibrationPage />}{page === 'jobs' && <JobsWatchPage />}+ {page === 'oauth-consent' && <OAuthConsentPage />}</main></div>);diff --git a/admin/src/api.ts b/admin/src/api.tsindex 4bec496bf7..76070718bc 100644--- a/admin/src/api.ts+++ b/admin/src/api.ts@@ -34,6 +34,9 @@ async function apiFetchText(path: string) {}export const api = {+ oauthRequest: (id: string) => apiFetch(`/admin/api/oauth-requests/${encodeURIComponent(id)}`),+ decideOAuthRequest: (id: string, decision: 'approve' | 'deny', csrf: string) =>+ apiFetch(`/admin/api/oauth-requests/${encodeURIComponent(id)}`, { method: 'POST', body: JSON.stringify({ decision, csrf }) }),login: (token: string) => apiFetch('/admin/login', { method: 'POST', body: JSON.stringify({ token }) }),signOutEverywhere: () => apiFetch('/admin/api/sign-out-everywhere', { method: 'POST' }),stats: () => apiFetch('/admin/api/stats'),diff --git a/admin/src/index.css b/admin/src/index.cssindex d5ca60fc5a..ad91a720f1 100644--- a/admin/src/index.css+++ b/admin/src/index.css@@ -359,3 +359,8 @@ label { display: block; font-size: 13px; font-weight: 500; margin-bottom: 6px; }.metrics { flex-wrap: wrap; }.drawer { width: 100%; }}+/* Consent uses the existing dashboard typography and semantic controls. */+.oauth-consent-details { display: grid; grid-template-columns: 160px minmax(0, 1fr); gap: 16px; }+.oauth-consent-details dt { color: var(--text-secondary); }+.oauth-consent-details dd { margin: 0; overflow-wrap: anywhere; }+@media (max-width: 640px) { .oauth-consent-details { grid-template-columns: 1fr; gap: 8px; } .oauth-consent-details dd { margin-bottom: 12px; } }diff --git a/admin/src/lib/oauth-request.ts b/admin/src/lib/oauth-request.tsnew file mode 100644index 0000000000..bc794c7fa2--- /dev/null+++ b/admin/src/lib/oauth-request.ts@@ -0,0 +1,22 @@+// This stores only an opaque pending-request ID, never an admin credential.+// It lets a single-use magic link return to consent in the same browser tab.+const KEY = 'gbrain.pending-oauth-request';+const valid = (value: string | null): value is string => value !== null && /^[a-f0-9]{64}$/.test(value);+export function pendingOAuthRequest(): string | undefined {+ const fromUrl = new URL(window.location.href).searchParams.get('oauth_request');+ if (valid(fromUrl)) {+ try { window.sessionStorage.setItem(KEY, fromUrl); } catch { /* query remains sufficient */ }+ return fromUrl;+ }+ try {+ const saved = window.sessionStorage.getItem(KEY);+ if (valid(saved)) return saved;+ } catch { /* browser storage may be disabled */ }+ return undefined;+}+export function clearOAuthRequest(): void {+ try { window.sessionStorage.removeItem(KEY); } catch { /* best effort */ }+ const url = new URL(window.location.href);+ url.searchParams.delete('oauth_request');+ window.history.replaceState(null, '', url);+}diff --git a/admin/src/pages/OAuthConsent.tsx b/admin/src/pages/OAuthConsent.tsxnew file mode 100644index 0000000000..7cd6368c94--- /dev/null+++ b/admin/src/pages/OAuthConsent.tsx@@ -0,0 +1,69 @@+import React, { useEffect, useState } from 'react';+import { api } from '../api';+import { clearOAuthRequest, pendingOAuthRequest } from '../lib/oauth-request';++interface ConsentRequest {+ id: string; clientId: string; clientName: string; redirectUri: string;+ scopes: string[]; sourceId: string | null; allowedSources: string[];+ allowedOperations: string[] | null; boundSlugPrefixes: string[] | null;+ delegatedTools: string[] | null; delegatedSlugPrefixes: string[] | null; delegatedNamespace: string | null;+ resource: string | null; expiresAt: number; csrf: string;+}++export function OAuthConsentPage() {+ const [request, setRequest] = useState<ConsentRequest>();+ const [error, setError] = useState('');+ const [busy, setBusy] = useState(false);+ useEffect(() => {+ let active = true;+ const id = pendingOAuthRequest();+ if (!id) { setError('No pending authorization request. Restart the connection from your client.'); return; }+ api.oauthRequest(id).then(value => { if (active) setRequest(value); })+ .catch(err => { if (active) setError(err.message); });+ return () => { active = false; };+ }, []);+ const decide = async (decision: 'approve' | 'deny') => {+ if (!request || busy) return;+ setBusy(true);+ setError('');+ try {+ const result = await api.decideOAuthRequest(request.id, decision, request.csrf);+ clearOAuthRequest();+ window.location.assign(result.redirectUrl);+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Approval failed. Restart the connection from your client.');+ setRequest(undefined); // do not retry a potentially committed approval+ setBusy(false);+ }+ };+ return <section aria-labelledby="consent-title" style={{ maxWidth: 760 }}>+ <h1 id="consent-title">Approve client access</h1>+ <p style={{ color: 'var(--text-secondary)', margin: '16px 0' }}>Only approve a connection you initiated. These permissions let the client act on your brain.</p>+ {error && <div role="alert" className="login-error" style={{ marginBottom: 16 }}>{error}</div>}+ {!request && !error && <p role="status">Loading authorization request…</p>}+ {request && <>+ <dl className="oauth-consent-details">+ <dt>Client</dt><dd>{request.clientName}</dd>+ <dt>Client ID</dt><dd><code>{request.clientId}</code></dd>+ <dt>Redirect destination</dt><dd><code>{request.redirectUri}</code></dd>+ <dt>Permissions</dt><dd>{request.scopes.length ? request.scopes.map(scope => <span key={scope} className={`badge ${scope.includes('admin') ? 'badge-error' : ''}`} style={{ marginRight: 8 }}>{scope}</span>) : 'No permissions'}</dd>+ <dt>Administrative access</dt><dd>{request.scopes.some(scope => scope === 'admin') ? 'Administration within the allowed operations shown below.' : request.scopes.some(scope => scope.endsWith('_admin')) ? 'Administrative capabilities are included in the permissions above.' : 'None'}</dd>+ <dt>Allowed operations</dt><dd>{request.allowedOperations === null ? 'All operations permitted by these scopes and the server policy' : request.allowedOperations.join(', ') || 'None'}</dd>+ <dt>Write paths</dt><dd>{request.boundSlugPrefixes === null ? 'Within the granted source' : request.boundSlugPrefixes.join(', ') || 'None'}</dd>+ {request.scopes.includes('agent') && <>+ <dt>Delegated tools</dt><dd>{request.delegatedTools?.join(', ') || 'None'}</dd>+ <dt>Delegated write paths</dt><dd>{request.delegatedNamespace === 'job' ? 'A separate namespace for each job' : request.delegatedSlugPrefixes?.join(', ') || 'None'}</dd>+ </>}+ <dt>Write source</dt><dd>{request.sourceId ?? 'Not configured'}</dd>+ <dt>Read sources</dt><dd>{request.allowedSources.length ? request.allowedSources.join(', ') : request.sourceId ?? 'Not configured'}</dd>+ <dt>Resource</dt><dd><code>{request.resource ?? 'No resource binding requested'}</code></dd>+ <dt>Request expires</dt><dd>{new Date(request.expiresAt).toLocaleTimeString()}</dd>+ </dl>+ <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 12, marginTop: 24 }}>+ <button className="btn" disabled={busy} onClick={() => decide('deny')}>Deny</button>+ <button className="btn btn-primary" disabled={busy} onClick={() => decide('approve')}>{busy ? 'Completing request…' : 'Approve access'}</button>+ </div>+ </>}+ {error && <button className="btn" onClick={() => { clearOAuthRequest(); window.location.hash = 'agents'; }}>Return to agents</button>}+ </section>;+}diff --git a/bun.lock b/bun.lockindex 41d04ec884..eefd1dc25b 100644--- a/bun.lock+++ b/bun.lock@@ -24,7 +24,6 @@"exifr": "^7.1.3","express": "^5.1.0","express-rate-limit": "^7.5.0",- "gray-matter": "^4.0.3","heic-decode": "^2.1.0","js-yaml": "^3.15.2","jsonc-parser": "^3.3.1",@@ -397,8 +396,6 @@"express-rate-limit": ["[email protected]", "", { "peerDependencies": { "express": ">= 4.11" } }, "sha512-7iN8iPMDzOMHPUYllBEsQdWVB6fPDMPqwjBaFrgr4Jgr/+okjvzAy+UHlYYL/Vs0OsOrMkwS6PJDkFlJwoxUnw=="],- "extend-shallow": ["[email protected]", "", { "dependencies": { "is-extendable": "^0.1.0" } }, "sha512-zCnTtlxNoAiDc3gqY2aYAWFx7XWWiasuF2K8Me5WbN8otHKTUKBwjPtNpRs/rbUZm7KxWAaNj7P1a/p52GbVug=="],-"fast-check": ["[email protected]", "", { "dependencies": { "pure-rand": "^8.0.0" } }, "sha512-GOJ158CUMnN6cSahsv4+ExARvIDuzzinFjkp0E9WtiBa5zcVeLozVkWaE4IzFcc+Y48Wp1EDlUZsXRyAztQcSg=="],"fast-deep-equal": ["[email protected]", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],@@ -429,8 +426,6 @@"gopd": ["[email protected]", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="],- "gray-matter": ["[email protected]", "", { "dependencies": { "js-yaml": "^3.13.1", "kind-of": "^6.0.2", "section-matter": "^1.0.0", "strip-bom-string": "^1.0.0" } }, "sha512-5v6yZd4JK3eMI3FqqCouswVqwugaA9r4dNZB1wwcmrD02QkV5H0y7XBQW8QwQqEaZY1pM9aqORSORhJRdNK44Q=="],-"has-symbols": ["[email protected]", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],"has-tostringtag": ["[email protected]", "", { "dependencies": { "has-symbols": "^1.0.3" } }, "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw=="],@@ -453,8 +448,6 @@"ipaddr.js": ["[email protected]", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],- "is-extendable": ["[email protected]", "", {}, "sha512-5BMULNob1vgFX6EjQw5izWDxrecWK9AM72rugNr0TFldMOi0fj6Jk+zeKIt0xGj4cEfQIJth4w3OKWOJ4f+AFw=="],-"is-promise": ["[email protected]", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],"is-unsafe": ["[email protected]", "", {}, "sha512-2LdV822R+wmI86unXA93WCFpL6g+av8ynWk0nrHyJqGop5VoocYsSLFgN8jrfalT6iGeLNM4KXuVSsULP53kEA=="],@@ -473,8 +466,6 @@"jsonc-parser": ["[email protected]", "", {}, "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ=="],- "kind-of": ["[email protected]", "", {}, "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw=="],-"libheif-js": ["[email protected]", "", {}, "sha512-vQJWusIxO7wavpON1dusciL8Go9jsIQ+EUrckauFYAiSTjcmLAsuJh3SszLpvkwPci3JcL41ek2n+LUZGFpPIQ=="],"marked": ["[email protected]", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-MrV5puXBfuiy6wl6DLaq3BtIJQAJToAd5zt/ZKhRfGRAuFPALE7/4Y7jnxRQoEgK/pBgurGqLyAuRgZ2xOjr6w=="],@@ -539,8 +530,6 @@"safer-buffer": ["[email protected]", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],- "section-matter": ["[email protected]", "", { "dependencies": { "extend-shallow": "^2.0.1", "kind-of": "^6.0.0" } }, "sha512-vfD3pmTzGpufjScBh50YHKzEu2lxBWhVEHsNGoEXmCmn2hKGfeNLYMzCJpe8cD7gqX7TJluOVpBkAequ6dgMmA=="],-"send": ["[email protected]", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="],"serve-static": ["[email protected]", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="],@@ -563,8 +552,6 @@"statuses": ["[email protected]", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],- "strip-bom-string": ["[email protected]", "", {}, "sha512-uCC2VHvQRYu+lMh4My/sFNmF2klFymLX1wHJeXnbEJERpV/ZsVuonzerjfrGpIGF7LBVa1O7i9kjiWvJiFck8g=="],-"strnum": ["[email protected]", "", { "dependencies": { "anynum": "^1.0.1" } }, "sha512-M9eUSMT2dCB2cTNPG7UYj6KuK7RJR2SN2+yCV/fTW3xzTCS6EaGZ5pSMgDIjB7r8zSfTGk+dvvn9rTjpVS9Mwg=="],"toidentifier": ["[email protected]", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],diff --git a/docker-compose.ci.yml b/docker-compose.ci.ymlindex 86b08dba31..e05705ea8c 100644--- a/docker-compose.ci.yml+++ b/docker-compose.ci.yml@@ -5,8 +5,8 @@# `bun run ci:local:diff` (see scripts/ci-local.sh).## All services are pulled as `image:` (no build) so `docker compose pull`-# refreshes everything. #4479: the bun tag is PINNED (default 1.3.14, matching-# the host/dev bun) instead of floating with `oven/bun:1` — a floating tag+# refreshes everything. #4479: the bun tag is PINNED (default 1.3.13, matching+# the CI/build bun) instead of floating with `oven/bun:1` — a floating tag# resolved to a newer bun than the host and produced container-only behavior# skew during release gates. Override per-run with GBRAIN_CI_BUN_TAG (e.g.# GBRAIN_CI_BUN_TAG=1 to deliberately test against latest). Named volumes@@ -125,8 +125,12 @@ services:runner:# #4479: pinned to the host bun version by default (see header comment).- image: oven/bun:${GBRAIN_CI_BUN_TAG:-1.3.14}+ image: oven/bun:${GBRAIN_CI_BUN_TAG:-1.3.13}working_dir: /app+ environment:+ # The bind-mounted checkout may contain private developer test keys.+ # This gate uses isolated DBs and synthetic provider fixtures, like CI.+ GBRAIN_CI_DISABLE_TEST_ENV_FILE: "1"# #3893 (reimplemented from @y2688): give a TERM'd runner up to 600s to# drain in-flight bun test shards and flush their results before docker# SIGKILLs the container mid-write (compose default grace is 10s).diff --git a/docs/TESTING.md b/docs/TESTING.mdindex cbb586f6ad..50bf5f638d 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -801,3 +801,34 @@ permission to run them — see the "run without asking" rule above.Never leave `gbrain-test-pg` running. If you find a stale one from a previous run,stop and remove it before starting a new one.++## Authorization regression gates++`test/data-frontmatter.test.ts` and `test/frontmatter-security.test.ts` pin inert+frontmatter parsing, opaque serialization, scalar compatibility, and import+errors. `test/authorization-boundaries.test.ts` covers scalar source grants,+foreign/private facts, and delegated tool exclusions.++`test/oauth-consent-security.test.ts` covers pending consent, CSRF, policy+changes, duplicate decisions, and uncertain completion. Production HTTP flows+live in `test/e2e/serve-http-consent.test.ts`; client-lock races and grant rollback+on Postgres live in `test/e2e/oauth-grant-transactions.test.ts`.++`test/minions-submission-authority.test.ts` covers submission schemas, durable+policy, lifecycle operations, legacy approval snapshots, file confinement, and+both workers. `test/e2e/minions-authority-parity.test.ts` exercises real Postgres+JSONB and authorization behavior. Filesystem write concurrency is pinned by the+existing fence and timeline suites.++`test/guarded-http.test.ts` and `test/guarded-http-tls.serial.test.ts` cover DNS,+TLS identity and ports, redirects, deadlines, body limits, and cleanup. CI runs+these boundaries on Bun 1.3.11 and 1.3.13, audits root and admin dependencies, and+executes `scripts/test-gitleaks-config.sh` to prove fixture exceptions still+report an unrelated secret in the same file. `scripts/scan-worktree-secrets.sh`+scans tracked files plus new files eligible for commit; tracked ignored files+remain included. Full-history scans use `gitleaks git . --log-opts=--all` from a+complete clone and reports must remain private.++The Docker gate sets `GBRAIN_CI_DISABLE_TEST_ENV_FILE=1` so a bind-mounted+developer `.env.testing` cannot add credentials or change the isolated test+database. Explicit local provider E2E runs can continue using that file.diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.mdindex bddcdd0ef3..d0f933f093 100644--- a/docs/TOOL_CATALOG.md+++ b/docs/TOOL_CATALOG.md@@ -4,7 +4,7 @@<!-- Regenerate: bun run scripts/generate-tool-catalog.ts --><!-- Freshness-guarded by scripts/check-tool-catalog-fresh.sh (bun run verify). -->-Every non-localOnly operation on the MCP surface: 122 tools across 23 areas. **Starter** marks membership in the ~28-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.+Every non-localOnly operation on the MCP surface: 122 tools across 23 areas. **Starter** marks membership in the ~26-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.## admin@@ -102,7 +102,7 @@ Every non-localOnly operation on the MCP surface: 122 tools across 23 areas. **S| `retry_job` | Re-queue a failed or dead job for retry | admin | | || `send_job_message` | Send a sidechannel message to a running job's inbox | admin | | || `submit_agent` | Submit an LLM agent job that the worker dispatches via the gateway-native tool loop. | agent | yes | |-| `submit_job` | Submit a background job to the Minions queue. | admin | | |+| `submit_job` | Submit a background job. | admin | | |## linksdiff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 467f20daf9..c95581be74 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -8,10 +8,16 @@ lives in `CHANGELOG.md` + `git log` / `git blame`, NOT here. Do not appendper-release `**vX.Y.Z:**` narration — CI enforces this(`scripts/check-key-files-current-state.sh`).+- `src/core/runtime-version.ts` — Bun 1.3.11 minimum enforced by the CLI entrypoint and guarded HTTP transport, with upgrade/restart guidance. Package engines and runtime checks share the same supported floor.+- `src/core/data-frontmatter.ts` — shared data-only YAML/JSON parsing and serialization. Rejects unsupported language selectors before parsing, uses js-yaml safe schema with existing scalar types, sanitizes parser errors, and keeps body text opaque. Used by markdown, capture, recipes, plugins, and greenfield ingestion. Independent fixtures: `test/data-frontmatter.test.ts`, `test/frontmatter-security.test.ts`.+- `src/core/oauth-grants.ts` — client-row-locked grant transactions shared by OAuth issuance, code/refresh consumption, and revocation. Preserves scope/resource ceilings and rolls back consumption with replacement writes. Bounded pending consent requests snapshot current operation and delegation policies. `src/commands/serve-http-oauth.ts` authenticates request details and enforces session-bound CSRF decisions; `admin/src/pages/OAuthConsent.tsx` renders the existing admin login/approval flow without exposing protected details in the page shell.+- `src/core/minions/submission-authority.ts` — versioned authority kept outside caller job data. Submission normalization and worker revalidation bind remote jobs to immutable principal/grant/source/payload ceilings; application authority preserves trusted internal work. `src/core/minions/authorize-legacy.ts` provides explicit local preview and transactional snapshot comparison for selected historical rows. `src/core/minions/source-filesystem.ts` provides reentrant canonical root/worktree locking and descriptor-based confined reads/writes. Both worker modes enforce the same authority gate. Upgrade protocol: `docs/guides/authorization-upgrade.md`.+- `src/core/guarded-http.ts` + `src/core/ssrf-validate.ts` — DNS answer classification, validated-address connections with original TLS/HTTP hostname and port, shared deadline/redirect policy, header-only probes, and bounded gzip/deflate/Brotli decoding. Ambient proxies fail closed with restart guidance. Consumers: URL reachability, remote images, and HTTP integration checks. Real TLS fixtures run on Bun 1.3.11 and 1.3.13.+- `docs/operations/conversation-parser-llm-fallback.md` — operator and maintainer contract for the default-off LLM parse fallback: exact config key, deterministic-first dispatch boundary, sampled data surface, untrusted-content prompt handling, page-date/cache-key coupling, timestamp validation, cache/checkpoint behavior, observability, limitations, and focused test commands.-- `src/core/operations.ts` — Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules under `src/core/ops/` (next entry) and are spread into the single exported `operations` array here; the shared contract types (`src/core/ops/contract.ts`) and the security/scope layer (`src/core/ops/context.ts`) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Same-source graph mutations (`add_link`, `add_timeline_entry`) preflight each endpoint against the scalar write source via `requireWritablePage` (`ops/context.ts`): a page readable only from another granted source returns endpoint-specific `permission_denied` naming the boundary, pages outside the caller's `get_page` visibility scope stay `page_not_found` (a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typed `PageMissingError` from `src/core/engine-errors.ts`, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope by `instanceof`, never message matching. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link/timeline hooks are skipped for remote-owned subagents even with explicit prefixes; only local subagents qualify as trusted workspaces. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Plain-startsWith semantics matching `submit_agent`'s check for the same column (NOT the glob grammar of the subagent allow-list); empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string would let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the `<prefix>/*` glob spelling via `normalizeSlugPrefix` (the column is also submit_agent's binding, so one stored value must mean one span of slugs on both paths), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` applies the same boundary-aware rule when validating a requested prefix against the binding, normalizes trailing-slash prefixes to the glob form `matchesSlugAllowList` expects before handing them to the child job, and collapses an EXPLICIT empty `allowed_tools`/`allowed_slug_prefixes` to the binding (the worker reads empty as "full registry" / "legacy `wiki/agents/<id>/` namespace", so `??`, which only substitutes null/undefined, would leave a vacuous-subset bypass). `put_page` additionally fences the RESOLVED slug when importFromContent's dedup pre-check redirects the write to a different page (same content_hash / `frontmatter.id`), since the disk write-through runs against that slug. That re-check applies whichever confinement the CALLER is under — OAuth binding and/or subagent allow-list/legacy namespace — via `slugOutsideCallerFence(ctx, slug)`, which composes `slugUnderBoundPrefixes` with the subagent fence's own match rule: the delegated `submit_agent` → subagent context carries `viaSubagent` + `allowedSlugPrefixes` while its `auth` carries current read scope without the parent's direct-write fence, so an auth-only check would let a slug-bound client holding `agent` scope reach an out-of-fence page simply by delegating the write. Denials never name the resolved slug (it would be a slug-enumeration oracle). Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/e2e/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (so a read+write OAuth token over HTTP MCP cannot submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `assertExplicitSourceLive(ctx, sourceIdParam)` is the async companion for the ops that accept a per-call `source_id` (`get_page`, `list_pages`, `search`, `query`): called right after `federatedSearchScope` (so the grant check has already run and it can only name a granted source), an explicit id with no live unarchived `sources` row throws `unknown_source` instead of silently scoping the read to an empty source — the CLI's `--source` existence rule applied to the op path; `__all__` and an omitted param skip it. `linkReadScopeOpts(ctx)` is the link-read sibling for `get_links`/`get_backlinks`: a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page`'s inline disk write-through is the shared `writePageThrough` helper (`src/core/write-through.ts`), ATOMIC via temp-sibling + rename so a crash or concurrent `gbrain sync` can't read a half-written `.md`; same helper backs `gbrain brainstorm/lsd --save`. Link provenance surface: `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).+- `src/core/operations.ts` — Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules under `src/core/ops/` (next entry) and are spread into the single exported `operations` array here; the shared contract types (`src/core/ops/contract.ts`) and the security/scope layer (`src/core/ops/context.ts`) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Same-source graph mutations (`add_link`, `add_timeline_entry`) preflight each endpoint against the scalar write source via `requireWritablePage` (`ops/context.ts`): a page readable only from another granted source returns endpoint-specific `permission_denied` naming the boundary, pages outside the caller's `get_page` visibility scope stay `page_not_found` (a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typed `PageMissingError` from `src/core/engine-errors.ts`, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope by `instanceof`, never message matching. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link/timeline hooks are skipped for remote-owned subagents even with explicit prefixes; only local subagents qualify as trusted workspaces. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Direct writes use the shared boundary-aware prefix rules; empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string would let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the `<prefix>/*` glob spelling via `normalizeSlugPrefix` (direct and delegated fences share normalization while storing independently reviewed spans), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` validates tools and namespaces against the independently stored `bound_tools`, `delegated_slug_prefixes`, and `delegated_namespace` grants. It normalizes accepted prefixes for `matchesSlugAllowList` and rejects explicit empty remote tool or prefix overrides. Workers interpret explicit empty tool lists as no tools, with defaults reserved for absent trusted-local bindings. `put_page` additionally fences the RESOLVED slug when importFromContent's dedup pre-check redirects the write to a different page (same content_hash / `frontmatter.id`), since the disk write-through runs against that slug. That re-check applies whichever confinement the CALLER is under — OAuth binding and/or subagent allow-list/legacy namespace — via `slugOutsideCallerFence(ctx, slug)`, which composes `slugUnderBoundPrefixes` with the subagent fence's own match rule: the delegated `submit_agent` → subagent context carries `viaSubagent` + `allowedSlugPrefixes` while its `auth` carries current read scope without the parent's direct-write fence, so an auth-only check would let a slug-bound client holding `agent` scope reach an out-of-fence page simply by delegating the write. Denials never name the resolved slug (it would be a slug-enumeration oracle). Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/e2e/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (so a read+write OAuth token over HTTP MCP cannot submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `assertExplicitSourceLive(ctx, sourceIdParam)` is the async companion for the ops that accept a per-call `source_id` (`get_page`, `list_pages`, `search`, `query`): called right after `federatedSearchScope` (so the grant check has already run and it can only name a granted source), an explicit id with no live unarchived `sources` row throws `unknown_source` instead of silently scoping the read to an empty source — the CLI's `--source` existence rule applied to the op path; `__all__` and an omitted param skip it. `linkReadScopeOpts(ctx)` is the link-read sibling for `get_links`/`get_backlinks`: a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page`'s inline disk write-through is the shared `writePageThrough` helper (`src/core/write-through.ts`), ATOMIC via temp-sibling + rename so a crash or concurrent `gbrain sync` can't read a half-written `.md`; same helper backs `gbrain brainstorm/lsd --save`. Link provenance surface: `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).- `src/core/ops/` — the operations contract's module directory (the meat behind the `operations.ts` façade). `contract.ts` is the foundation contract: the error envelope (`ErrorCode`/`OperationError`/`verbError`), the shared param/logger/auth/context types, and the `Operation` interface — re-exported wholesale by the façade. `context.ts` carries the context validators + scope resolvers: the upload/slug/filename validators, the subagent and bound-client slug fences, and the source-scope resolution ladder (some internal helpers are exported only here and deliberately NOT re-exported from the façade — import those from `context.ts` directly). The remaining modules are one-per-op-domain (`pages.ts`, `search.ts`, `takes.ts`, `tags.ts`, `links.ts`, `timeline.ts`, `admin.ts`, `skills-catalog.ts`, `sync-status.ts`, `raw-data.ts`, `chunks.ts`, `ingest-log.ts`, `files.ts`, `jobs.ts`, `orphans.ts`, `calibration.ts`, `salience.ts`, `facts.ts`, `sources.ts`, `transcripts.ts`, `insights.ts`, `image.ts`, `extraction.ts`, `code-intel.ts`, `chronicle.ts`, `embedding-migration.ts`, `request-tools.ts`, `schema-packs.ts`, `skillopt.ts`), each exporting a `<domain>Operations` map that the façade spreads into the single `operations` export. Add a new op in the matching domain module — an existing domain needs no façade change; a brand-new domain module gets one spread line in `operations.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` maps the façade to this whole directory so every module's `--flag` text stays on the command flag-scan surface.- `src/core/ops/links.ts` — the link-domain op module (`add_link`, `remove_link`, `get_links`, `get_backlinks`, `list_link_sources`, `traverse_graph`). Two load-bearing behaviors. (1) Pack vocabulary at the write surface: an EXPLICIT `link_type` on `add_link` must be declared by the active schema pack when one resolves (`schema-pack/write-vocabulary.ts`; no resolvable pack = no enforcement; omitted/empty link_type is the untyped-edge default and stays unchecked; the check runs before the dry-run return so dry runs preview the rejection). (2) `traverse_graph` output shape: trusted local no-filter callers (`ctx.remote === false`, no `link_type`/`direction`) keep the legacy `GraphNode[]` shape that `gbrain graph` renders; remote callers default to `direction: 'both'` and always receive explicit `GraphPath[]` edges, so a page whose typed edges are all inbound does not read as edge absence. An explicit `direction` param wins for every caller. Depth: default 5 (`DEFAULT_TRAVERSE_DEPTH`), except a remote call that let direction default to `both` ALSO defaults depth to `REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH` (2) — bidirectional path enumeration is combinatorial on entity hubs and this is the per-agent-turn path; a `link_type`-only remote call still takes both/2; an explicit depth is honored up to `TRAVERSE_DEPTH_CAP` (10, clamped with a warn). The edge walk runs through `engine.traversePathsDetailed`, and a hit on `TRAVERSE_PATH_ROW_CAP` (`engine-constants.ts`) surfaces as a stderr warn naming the cap (shallowest edges kept) — the `GraphPath[]` wire shape stays unchanged. Pinned by `test/traverse-graph-op-default.test.ts` + `test/traverse-paths-row-cap.test.ts`.- `src/core/ops/pages.ts` — the page-domain op module (`get_page`, `put_page`, `delete_page`/`restore_page`, `capture`, …; the source-scoping contract of the delete/restore trio is described under `src/core/destructive-guard.ts`). `get_page` resolution ladder: exact read in the caller's scope → alias hop → fuzzy. The alias hop scopes its lookup to the federated grant (`sourceIds[]`) > the scalar `sourceId` > (trusted unscoped only) every LIVE source — archived sources' alias rows count only when `include_deleted` asks for archived material — through `engine.resolveSlugWithAliasDetailed`, then reads the canonical page IN THE SOURCE THAT OWNS THE ALIAS ROW (`getPage(canonical, { sourceId: hit.source_id })`): a federated `getPage` prefers the anchor source, so an unrelated live page at the canonical slug in another granted source would otherwise shadow the alias owner's page. The redirect target composes with the same private-page gate as the exact read and reports `resolved_slug`. `capture`: an EXPLICIT type (the `type` param, else a frontmatter `type:` in the content — `explicitCaptureType` in `src/core/capture-content.ts`, BOM/CRLF tolerant, malformed YAML → none) is validated against the active pack when one resolves (`schema-pack/write-vocabulary.ts`) and IS the effective type for both the default slug and the merged frontmatter — approved as X, stored as X; no explicit type stamps `note` (never checked). Sits at its module-size ratchet ceiling (`scripts/module-size-limits.tsv`); the next growth peels a submodule. Pinned by `test/get-page-federated-scope.test.ts`, `test/capture-explicit-type.test.ts`, and the engine-parity suite (both engines pick the same owning row). The alias hop has no catch of its own: both engines return `null` for the pre-v104 missing-table case, so any other rejection (connection reset, timeout) propagates instead of degrading to `page_not_found`.@@ -111,7 +117,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/search/` — Hybrid search: vector + keyword + RRF + multi-query expansion + dedup. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking at the SQL layer (curated content like `originals/`, `concepts/`, `writing/` outranks bulk content like `<fork>/chat/`, `daily/`, `media/x/`). `searchVector` uses a two-stage CTE so source-boost re-ranking doesn't kill the HNSW index. Hard-exclude prefixes (`test/`, `archive/`, `attachments/`, `.raw/` by default) filter at retrieval, not post-rank. Both gates honor `detail !== 'high'` so temporal queries surface chat pages normally.- `src/core/search/query-intent.ts` — Deterministic query classifiers (pure, no LLM): `classifyQuery`/`classifyQueryIntent` (entity/temporal/event/concept/general → auto-selects detail level, salience/recency/modality axes; `concept` fires on definitional-paraphrase OR landscape/quantifier cues with a proper-noun name-guard — capitalized names, quoted phrases, slugs, and sub-3-word queries never trigger — and ranks vector-lean via the RRF-k tilt in `intent-weights.ts`), `isAmbiguousModalityQuery` (LLM-escalation gate), and the concept-shape pair — `looksConceptShaped` (fuzzy-quantifier/landscape cues minus exact-identifier anti-signals, tuned to favor false-negatives; cues owned by other routers like "who are the"/find_experts and bare "anything"/salience are deliberately excluded) + `conceptNudge` (full one-line CLI hint string steering a concept-shaped `search` toward `query`; consumed by `maybePrintConceptNudge` in `src/cli.ts` on BOTH the local-engine and thin-client result paths, stderr-only, `--quiet`-gated). Pinned by `test/query-intent-concept.test.ts` + `test/cli-concept-nudge.test.ts`.- `src/core/search/llm-intent.ts` — opt-in LLM modality tie-break. `classifyModalityWithLLM(query, fallback)` routes through `gateway.chat()` with a fixed single-word-output system prompt; 1s timeout via AbortController. `parseModality(raw, fallback)` is the pure parser (tolerates trailing punctuation + casing). Fail-open on every error (gateway unavailable, timeout, parse failure, unrecognized output) — returns the fallback so a misbehaving LLM can never break search. Cost-bounded by `isAmbiguousModalityQuery` in `query-intent.ts` so the LLM call fires on only a small fraction of queries when on.-- `src/core/search/image-loader.ts` — `loadImageInput(input, opts)` accepts a local path, `data:` URI, or `http(s)://` URL. Magic-byte sniff for PNG/JPEG/WebP. Hard size cap (default 10 MB, configurable via `search.image_query.max_bytes`). URLs route through `fetchWithSSRFGuard` so DNS rebinding + redirect chains are defeated; pre-flight Content-Length check + post-fetch size guard for lying servers. `ImageLoadError` with discriminated `code` (INVALID_FORMAT / OVERSIZED / INVALID_URL / FETCH_FAILED / TIMEOUT / SSRF_BLOCKED / NOT_FOUND).+- `src/core/search/image-loader.ts` — `loadImageInput(input, opts)` accepts a local path, `data:` URI, or `http(s)://` URL. Magic-byte sniff for PNG/JPEG/WebP. Hard size cap (default 10 MB, configurable via `search.image_query.max_bytes`). URLs route through `fetchWithSSRFGuard` so DNS rebinding + redirect chains are defeated; shared guarded transport pins validated DNS answers and streams decoded bodies with a 2 MiB remote cap (10 MiB local cap). `ImageLoadError` with discriminated `code` (INVALID_FORMAT / OVERSIZED / INVALID_URL / FETCH_FAILED / TIMEOUT / SSRF_BLOCKED / NOT_FOUND).- `src/core/search/by-image.ts` — `searchByImage(engine, input, opts)`. Always runs the image branch (`embedQueryMultimodalImage` + `searchVector(embedding_image)`). Hybrid intersect: when the caller provides an optional `query`, runs a parallel text branch via `embedQueryMultimodal(query)` and merges via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the resolved mode's refinement weights. Widens to the unified column when `search.unified_multimodal=true` (transparently upgrades retrieval quality post-reindex).- `src/core/ssrf-validate.ts` — DNS-rebinding-defended URL validation. `validateAndResolveUrl(url)` resolves the hostname via `dns.lookup({all: true, family: 0})`, checks EVERY A and AAAA record against the internal-IP deny list, and returns the resolved IP so callers fetch by IP (validation IP === fetch IP defeats DNS rebinding). `fetchWithSSRFGuard(url, opts)` does redirect-aware fetching with per-hop re-validation (max 3 hops by default). Reusable across all URL-fetching features. Test seam `__setDnsLookupForTests` for hermetic tests.- `src/core/spend-log.ts` — per-OAuth-client paid-API spend tracking against the `mcp_spend_log` table. `checkBudget(engine, clientId, capCents)` is the pre-flight gate; throws `BudgetExceededError` when today's spend has hit the cap. `recordSpend(engine, entry)` is best-effort post-call. UTC day-aligned aggregation so caps roll over deterministically regardless of server timezone. Local CLI callers (no clientId) bypass the gate; brains without the table fail open to spend=0. `VOYAGE_MULTIMODAL_3_PER_IMAGE_CENTS` = 0.12 cents per image embed.@@ -287,7 +293,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). No in-memory dedup pre-load — candidates buffered 100 at a time and flushed via `addLinksBatch` / `addTimelineEntriesBatch`; `ON CONFLICT DO NOTHING` enforces uniqueness at the DB layer, `created` counter returns real rows inserted. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale. Embedded callers (the cycle) pass `quiet: true` so the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. In `jsonMode` every fs path, `extractForSlugs` included, reports a dropped flush as a `{event:'batch_error'}` stderr line rather than going silent. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: link/timeline flush throws propagate and abort the batch; stamp LAST so a crash leaves pages unstamped and they re-extract idempotently (`addLinksBatch` ON CONFLICT DO NOTHING + timeline dedup). `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Schema parity in schema.sql + pglite-schema.ts + schema-embedded.generated.ts + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` carries `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` for `pagesAffected` at the inline-extract call site, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` lists `'extract.stale'` in `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` lists `links_extraction_lag` in `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp + crash-contract), `test/sync-inline-extract-stamps.serial.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite case in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0.- Extract CLI help — `EXTRACT_HELP` in `src/commands/extract.ts` is the canonical detailed usage shared by `--help` and invalid-subcommand errors. `src/cli.ts` routes `extract --help` before engine connection so help works on unconfigured installs; the top-level TOOLS block advertises every mode-specific flag. Pinned by `test/cli-help-discoverability.test.ts`.- `src/core/extract/receipt-writer.ts` + `src/core/extract/rollup-writer.ts` + `src/commands/extract-status.ts` + `src/commands/extract-explain.ts` + `src/commands/extract-benchmark.ts` + `src/core/schema-pack/scaffold-extractable.ts` — unified extract operator surface. Every shipped extractor (deterministic `facts.conversation` in `src/commands/extract-conversation-facts.ts` + three LLM-backed cycle phases at `src/core/cycle/{extract-atoms,synthesize-concepts,propose-takes,extract-facts}.ts`) writes ONE receipt page per run (`writeReceipt`) + UPSERTs a row to `extract_rollup_7d` (`upsertExtractRollup`). Receipt slug `extracts/{date}/{kind}/{source_id}/{run_id_short}/round-{N}.md`; frontmatter stamps BOTH `type: extract_receipt` AND `dream_generated: true` (belt+suspenders against extraction-loop guard drift). `extract_receipt` joins `ALL_PAGE_TYPES` in `src/core/types.ts`; `extracts/` prefix gets a 0.3x source-boost demote in `src/core/search/source-boost.ts`. Migration v104 adds `extract_rollup_7d (kind, source_id, day, cost_usd, halt_count, eval_pass_count, eval_fail_count, round_completed_count, rollup_write_failures, updated_at)` with PK `(kind, source_id, day)` + `idx_extract_rollup_7d_day`. Rollup writes best-effort with process-scoped error-dedup so transient DB failures bump `rollup_write_failures` instead of crashing the cycle. `extract_health` doctor check reads last 7 days, warns at halt-rate > 10% AND when rollup_write_failures > 0; pre-v104 brains report `ok`. CLI: `gbrain extract status [--source-id ID] [--kind X] [--verbose] [--json]` (7-day rollup, sorted halt_rate desc + cost desc, top-5 + "more rows" hint, stable `schema_version: 1`); `gbrain extract --explain <kind>` (resolution chain pack-declared vs built-in cycle phase, prompt_template + fixture_corpus paths with `✓`/`(missing)`, last 7d rollup); `gbrain extract benchmark --pack X --kind Y` (loads pack fixture corpus through strict path validation — rejects absolute paths, `..` traversal, null bytes, AND symlinks resolving outside pack root; ships as a stub-reporter). `src/core/schema-pack/manifest-v1.ts` widens `extractable` from `z.boolean()` to `z.union([z.boolean(), ExtractableSpecSchema])` (carries `prompt_template`, `fixture_corpus`, `eval_dimensions`, `benchmark_min_recall`, plus reserved `verifier_path` — parses but refuses at runtime); `extractableSpecsFromPack` + `getExtractableSpec` + `refuseVerifierPathInV042` in `src/core/schema-pack/extractable.ts`; `gbrain schema scaffold-extractable <type> --pack <pack>` declares the type extractable, generates 5 placeholder fixtures + a prompt template stub under `packs/<pack>/{fixtures,prompts}/extract/`, refuses to overwrite without `--force`. Pinned by `test/extractable-spec-widening.test.ts` (22), `test/extract/receipt-writer.test.ts` (12, canonical PGLite block R3+R4), `test/extract/benchmark.test.ts` (17), `test/extract/status.test.ts` (15), `test/schema-pack/scaffold-extractable.test.ts` (15, privacy guards), `test/doctor-extract-health.test.ts` (8).-- `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with the path-set checkpoint. `runImport` contains NO `process.exit`: all five preflight/argv failure sites (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target) throw the exported typed `ImportAbortError` (carries `exitCode`; the user-facing message is printed at the throw site), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.serial.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Uses a path-set checkpoint via `src/core/import-checkpoint.ts` (the walk still applies `sortNewestFirst()` for embed-cost ordering, but checkpoint correctness does not depend on sort order). A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. This rules out three failure classes: parallel-import-with-slow-worker dropping the slow file on crash-resume (the slow file isn't in `completed` until its own `processFile` resolves), failed-file-bumps-counter-past-itself (failures don't add to `completed`), and sort-flip-drops-newest-N-on-cross-version-resume (order is not part of the checkpoint). Old positional checkpoints are detected and discarded with a stderr line on first resume (re-walking is cheap because `content_hash` short-circuits unchanged files). Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the resume checkpoint stays dir-relative per `resumeFilter`'s contract). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — the per-file failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under `skipped`, not `errors`, and the failure ledger is written only for git-repo dirs, so this list is a non-git caller's only per-file channel. Pinned by `test/import-json-stdout.serial.test.ts`.+- `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with the path-set checkpoint. `runImport` contains NO `process.exit`: all five preflight/argv failure sites (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target) throw the exported typed `ImportAbortError` (carries `exitCode`; the user-facing message is printed at the throw site), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.serial.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Uses a path-set checkpoint via `src/core/import-checkpoint.ts` (the walk still applies `sortNewestFirst()` for embed-cost ordering, but checkpoint correctness does not depend on sort order). A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. This rules out three failure classes: parallel-import-with-slow-worker dropping the slow file on crash-resume (the slow file isn't in `completed` until its own `processFile` resolves), failed-file-bumps-counter-past-itself (failures don't add to `completed`), and sort-flip-drops-newest-N-on-cross-version-resume (order is not part of the checkpoint). Old positional checkpoints are detected and discarded with a stderr line on first resume (re-walking is cheap because `content_hash` short-circuits unchanged files). Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the resume checkpoint stays dir-relative per `resumeFilter`'s contract). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — returned per-file failures (invalid frontmatter, oversize, symlink, slug mismatch) count under both `skipped` and `errors`, are excluded from `unchanged`, and produce `status: "partial"` with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for Git repositories, so the JSON failure list remains a non-Git caller's per-file channel. Pinned by `test/import-json-stdout.serial.test.ts`.- `src/core/import-checkpoint.ts` — `loadCheckpoint(brainDir)`, `saveCheckpoint(brainDir, completed)`, `resumeFilter(files, completed, brainDir)`, `clearCheckpoint()`, plus the `ImportCheckpoint` type. Path-set format `{schema_version, brainDir, completed: string[]}`. Atomic write via `.tmp` + `rename()` so a mid-write crash never leaves a partial JSON. `loadCheckpoint` returns `null` on: missing file, malformed JSON, brainDir mismatch (ran against a different brain), and the old positional format (logged to stderr before discard). `resumeFilter` returns `{toProcess, skippedCount}` — pure, no I/O, deterministic. `clearCheckpoint` is no-op-on-missing for clean-exit cleanup. Honors `GBRAIN_HOME` via `gbrainPath()` so `withEnv({GBRAIN_HOME: tmpdir})` test isolation works without monkey-patching fs. Best-effort persistence — `saveCheckpoint` logs warnings on write errors but never throws.- `src/commands/graph-query.ts` — `gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both] [--source <id>] [--include-foreign]`: typed-edge relationship traversal (renders indented tree). The local walk is scoped to the resolved source (`--source` / `GBRAIN_SOURCE` / `.gbrain-source` / path match / brain default via `resolveSourceId`, the same scalar scope the `traverse_graph` op gets from `sourceScopeOpts`); an explicit `--source` that fails to resolve throws. `--include-foreign` (or `--source __all__`) drops the scope so the walk spans every source. The foreign-edge footer (`N edges to foreign-source pages hidden; pass --include-foreign`) prints only when the walk was actually scoped, so cross-source edges never disappear silently and the footer never describes a filter that did not apply. The local path uses `engine.traversePathsDetailed` and prints a stderr note when the walk hit `TRAVERSE_PATH_ROW_CAP` (shallowest edges kept; lower `--depth` or narrow with `--type`/`--direction`); the thin-client path goes through the `traverse_graph` op, which has no `source_id` param (the server scopes the walk to the caller's grant): an explicit `--source` there is rejected with exit 1 (same policy + wording as `applyThinClientSourceScope`, never silently dropped) and `--include-foreign` prints a stderr note that it is not forwarded. Pinned by `test/graph-query.test.ts` (local) + `test/graph-query-thin-client-source-flag.serial.test.ts` (thin client; mocks `isThinClient` + `callRemoteTool`).- `src/commands/sources.ts` — `gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit}`. `current [--json]` calls `resolveSourceWithTier()` and prints `source_id`, `tier` (`flag | env | dotfile | local_path | brain_default | seed_default`), and optional `detail` (decision table in `skills/conventions/brain-routing.md`). `status [--json]` — read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper around `buildSyncStatusReport` + `printSyncStatusReport` from `src/commands/sync.ts`; `--json` emits stable `{schema_version: 1, sources, ...}` on stdout; filters input to `local_path IS NOT NULL AND archived IS NOT TRUE`. `audit <id> [--json]` — read-only dry-run disk scan for size distribution + would-blocks + junk-pattern hits WITHOUT touching the DB; walks `sources.local_path`, reads each markdown file, runs `assessContent()` from `src/core/content-sanity.ts`, aggregates by verdict (`ok | warn_oversize | hard_block_junk_pattern`). The live `runStatus` health table gains a `BACKFILL` column between `EMBED` and `FAILS` (`active(N)` beats `queued(N)` beats `idle`, from `SourceMetrics.backfill_active` / `backfill_queued` in `src/core/source-health.ts`) so operators see deferred `embed-backfill` minion work after `sync --all` exits 0; `jobCountsBySource` in `source-health.ts` widens its `minion_jobs` SQL with two `COUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...)` aggregates (best-effort, all-0 on pre-minions brains). `remove` pre-checks OAuth-client referents (guided refusal via `formatClientReferentsBlock` — the raw FK violation never reaches the operator), then commits the row DELETE atomically with an in-tx referents re-check (a registration racing the pre-check maps to the same guided refusal); durability-scaffolding teardown (`unhardenBrainRepo`: hook/cron/credential) runs only AFTER the commit, so a refused delete leaves the scaffolding intact. `purge` runs the same referents pre-check before its hard DELETE. Pinned by `test/content-sanity.test.ts`, `test/import-file-content-sanity.test.ts`, `test/source-health.test.ts`.@@ -327,6 +333,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/minions/handler-timeouts.ts` — per-handler-type defaults for BOTH per-job time knobs, co-located so they can't drift apart unseen (they are different quantities: the budget bounds total runtime, the lease bounds dead-worker reclaim — never derive one from the other). `HANDLER_DEFAULT_TIMEOUT_MS`: 30 min for `subagent`, `subagent_aggregator`, `embed-backfill`, `autopilot-cycle`, `autopilot-global-maintenance`; 10 min for `chronicle_extract` + `facts-absorb`; 60 min for `contextual_reindex_per_chunk`. `HANDLER_DEFAULT_LOCK_DURATION_MS`: 300 s for the long LLM/loop handlers, 120 s for the single-LLM-call handlers, `shell` deliberately absent (fast dead-worker reclaim; verify-before-evict protects it anyway). `defaultTimeoutMsFor` / `defaultLockDurationMsFor` return the mapped default or `null` (short handlers keep the tight null-default wall-clock / the 30 s worker lease). `clampLockDurationMs` + `LOCK_DURATION_MS_MIN/MAX` ([5s, 1h]) is the ONE clamp shared by `queue.add`, the CLI `--lock-duration-ms` flag (`--dry-run` echoes the clamped value), and the MCP `submit_job` param; the same bound is mirrored in SQL at claim time and by the `minion_jobs.lock_duration_ms` range CHECK, so every layer agrees. Layers (explicit value always wins): `MinionQueue.add()` stamps at submit; `MinionQueue.claim()` COALESCEs NULL columns from the maps (durable invariant); migration v128 one-shot backfilled `timeout_ms` with authoring-time snapshot values — do NOT sync v128 when editing the maps (`lock_duration_ms` has no backfill: NULL = worker default). Pinned by `test/minions.test.ts` + `test/migrations-v128.test.ts` + `test/migrations-v130.test.ts`.- `src/core/minions/admission.ts` — submit-side queue admission control (the drain-side pool-starvation half is the job-isolation work; claim fairness is a filed TODO, deliberately out of scope). Three primitives resolved per name via `resolveAdmissionPolicy` (config `minions.*` > per-name defaults tables, 60s in-process cache, fail-open with a once-per-process stderr warn; env kill-switch `GBRAIN_MINIONS_ADMISSION=0` disables all three): PARAM-COALESCING (`PARAM_COALESCE_DEFAULT` — on for `subagent`; `computeParamHash` = sha256 of stable-stringified payload excluding only `__param_hash` itself — `__owner_client_id` is deliberately INCLUDED so owner lanes never cross; parentless + waiting-only + age-bounded to ttl/2), WAITING-TTL (`WAITING_TTL_DEFAULT_HOURS` — 48h for `subagent`; swept by `MinionQueue.handleWaitingTTL` through `cancelJobs(ids, {reason, rootStatuses:['waiting']})` so descendants cancel, child_done lands, aggregator parents resolve, and the reason stamps ROOT ids only; ≤500/tick oldest-first; warn-before-act is `runWaitingTtlTick` — first tick counts affected + stamps `TTL_NOTICE_SHOWN_KEY` with an ISO timestamp, sweeping starts only after `ttlNoticeGraceMs()` (1h default, env `GBRAIN_MINIONS_TTL_NOTICE_GRACE_MS`) elapses; `gbrain upgrade` prints the same one-shot notice and starts the same clock; legacy `'true'` flag values sweep immediately), and NAME-GLOBAL QUOTA (`QUOTA_MAX_WAITING_DEFAULT` EMPTY by operator decision — activates only via `minions.quota_max_waiting.<name>`; counts the name across ALL queues so per-run `dream-inline-*` fanout queues can't dodge it, EXACT under concurrency via a `minion_quota:<name>` advisory xact lock taken only when a quota is configured; throws typed `QueueQuotaExceededError`, checked everywhere via `isQueueQuotaExceededError` — dream submitters record a phase skip, synthesize rolls back the current transcript's fresh chunks, agent fanout cancels the whole tree, `submit_agent` maps to a structured `rate_limited` OperationError). `TTL_REASON_PREFIX` is the single source for the sweep's error_text prefix and the stats/doctor LIKE patterns; `safeConfigSegment` gates untrusted job names out of copy-pasteable config hints. Alerting rides `getStats` (`drained_completed/failed/dead/cancelled` keyed on finished_at + `waiting_now` + `oldest_waiting_minutes`), the `jobs stats` DIVERGENT-QUEUE / waiting-TTL screams (`GBRAIN_QUEUE_DIVERGENCE_RATIO`=2, `GBRAIN_QUEUE_DIVERGENCE_MIN_WAITING`=50; divergence compares intake vs COMPLETED so TTL-cancel storms can't masquerade as throughput) + `--json`, and doctor `checkQueueHealth`. Pinned by `test/minions-admission.test.ts` + `test/jobs-stats-divergence.serial.test.ts`.- `src/core/minions/types.ts` — `MinionJobInput` + `MinionJobStatus` + handler context types. `MinionJobInput.max_stalled` is optional; omitted values let the schema DEFAULT (5) kick in, provided values are clamped to `[1, 100]`.+- `src/core/minions/errors.ts` — dependency-free `UnrecoverableError`, re-exported through `types.ts` for compatibility. Delegated policy imports this leaf directly, avoiding initialization cycles through durable authority. Fresh-process import tests preserve the shared error identity and isolated-worker reconstruction.- `src/core/minions/protected-names.ts` — side-effect-free constant module exporting `PROTECTED_JOB_NAMES` + `isProtectedJobName()`. Kept pure so queue core can import without loading handler modules. `PROTECTED_JOB_NAMES` includes `synthesize`, `patterns`, `consolidate`. These phases internally submit `subagent` children with `allowProtectedSubmit=true` and can spend Anthropic credits. Only trusted local callers (CLI, autopilot, `doctor --remediate`) can submit them; MCP requests are rejected by `submit_job`'s protected-name guard.- `src/core/minions/handlers/shell.ts` — `shell` job handler. Spawns `/bin/sh -c cmd` (absolute path, PATH-override-safe) or `argv[0] argv[1..]` (no shell). Env allowlist `PATH, HOME, USER, LANG, TZ, NODE_ENV` + caller `env:` overrides + `inherit:`-resolved keys. UTF-8-safe stdout/stderr tail via `string_decoder.StringDecoder`. Abort (either `ctx.signal` or `ctx.shutdownSignal`) fires SIGTERM → 5s grace → SIGKILL on child. Requires `GBRAIN_ALLOW_SHELL_JOBS=1` on worker (gated by `registerBuiltinHandlers`). `ShellJobParams.inherit?: string[]` is a free-form list of snake_case config-key names; the worker resolves each via `loadConfig()` and injects the value under the derived env key (`database_url` → `GBRAIN_DATABASE_URL`; else uppercased). Names persist in `minion_jobs.data` (and the shell-audit JSONL); values never do. The canonical validator `validateShellJobParams` (sibling `shell-validate.ts`) runs PRE-ENQUEUE in both submit surfaces — `gbrain jobs submit shell` (jobs.ts:271) AND the `submit_job` op for `name='shell'` (operations.ts:2085); the handler-entry re-validation here is defense-in-depth (so validation can never run only AFTER `queue.add()` has persisted the row). The validator does NOT police which config keys the agent inherits — same-uid trust model treats the agent as a peer of the worker.- `src/core/minions/handlers/shell-inherit.ts` — three helpers. `INHERIT_NAME_RE` (`/^[a-z][a-z0-9_]*$/`) is the snake_case shape guard used by the validator; rejects `__proto__`, leading-underscore, uppercase, and path-traversal shapes so audit logs stay readable and prototype-pollution lookups can't smuggle through. `deriveEnvKey(name)` maps config-key → child-env-key (`name.toUpperCase()` with one override: `database_url` → `GBRAIN_DATABASE_URL` because plain `DATABASE_URL` is ambiguous). `resolveInheritValue(cfg, name)` is the value lookup; uses `Object.hasOwn` to defeat prototype-pollution lookups, returns undefined for missing / non-string / empty-string values. No closed enum — agent and worker share a uid, so refusing arbitrary config keys defends nothing in that trust model.@@ -347,7 +354,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/minions/wait-for-completion.ts` — poll-until-terminal helper for CLI callers. `TimeoutError` does NOT cancel the job; `AbortSignal` exits without throwing. Default `pollMs`: 1000 on Postgres, 250 on PGLite inline.- `src/core/minions/transcript.ts` — renders `subagent_messages` + `subagent_tool_executions` to markdown. Tool rows splice under their owning assistant `tool_use` by `(message_idx, tool_use_id)` — raw provider tool ids may repeat across turns, so `tool_use_id` alone is not an identity; echoed `tool_result` blocks check ownership against the nearest preceding assistant turn's key. UTF-8-safe truncation; unknown block types fall through to fenced JSON.- `src/core/minions/plugin-loader.ts` — `GBRAIN_PLUGIN_PATH` discovery. Absolute paths only, left-wins collision, `gbrain.plugin.json` with `plugin_version: "gbrain-plugin-v1"`, plugins ship DEFS only (no new tools), `allowed_tools:` validated at load time against the derived registry.-- `src/core/minions/tools/brain-allowlist.ts` — derives the subagent tool registry from `src/core/operations.ts` (15-name allow-list, size pinned by `test/brain-allowlist.serial.test.ts`). Includes `add_timeline_entry` (the canonical timeline write), fenced server-side by the same `enforceSubagentSlugFence` policy as `put_page`. By default `put_page` schema is namespace-wrapped per subagent (`^wiki/agents/<subagentId>/.+`). When `BuildBrainToolsOpts.allowedSlugPrefixes` is set, the put_page schema describes the prefix list to the model and the OperationContext is threaded with `allowedSlugPrefixes` — trusted local jobs receive these from the submitter; remote-owned jobs receive the grant intersection plus `delegatedAuth`. Their per-call operation contexts carry current source grants and retain remote visibility policy, without requiring direct read/write scopes for independently bound delegated tools. `BuildBrainToolsOpts.deferEmbeds` (server-side-only, set by the oneshot runner for its programmatic writes; never hydrated from any wire payload) threads `OperationContext.deferEmbeds` so put_page defers chunk embeddings for the phase-end backfill. Allow-list includes `get_recent_salience` + `find_anomalies` but deliberately NOT `get_recent_transcripts` (all subagent calls run `ctx.remote === true` and the trust gate rejects remote callers, so it would always reject; the cycle synthesize phase calls `discoverTranscripts` directly instead). `paramsToInputSchema()` consumes `paramDefToSchema` from `src/mcp/tool-defs.ts`; required-aggregation at the tool-def level stays here (the shared helper is per-param). `execute()` runs the same `validateParams` the MCP dispatchers use before the op handler, so a call that omits a required parameter (or sends the wrong type / an unknown enum value) fails with `<tool>: Missing required parameter: <name>` the model can act on, instead of a handler crash.+- `src/core/minions/tools/brain-allowlist.ts` — derives the subagent tool registry from `src/core/operations.ts` (13-name allow-list, size pinned by `test/brain-allowlist.serial.test.ts`). Attachment tools `file_list` and `file_url` are excluded. Registry construction and execution reject every `localOnly` operation; `selectAllowedTools` rejects malformed bindings and preserves explicit empty lists as no tools. Includes `add_timeline_entry` (the canonical timeline write), fenced server-side by the same `enforceSubagentSlugFence` policy as `put_page`. By default `put_page` schema is namespace-wrapped per subagent (`^wiki/agents/<subagentId>/.+`). When `BuildBrainToolsOpts.allowedSlugPrefixes` is set, the put_page schema describes the prefix list to the model and the OperationContext is threaded with `allowedSlugPrefixes` — trusted local jobs receive these from the submitter; remote-owned jobs receive the grant intersection plus `delegatedAuth`. Their per-call operation contexts carry current source grants and retain remote visibility policy, without requiring direct read/write scopes for independently bound delegated tools. `BuildBrainToolsOpts.deferEmbeds` (server-side-only, set by the oneshot runner for its programmatic writes; never hydrated from any wire payload) threads `OperationContext.deferEmbeds` so put_page defers chunk embeddings for the phase-end backfill. Allow-list includes `get_recent_salience` + `find_anomalies` but deliberately NOT `get_recent_transcripts` (all subagent calls run `ctx.remote === true` and the trust gate rejects remote callers, so it would always reject; the cycle synthesize phase calls `discoverTranscripts` directly instead). `paramsToInputSchema()` consumes `paramDefToSchema` from `src/mcp/tool-defs.ts`; required-aggregation at the tool-def level stays here (the shared helper is per-param). `execute()` runs the same `validateParams` the MCP dispatchers use before the op handler, so a call that omits a required parameter (or sends the wrong type / an unknown enum value) fails with `<tool>: Missing required parameter: <name>` the model can act on, instead of a handler crash.- `src/mcp/tool-defs.ts` — `buildToolDefs(ops, opts?)` helper; the stdio MCP server, the OAuth HTTP `tools/list`, and the subagent tool registry all consume it, byte-for-byte equivalence pinned by `test/mcp-tool-defs.test.ts`. `opts.strictParams: true` (when `mcp.strict_params` resolves `'reject'`) additionally declares the `_meta`/`dry_run` passthrough keys in `properties` and closes each schema with `additionalProperties: false` (schema-validating clients must not strip `_meta.session_id`); both emission states pinned. Exports the recursive `paramDefToSchema(p: ParamDef)` — single source of truth for ParamDef→JSON Schema mapping shared by `buildToolDefs` and `src/core/minions/tools/brain-allowlist.ts` (subagent registry). Recursive on `items` so nested array-of-arrays preserves inner shape on the wire. Key ordering (type, description, enum, default, items) is intentional so `JSON.stringify` output stays byte-stable. `test/mcp-tool-defs.test.ts` has a `findArrayWithoutItems` walker that fails on any `type: 'array'` lacking `items.type`.- `src/core/verbs.ts` — MEMORY_VERBS v1: the four frozen protocol verbs (`remember`, `entity`, `synthesize`, `forget`) as first-class Operations, plus `MEMORY_VERBS_VERSION` (single source of truth, =1), `VERB_NAMES`, the hand-authored `RESPONSE_SCHEMAS` registry (Operation carries input params only; response shapes live here and conformance validates LIVE responses against them), and `ERROR_SCHEMA`. The fifth verb is the extended `recall` op in operations.ts. RUNTIME LEAF invariant: operations.ts spreads `verbOperations` into its array at module-eval time, so this file must never statically import operations.ts VALUES (type-only imports fine; handlers use dynamic import) — violating it causes a TDZ crash on whichever module evaluates second. Every verb error carries a populated `suggestion` + `protocol_version` (via `verbError` in operations.ts). The `forget` verb deliberately has NO cliHints (CLI_ONLY `forget` dispatches first and would shadow it). Frozen contract: docs/protocol/MEMORY_VERBS_v1.md; pinned by test/memory-verbs-conformance.test.ts.- `src/core/verbs/entity-card.ts` — `buildEntityCard(engine, sourceId, name, {remote})`: the zero-LLM sub-100ms card behind the `entity` verb. Resolution reuses the Retrieval Reflex precision arms (alias > exact slug > exact title > slug-suffix; exact-slug candidates include the RAW input because slugify flattens slashes in namespaced slugs). Within exact-title collisions, canonical entity types (`person`, `company`, `organization`, `entity`) outrank note/conversation containers, then GREATEST(updated_at, last_retrieved_at) breaks same-shape ties; a lone non-entity exact-title page remains a valid fallback. Per-arm degradation: a pre-page_aliases brain still resolves via arm 2 (aka returns empty, never throws). Card assembly is a parallel Promise.all of depth-1 indexed reads (page row, alias reverse lookup, getLinks+getBacklinks mentions-excluded cap 10, getBacklinkCounts, getTimeline(5), listFactsByEntity world-only-when-remote); deliberately NOT the recursive-CTE traversePaths — the card is a latency contract (CI gate: test/entity-card-perf.slow.test.ts, p99 < 100ms × GBRAIN_PERF_BUDGET_MULTIPLIER + 50× getPage-p50 ratio guard on a 20K corpus). `summary` runs through the exported `safeSynopsis` (the get_page fence boundary). Miss → keyword near-miss suggestions with create_safety hints.@@ -387,7 +394,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/serve.ts` — `gbrain serve` stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Stdio EOF, SIGTERM, SIGINT, SIGHUP, and parent-process death (every reparent case — PID 1, launchd subreaper, systemd, tmux, or a parent shell with `PR_SET_CHILD_SUBREAPER`) all funnel into one `cleanup(reason)` that first awaits `shutdownDelegatedSync()` (idempotent shared promise; a running delegated sync is aborted and settles its checkpoint against the live engine, with the cleanup deadline extended by `GBRAIN_SERVE_SYNC_SETTLE_MS` only while a job runs) and then releases the engine and the PGLite write-lock dir within 5 seconds (otherwise the lock is held indefinitely after Claude Desktop / Cursor / launchd-managed gateways disconnect, forcing a 5-minute stale-lock wait on next start). Watchdog reparent check is `getParentPid() !== initialParentPid` (the `=== 1` check missed the subreaper case under launchd/systemd). Bun's `process.ppid` cache is stale across reparenting ([oven-sh/bun#30305](https://github.com/oven-sh/bun/issues/30305)) so `getParentPid()` runs `spawnSync('ps', ['-o', 'ppid=', '-p', PID])` per tick. Startup probe verifies `ps` is on PATH; if not (stripped containers, busybox), the watchdog skips installing AND emits a loud `[gbrain serve] watchdog disabled: ps unavailable ...` stderr line so operators see the degraded mode. The idle maintenance sweep skips ticks while a delegated sync runs and drains deferred embeds afterwards (`maybeDrainDeferredEmbeds`). Both stdin activity listeners (the default-on idle sweep and the opt-in `--stdio-idle-timeout`) attach only AFTER the MCP SDK transport's own stdin listener — the sweep on its first interval tick, the idle timeout through the activator `installStdioLifecycle` returns, which `runServe` invokes once `startMcpServer` resolves (and which re-arms the countdown so boot time does not eat into the idle window) — so neither can flip stdin into flowing mode and consume a fast client's initialize frame before the SDK sees it. Pinned by `test/serve-stdio-lifecycle.test.ts` (22 cases).- `src/core/grants/` — canonical OAuth client grant model shared by CLI, admin HTTP, provisioning, and worker admission. `model.ts` validates active sources, independent direct/delegated fences, explicit reviewed tools, namespaces, concurrency, spend, and TTL; `host`/`current` brain aliases normalize to the serving brain (`null`), while other IDs need independently verified host identity. `profiles.ts` snapshots current eligible operation names for six explicit profiles; new defaults are renewable 1 hour (static 30 days), concurrency 1, and unlimited delegated spend. `allowed_operations = NULL` preserves legacy scope-based behavior; a new profile missing its snapshot fails closed. `service.ts` locks the client, checks `grant_revision`, and commits the grant, secret-free audit, and original ceilings for pending/active legacy jobs atomically; stale edits fail, repeated repair is a no-op, and repair preserves populated limits. Issued scopes intersect live scopes on access and refresh; source/path/operation/delegation changes are live, newly added scopes require new issuance, and TTL changes do not rewrite existing expiry. `migration.ts` splits legacy fences and removes only invalid `agent` grants with repair reasons; it loads registry validation lazily only after locking existing delegated clients, so empty engine imports and cold migrations do not register unrelated background sinks. This justified engine-live import is line-marked; constraints still install when no clients exist. `schema.ts` supplies migration147/bootstrap columns and invariants for both engines. SQL JSON passes through `text::jsonb` for driver parity. Tests: `test/client-grants.test.ts`, OAuth compatibility suites, and `test/e2e/client-grants.test.ts` (Postgres CAS, job ceilings, and actual HTTP preview/edit).- `src/commands/serve-http-grants.ts` + `admin/src/components/ClientGrant.tsx` — typed admin grant request validation and shared profile/advanced permission editor. Register/rescope/TTL routes in `serve-http.ts` use canonical grant validation and audit; legacy response shapes remain available. New UI creation defaults to memory-writer and requires a preview, while edits carry the displayed revision and require a fresh preview after any field change or conflict. Detail/catalog endpoints expose non-secret grants and the shared harness registry. Operation authority snapshots, source sets, delegated tools/namespaces, spend, concurrency, and future TTL are independently reviewable; profile regrant is explicit. `admin/src/pages/Agents.tsx` downloads the private `HarnessCredentials` handoff and links current harness guides instead of maintaining native config snippets. Rebuild committed `admin/dist` and `src/admin-embedded.ts` after SPA edits.-- `src/core/oauth-provider.ts` — `GBrainOAuthProvider` implementing the MCP SDK's `OAuthServerProvider` + `OAuthRegisteredClientsStore`. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1: `authorize` + `exchangeAuthorizationCode` with PKCE, `client_credentials`, `refresh_token` with rotation, `revokeToken`, `registerClient` (DCR validates redirect_uri is `https://` or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Auth codes single-use with 10-minute TTL via atomic `DELETE...RETURNING` (closes RFC 6749 §10.5 TOCTOU); refresh rotation also `DELETE...RETURNING` (§10.4 stolen-token detection). `pgArray()` escapes commas/quotes/braces so a comma-bearing redirect_uri can't smuggle a second array element. Legacy `access_tokens` fallback in `verifyAccessToken` honors the original-schema `scopes TEXT[]` column via `normalizeTokenScopes` (NULL = grandfathered `read+write+admin`, so every pre-scopes token is byte-identical; an array is filtered to known scopes and honored as-is, `[]`/all-unknown preserved as deny — a dedicated column is structurally immune to the permissions-object-replacement wipe class), and threads BOTH stored grants off the token's `permissions` JSONB: `source_id` via `parseLegacyTokenScope` and `takes_holders` via `parseTakesHoldersAllowList` (both in `src/core/legacy-token-scope.ts`, shared with the legacy HTTP transport so the two transports cannot drift; `[]` takes-holders preserved as explicit deny-all, missing/non-array → undefined → the `/mcp` dispatch site's fail-closed `['world']`; OAuth-client tokens carry no takes-holders grant pending per-client storage — TODOS.md). `sweepExpiredTokens()` runs on startup in try/catch and returns the count via `RETURNING 1` + array length. RFC hardening: `client_id` folded atomically into the `DELETE WHERE` for both auth-code exchange and refresh rotation (wrong-client paths don't burn the row); refresh-scope-subset enforced against the original grant on the row (RFC 6749 §6, so revoking a scope shrinks existing refresh tokens); `client_id` bound on `revokeToken` (RFC 7009 §2.1); `/token` `redirect_uri` validated against the `/authorize` value (RFC 6749 §4.1.3, empty-string treated as missing not wildcard); `verifyAccessToken`/`getClient` catch only `isUndefinedColumnError` from `src/core/utils.ts` (only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw); `dcrDisabled` constructor option lets `serve-http.ts` disable `/register` without monkey-patching the router. Module-private `coerceTimestamp()` normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (`getClient` for RFC 7591 §3.2.1 numeric timestamps, `exchangeRefreshToken` + `verifyAccessToken` for the SDK's `typeof === 'number'` check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted to `utils.ts` — generic BIGINT precision-loss risk. `registerClient` honors `token_endpoint_auth_method: "none"` (RFC 7591 §3.2.1): public PKCE clients store `client_secret_hash = NULL` and the response omits `client_secret`; confidential clients (`client_secret_post` / `client_secret_basic`) keep their one-time-reveal shape; `getClient` normalizes NULL `client_secret_hash` to JS `undefined` so the SDK's clientAuth path accepts public clients. `verifyAccessToken` JOINs `oauth_clients.source_id` (write scope, scalar) + `oauth_clients.federated_read` (read scope, TEXT[]) + `oauth_clients.bound_slug_prefixes` (write fence, TEXT[] — consumed by `enforceClientSlugFence` in `operations.ts`) onto the returned `AuthInfo`; legacy brains degrade via `isUndefinedColumnError` fallback, dropping the newest projection first. `rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?})` is the trusted-operator rescope (CLI `gbrain auth rescope-client`, admin `POST /admin/api/rescope-client`); `boundSlugPrefixes` is tri-state — undefined leaves the binding untouched, `null` clears it, a non-empty array replaces it (explicit empty array rejected as ambiguous deny-all) — so roster churn updates the write fence in place without rotating secrets. with `src/commands/serve-http.ts`: custom `/token` middleware that runs BEFORE the MCP SDK's `clientAuth`. The SDK does plaintext compare against the request's `client_secret`; gbrain stores SHA-256 hashes only, so every confidential-client `/token` request would fail. The middleware detects confidential auth via `Authorization: Basic` header OR `client_secret_post` form body (both shapes per RFC 6749 §2.3.1), verifies via `verifyClient(client_id, presented_secret)` (SHA-256 hash compare), and falls through to the SDK for public PKCE clients (which the SDK's clientAuth still accepts via NULL-`client_secret_hash` normalization). Pinned by `test/oauth-confidential-client.test.ts` (both `client_secret_basic` and `client_secret_post`).+- `src/core/oauth-provider.ts` — `GBrainOAuthProvider` implementing the MCP SDK's `OAuthServerProvider` + `OAuthRegisteredClientsStore`. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1: `authorize` + `exchangeAuthorizationCode` with PKCE, `client_credentials`, `refresh_token` with rotation, `revokeToken`, `registerClient` (DCR validates redirect_uri is `https://` or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Owner-approved authorization codes have a 10-minute TTL. Grant transactions lock the active client row before consuming codes or refresh tokens and creating replacements; revocation uses the same lock. Provider-side S256 PKCE validation is mandatory (`skipLocalPkceValidation=true` prevents the SDK from discarding the verifier first). Existing active-client grants remain usable. `pgArray()` escapes commas/quotes/braces so a comma-bearing redirect_uri can't smuggle a second array element. Legacy `access_tokens` fallback in `verifyAccessToken` honors the original-schema `scopes TEXT[]` column via `normalizeTokenScopes` (NULL = grandfathered `read+write+admin`, so every pre-scopes token is byte-identical; an array is filtered to known scopes and honored as-is, `[]`/all-unknown preserved as deny — a dedicated column is structurally immune to the permissions-object-replacement wipe class), and threads BOTH stored grants off the token's `permissions` JSONB: `source_id` via `parseLegacyTokenScope` and `takes_holders` via `parseTakesHoldersAllowList` (both in `src/core/legacy-token-scope.ts`, shared with the legacy HTTP transport so the two transports cannot drift; `[]` takes-holders preserved as explicit deny-all, missing/non-array → undefined → the `/mcp` dispatch site's fail-closed `['world']`; OAuth-client tokens carry no takes-holders grant pending per-client storage — TODOS.md). `sweepExpiredTokens()` runs on startup in try/catch and returns the count via `RETURNING 1` + array length. RFC hardening: `client_id` folded atomically into the `DELETE WHERE` for both auth-code exchange and refresh rotation (wrong-client paths don't burn the row); refresh-scope-subset enforced against the original grant on the row (RFC 6749 §6, so revoking a scope shrinks existing refresh tokens); `client_id` bound on `revokeToken` (RFC 7009 §2.1); `/token` `redirect_uri` validated against the `/authorize` value (RFC 6749 §4.1.3, empty-string treated as missing not wildcard); `verifyAccessToken`/`getClient` catch only `isUndefinedColumnError` from `src/core/utils.ts` (only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw); `dcrDisabled` constructor option lets `serve-http.ts` disable `/register` without monkey-patching the router. Module-private `coerceTimestamp()` normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (`getClient` for RFC 7591 §3.2.1 numeric timestamps, `exchangeRefreshToken` + `verifyAccessToken` for the SDK's `typeof === 'number'` check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted to `utils.ts` — generic BIGINT precision-loss risk. `registerClient` honors `token_endpoint_auth_method: "none"` (RFC 7591 §3.2.1): public PKCE clients store `client_secret_hash = NULL` and the response omits `client_secret`; confidential clients (`client_secret_post` / `client_secret_basic`) keep their one-time-reveal shape; `getClient` normalizes NULL `client_secret_hash` to JS `undefined` so the SDK's clientAuth path accepts public clients. `verifyAccessToken` JOINs `oauth_clients.source_id` (write scope, scalar) + `oauth_clients.federated_read` (read scope, TEXT[]) + `oauth_clients.bound_slug_prefixes` (write fence, TEXT[] — consumed by `enforceClientSlugFence` in `operations.ts`) onto the returned `AuthInfo`; legacy brains degrade via `isUndefinedColumnError` fallback, dropping the newest projection first. `rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?})` is the trusted-operator rescope (CLI `gbrain auth rescope-client`, admin `POST /admin/api/rescope-client`); `boundSlugPrefixes` is tri-state — undefined leaves the binding untouched, `null` clears it, a non-empty array replaces it (explicit empty array rejected as ambiguous deny-all) — so roster churn updates the write fence in place without rotating secrets. with `src/commands/serve-http.ts`: custom `/token` middleware that runs BEFORE the MCP SDK's `clientAuth`. The SDK does plaintext compare against the request's `client_secret`; gbrain stores SHA-256 hashes only, so every confidential-client `/token` request would fail. The middleware detects confidential auth via `Authorization: Basic` header OR `client_secret_post` form body (both shapes per RFC 6749 §2.3.1), verifies via `verifyClient(client_id, presented_secret)` (SHA-256 hash compare), and falls through to the SDK for public PKCE clients (which the SDK's clientAuth still accepts via NULL-`client_secret_hash` normalization). Pinned by `test/oauth-confidential-client.test.ts` (both `client_secret_basic` and `client_secret_post`).- `admin/` — React 19 + Vite + TypeScript admin SPA embedded in the binary via `admin/dist/` served by `serve-http.ts`. 7 screens: Login (bootstrap token → session cookie), Dashboard (metrics + SSE feed + token health), Agents (sortable table + sparklines + Register), Register (modal with scope checkboxes + grant type selector), Credentials reveal (Copy + Download JSON + one-time-only warning), Request Log (filterable paginated), Agent Detail drawer (Details / Activity / Config Export tabs + Revoke). Design tokens: `#0a0a0f` bg, Inter for UI, JetBrains Mono for data, 4-32px spacing scale, rounded pill badges. HTTP-only SameSite=Strict cookie auth. 65KB gzip. Build: `cd admin && bun install && bun run build`; output at `admin/dist/` is committed for self-contained binaries.- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`create --scopes read,write` narrows a token via the `scopes TEXT[]` column with mint-time validation — a typo'd scope refuses loudly, never silently denies or widens; `list` shows id + scopes columns with grandfathered rows rendered honestly; `revoke --id <uuid>` revokes exactly one row since names are not unique, and bulk revoke-by-name says when it hit several; `permissions set-takes-holders` MERGES into the permissions JSONB via `COALESCE(permissions,'{}'::jsonb) || $2::jsonb` — a whole-object replace would silently wipe the `source_id` federation grant), plus `gbrain auth register-client` and `gbrain auth revoke-client <client_id>` for OAuth 2.1 client lifecycle. `revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; clients without a `source_id` backfill to `'default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), and federated reads (`federated_read`) — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `--usage` joins per-client op-call counts via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)`. Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`.- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`.@@ -469,7 +476,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `scripts/build-pglite-snapshot.ts` — `bun run build:pglite-snapshot`: bakes a post-`initSchema()` PGLite data dir into `test/fixtures/pglite-snapshot.tar` + a version file (schema hash line, then `dims=`/`model=` lines recording the embedding shape it was baked with). Idempotent (hash short-circuit ~40ms when fresh; rebuilds stale) and concurrency-safe (atomic `mkdir` lock at `test/fixtures/.pglite-snapshot.lock` with staleness-verified takeover — a live lock is never stolen; tar written first, version file last, so a crash can't leave a fresh-looking torn fixture; waiter bounded by `GBRAIN_SNAPSHOT_LOCK_TIMEOUT_MS`, default 120000; an exhausted waiter facing a still-live lock proceeds unlocked as a last resort — the loader's hash/shape gate validates the version file, not the tar bytes). Called through the shared `ensure_pglite_snapshot` helper in `scripts/lib/test-env.sh` (also home of `detect_cpus` + `detect_available_mem_mb`; sourced by `run-unit-parallel.sh`, `test-shard.sh`, `run-slow-tests.sh`, `run-serial-tests.sh`, `run-verify-parallel.sh`, and `run-e2e.sh` — default-on, opt out `GBRAIN_NO_SNAPSHOT=1`, no-op when a parent already exported the path, non-fatal on build failure with a one-line "active" echo so a silent cold-init fallback stays visible) and directly by `scripts/ci-local.sh`; every caller exports `GBRAIN_PGLITE_SNAPSHOT`. The loader side is `tryLoadSnapshot` + `computeSnapshotSchemaHash` (exported from `src/core/pglite-engine.ts`): the coverage-immune hash reads raw file bytes for the schema/migration entry modules and imported helpers, including grant SQL/policy/repair dependencies and withdrawal triggers (keep its dependency list and CI cache keys aligned when adding a helper); any hash or embedding-shape mismatch warns once and falls through to normal cold init — the snapshot is an optimization, never authoritative. The loader memoizes per process: the schema hash computes once (source bytes are static for the process lifetime) and the version file + ~42MB tar are read once per (path, process) instead of once per engine construction (a full suite constructs 600+ engines); a terminally-unusable path (missing/stale/torn) memoizes as null and is never retried, the tar blob loads lazily only after the FIRST caller passes the shape gate, and the dims/model shape gate itself is deliberately NOT memoized (tests reconfigure the gateway mid-process — a mismatched engine must still fall back to cold init). Accepted limitation: a snapshot rewritten mid-process is not observed; the only writer runs before test fan-out. Test seams `__snapshotMemoStatsForTests`/`__resetSnapshotMemoForTests`. Pinned by `test/snapshot-shape-guard.test.ts`.- `docker-compose.ci.yml` + `scripts/ci-local.sh` — Local CI gate. `bun run ci:local` spins up four `pgvector/pgvector:pg16` services (postgres-1..4) + `oven/bun:1` with named volumes (`gbrain-ci-pg-data-{1..4}`, `gbrain-ci-node-modules`, `gbrain-ci-bun-cache`), runs gitleaks on host, smoke-tests `scripts/run-e2e.sh` argv handling, runs guards + typecheck, then the Tier 1 default: 4-shard parallel unit + E2E (`xargs -P4`, one Postgres per shard; unit phase keeps `DATABASE_URL` unset). `--no-shard` falls back to the legacy unsharded sequential flow (debug aid); `--diff` runs the diff-aware selector unsharded. Also runs a `pgbouncer` service (`edoburu/pgbouncer`, `POOL_MODE: transaction`, `AUTH_TYPE: plain` — pg16 stores SCRAM verifiers, so the userlist must hold the plaintext password; `IGNORE_STARTUP_PARAMETERS` whitelists gbrain's `statement_timeout`/`idle_in_transaction_session_timeout` startup params the way the Supabase pooler does) fronting postgres-1 on host port `GBRAIN_CI_PGBOUNCER_PORT` (default 6543); every E2E invocation exports `GBRAIN_PGBOUNCER_URL` (pooled; dedicated `gbrain_pgbouncer` database so it never races the `gbrain_test` TRUNCATE fixtures) + `GBRAIN_PGBOUNCER_DIRECT_URL`, consumed by `test/e2e/pgbouncer-teardown.test.ts` — which reproduces the transaction-mode teardown failure in the local gate. `--no-pull` skips upstream pulls; `--clean` nukes named volumes. Postgres host port defaults to 5434; override with `GBRAIN_CI_PG_PORT=NNNN`. Stronger gate than PR CI's 2-file Tier 1 set.- `scripts/select-e2e.ts` + `scripts/e2e-test-map.ts` — Diff-aware E2E test selector. Reads three git sources (committed `origin/master...HEAD`, working-tree `HEAD`, and `git ls-files --others --exclude-standard` for untracked NOT-gitignored files), classifies as EMPTY / DOC_ONLY / SRC. Fail-closed: EMPTY → all files; DOC_ONLY (every path matches the README/CLAUDE/AGENTS/CHANGELOG/TODOS allowlist) → empty stdout; SRC → escape-hatch paths (schema, package.json, skills/) trigger all, else the hand-tuned `E2E_TEST_MAP` glob narrows, and an unmapped src/ change still emits ALL files (never silently nothing). Pure-function exports `selectTests`, `classify`, `matchGlob`. `bun run ci:select-e2e` prints the current selection on stdout. `test/select-e2e.test.ts` covers all 4 branches plus 3 guards (skills/, untracked files, unmapped src/) — 24 cases.-- `scripts/run-e2e.sh` — Sequential E2E runner. Accepts an optional argv-driven file list (used by `ci:local:diff`) and a `--dry-run-list` flag that prints the resolved file list and exits (used by `ci-local.sh`'s startup smoke-test). Falls back to `test/e2e/*.test.ts` plus `test/phantom-redirect-engine-parity.test.ts` when invoked with no args (the phantom-redirect Postgres arm is only reachable through a DATABASE_URL-bearing lane; the unit wrappers strip the URL, so this lane must carry it). This wrapper is the database-URL opt-in boundary: it exports `GBRAIN_TEST_ALLOW_DATABASE_URL=1` so the bunfig preload guard (`test/helpers/database-url-guard-preload.ts`) lets the run start, unsets `GBRAIN_DATABASE_URL` (the e2e suite runs on `DATABASE_URL` only — an ambient `GBRAIN_DATABASE_URL` would pass the opt-in yet reach CLI-subprocess paths with no name floor), and its GBRAIN_* env scrub preserves `GBRAIN_E2E_ALLOW_DB` so the name-floor escape hatch the guard's own error message names stays usable. It also exports `GBRAIN_TEST_KEEP_PROVIDER_KEYS=1` so the unit-lane provider-key strip preload (`test/helpers/provider-keys-preload.ts`) leaves the real keys that live embed/parity e2e tests skip-gate on. Each file runs under a gtimeout/timeout wedge backstop (default signal: SIGTERM — the bun test child installs no JS-level handler for it, so kernel-default termination applies) — 180s default, with a per-file override for known-slow files (`skills.test.ts` gets 420s: the real ingest-skill run replays every migration, so its floor grows as master adds migrations); the cap is a wedge backstop, not a per-test budget, and bare `bun` (no outer cap) is the fallback when neither timeout binary is installed. It activates the PGLite schema snapshot like the other runners: sources `scripts/lib/test-env.sh` + `ensure_pglite_snapshot` after the `--dry-run-list` early exit (list mode stays instant; non-fatal on build failure), re-exports `GBRAIN_PGLITE_SNAPSHOT` as an ABSOLUTE path (e2e tests spawn CLI subprocesses with varying cwd — a relative path silently misses the tar there), and its env keep-list preserves the var; e2e files that assert the path TO post-`initSchema()` state carry per-file `delete process.env.GBRAIN_PGLITE_SNAPSHOT` opt-outs with one-line reasons.+- `scripts/run-e2e.sh` — Sequential E2E runner. Accepts an optional argv-driven file list (used by `ci:local:diff`) and a `--dry-run-list` flag that prints the resolved file list and exits (used by `ci-local.sh`'s startup smoke-test). Falls back to `test/e2e/*.test.ts` plus `test/phantom-redirect-engine-parity.test.ts` when invoked with no args (the phantom-redirect Postgres arm is only reachable through a DATABASE_URL-bearing lane; the unit wrappers strip the URL, so this lane must carry it). This wrapper is the database-URL opt-in boundary: it exports `GBRAIN_TEST_ALLOW_DATABASE_URL=1` so the bunfig preload guard (`test/helpers/database-url-guard-preload.ts`) lets the run start, unsets `GBRAIN_DATABASE_URL` (the e2e suite runs on `DATABASE_URL` only — an ambient `GBRAIN_DATABASE_URL` would pass the opt-in yet reach CLI-subprocess paths with no name floor), and its GBRAIN_* env scrub preserves `GBRAIN_E2E_ALLOW_DB` so the name-floor escape hatch the guard's own error message names stays usable. It also preserves `GBRAIN_CI_DISABLE_TEST_ENV_FILE=1`, keeping CI runs from loading checkout-local `.env.testing` credentials after the shell-to-Bun handoff. It also exports `GBRAIN_TEST_KEEP_PROVIDER_KEYS=1` so the unit-lane provider-key strip preload (`test/helpers/provider-keys-preload.ts`) leaves the real keys that live embed/parity e2e tests skip-gate on. Each file runs under a gtimeout/timeout wedge backstop (default signal: SIGTERM — the bun test child installs no JS-level handler for it, so kernel-default termination applies) — 180s default, with a per-file override for known-slow files (`skills.test.ts` gets 420s: the real ingest-skill run replays every migration, so its floor grows as master adds migrations); the cap is a wedge backstop, not a per-test budget, and bare `bun` (no outer cap) is the fallback when neither timeout binary is installed. It activates the PGLite schema snapshot like the other runners: sources `scripts/lib/test-env.sh` + `ensure_pglite_snapshot` after the `--dry-run-list` early exit (list mode stays instant; non-fatal on build failure), re-exports `GBRAIN_PGLITE_SNAPSHOT` as an ABSOLUTE path (e2e tests spawn CLI subprocesses with varying cwd — a relative path silently misses the tar there), and its env keep-list preserves the var; e2e files that assert the path TO post-`initSchema()` state carry per-file `delete process.env.GBRAIN_PGLITE_SNAPSHOT` opt-outs with one-line reasons.- `scripts/llms-config.ts` + `scripts/build-llms.ts` — Generator for `llms.txt` (llmstxt.org-spec web index) + `llms-full.txt` (inlined single-fetch bundle). Curated config drives both. Run `bun run build:llms` after adding a new doc. `LLMS_REPO_BASE` env lets forks regenerate with their own URL base. `FULL_SIZE_BUDGET` (600KB) caps the inline bundle; generator WARNs if exceeded. Committed output has no runtime consumer; committed for GitHub browsing and fork-safe fetching.- `AGENTS.md` — Local-clone entry point for non-Claude agents (Codex, Cursor, OpenClaw, Aider). Mirrors `CLAUDE.md` intent via relative links. Claude Code keeps using `CLAUDE.md`.- `docs/UPGRADING_DOWNSTREAM_AGENTS.md` — Patches for downstream agent skill forks to apply when upgrading. Each release appends a new section; includes diffs for brain-ops, meeting-ingestion, signal-detector, enrich.@@ -531,7 +538,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `skills/plugin-lanes.json` — curation record for the plugin lanes: lane set = (openclaw bundle ∖ base_exclusions) ∪ additions, a reason per entry; `starter_gaps` is the generated snapshot of per-skill beyond-starter MCP ops (refresh via `--write-gaps`). The openclaw lane's own curation is untouched — plugin users ARE the brain host (the downstream-vs-host inversion).- `scripts/generate-plugin-tree.ts` + `scripts/check-plugin-tree.sh` + `plugin/` — generator, byte-diff drift gate (in the skills commit gate), and the committed curated skill tree both plugin lanes ship (67 skills + shared conventions/_*.md deps + a generated README carrying the CLI-primary starter note).- `test/e2e/codex-plugin-install-real.serial.test.ts` + `test/e2e/claude-plugin-install-real.serial.test.ts` — the plugin doors: clean-tree staging (`git archive HEAD`), real marketplace add/plugin add, snapshot + exec-bit + non-root-mcp.json pins, tools/list starter-surface oracle, cold-home fast-fail, --source-guard block/allow, coexistence + removal probes, auth-gated SMOKE turns. CI: the `plugin-doors` job in heavy-tests.yml (pinned binary provisioning + expected-pass-count refuse-green).-- `src/commands/capture.ts` + `src/commands/serve-http.ts` + `src/core/{operations,import-file,types,utils,facts/absorb-log,brainstorm/{orchestrator,error-classify},scope,postgres-engine,pglite-engine}.ts` — ingestion hardening. Capture frontmatter merge via `mergeCaptureFrontmatter` (uses gray-matter directly, NOT the lossy `parseMarkdown`); `/ingest` null-guard + outer try/catch envelope with `!res.headersSent` guard; dedup via separate normalize-for-hash (`normalizeForHash` strips BOM/CRLF/whitespace/NFKC) + body-after-frontmatter-strip on the DB hash (excludes `captured_at` + `ingested_at` so capture-cli timestamp variations don't invalidate the chunk cache); friendly `pages_source_id_fk` rewrite via `maybeRewriteSourceFkError` on BOTH local + thin-client `callRemoteTool` catch blocks; `facts:absorb` 'No database connection' suppression via typed `instanceof GBrainError && e.problem` check + first-occurrence stack-trace info log (module-scoped `_hasLoggedDisconnectedFactsAbsorb` flag, test seam `_resetFactsAbsorbDisconnectedFlagForTests`); CLI help discoverability (`capture` in `CLI_ONLY_SELF_HELP` + pre-engine-bind `--help` short-circuit in `handleCliOnly` + a `BRAIN` section in `printHelp`); binary-file guard via `detectBinaryNullByte(buf)` first-8KB NUL scan on `--file` (Buffer-read, no encoding) and `--stdin` (`readStdinBuffer` accumulator); provenance write-through — put_page accepts 3 optional params (source_kind, source_uri, ingested_via; `ingested_at` server-stamped) + trust gate (when `ctx.remote !== false` IGNORE client params, server stamps `mcp:put_page`, fail-closed) + COALESCE-preserve UPDATE semantics (omitting params on a later put_page preserves prior values; first-write-wins); `/admin/api/register-client` scopes normalization via `normalizeScopesInput(raw: unknown)` in `src/core/scope.ts` (accepts string/string[]/missing; rejects `['read write']` space-in-element shape, non-string elements, empty array, unknown scopes; deduped + sorted); brainstorm timeout surfacing via an orchestrator-level try/catch at `runBrainstorm` entry (single-point wrap covers every internal SQL site, classifies SQLSTATE 57014 via postgres.js `.code` / `.sqlState` / message fallback into `StructuredAgentError` code `brainstorm_timeout` with a hint covering all 3 PG cancel sub-causes); read-path surfaces all 4 provenance columns via `getPage` projection + `rowToPage` 3-state optional read + `Page` interface; canonical source resolver routes capture through `resolveSourceWithTier(engine, parsed.source, cwd)`; thin-client `--source` rejection (server-side OAuth client registration owns source scope); the `source_kind` taxonomy is closed (`capture-cli | put_page | mcp:put_page | webhook | file-watcher | inbox-folder | cron-scheduler`), `--source` maps to source_id only. Tests: `test/capture-build-content.test.ts`, `test/capture-runcapture.test.ts`, `test/put-page-provenance.test.ts`, `test/scope-normalize.test.ts`, `test/cli-help-discoverability.test.ts`, `test/brainstorm-timeout.test.ts`; extended `test/facts-absorb-log.test.ts`, `test/import-file.test.ts`, `test/e2e/engine-parity.test.ts`, `test/e2e/serve-http-ingest-webhook.test.ts`. Report at `docs/v0.38-smoke-test-report.md`. Follow-ups in TODOS.md: SQL-shape rewrite of `listPrefixSampledPages` for PgBouncer, magic-byte allowlist for binary detection, `--source-kind` override flag, ingest_capture handler migration, provenance-history table, facts:absorb root-cause trace.+- `src/commands/capture.ts` + `src/commands/serve-http.ts` + `src/core/{operations,import-file,types,utils,facts/absorb-log,brainstorm/{orchestrator,error-classify},scope,postgres-engine,pglite-engine}.ts` — ingestion hardening. Capture frontmatter merge via `mergeCaptureFrontmatter` (uses shared data-only `data-frontmatter`, preserving metadata beyond `parseMarkdown`); `/ingest` null-guard + outer try/catch envelope with `!res.headersSent` guard; dedup via separate normalize-for-hash (`normalizeForHash` strips BOM/CRLF/whitespace/NFKC) + body-after-frontmatter-strip on the DB hash (excludes `captured_at` + `ingested_at` so capture-cli timestamp variations don't invalidate the chunk cache); friendly `pages_source_id_fk` rewrite via `maybeRewriteSourceFkError` on BOTH local + thin-client `callRemoteTool` catch blocks; `facts:absorb` 'No database connection' suppression via typed `instanceof GBrainError && e.problem` check + first-occurrence stack-trace info log (module-scoped `_hasLoggedDisconnectedFactsAbsorb` flag, test seam `_resetFactsAbsorbDisconnectedFlagForTests`); CLI help discoverability (`capture` in `CLI_ONLY_SELF_HELP` + pre-engine-bind `--help` short-circuit in `handleCliOnly` + a `BRAIN` section in `printHelp`); binary-file guard via `detectBinaryNullByte(buf)` first-8KB NUL scan on `--file` (Buffer-read, no encoding) and `--stdin` (`readStdinBuffer` accumulator); provenance write-through — put_page accepts 3 optional params (source_kind, source_uri, ingested_via; `ingested_at` server-stamped) + trust gate (when `ctx.remote !== false` IGNORE client params, server stamps `mcp:put_page`, fail-closed) + COALESCE-preserve UPDATE semantics (omitting params on a later put_page preserves prior values; first-write-wins); `/admin/api/register-client` scopes normalization via `normalizeScopesInput(raw: unknown)` in `src/core/scope.ts` (accepts string/string[]/missing; rejects `['read write']` space-in-element shape, non-string elements, empty array, unknown scopes; deduped + sorted); brainstorm timeout surfacing via an orchestrator-level try/catch at `runBrainstorm` entry (single-point wrap covers every internal SQL site, classifies SQLSTATE 57014 via postgres.js `.code` / `.sqlState` / message fallback into `StructuredAgentError` code `brainstorm_timeout` with a hint covering all 3 PG cancel sub-causes); read-path surfaces all 4 provenance columns via `getPage` projection + `rowToPage` 3-state optional read + `Page` interface; canonical source resolver routes capture through `resolveSourceWithTier(engine, parsed.source, cwd)`; thin-client `--source` rejection (server-side OAuth client registration owns source scope); the `source_kind` taxonomy is closed (`capture-cli | put_page | mcp:put_page | webhook | file-watcher | inbox-folder | cron-scheduler`), `--source` maps to source_id only. Tests: `test/capture-build-content.test.ts`, `test/capture-runcapture.test.ts`, `test/put-page-provenance.test.ts`, `test/scope-normalize.test.ts`, `test/cli-help-discoverability.test.ts`, `test/brainstorm-timeout.test.ts`; extended `test/facts-absorb-log.test.ts`, `test/import-file.test.ts`, `test/e2e/engine-parity.test.ts`, `test/e2e/serve-http-ingest-webhook.test.ts`. Report at `docs/v0.38-smoke-test-report.md`. Follow-ups in TODOS.md: SQL-shape rewrite of `listPrefixSampledPages` for PgBouncer, magic-byte allowlist for binary detection, `--source-kind` override flag, ingest_capture handler migration, provenance-history table, facts:absorb root-cause trace.### BrainBench — in a sibling repo@@ -726,4 +733,3 @@ operation: `skills/google-loops/SKILL.md`.- `src/core/harness/capabilities.ts` + `src/mcp/capabilities.ts` — Shared effective-grant orientation for OAuth whoami and authenticated `gbrain://capabilities`. The resource preserves the exact seven-tool surface; source, operation, scope, fence and server-gate restrictions remain enforced at dispatch. No worker probe or per-tool database query during discovery.- `src/core/harness/verify.ts` — Randomized server-side memory verification with separate transport, identity, authority, read, write/readback, delegation and cleanup verdicts. Lost mutation responses are reconciled before retry; server success never certifies native-harness activation or cross-conversation behavior.- `src/commands/mcp.ts` + `mcp-provision.ts` + `harness-connect.ts` — Host-side grant/preview/CAS and recoverable private delivery, followed by installation inside the intended harness. Running PGLite hosts are administered through their authenticated API, never by opening a second database process. CLI status uses the delivery-aware exit verdict.-- `src/commands/serve-http-consent.ts` — Browser owner approval before OAuth authorization. Single-use nonces bind the complete authorization query to an authenticated admin session; redirects, PKCE and resource validation still run through the OAuth provider. Public metadata contains adapter/profile identifiers and documentation, never client inventories.diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.mdindex 21c42abf53..a93532b1a7 100644--- a/docs/architecture/topologies.md+++ b/docs/architecture/topologies.md@@ -138,9 +138,12 @@ gbrain auth register-client neuromancer-dept \```The `register-client` command prints a `client_id` and `client_secret`.-Note both. **Scope must include `admin`** — `submit_job` (used by-`gbrain remote ping`) and `run_doctor` (used by `gbrain remote doctor`)-both require it.+Note both. **Scope must include `admin`** for `run_doctor` (used by+`gbrain remote doctor`) and generic background jobs. `submit_job` accepts+only `sync`, `import`, `lint`, and `lint-fix` with the authenticated source's+registered root. `gbrain remote ping` no longer submits an autopilot cycle;+run maintenance on the brain host. See the+[authorization upgrade guide](../guides/authorization-upgrade.md#generic-remote-background-jobs).**Step 2 — On the thin client (neuromancer):**diff --git a/docs/guides/authorization-upgrade.md b/docs/guides/authorization-upgrade.mdnew file mode 100644index 0000000000..e8f723906a--- /dev/null+++ b/docs/guides/authorization-upgrade.md@@ -0,0 +1,182 @@+# Authorization and worker upgrade++This upgrade adds owner approval for OAuth authorization-code connections and durable authorization+for queued work. It requires a coordinated worker cutover. Back up the database+and source repositories before applying migrations.++**Say to your agent:** *"Plan my GBrain upgrade, preserve my connections, and+show me which queued jobs need review before services restart."* Your agent+uses `gbrain jobs authorize-legacy` to preview selected work for review.++## Runtime and outbound requests++Use Bun **1.3.11 or newer**. CI covers 1.3.11 and the build runtime, 1.3.13.+Compiled distributions include their Bun runtime.++URL reachability checks, HTTP integration checks, and remote image loading use+direct connections to validated destinations. If they return+`PROXY_NOT_SUPPORTED`, remove `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, and their+lowercase variants from the service environment, then restart GBrain. A+`NO_PROXY` exception does not enable these requests. This requirement concerns+these guarded URL operations; configure provider connections separately.++Remote images have a 2 MiB decoded limit; local images retain the 10 MiB limit.+HTTP checks read response headers only. Redirects share the original deadline;+HTTPS cannot redirect to HTTP. Checks carrying configured headers, credentials,+or bodies stay on the original origin through redirects.++## Connecting an OAuth client++An authorization request opens the existing admin login and then an approval+page. Review the client, redirect destination, requested scopes, administrative+capabilities, and source before approving. The page preserves the pending+request through password or magic-link login. Authorization grants require+S256 PKCE for both public and confidential clients.++Pending requests expire after ten minutes and are held only in server memory.+After expiry, server restart, a policy change, or an uncertain approval result,+restart the connection from the client. Repeated clicks cannot produce another+code. At most 1,000 requests can be pending; retry when capacity is available.++Existing access tokens, refresh tokens, and unexpired authorization codes for+active clients remain valid. There is no session purge or retroactive approval+requirement. Review existing clients in **Admin → Agents**, narrow their grants+where appropriate, and revoke clients that should no longer connect. Revoking+a client invalidates its outstanding grants and prevents its queued work from+starting. Rotating or expiring an individual OAuth credential does not cancel+work already accepted for that client. Revoking or deleting a legacy bearer+token prevents work accepted under that token from starting.++## Generic remote background jobs++`submit_job` accepts four generic filesystem jobs for the authenticated source:++| Name | Caller `data` | Execution |+| --- | --- | --- |+| `sync` | Absent, empty, or boolean `pull` / legacy `noPull`; never both | Registered root, configured concurrency, no embedding, extraction, or embed backfill |+| `import` | Absent or empty | Registered root, authenticated source, no embedding |+| `lint` | Absent or empty | Inspect the registered root |+| `lint-fix` | Absent or empty | Fix files inside the registered root |++The source must be active, have a valid filesystem configuration (`kind` absent+or null), and have an existing registered directory. Connector and unknown+source kinds require their dedicated operations. A path, source override,+GitHub-item parameter, or unknown field is rejected.++Pull defaults on only for a source covering the entire Git worktree. Nested+sources default off and cannot explicitly enable pull. `sync` requires an+existing Git worktree; use `import` for an ordinary non-Git directory.++Generic background submission requires a durable authenticated principal.+Stdio agents should use the local CLI or a dedicated authorized operation.+Local application maintenance retains its existing job and budget restrictions.++`gbrain remote ping` previously submitted an `autopilot-cycle` job and now+receives the generic-job denial. Run the existing maintenance workflow on the+brain host, or use dedicated authorized operations such as `sync_brain` and+`connector_sync`. `gbrain remote doctor` remains available with its required+scope.++Execution rechecks the original authorization against current principal and+source policy. Revocation, narrowed permissions, incompatible bindings,+archiving, or a changed source root stops execution. Retry, replay, and+coalescing preserve the original authority. Cancel jobs through the existing+job controls when their work is no longer wanted.++Delegated tools exclude `file_list`, `file_url`, and every `localOnly` operation.+Update existing bindings referencing removed tools before resubmission. Remote+tool bindings must be nonempty. Internally, an explicit empty tool list means+no tools; only an absent trusted-local binding uses the default registry.++## Queue cutover++1. Pause HTTP ingress, schedules, producers, and automatic upgraders so no new+ work enters. Let active work drain, then stop supervisors, workers, reapers,+ and every other process sharing the database. Back up the stopped database,+ repositories, service configuration, and compatible application version.+ Keep services stopped throughout review and migration.+2. Install the same new application version everywhere without running+ post-upgrade helpers or package lifecycle scripts. For a **published binary**+ installation, use `gbrain upgrade --swap-only`. For a **Bun package**+ installation, replace `vX.Y.Z.W` below with the exact release being installed:++ ```sh+ bun install --global --ignore-scripts github:garrytan/gbrain#vX.Y.Z.W+ ```++ For a linked source checkout, update that checkout to the chosen release+ through its normal Git workflow, then run `bun install --ignore-scripts`.+ Do not use `gbrain upgrade --swap-only` for this source/package cutover: its+ underlying Bun installation can still run postinstall. Plain `gbrain upgrade`,+ `gbrain post-upgrade`, and `gbrain apply-migrations --yes` can run pending+ setup phases that start autopilot or perform other maintenance.++ Verify the installed version, then apply only schema migrations:++ ```sh+ gbrain --version+ gbrain apply-migrations --force-schema --yes+ ```++ `--force-schema` runs pending schema migrations and returns before setup+ orchestrators. It does not approve queued work or bypass the drain check.+ The nullable `submission_authority` column leaves historical rows untrusted.+ Protocol checks reject old producer inserts and worker claims. Do not run+ old workers, reapers, or supervisors against this queue. If active historical+ work blocks migration and the new CLI cannot inspect or cancel it, restore+ compatible pre-upgrade application and database state, resolve that work+ locally, and repeat the cutover.+3. Inspect outstanding jobs with local job controls. Preview only explicitly+ selected legacy rows whose `submission_authority` is **SQL NULL**:++ ```sh+ gbrain jobs authorize-legacy --ids 101,102 --json+ ```++ Review the payloads, schedules, attempts, and transitive dependency effects. The command+ does not authorize or mutate work without the apply flags.+ Non-NULL authority is never rewritten by this command, including future+ versions, malformed objects, and JSON `null`. Use matching application and+ database versions to interpret that work, or explicitly cancel it locally.+4. Apply exactly the reviewed snapshot digest:++ ```sh+ gbrain jobs authorize-legacy --ids 101,102 --expect <snapshot_digest> --yes --json+ ```++ A changed snapshot or dependency graph refuses approval; preview and review+ again. Only selected SQL-NULL rows receive application authority. IDs, schedules, attempts, and+ dependencies remain intact. Dependencies require their own explicit review.+5. Explicitly authorize or cancel every nonterminal legacy job before restarting+ services. Worker startup refuses unresolved work. Historical terminal rows+ remain unchanged; review them explicitly before a later local replay.+ Remote replay cannot authorize legacy rows.+6. Start the matching application, producers, and workers and inspect job+ diagnostics for bounded authorization denials. Resume normal post-upgrade+ setup and automatic-upgrade schedules only after the queue review is complete+ and every process uses the matching version.++For rollback, stop all services and restore compatible application and database+state together. An older worker must never run against the enforced queue.++For installations using automatic upgrades, pause the automatic upgrade+schedule before this cutover and keep it paused until every worker runs the+matching version. If the new binary has already migrated the database, stop all+old processes immediately and continue with the local queue review above.+Keep preview output and backup contents private; they can contain job payloads.++## Files and documents++Frontmatter accepts data-only YAML and JSON, preserving existing scalar types.+Unsupported language selectors and malformed documents return errors, including+in import summaries. An import with per-file failures exits nonzero and reports+`status: "partial"` in JSON; its checkpoint retains completed files for retry.+No bulk reserialization, reindex, or content migration is needed; document+bodies remain opaque to serialization.++Filesystem jobs validate registered canonical roots and reject escaping paths+and symlink targets. POSIX final files are opened with `O_NOFOLLOW` and accessed+through that descriptor. Platforms without `O_NOFOLLOW` support refuse remote+file access. Cooperating writers share root and source locks.+Local filesystem writers and source ancestors remain trusted; these checks do+not provide an OS sandbox against hostile directory replacement.diff --git a/docs/guides/minions-shell-jobs.md b/docs/guides/minions-shell-jobs.mdindex 2baa328b0e..10250d177b 100644--- a/docs/guides/minions-shell-jobs.md+++ b/docs/guides/minions-shell-jobs.md@@ -287,7 +287,7 @@ gbrain jobs list --status dead --name shell| `shell: inherit name "<X>" must match [a-z][a-z0-9_]*` | Name failed snake_case regex (uppercase, leading digit/underscore, special char). | Use the config-key name verbatim — `database_url`, not `DATABASE_URL`. || `shell: inherit requested "<X>" but worker has no <X> configured` | Worker can't resolve the requested name from `loadConfig()`. | Run `gbrain config set <X> <value>` on the worker host, OR check the config file at `~/.gbrain/config.json`. || `shell: redact_secrets must be a boolean if set` | Caller passed a non-boolean for `redact_secrets`. | Pass `true` or `false` (or omit). The CLI `--redact-secrets` flag sets it automatically. |-| `permission_denied: shell jobs cannot be submitted over MCP` | An MCP client tried to submit a shell job. By design CLI-only. | Submit from CLI or via a trusted operation handler (`ctx.remote === false`). |-| `protected job name 'shell' requires CLI or operation-local submitter` | A caller invoked `MinionQueue.add('shell', ...)` without the `trusted` opt-in. | Pass `{ allowProtectedSubmit: true }` as the 4th arg. CLI and `submit_job` do this automatically. |+| `permission_denied` with an unsupported remote job message | An MCP client tried to submit a shell job. Shell submission requires local authority. | Submit from the local CLI or an authorized application handler. |+| `protected job name 'shell' requires CLI or operation-local submitter` | An application called `MinionQueue.add('shell', ...)` without the protected-job opt-in. | An authorized local submitter supplies `{ allowProtectedSubmit: true }` as the fourth argument. The local CLI handles this; remote `submit_job` cannot grant it. || `aborted: timeout` / `aborted: cancel` / `aborted: shutdown` / `aborted: lock-lost` | The worker's abort signal fired mid-execution. Child got SIGTERM, 5s grace, then SIGKILL. | Expected: timeout / user cancel / deploy restart / stall. Inspect `gbrain jobs get` to see which. || `exit N: <stderr_tail_500>` | Script exited non-zero. | Read `stderr_tail` in `gbrain jobs get`. |diff --git a/docs/mcp/DEPLOY.md b/docs/mcp/DEPLOY.mdindex 5435c9199a..2e0add4784 100644--- a/docs/mcp/DEPLOY.md+++ b/docs/mcp/DEPLOY.md@@ -15,6 +15,11 @@ Access your brain from any device, any AI client. GBrain ships two transports:`gbrain serve` (stdio) for local agents, and `gbrain serve --http` for remoteclients over OAuth 2.1.+Authorization-code connections require owner approval in the admin dashboard.+Existing sessions are preserved. Before upgrading an installation with queued+work, follow the [authorization and worker upgrade guide](../guides/authorization-upgrade.md)+for the coordinated cutover, consent recovery, and Bun requirements.+## Three Paths### Local stdio (zero setup)diff --git a/llms-full.txt b/llms-full.txtindex 0bffa4c0c8..0227acb265 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -2720,6 +2720,10 @@ This is the difference between a search engine and a brain. Search finds the pag## Install+Requires **Bun 1.3.11 or newer**. Existing worker installations should follow the+[authorization and queue upgrade guide](docs/guides/authorization-upgrade.md)+before restarting services with this version.+> [!WARNING]> **GBrain is NOT distributed on npm.** The npm package named `gbrain` is an unrelated> package with no connection to this project. Do not run `npm install -g gbrain` or@@ -5755,6 +5759,11 @@ Access your brain from any device, any AI client. GBrain ships two transports:`gbrain serve` (stdio) for local agents, and `gbrain serve --http` for remoteclients over OAuth 2.1.+Authorization-code connections require owner approval in the admin dashboard.+Existing sessions are preserved. Before upgrading an installation with queued+work, follow the [authorization and worker upgrade guide](../guides/authorization-upgrade.md)+for the coordinated cutover, consent recovery, and Bun requirements.+## Three Paths### Local stdio (zero setup)diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 32b8dda44d..e98ac19a21 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.49.0.0",+ "version": "0.50.0.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","configSchema": {diff --git a/package.json b/package.jsonindex 88130b6d10..75450e0ee5 100644--- a/package.json+++ b/package.json@@ -146,7 +146,6 @@"exifr": "^7.1.3","express": "^5.1.0","express-rate-limit": "^7.5.0",- "gray-matter": "^4.0.3","heic-decode": "^2.1.0","js-yaml": "^3.15.2","jsonc-parser": "^3.3.1",@@ -172,10 +171,10 @@"@electric-sql/pglite"],"engines": {- "bun": ">=1.3.10"+ "bun": ">=1.3.11"},"license": "MIT",- "version": "0.49.0.0",+ "version": "0.50.0.0","overrides": {"@ai-sdk/provider-utils": "4.0.33","@hono/node-server": "^2.0.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex c042fe3f38..1a3ccf9b01 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.49.0.0",+ "version": "0.50.0.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex 422e2a5202..9b9e43e9be 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.49.0.0",+ "version": "0.50.0.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex 45c6611f19..77ba824bc6 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.49.0.0 -->+<!-- gbrain-plugin-tree-stamp: 0.50.0.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 530faf0e44..fbf6db251a 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.49.0.0",+ "version": "0.50.0.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex 143136e47f..74f4c99931 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.49.0.0",+ "version": "0.50.0.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex 6112593a77..39fc2a0c21 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.49.0.0 -->+<!-- gbrain-plugin-tree-stamp: 0.50.0.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin/README.md b/plugin/README.mdindex bdae533309..88b82391fd 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.49.0.0 -->+<!-- gbrain-plugin-tree-stamp: 0.50.0.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Code@@ -9,7 +9,7 @@ addition/exclusion).## MCP surface note (read once)The plugin's MCP server runs `gbrain serve --surface starter` — the-28-op daily-driver surface (the seven memory verbs + daily+26-op daily-driver surface (the seven memory verbs + dailybrain ops + capture). 22bundled skills reference gbrain operations beyond that surface; every one ofthem has a first-class `gbrain` CLI path, which is the primary way skillsdiff --git a/plugin/skills/minion-orchestrator/SKILL.md b/plugin/skills/minion-orchestrator/SKILL.mdindex 008a49100c..801e372b82 100644--- a/plugin/skills/minion-orchestrator/SKILL.md+++ b/plugin/skills/minion-orchestrator/SKILL.md@@ -130,8 +130,8 @@ tasks where no LLM reasoning loop is needed.The daemon mode is not available on PGLite (exclusive file lock). See`docs/guides/minions-shell-jobs.md`.- **MCP boundary:** shell-job submission is CLI-only. `submit_job name="shell"`- over MCP throws an `OperationError` with code `permission_denied` ("'shell'- jobs cannot be submitted over MCP") because `shell` is in `PROTECTED_JOB_NAMES`.+ over MCP throws an `OperationError` with code `permission_denied`; generic+ remote submission accepts only `sync`, `import`, `lint`, and `lint-fix`.Agents CAN observe shell jobs via `get_job` / `list_jobs` / `get_job_progress`(not protected), but cannot submit them. Operator or autopilot submits;agent observes.@@ -195,9 +195,9 @@ Use for open-ended reasoning, tool-using research, and fan-out synthesis.**User-facing entrypoint:** `gbrain agent run <prompt>` is the canonical wayto submit subagent work. It handles the elevated-trust plumbing — `subagent`-and `subagent_aggregator` are both in `PROTECTED_JOB_NAMES`, so direct MCP-submission requires `{allowProtectedSubmit: true}`, which `gbrain agent run`-supplies.+and `subagent_aggregator` are protected job names. Remote agents use the+dedicated `submit_agent` operation with their configured source, tools, and+slug binding; generic `submit_job` does not accept these job names.## Phase 1: Submit@@ -207,9 +207,12 @@ gbrain agent run "Research Acme Corp revenue" --tools "search,query"`--tools` accepts a comma-separated subset of `BRAIN_TOOL_ALLOWLIST` (see`src/core/minions/tools/brain-allowlist.ts`): `query`, `search`, `get_page`,-`list_pages`, `file_list`, `file_url`, `get_backlinks`, `traverse_graph`,-`resolve_slugs`, `get_ingest_log`, `put_page`. Anything outside the allow-list-is rejected at submit time with `allowed_tools references unknown tool`.+`list_pages`, `get_backlinks`, `traverse_graph`, `list_link_sources`,+`resolve_slugs`, `get_ingest_log`, `put_page`, `add_timeline_entry`,+`get_recent_salience`, `find_anomalies`. Attachment tools and local-only+operations are unavailable. Update old bindings before resubmitting jobs+that reference removed tools. Remote bindings must be nonempty; an explicit+empty local tool list grants no tools.For parallel work with a fan-out manifest:```@@ -512,7 +515,7 @@ Total tokens so far: 4.3k## Tools Used-- Submit a background job — `submit_job` (MCP, non-protected names only; shell jobs are CLI-only, subagent jobs via `gbrain agent run`)+- Submit a background job — `submit_job` (MCP: only `sync`, `import`, `lint`, and `lint-fix`, under the contract in `docs/guides/authorization-upgrade.md`; shell jobs use the local CLI, remote subagents use `submit_agent`)- Get job details — `get_job` (MCP)- List jobs with filters — `list_jobs` (MCP)- Cancel a job — `cancel_job` (MCP)diff --git a/scripts/check-pglite-embedded.sh b/scripts/check-pglite-embedded.shindex 1a32e714ff..a41f210c01 100755--- a/scripts/check-pglite-embedded.sh+++ b/scripts/check-pglite-embedded.sh@@ -36,12 +36,11 @@ GBRAIN_HOME_DIR="$BUILD_DIR/home"trap 'rm -rf "$BUILD_DIR"' EXITmkdir -p "$BUILD_DIR/scripts" "$GBRAIN_HOME_DIR"cp -R "$REPO_ROOT/src" "$BUILD_DIR/src"-cp "$REPO_ROOT/package.json" "$BUILD_DIR/package.json"-# Grant migrations validate against the running operation registry, whose-# shipped templates are compile-time assets too. Preserve package-relative paths.+# Shared operation/queue boundaries can reach embedded bootstrap assets even+# from an engine-only import. Keep the compiled graph's file imports available.cp -R "$REPO_ROOT/templates" "$BUILD_DIR/templates"-mkdir -p "$BUILD_DIR/skills"-cp "$REPO_ROOT/skills/_brain-filing-rules.json" "$BUILD_DIR/skills/_brain-filing-rules.json"+cp -R "$REPO_ROOT/skills" "$BUILD_DIR/skills"+cp "$REPO_ROOT/package.json" "$BUILD_DIR/package.json"cp "$REPO_ROOT/scripts/pglite-embedded-smoketest.ts" "$BUILD_DIR/scripts/pglite-embedded-smoketest.ts"ln -s "$REPO_ROOT/node_modules" "$BUILD_DIR/node_modules"diff --git a/scripts/ci-local.sh b/scripts/ci-local.shindex 91e53468d3..cf8e9773eb 100755--- a/scripts/ci-local.sh+++ b/scripts/ci-local.sh@@ -67,7 +67,8 @@ if [ "$DIFF" = "1" ]; thenecho "[ci-local] ERROR: gitleaks not installed; the required secrets scan cannot run. Install gitleaks and retry." >&2exit 1else- gitleaks dir . --redact --no-banner+ bash scripts/test-gitleaks-config.sh+ bash scripts/scan-worktree-secrets.shgitleaks git . --redact --no-banner --log-opts="origin/master..HEAD"fiecho "[ci-local] Doc-only fast-path complete. No code paths exercised."@@ -122,7 +123,8 @@ fi# 1. Working-tree files (catch uncommitted secrets sitting in files)# 2. Branch commits vs origin/master (catch secrets committed on this branch)# Full-history scan is ~4 min on this repo's 3700+ commits; not useful pre-push.-gitleaks dir . --redact --no-banner+bash scripts/test-gitleaks-config.sh+bash scripts/scan-worktree-secrets.shgitleaks git . --redact --no-banner --log-opts="origin/master..HEAD"# Step 1: pull. Refreshes pgvector + the pinned oven/bun tag (both are `image:` not `build:`).diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex c6e77f4a55..4add9996df 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -15,11 +15,11 @@// No brace expansion, no ?, no [ ].export const E2E_TEST_MAP: Record<string, string[]> = {+ "src/core/minions/errors.ts": ["test/e2e/subagent-gateway-path.test.ts", "test/e2e/delegated-http-worker.test.ts", "test/e2e/subagent-crash-replay-multi-provider.test.ts"],"src/core/harness/**": ["test/e2e/harness-access.test.ts"],"src/core/grants/**": ["test/e2e/client-grants.test.ts", "test/e2e/harness-access.test.ts", "test/e2e/delegated-grants-withdrawal.test.ts", "test/e2e/delegated-http-worker.test.ts"],"src/core/facts/withdrawal*.ts": ["test/e2e/delegated-grants-withdrawal.test.ts"],"src/commands/mcp*.ts": ["test/e2e/harness-access.test.ts"],- "src/commands/serve-http-consent.ts": ["test/e2e/harness-access.test.ts"],// OpenRouter subagent-loop families: the family allowlist + recipe feed the// key-gated live DeepSeek replay (self-skips without OPENROUTER_API_KEY)."src/core/ai/openrouter-families.ts": ["test/e2e/openrouter-deepseek-subagent-replay.live.test.ts"],@@ -105,6 +105,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {// reduce coverage vs the fail-closed run-everything default for unmapped paths."src/core/cycle/inline-drain.ts": ["test/e2e/dream-synthesize-pglite.test.ts",+ "test/e2e/minions-authority-parity.test.ts","test/e2e/minions-concurrency.test.ts","test/e2e/minions-resilience.test.ts","test/e2e/minions-shell.test.ts",@@ -268,7 +269,11 @@ export const E2E_TEST_MAP: Record<string, string[]> = {// (per the plan-eng-review E1 decision); the daemon + built-in sources// + ingest_capture Minion handler all feed the in-process roundtrip// E2E AND the HTTP contract E2E for the webhook route.+ "src/core/oauth-provider.ts": ["test/e2e/oauth-grant-transactions.test.ts", "test/e2e/serve-http-oauth.test.ts"],+ "src/core/oauth-grants.ts": ["test/e2e/oauth-grant-transactions.test.ts", "test/e2e/serve-http-consent.test.ts"],+ "src/commands/serve-http-oauth.ts": ["test/e2e/serve-http-consent.test.ts"],"src/commands/serve-http.ts": [+ "test/e2e/serve-http-consent.test.ts","test/e2e/serve-http-ingest-webhook.test.ts","test/e2e/serve-http-oauth.test.ts","test/e2e/harness-access.test.ts",diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 315aa55731..2041ac1457 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -3,33 +3,33 @@# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy note-src/cli.ts 4081 ratchet +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards+src/cli.ts 4087 ratchet +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue reviewsrc/commands/autopilot.ts 2668 ratchet grown v0.46.26.0 megawave (#4300 #4285 #3696) + master v0.46.27.0 env-file lane + boot warning + reload-safe install (#2608 #4443) + 1 nosemgrep dataflow annotation (path-traversal audit); +chat-connectors wiring; +20 #4728 wrapper exec guard (baked CLI path gone -> PATH fallback / --install hint)src/commands/doctor.ts 4641 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): one in-branch live-column diff on detectMissingColumns + engine-aware superseded upgrade-error suppression (explicit ok); grown db-availability loop: classified connection check + synthesized total-outage entry + hoisted pgbouncer helper + engine-fit check wiring + report engine/db_url_source fields; +chat-connectors wiring (master merge); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +7 backup_coverage check registration (monthly backup check); +master-merge true-up; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +9 v0.47 gmail-loops: google_oauth vault-health check dispatch; +17 (#4712: git-root-pinned source skip note wiring + all-skipped warn-not-ok status for multi_source_drift); +8 memorable_relay_health wiring (check itself is a peel: doctor/checks/integrations-memorable.ts); +9 ambient-writeback WP6: memory_writeback check registration (logic lives in doctor/checks/memory-writeback.ts); +14 default_source_local_path registration (#4739 — check body peeled to doctor/checks/default-source-path.ts); +9 atom_provenance_drift registration (#4566 — check body lives in doctor/checks/extraction-sync.ts); master: | merged v0.48.1.0 true-upsrc/commands/embed.ts 2147 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment)src/commands/extract-conversation-facts.ts 2105 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failedsrc/commands/extract.ts 2536 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode)-src/commands/jobs.ts 3151 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled)-src/commands/serve-http.ts 3486 ratchet +20 #4866: RFC 9728 PRM resource=/mcp + root-path alias rewrite; grown v0.46.25.0 D2: /mcp per-request teardown (#2844); grown wave-g (#4474): resolve-IPC socket under --http via shared helper; +15: metrics wiring — tracker mount + admin-gated /metrics route, helpers live in serve-http-metrics.ts (#3893); +7 test-gap wave C6: adminAuthRateLimiter on admin login + magic-link issuance, 429 JSON envelope; +29 ambient-writeback: per-request buildMcpInstructions (writeback bundle + write-scope gate + allowed-ops extract_facts probe); +6 adversarial fix wave: remember-op bound-client fence probe gates the ambient section; +2 #4748: startup resolveMcpInstructions (deployment identity) threaded into the per-request MCP server | merged v0.48.1.0: master #4788 writeback resolve + wave #4748 identity; master: | merged v0.48.1.0 true-up; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; +12: reject snapshot-bound webhook ingestion outside the shared MCP grant contract-src/core/ai/gateway.ts 4846 ratchet +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards-src/commands/sync.ts 5870 ratchet +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed+src/commands/jobs.ts 3174 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled)+src/commands/serve-http.ts 3313 ratchet +20 #4866: RFC 9728 PRM resource=/mcp + root-path alias rewrite; grown v0.46.25.0 D2: /mcp per-request teardown (#2844); grown wave-g (#4474): resolve-IPC socket under --http via shared helper; +15: metrics wiring — tracker mount + admin-gated /metrics route, helpers live in serve-http-metrics.ts (#3893); +7 test-gap wave C6: adminAuthRateLimiter on admin login + magic-link issuance, 429 JSON envelope; +29 ambient-writeback: per-request buildMcpInstructions (writeback bundle + write-scope gate + allowed-ops extract_facts probe); +6 adversarial fix wave: remember-op bound-client fence probe gates the ambient section; +2 #4748: startup resolveMcpInstructions (deployment identity) threaded into the per-request MCP server | merged v0.48.1.0: master #4788 writeback resolve + wave #4748 identity; master: | merged v0.48.1.0 true-up; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; +12: reject snapshot-bound webhook ingestion outside the shared MCP grant contract; merged v0.49: one owner-consent route with shared grant editing+src/core/ai/gateway.ts 4846 ratchet +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards+src/commands/sync.ts 5929 ratchet +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; master integration: +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summedsrc/core/cycle.ts 3207 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:falsesrc/core/cycle/synthesize.ts 3216 ratchet merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance)src/core/cycle/extract-atoms.ts 1742 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns oncesrc/core/engine.ts 2645 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc-src/core/import-file.ts 2250 ratchet grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards-src/core/migrate.ts 690 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards+src/core/import-file.ts 2251 ratchet grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing+src/core/migrate.ts 690 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guardssrc/core/operations.ts 321 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS-src/core/pglite-engine.ts 6105 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards+src/core/pglite-engine.ts 6118 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap paritysrc/core/postgres-engine.ts 5577 ratchet +6 #4881: ontology provenance-page visibility gate (parity twin); lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069); +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +61: #4592 source-scoped getStats/getHealth (scope predicate, both-endpoint link rule); +11 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); rule); +12: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata, parity twin); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +3: #4681 listPages projects updated_at_iso (microsecond keyset cursor, parity twin)src/core/search/hybrid.ts 3295 ratchet grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380); +59 2026-09 adversarial batch 2: both-mode text-only demotion gate (textVectorArmNonEmpty) + relaxed_dropped meta + keyword_relaxed_carried degraded stamp + intent-skew caveat docs; +35 #3617 follow-up: relaxed-row fusion demotion (vectorArmNonEmpty gate + keywordFusionList/titleFusionList) with the LongMemEval 51.3%-vs-93.8% receipt comment; +24 2026-08 eval fix wave (E5b/D8): adaptive-return knobs-hash v27 fold (resolved gate + intent class threaded to the cache key), adaptive-on skipCache removal, dedupOpts cache-skip honesty, explicit-maxPerPage min() precedence under walk widening; (#4380); +20 wave #4256: compiledTruthBoost helper — synthetic chunkless title rows (chunk_id 0 + empty chunk_text) never gain the 2x compiled-truth boost (#3695); composition true-up (fix-wave multi-train) | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: read-policy propagation and semantic result-cache containment; ranker wave v0.48.4.0: role-tagged fusion arms, relational rerank pin, metadata boost gate, per-call knob seams, onRerankPool hook (+150) merged over master's read-policy plumbing (+31)src/core/types.ts 2118 ratchet +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs-src/core/minions/queue.ts 2450 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards-src/commands/init.ts 2050 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 normalized ZE provider check; +3: v0.48.2 review fixes; +2: preserve typed PGLite busy errors in schema-only init-src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)-src/core/minions/handlers/subagent.ts 1905 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards+src/core/minions/queue.ts 2484 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced+src/commands/init.ts 2050 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 normalized ZE provider check; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init+src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900); bounded recipe diagnostics; master integration: grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)+src/core/minions/handlers/subagent.ts 1905 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guardssrc/commands/bootstrap.ts 2115 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics-src/core/minions/worker.ts 1560 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave+src/core/minions/worker.ts 1546 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatchsrc/commands/sources.ts 1963 ratchet grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping servicessrc/core/link-extraction.ts 1785 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class)src/core/embedding-migration.ts 1545 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers)@@ -38,6 +38,6 @@ src/commands/hook.ts 1881 ratchet cathedral-5 heartbeat extraction offsets partsrc/core/chunkers/code.ts 1582 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPESsrc/core/config.ts 1777 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loadssrc/core/bootstrap/harness.ts 2420 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted-src/core/oauth-provider.ts 1552 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard)-src/core/ops/pages.ts 1484 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; +4: authenticated delegated private-write boundary and auto-link suppression+src/core/oauth-provider.ts 1235 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies+src/core/ops/pages.ts 1484 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppressionsrc/core/search/mode.ts 1752 ratchet +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6)diff --git a/scripts/run-e2e.sh b/scripts/run-e2e.shindex 05ad705d0e..fa1179cf60 100755--- a/scripts/run-e2e.sh+++ b/scripts/run-e2e.sh@@ -118,6 +118,7 @@ for _e2e_var in $(env | grep -oE '^(CONDUCTOR_|MCP_|OPENCLAW_|HERMES_|GROK_|OPENGBRAIN_PGLITE_SNAPSHOT) ;; # snapshot fast-path fixture (exported by ci-local.sh / runners) — keepGBRAIN_TEST_ALLOW_DATABASE_URL) ;; # #3485 preload opt-in (set above) — keepGBRAIN_TEST_KEEP_PROVIDER_KEYS) ;; # provider-keys preload opt-in (set above) — keep+ GBRAIN_CI_DISABLE_TEST_ENV_FILE) ;; # CI forbids loading checkout-local .env.testing — keep through Bun startupGBRAIN_TEST_DB) ;; # explicit schema-reset opt-in for service hosts; schema-drift still requires a test-shaped DB nameGBRAIN_PGBOUNCER_URL|GBRAIN_PGBOUNCER_DIRECT_URL|GBRAIN_CI_REQUIRE_PGBOUNCER) ;; # explicit pooler test target and execution requirementGBRAIN_E2E_FILE_TIMEOUT) ;; # per-file cap override — read AFTER this scrub, so it must survive itdiff --git a/scripts/scan-worktree-secrets.sh b/scripts/scan-worktree-secrets.shnew file mode 100644index 0000000000..623b62a35a--- /dev/null+++ b/scripts/scan-worktree-secrets.sh@@ -0,0 +1,25 @@+#!/usr/bin/env bash+# Scan all tracked files and new files eligible for commit. Local ignored+# credentials are not publishable inputs; tracked files are always included,+# even if a later .gitignore rule would otherwise hide them.+set -euo pipefail+cd "$(dirname "$0")/.."+python3 - <<'PY'+import os, pathlib, shutil, subprocess, tempfile+root = pathlib.Path.cwd()+paths = subprocess.check_output(['git', 'ls-files', '-z', '--cached', '--others', '--exclude-standard']).split(b'\0')+with tempfile.TemporaryDirectory(prefix='gbrain-secrets-') as directory:+ dest = pathlib.Path(directory)+ for raw in set(paths):+ if not raw:+ continue+ relative = pathlib.Path(os.fsdecode(raw))+ source = root / relative+ if not source.is_file():+ continue # Deleted files and submodules are covered by the Git scan.+ target = dest / relative+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(source, target)+ subprocess.run(['gitleaks', 'dir', '.', '--config', str(root / '.gitleaks.toml'),+ '--redact', '--no-banner'], cwd=dest, check=True)+PYdiff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 9f79c82e34..62770982c8 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -241,6 +241,7 @@ test/scripts/ci-gates.test.ts CI execution evidence 5 readFileSynctest/scripts/ci-gates.test.ts test:full exit status 0 readFileSynctest/scripts/ci-local-rendering.test.ts ci-local command rendering 1 readFileSynctest/scripts/ci-local-rendering.test.ts ci-local execution coverage 3 readFileSync+test/scripts/ci-local-rendering.test.ts local test configuration through run-e2e 2 readFileSynctest/scripts/ci-local-rendering.test.ts required PgBouncer execution through run-e2e 1 readFileSynctest/scripts/classify-tests.test.ts classify-tests detectors 18 bun-file,doctor-source-helper,exec-scan,readFileSynctest/scripts/coverage-diff-gate.test.ts exemptions 3 readFileSync@@ -248,6 +249,7 @@ test/scripts/e2e-wiring.test.ts e2e file claim ratchet 5 readFileSynctest/scripts/e2e-wiring.test.ts selected-e2e job wiring 6 readFileSynctest/scripts/run-verify-parallel.test.ts guard registration ⇒ execution coverage 1 readFileSynctest/scripts/test-shard.slow.test.ts test-shard.sh — LPT balance contract 5 readFileSync+test/serve-http-admin-route-guard.test.ts (file-level) 4 readFileSynctest/serve-http-github-webhook.test.ts handler wiring (source pin) 1 readFileSynctest/serve-http-mcp-transport-cleanup.test.ts POST /mcp transport cleanup (#2844) 2 readFileSynctest/serve-http-metrics.test.ts serve-http.ts wiring (structural — the two defects of the original PR) 2 readFileSyncdiff --git a/scripts/test-gitleaks-config.sh b/scripts/test-gitleaks-config.shnew file mode 100644index 0000000000..008eec0048--- /dev/null+++ b/scripts/test-gitleaks-config.sh@@ -0,0 +1,24 @@+#!/usr/bin/env bash+# Prove the configured detector is active and fixture exceptions stay narrow.+set -euo pipefail+repo_root=$(cd "$(dirname "$0")/.." && pwd)+fixture_root=$(mktemp -d)+trap 'rm -rf "$fixture_root"' EXIT+mkdir -p "$fixture_root/test"+cd "$fixture_root"+printf "const clientSecret = '%s%s';\n" 'gbrain_cs_' 'secret456' > "$fixture_root/test/auth-register-client-output-pin.test.ts"+gitleaks dir . --config "$repo_root/.gitleaks.toml" --redact --no-banner --log-level error+python3 - "$fixture_root/test/auth-register-client-output-pin.test.ts" <<'PY'+import hashlib, sys+with open(sys.argv[1], 'a') as fixture:+ fixture.write('const api_key = "' + hashlib.sha256(b'synthetic-gitleaks-canary').hexdigest() + '";\n')+PY+set +e+gitleaks dir . --config "$repo_root/.gitleaks.toml" --redact --no-banner --log-level error+result=$?+set -e+if [ "$result" -ne 1 ]; then+ echo "gitleaks configuration failed its synthetic detection canary (exit $result)" >&2+ exit 1+fi+echo "gitleaks configuration: fixture accepted; independent synthetic secret detected"diff --git a/skills/migrations/v0.50.0.0.md b/skills/migrations/v0.50.0.0.mdnew file mode 100644index 0000000000..cf5328c291--- /dev/null+++ b/skills/migrations/v0.50.0.0.md@@ -0,0 +1,131 @@+# v0.50.0.0: coordinate authorization and worker upgrades++This release preserves existing OAuth sessions and changes how background jobs+are authorized. Read [the upgrade guide](../../docs/guides/authorization-upgrade.md)+before upgrading a host with queued work. Perform these steps on the brain host;+a thin client cannot authorize historical jobs.++1. **Prepare a stopped-service cutover.** Identify every process sharing the+ database: HTTP ingress, scheduled producers, autopilot, supervisors, workers,+ and automatic upgraders. Pause schedules and ingress, stop new submissions,+ and let active work drain. Then stop all remaining processes. Back up the+ database, source repositories, and service configuration while they are+ stopped. Preserve the compatible application version with the backup.++ Do not run an unattended upgrade across this cutover. Do not run old workers,+ reapers, or supervisors against the upgraded database. If an automatic+ upgrade already installed this version, stop old processes before continuing.++2. **Install one matching version everywhere without starting setup phases.**+ Source installations need Bun 1.3.11 or newer; published binaries contain+ their runtime. For a published binary installation, use+ `gbrain upgrade --swap-only`. For a Bun package installation, use+ the following version-pinned command:++ ```bash+ bun install --global --ignore-scripts github:garrytan/gbrain#v0.50.0.0+ ```++ For a linked source checkout, update that checkout to the chosen release+ through its normal Git workflow, then run `bun install --ignore-scripts`.+ A source/package `gbrain upgrade --swap-only` still runs Bun's installation+ scripts; do not use it for this cutover. Plain upgrade, post-upgrade, and+ apply-migrations can run pending setup phases that start autopilot or other+ maintenance. Keep them deferred until review is complete.++ With all services still stopped, verify the installed binary and apply only+ schema migrations:++ ```bash+ gbrain --version+ gbrain apply-migrations --force-schema --yes+ ```++ `--force-schema` returns before setup orchestrators; it does not approve+ queued work or bypass migration checks. Migration 149 refuses active work+ and leaves historical jobs without new authority. Never backfill that+ authority with SQL or authorize the whole+ queue automatically. If migration reports active jobs, keep services stopped.+ If the new CLI cannot inspect or cancel them because migration runs first,+ restore the compatible pre-upgrade application and database, resolve that+ work locally, and repeat the cutover. Do not restore an older worker to drain+ an upgraded queue.++3. **Inspect the outstanding queue locally.** Review all nonterminal states:+ `waiting`, `active`, `delayed`, `waiting-children`, and `paused`. For example:++ ```bash+ gbrain jobs list --status waiting --limit 1000 --json+ gbrain jobs list --status delayed --limit 1000 --json+ gbrain jobs list --status waiting-children --limit 1000 --json+ gbrain jobs list --status paused --limit 1000 --json+ gbrain jobs list --status active --limit 1000 --json+ ```++ Increase the limit if a listing reaches it. Keep these results private:+ payloads and dependency previews can contain user data.++4. **Preview only selected historical jobs.** Replace the example IDs with jobs+ the operator intends to retain:++ ```bash+ gbrain jobs authorize-legacy --ids 101,102 --json+ ```++ This is read-only. Review the original payloads, schedules, attempts,+ dependencies, and cancellation/failure effects with the operator. Only+ `submission_authority IS NULL` rows are eligible. Future, malformed, or+ JSON-null authority requires matching application/database versions or an+ explicit local cancellation; it cannot be converted through this command.++5. **Apply the exact reviewed selection.** After the operator approves the+ concrete preview, replace the example IDs and digest with that preview:++ ```bash+ gbrain jobs authorize-legacy --ids 101,102 --expect REVIEWED_SNAPSHOT_DIGEST --yes --json+ ```++ Changed snapshots refuse approval. Preview and review again rather than+ retrying with a newly calculated digest without review. Dependencies are+ displayed for context and never implicitly authorized; review each needed+ dependency explicitly. To discard selected work instead, use the existing+ `gbrain jobs cancel JOB_ID` command after reviewing its dependency effects.++6. **Resolve every nonterminal historical job before restarting.** Keep terminal+ history unchanged. A later local replay of an unreviewed terminal row needs+ the same explicit review; remote replay cannot approve it. Start only matching+ application and worker versions after review/cancellation is complete. If+ startup reports unresolved authority, stop and inspect the named class of+ work rather than editing the authority column.++7. **Preserve connections and update callers.** Existing active-client tokens,+ refresh tokens, and unexpired codes remain valid. Do not purge or re-register+ them as part of this migration. New authorization-code connections use the+ admin approval page; after expiry, restart, or a changed client policy, restart the connection+ from the client. Review unwanted connections in **Admin → Agents**.++ Generic remote jobs accept only `sync`, `import`, `lint`, and `lint-fix` under+ the source-bound schemas in the upgrade guide. Use dedicated operations for+ connector work and the local host's maintenance workflow for autopilot.+ Update delegated-tool bindings that reference removed attachment tools;+ remote bindings must contain at least one permitted tool.++8. **Check runtime and import recovery.** Guarded URL operations use direct+ connections. If they report `PROXY_NOT_SUPPORTED`, remove the listed proxy+ variables from that service environment and restart it; a `NO_PROXY`+ exception is insufficient. Do not change provider connection configuration+ merely to address this error.++ Frontmatter remains ordinary YAML or JSON. Fix individual malformed files+ reported by imports, then retry using the preserved checkpoint. Do not bulk+ rewrite content, reindex, or re-embed for this release.++9. **Verify before restoring schedules.** Run `gbrain doctor` and+ `gbrain jobs stats --json`, inspect authorization/job diagnostics, and verify+ an existing connection still works. Restore the reviewed service schedules+ and automatic-upgrade policy only after every process uses the matching+ version and the queue is ready.++Rollback requires stopping every service and restoring compatible database and+application state together. Never downgrade only the binary while leaving old+workers attached to the upgraded queue.diff --git a/skills/minion-orchestrator/SKILL.md b/skills/minion-orchestrator/SKILL.mdindex 008a49100c..801e372b82 100644--- a/skills/minion-orchestrator/SKILL.md+++ b/skills/minion-orchestrator/SKILL.md@@ -130,8 +130,8 @@ tasks where no LLM reasoning loop is needed.The daemon mode is not available on PGLite (exclusive file lock). See`docs/guides/minions-shell-jobs.md`.- **MCP boundary:** shell-job submission is CLI-only. `submit_job name="shell"`- over MCP throws an `OperationError` with code `permission_denied` ("'shell'- jobs cannot be submitted over MCP") because `shell` is in `PROTECTED_JOB_NAMES`.+ over MCP throws an `OperationError` with code `permission_denied`; generic+ remote submission accepts only `sync`, `import`, `lint`, and `lint-fix`.Agents CAN observe shell jobs via `get_job` / `list_jobs` / `get_job_progress`(not protected), but cannot submit them. Operator or autopilot submits;agent observes.@@ -195,9 +195,9 @@ Use for open-ended reasoning, tool-using research, and fan-out synthesis.**User-facing entrypoint:** `gbrain agent run <prompt>` is the canonical wayto submit subagent work. It handles the elevated-trust plumbing — `subagent`-and `subagent_aggregator` are both in `PROTECTED_JOB_NAMES`, so direct MCP-submission requires `{allowProtectedSubmit: true}`, which `gbrain agent run`-supplies.+and `subagent_aggregator` are protected job names. Remote agents use the+dedicated `submit_agent` operation with their configured source, tools, and+slug binding; generic `submit_job` does not accept these job names.## Phase 1: Submit@@ -207,9 +207,12 @@ gbrain agent run "Research Acme Corp revenue" --tools "search,query"`--tools` accepts a comma-separated subset of `BRAIN_TOOL_ALLOWLIST` (see`src/core/minions/tools/brain-allowlist.ts`): `query`, `search`, `get_page`,-`list_pages`, `file_list`, `file_url`, `get_backlinks`, `traverse_graph`,-`resolve_slugs`, `get_ingest_log`, `put_page`. Anything outside the allow-list-is rejected at submit time with `allowed_tools references unknown tool`.+`list_pages`, `get_backlinks`, `traverse_graph`, `list_link_sources`,+`resolve_slugs`, `get_ingest_log`, `put_page`, `add_timeline_entry`,+`get_recent_salience`, `find_anomalies`. Attachment tools and local-only+operations are unavailable. Update old bindings before resubmitting jobs+that reference removed tools. Remote bindings must be nonempty; an explicit+empty local tool list grants no tools.For parallel work with a fan-out manifest:```@@ -512,7 +515,7 @@ Total tokens so far: 4.3k## Tools Used-- Submit a background job — `submit_job` (MCP, non-protected names only; shell jobs are CLI-only, subagent jobs via `gbrain agent run`)+- Submit a background job — `submit_job` (MCP: only `sync`, `import`, `lint`, and `lint-fix`, under the contract in `docs/guides/authorization-upgrade.md`; shell jobs use the local CLI, remote subagents use `submit_agent`)- Get job details — `get_job` (MCP)- List jobs with filters — `list_jobs` (MCP)- Cancel a job — `cancel_job` (MCP)diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 74fa1cc7f4..dd4175a342 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -136,12 +136,13 @@"migrations/v0.48.3.0.md": "1d9a23b6078164717944c94791b18effc7af630b716e8fde2680d6b6de47ce81","migrations/v0.49.0.0.md": "adf719246c3d6bcc7a1e5d24badb9968fe636651183a75c18d534e16aaa33ee8","migrations/v0.5.0.md": "5e0dabc451595295c4d971e19bcb33c258a127223d25859d8321cb7e1ce60711",+ "migrations/v0.50.0.0.md": "f221a6c907437a7500d2ad8ee9fdc5e14821514d4c1e72164b7aafac0bd5d89b","migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a","migrations/v0.8.0.md": "1919ff8b8f3680612ff888e7cfcc0d86ece5d5304ae19af4497bdf40b050561a","migrations/v0.8.1.md": "fad7341cfb5e02545fb8a23221d12ab395fc3d8db15d1d8ee8a18844aea6563a","migrations/v0.9.0.md": "773fab0a8d7f330576265a3f510c1f318f47789b6136c46d43e08121acbc20eb","migrations/v0.9.1.md": "75761bad6c0ad37b69ec8197c6a678bb6a1484f9a76e4b70f2d1e86dc80102b3",- "minion-orchestrator/SKILL.md": "0b6799dbe6bccc83984371545db0d1d6216d152578d035bb869471cca7ab9b69",+ "minion-orchestrator/SKILL.md": "63e7ead284ae03f039e5789e1479d9e49d8897cb2cedf1663746c727d86fd3be","minion-orchestrator/routing-eval.jsonl": "501ed2e19cb16847ff8425219d246b7a774de1accd42cb28fd44edbb64204992","perplexity-research/SKILL.md": "c25f5c471cbe3c6e0f975d8397e8382b00a85f8aa75302231d53c52855369e97","perplexity-research/routing-eval.jsonl": "f1a40d87e710d5d2acd602a372d83f46c95da022b6e635228fffeaacb3bb2b27",diff --git a/src/admin-embedded.ts b/src/admin-embedded.tsindex de6ba953f0..6ba5995392 100644--- a/src/admin-embedded.ts+++ b/src/admin-embedded.ts@@ -7,9 +7,9 @@// the request path the express handler sees to (resolved-path, mime).// @ts-ignore — type: 'file' is Bun ESM, not in lib.d.ts-import A_0_assets_index_B5gNvpC1_js from '../admin/dist/assets/index-B5gNvpC1.js' with { type: 'file' };+import A_0_assets_index_DECOlanw_css from '../admin/dist/assets/index-DECOlanw.css' with { type: 'file' };// @ts-ignore — type: 'file' is Bun ESM, not in lib.d.ts-import A_1_assets_index_CLnyXRh0_css from '../admin/dist/assets/index-CLnyXRh0.css' with { type: 'file' };+import A_1_assets_index_DfSDTH_v_js from '../admin/dist/assets/index-DfSDTH-v.js' with { type: 'file' };// @ts-ignore — type: 'file' is Bun ESM, not in lib.d.tsimport A_2_index_html from '../admin/dist/index.html' with { type: 'file' };@@ -19,8 +19,8 @@ export interface AdminAsset {}export const ADMIN_ASSETS: Record<string, AdminAsset> = {- "/admin/assets/index-B5gNvpC1.js": { path: A_0_assets_index_B5gNvpC1_js as unknown as string, mime: "application/javascript; charset=utf-8" },- "/admin/assets/index-CLnyXRh0.css": { path: A_1_assets_index_CLnyXRh0_css as unknown as string, mime: "text/css; charset=utf-8" },+ "/admin/assets/index-DECOlanw.css": { path: A_0_assets_index_DECOlanw_css as unknown as string, mime: "text/css; charset=utf-8" },+ "/admin/assets/index-DfSDTH-v.js": { path: A_1_assets_index_DfSDTH_v_js as unknown as string, mime: "application/javascript; charset=utf-8" },"/admin/index.html": { path: A_2_index_html as unknown as string, mime: "text/html; charset=utf-8" },};diff --git a/src/cli.ts b/src/cli.tsindex 720aafd514..157dd324f6 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -42,6 +42,7 @@ import { callRemoteTool, RemoteMcpError, unpackToolResult, extractResponseMeta }import { maybePromptForUpgrade } from './core/thin-client-upgrade-prompt.ts';import { CLI_FLAG_REGISTRY } from './core/cli-flag-registry.generated.ts';import { VERSION } from './version.ts';+import { assertSupportedBun } from './core/runtime-version.ts';import { bigintToStringReplacer } from './core/utils.ts';// db-availability loop: best-effort brain-id for the GBRAIN_DB_ACCESS marker,@@ -1993,9 +1994,9 @@ export const THIN_CLIENT_REFUSED_COMMANDS = new Set([* place during code review.*/const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {- sync: 'sync runs on the host. Trigger a remote cycle with `gbrain remote ping` (queues an autopilot-cycle job).',- embed: 'embed runs on the host as part of the autopilot cycle. `gbrain remote ping` triggers a full cycle including embed.',- extract: 'extract runs on the host. Use `gbrain remote ping` to trigger a cycle including extract.',+ sync: 'sync runs on the host. Use the dedicated `sync_brain` MCP operation, or run `gbrain sync` on the host.',+ embed: 'embed runs on the host. Run `gbrain embed` or `gbrain cycle` on the host machine.',+ extract: 'extract runs on the host. Run `gbrain extract` or `gbrain cycle` on the host machine.','extract-conversation-facts': 'extract-conversation-facts runs on the host (requires local engine + chat gateway). Run on the host machine.',enrich: 'enrich runs on the host (requires local engine + chat gateway for grounded synthesis). Run on the host machine.',migrate: "migrate runs on the host's local engine. Run on the host machine.",@@ -2004,7 +2005,7 @@ const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {'repair-jsonb': 'repair-jsonb operates on the local DB only.',integrity: 'integrity scans local files. Run on the host machine.',serve: 'serve starts a server. Run on the host, not the thin client.',- dream: 'dream runs the autopilot cycle on the host. `gbrain remote ping` queues one. (Native `gbrain dream` thin-client routing planned for v0.31.2.)',+ dream: 'dream runs the autopilot cycle on the host. Run `gbrain dream` on the host machine.',orphans: "orphans needs the host's brain. Run on the host or use the `find_orphans` MCP tool from your agent.",transcripts: 'transcripts is server-private (raw chat exports stay on the host). Read transcripts on the host machine.',storage: 'storage operates on the local repo on disk. Run on the host.',@@ -4023,6 +4024,11 @@ Run gbrain <command> --help for command-specific help.// process alive. A fatal error still exits 1 for every command, daemons// included (matches the prior unconditional process.exit(1) on rejection).if (import.meta.main) {+ try { assertSupportedBun(); }+ catch (error) {+ console.error((error as Error).message);+ process.exit(1);+ }// v0.41.6.0 D5: cleanup registry + signal handlers for SIGTERM/SIGHUP/SIGPIPE/// uncaughtException. NOT SIGINT (the existing AbortController path owns SIGINT).// Installed before main() so locks acquired during boot (e.g. connectEngine'sdiff --git a/src/commands/agent-register.ts b/src/commands/agent-register.tsindex 4bcef49e26..51185b3fe0 100644--- a/src/commands/agent-register.ts+++ b/src/commands/agent-register.ts@@ -661,7 +661,10 @@ async function mintAndProbe(): Promise<RegisterOutput> {const { GBrainOAuthProvider } = await import('../core/oauth-provider.ts');// The tx-scoped sql is dead after COMMIT — the exchange runs on the OUTER engine.- const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine) });+ const provider = new GBrainOAuthProvider({+ sql: sqlQueryForEngine(engine),+ transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))),+ });let accessToken: string | undefined;let tokenExpiresAt: string | undefined;diff --git a/src/commands/auth.ts b/src/commands/auth.tsindex 89bb43070d..4d349c32e7 100644--- a/src/commands/auth.ts+++ b/src/commands/auth.ts@@ -538,6 +538,7 @@ export function parseRegisterClientArgs(args: string[]): RegisterClientArgs {case '--bound-tools': {const v = requireValue();out.boundTools = v.split(',').map(s => s.trim()).filter(Boolean);+ if (out.boundTools.length === 0) throw new Error('--bound-tools requires at least one tool name');i += 2; break;}case '--delegated-slug-prefixes': out.delegatedSlugPrefixes = requireValue().split(',').map(s => s.trim()).filter(Boolean); i += 2; break;diff --git a/src/commands/import.ts b/src/commands/import.tsindex e3a7bd1c96..68419ca84f 100644--- a/src/commands/import.ts+++ b/src/commands/import.ts@@ -1,4 +1,5 @@-import { readdirSync, lstatSync, existsSync } from 'fs';+import { hasSourceFilesystemLock, withSourceFilesystemLock, currentSourceFilesystemSignal } from '../core/minions/source-filesystem.ts';+import { readdirSync, lstatSync, existsSync, mkdirSync } from 'fs';import { execFileSync } from 'child_process';import { isAbsolute, join, relative, resolve, sep } from 'path';import { cpus, totalmem } from 'os';@@ -124,12 +125,15 @@ function defaultWorkers(): number {*/export class ImportAbortError extends Error {readonly exitCode: number;+ /** Present only after an interrupted import has drained and checkpointed. */+ readonly partialResult?: RunImportResult;/** True: the user-facing message was already printed at the throw site. */readonly alreadyReported = true;- constructor(reason: string, exitCode = 1) {+ constructor(reason: string, exitCode = 1, partialResult?: RunImportResult) {super(`import aborted: ${reason}`);this.name = 'ImportAbortError';this.exitCode = exitCode;+ this.partialResult = partialResult;}}@@ -167,6 +171,7 @@ export async function runImport(engine: BrainEngine,args: string[],opts: {+ signal?: AbortSignal;commit?: string;strategy?: SyncStrategy;sourceId?: string;@@ -200,6 +205,9 @@ export async function runImport(slugRoot?: string;} = {},): Promise<RunImportResult> {+ const inheritedSignal = currentSourceFilesystemSignal();+ const signal = opts.signal && inheritedSignal ? AbortSignal.any([opts.signal, inheritedSignal]) : opts.signal ?? inheritedSignal;+ signal?.throwIfAborted();const noEmbed = args.includes('--no-embed');const allowNoncanonicalRoot = args.includes('--allow-noncanonical-root');const fresh = args.includes('--fresh');@@ -416,6 +424,21 @@ export async function runImport(throw new ImportAbortError(`import target not readable: ${dirArg}`);}+ if (!hasSourceFilesystemLock(dir)) {+ let entered = false;+ try {+ return await withSourceFilesystemLock(engine, dir, () => {+ entered = true;+ return runImport(engine, args, opts);+ }, { signal });+ } catch (error) {+ // Root discovery is part of admission. Preserve the CLI/library's typed+ // preflight error contract without changing errors from an import in flight.+ if (entered || signal?.aborted) throw error;+ throw new ImportAbortError('source filesystem lock admission failed');+ }+ }+if (!allowNoncanonicalRoot) {try {const strictRoot = (await engine.getConfig('import.require_configured_root')) === 'true';@@ -585,6 +608,7 @@ export async function runImport(}async function processFile(eng: BrainEngine, filePath: string) {+ if (signal?.aborted) return;const relativePath = relative(dir, filePath);// #753/#774: slug + source_path base. When performFullSync syncs a// monorepo subdir, slugRoot is the git root so slugs stay git-root-@@ -603,6 +627,8 @@ export async function runImport(const result = isImageFilePath(relativePath) && process.env.GBRAIN_EMBEDDING_MULTIMODAL === 'true'? await importImageFile(eng, filePath, importRelPath, { noEmbed, sourceId }): await importFile(eng, filePath, importRelPath, { noEmbed, sourceId, activePack: importActivePack });+ // An import that landed while cancellation arrived is still complete.+ // Account for it before stopping, so resume never loses a successful path.noteTypeWarning((result as { type_warning?: Parameters<typeof noteTypeWarning>[0] }).type_warning);const _fileMs = Date.now() - _fileT0;if (_fileMs > 5000) {@@ -624,6 +650,7 @@ export async function runImport(malformedFileSkips++;completed.add(relativePath);} else if (result.error && result.error !== 'unchanged') {+ errors++;console.error(` Skipped ${relativePath}: ${result.error}`);// Bug 9 — non-"unchanged" skips carry a real error reason.// #774: ledger paths use the slug base so an incremental sync's@@ -637,6 +664,11 @@ export async function runImport(}}} catch (e: unknown) {+ if (signal?.aborted) {+ // Do not turn an unrelated infrastructure failure into a timeout.+ if (e !== signal.reason && !(e instanceof Error && e.name === 'AbortError')) throw e;+ return;+ }const msg = e instanceof Error ? e.message : String(e);const { count, sample } = recordImportFailure(errorCounts, errorSamples, msg);if (count <= 5) {@@ -680,68 +712,88 @@ export async function runImport(}}- if (actualWorkers > 1) {- // v0.22.13 (PR #490 A1 + Q3): use engine.kind discriminator (not config.engine- // string sniff) and fall back to serial when database_url is unset. Both- // checks belt-and-suspenders so we never crash on a null assertion.- const config = loadConfig();- if (engine.kind === 'pglite' || !config?.database_url) {- for (const file of files) {- await processFile(engine, file);- }- } else {- const { PostgresEngine } = await import('../core/postgres-engine.ts');- const { resolvePoolSize } = await import('../core/db.ts');- // Each child keeps the established two-connection pool. GBRAIN_POOL_SIZE- // controls the parent pool; GBRAIN_MAX_CONNECTIONS clamps the child- // count above so the combined footprint stays within the operator's cap.- const workerPoolSize = Math.min(2, resolvePoolSize(2));- const databaseUrl = config.database_url;-- // v0.22.13 (PR #490 A2): connect workers serially so a partial failure- // leaves us with the connected ones already pushed onto workerEngines- // for the finally-block cleanup. The prior Promise.all could leak any- // engine that connected before another's connect() rejected.- const workerEngines: InstanceType<typeof PostgresEngine>[] = [];- try {- for (let i = 0; i < actualWorkers; i++) {- const eng = new PostgresEngine();- await eng.connect({ database_url: databaseUrl, poolSize: workerPoolSize });- workerEngines.push(eng);+ let workerError: unknown;+ let workerFailed = false;+ try {+ if (actualWorkers > 1) {+ // v0.22.13 (PR #490 A1 + Q3): use engine.kind discriminator (not config.engine+ // string sniff) and fall back to serial when database_url is unset. Both+ // checks belt-and-suspenders so we never crash on a null assertion.+ const config = loadConfig();+ if (engine.kind === 'pglite' || !config?.database_url) {+ for (const file of files) {+ if (signal?.aborted) break;+ await processFile(engine, file);}+ } else {+ const { PostgresEngine } = await import('../core/postgres-engine.ts');+ const { resolvePoolSize } = await import('../core/db.ts');+ // Each child keeps the established two-connection pool. GBRAIN_POOL_SIZE+ // controls the parent pool; GBRAIN_MAX_CONNECTIONS clamps the child+ // count above so the combined footprint stays within the operator's cap.+ const workerPoolSize = Math.min(2, resolvePoolSize(2));+ const databaseUrl = config.database_url;- // Thread-safe queue: atomic index counter (JS is single-threaded; the- // read-then-increment happens between awaits so no lock is needed).- let queueIndex = 0;- await Promise.all(workerEngines.map(async (eng) => {- while (true) {- const idx = queueIndex++;- if (idx >= files.length) break;- await processFile(eng, files[idx]);+ // v0.22.13 (PR #490 A2): connect workers serially so a partial failure+ // leaves us with the connected ones already pushed onto workerEngines+ // for the finally-block cleanup. The prior Promise.all could leak any+ // engine that connected before another's connect() rejected.+ const workerEngines: InstanceType<typeof PostgresEngine>[] = [];+ try {+ for (let i = 0; i < actualWorkers; i++) {+ if (signal?.aborted) break;+ const eng = new PostgresEngine();+ await eng.connect({ database_url: databaseUrl, poolSize: workerPoolSize });+ workerEngines.push(eng);}- }));- } finally {- // v0.22.13 (PR #490 A2): try/finally guarantees cleanup even when the- // worker loop throws. Each disconnect is best-effort — one failing- // disconnect must not strand the others.- await Promise.all(- workerEngines.map(e =>- e.disconnect().catch((err: unknown) =>- console.error(` worker disconnect failed: ${err instanceof Error ? err.message : String(err)}`),++ // Thread-safe queue: atomic index counter (JS is single-threaded; the+ // read-then-increment happens between awaits so no lock is needed).+ let queueIndex = 0;+ let stopWorkers = false;+ const outcomes = await Promise.allSettled(workerEngines.map(async (eng) => {+ try {+ while (!stopWorkers && !signal?.aborted) {+ const idx = queueIndex++;+ if (idx >= files.length) break;+ await processFile(eng, files[idx]);+ }+ } catch (error) {+ stopWorkers = true;+ throw error;+ }+ }));+ // Drain every in-flight file before disconnecting pools or releasing+ // the source lock, even when one worker fails or cancellation arrives.+ const failed = outcomes.find(outcome => outcome.status === 'rejected');+ if (failed?.status === 'rejected') throw failed.reason;+ } finally {+ // v0.22.13 (PR #490 A2): try/finally guarantees cleanup even when the+ // worker loop throws. Each disconnect is best-effort — one failing+ // disconnect must not strand the others.+ await Promise.all(+ workerEngines.map(e =>+ e.disconnect().catch((err: unknown) =>+ console.error(` worker disconnect failed: ${err instanceof Error ? err.message : String(err)}`),+ ),),- ),- );+ );+ }+ } // end else (postgres parallel)+ } else {+ // Sequential: use the provided engine+ for (const filePath of files) {+ if (signal?.aborted) break;+ await processFile(engine, filePath);}- } // end else (postgres parallel)- } else {- // Sequential: use the provided engine- for (const filePath of files) {- await processFile(engine, filePath);}+ } catch (error) {+ workerFailed = true;+ workerError = error;+ } finally {+ progress.finish();}- progress.finish();-// Error summaryfor (const [key, count] of Object.entries(errorCounts)) {if (count > 5) {@@ -749,62 +801,28 @@ export async function runImport(}}- // Final checkpoint save BEFORE the clear/preserve decision below. The- // periodic triggers above are gated on a 100-file boundary or an interval,- // so a run that ends between them would otherwise leave its tail unsaved.- // This must run before clearCheckpoint() so a clean run still ends with no- // checkpoint file — it only makes the ERROR path's preserved checkpoint- // complete.- if (errors > 0 && completed.size > lastCheckpointSize) {+ // Save the successful tail on interruption/failure. Keep this synchronous:+ // checkpoint and cancellation decisions must not race another worker.+ function preserveCompletedPaths(): void {+ if (completed.size <= lastCheckpointSize) return;try {- const cpDir = gbrainPath();- if (!existsSync(cpDir)) {- const { mkdirSync } = await import('fs');- mkdirSync(cpDir, { recursive: true });- }+ mkdirSync(gbrainPath(), { recursive: true });saveCheckpoint(checkpointPath, {- schema_version: 1,- owner: 'gbrain',- kind: 'import',- dir,- completedPaths: Array.from(completed),- timestamp: new Date().toISOString(),+ schema_version: 1, owner: 'gbrain', kind: 'import', dir,+ completedPaths: Array.from(completed), timestamp: new Date().toISOString(),});- } catch { /* non-fatal: the next run simply redoes the tail */ }+ lastCheckpointSize = completed.size;+ } catch { /* non-fatal: resume can safely recheck content hashes */ }}-- // Clear checkpoint on clean completion. On error, the path-based checkpoint- // preserves only the successfully-completed paths, so the next run retries- // failed files automatically (they never entered `completed`).- if (errors === 0) {- clearCheckpoint(checkpointPath);- } else if (existsSync(checkpointPath)) {- info(` Checkpoint preserved (${errors} errors). Run again to retry failed files.`);- }-- const totalTime = ((Date.now() - startTime) / 1000).toFixed(1);- if (jsonOutput) {- // `skipped` includes every per-file failure importFile RETURNS (invalid- // frontmatter, oversize, symlink, slug mismatch) as well as content-hash- // no-ops, and `errors` counts only the thrown ones — so a caller cannot- // tell "unchanged" from "failed" by counts alone. The failure ledger is- // written only for git-repo dirs (see the gitHead gate below), so a caller- // importing a scratch directory has no other channel. Emit the per-file- // list so state can be gated per file.- console.log(JSON.stringify({- status: 'success', duration_s: parseFloat(totalTime),- imported, skipped, errors, chunks: chunksCreated,- total_files: allFiles.length,- unchanged: skipped - failures.length - malformedFileSkips,- malformed_skipped: malformedFileSkips,- failures,- }));- } else {- slog(`\nImport complete (${totalTime}s):`);- slog(` ${imported} pages imported`);- slog(` ${skipped} pages skipped (${skipped - errors} unchanged, ${errors} errors)`);- slog(` ${chunksCreated} chunks created`);+ function throwIfInterrupted(): void {+ if (!signal?.aborted) return;+ preserveCompletedPaths();+ console.error(`Import interrupted: ${imported} pages imported; completed paths preserved for resume.`);+ throw new ImportAbortError('interrupted', 1, { imported, skipped, errors, chunksCreated, failures });}+ if (errors > 0 || workerFailed) preserveCompletedPaths();+ if (workerFailed) throw workerError;+ throwIfInterrupted();// v0.39 T7 — end-of-run schema mismatch warn. Fires ONCE per import,// not per page. Counts untyped pages in the affected source AND@@ -871,6 +889,8 @@ export async function runImport(});}+ throwIfInterrupted();+// Import → sync continuity: write sync checkpoint if this is a git repo.// Bug 9 — gate last_commit on "no failures" so import doesn't silently// stomp on the sync bookmark when parsing broke. last_run + repo_path are@@ -926,6 +946,7 @@ export async function runImport(// legacy branch in sync.ts, so the two layers cannot drift).const { ownsGlobalSyncAnchor } = await import('../core/sync.ts');const { owns, configured } = await ownsGlobalSyncAnchor(engine, sourceId, dir);+ throwIfInterrupted();if (owns) {if (failures.length === 0) {@@ -1017,13 +1038,44 @@ export async function runImport(}}if (row?.local_path && coversRegisteredRoot && !sourceConfigHasRemoteUrl(row.config) && !isGitTracked && !isConnectorManaged) {+ throwIfInterrupted();await engine.executeRaw(`UPDATE sources SET last_sync_at = now() WHERE id = $1`, [sourceId]);}- } catch {+ } catch (error) {+ if (error instanceof ImportAbortError) throw error;// best-effort — a freshness nicety never fails the import (see above).}}+ throwIfInterrupted();+ // Only a fully completed run removes resume state, including async metadata.+ if (errors === 0) clearCheckpoint(checkpointPath);+ else if (existsSync(checkpointPath)) info(` Checkpoint preserved (${errors} errors). Run again to retry failed files.`);++ const totalTime = ((Date.now() - startTime) / 1000).toFixed(1);+ if (jsonOutput) {+ // `skipped` includes every per-file failure importFile RETURNS (invalid+ // frontmatter, oversize, symlink, slug mismatch) as well as content-hash+ // no-ops. `errors` counts both returned failures and thrown failures.+ // The failure ledger is+ // written only for git-repo dirs (see the gitHead gate below), so a caller+ // importing a scratch directory has no other channel. Emit the per-file+ // list so state can be gated per file.+ console.log(JSON.stringify({+ status: errors > 0 ? 'partial' : 'success', duration_s: parseFloat(totalTime),+ imported, skipped, errors, chunks: chunksCreated,+ total_files: allFiles.length,+ unchanged: skipped - failures.length - malformedFileSkips,+ malformed_skipped: malformedFileSkips,+ failures,+ }));+ } else {+ slog(`\nImport complete (${totalTime}s):`);+ slog(` ${imported} pages imported`);+ slog(` ${skipped} pages skipped (${skipped - failures.length - malformedFileSkips} unchanged, ${errors} errors, ${malformedFileSkips} malformed filenames)`);+ slog(` ${chunksCreated} chunks created`);+ }+return {imported, skipped, errors, chunksCreated, failures,...(totalMalformed > 0 ? { malformedSkipped: totalMalformed } : {}),diff --git a/src/commands/integrations.ts b/src/commands/integrations.tsindex b2881e51e1..1b45513604 100644--- a/src/commands/integrations.ts+++ b/src/commands/integrations.ts@@ -19,13 +19,14 @@* └── append-only, pruned to 30 days on read*/-import matter from 'gray-matter';+import { dataFrontmatter as matter } from '../core/data-frontmatter.ts';import { readFileSync, existsSync, writeFileSync, mkdirSync, readdirSync } from 'fs';import { join, basename } from 'path';import { homedir } from 'os';import { gbrainPath, loadConfig } from '../core/config.ts';import { buildGatewayConfig } from '../core/ai/build-gateway-config.ts';import { execSync } from 'child_process';+import { fetchWithSSRFGuard, HttpProxyError, SSRFError } from '../core/ssrf-validate.ts';// --- Types ---@@ -206,7 +207,9 @@ export async function executeHealthCheck(integrationId: string,isEmbedded: boolean,): Promise<CheckResult> {- const label = typeof check === 'string' ? check : (check as any).label || JSON.stringify(check);+ // Typed checks can contain HTTP credentials, including under any_of. Keep+ // the operator's display label, but never serialize the configuration.+ const label = typeof check === 'string' ? check : (check as any).label || (check.type === 'http' ? 'HTTP' : check.type);const base = { integration: integrationId, check: label };// String health checks (deprecated path)@@ -235,16 +238,16 @@ export async function executeHealthCheck(// Fix 4: gate http health_checks on embedded trust. User-provided recipes// must NOT be able to make arbitrary outbound HTTP (SSRF / internal reconnaissance).if (!isEmbedded) {- return { ...base, status: 'blocked', output: `Blocked: http health_checks are restricted to embedded recipes. (${check.label || check.url})` };+ return { ...base, status: 'blocked', output: 'Blocked: http health_checks are restricted to embedded recipes.' };}try {const url = expandVars(check.url);if (!url || url.includes('undefined')) {- return { ...base, status: 'fail', output: `Missing env var in URL: ${check.url}` };+ return { ...base, status: 'fail', output: 'HTTP: missing env var in URL' };}// B4: scheme allowlist. B3: manual redirect with per-hop re-validation.if (isInternalUrl(url)) {- return { ...base, status: 'blocked', output: `Blocked: URL targets internal/private network or uses non-http(s) scheme: ${check.url}` };+ return { ...base, status: 'blocked', output: 'Blocked: URL targets internal/private network or uses non-http(s) scheme' };}const headers: Record<string, string> = {};if (check.headers) {@@ -260,51 +263,38 @@ export async function executeHealthCheck(headers['Authorization'] = 'Bearer ' + expandVars(check.auth_token);}const method = check.method || 'GET';- const body = check.body ? expandVars(check.body) : undefined;+ const body = check.body !== undefined ? expandVars(check.body) : undefined;if (body && !headers['Content-Type']) headers['Content-Type'] = 'application/json';- // B3: manual redirect handling. Follow up to 3 hops, re-validating each Location.- const MAX_REDIRECTS = 3;- let currentUrl = url;- let resp: Response | null = null;- for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {- const fetchOpts: RequestInit = {- method,- headers,- redirect: 'manual',- signal: AbortSignal.timeout(10000),- };- if (body) fetchOpts.body = body;- resp = await fetch(currentUrl, fetchOpts);- if (resp.status < 300 || resp.status >= 400) break; // terminal- const location = resp.headers.get('location');- if (!location) break;- // Resolve relative redirects against the current URL- let next: string;- try {- next = new URL(location, currentUrl).toString();- } catch {- return { ...base, status: 'blocked', output: `Blocked: malformed redirect Location header from ${currentUrl}` };- }- if (isInternalUrl(next)) {- return { ...base, status: 'blocked', output: `Blocked: redirect hop ${hop + 1} targets internal URL: ${next}` };- }- if (hop === MAX_REDIRECTS) {- return { ...base, status: 'fail', output: `${check.label || 'HTTP'}: exceeded ${MAX_REDIRECTS} redirect hops` };- }- currentUrl = next;- }- if (!resp) {- return { ...base, status: 'fail', output: `${check.label || 'HTTP'}: no response` };- }+ const resp = await fetchWithSSRFGuard(url, {+ method,+ headers,+ body,+ headerOnly: true,+ maxRedirects: 3,+ timeoutMs: 10000,+ // Even an otherwise harmless configured header can contain an env+ // secret. Preserve recipe method/body on same-origin redirects only.+ sameOrigin: Object.keys(check.headers ?? {}).length > 0 || check.auth !== undefined+ || check.body !== undefined || !['GET', 'HEAD'].includes(method.toUpperCase()),+ });const ok = resp.status >= 200 && resp.status < 400;- return { ...base, status: ok ? 'ok' : 'fail', output: `${check.label || 'HTTP'}: ${ok ? 'OK' : `HTTP ${resp.status}`}` };+ return { ...base, status: ok ? 'ok' : 'fail', output: `HTTP: ${ok ? 'OK' : `HTTP ${resp.status}`}` };} catch (e: unknown) {const msg = e instanceof Error ? e.message : String(e);+ if (e instanceof HttpProxyError) {+ return { ...base, status: 'blocked', output: `HTTP: blocked (${e.code}). ${e.message}` };+ }+ if (e instanceof SSRFError) {+ if (e.code === 'REQUEST_TIMEOUT' || e.code === 'REQUEST_ABORTED') {+ return { ...base, status: 'timeout', output: 'HTTP: timeout' };+ }+ return { ...base, status: 'blocked', output: `HTTP: blocked (${e.code})` };+ }if (msg.includes('TimeoutError') || msg.includes('abort')) {- return { ...base, status: 'timeout', output: `${check.label || 'HTTP'}: timeout` };+ return { ...base, status: 'timeout', output: 'HTTP: timeout' };}- return { ...base, status: 'fail', output: `${check.label || 'HTTP'}: ${msg}` };+ return { ...base, status: 'fail', output: 'HTTP: request failed' };}}@@ -380,29 +370,28 @@ export async function executeHealthCheck(// --- Recipe Parsing ---/**- * Parse a recipe markdown file. Uses gray-matter directly (NOT parseMarkdown,- * which splits on --- as timeline separator and would corrupt recipe bodies- * that use horizontal rules).+ * Parse recipe metadata as data, retaining the complete recipe body rather+ * than applying the page parser's timeline splitting.*/export function parseRecipe(content: string, filename: string): ParsedRecipe | null {try {const { data, content: body } = matter(content);- if (!data.id) return null;+ if (typeof data.id !== 'string' || !data.id) return null;const installKind: InstallKind =data.install_kind === 'copy-into-host-repo' ? 'copy-into-host-repo' : 'local-managed';return {frontmatter: {id: data.id,- name: data.name || data.id,- version: data.version || '0.0.0',- description: data.description || '',- category: data.category || 'sense',+ name: typeof data.name === 'string' && data.name ? data.name : data.id,+ version: typeof data.version === 'string' && data.version ? data.version : '0.0.0',+ description: typeof data.description === 'string' ? data.description : '',+ category: ['reflex', 'infra', 'sense', 'voice'].includes(String(data.category)) ? data.category as RecipeFrontmatter['category'] : 'sense',install_kind: installKind,- requires: data.requires || [],- secrets: data.secrets || [],+ requires: Array.isArray(data.requires) ? data.requires.filter((v): v is string => typeof v === 'string') : [],+ secrets: Array.isArray(data.secrets) ? data.secrets as RecipeSecret[] : [],health_checks: (data.health_checks || []) as HealthCheck[],- setup_time: data.setup_time || 'unknown',- cost_estimate: data.cost_estimate,+ setup_time: typeof data.setup_time === 'string' ? data.setup_time : 'unknown',+ cost_estimate: typeof data.cost_estimate === 'string' ? data.cost_estimate : undefined,output_paths: Array.isArray(data.output_paths) ? data.output_paths.map(String) : [],},body: body.trim(),diff --git a/src/commands/jobs.ts b/src/commands/jobs.tsindex 1dda515a8e..046731ae03 100644--- a/src/commands/jobs.ts+++ b/src/commands/jobs.ts@@ -1,3 +1,4 @@+import { authorizeLegacyJobs, parseLegacyJobIds } from '../core/minions/authorize-legacy.ts';/*** CLI handler for `gbrain jobs` subcommands.* Thin wrapper around MinionQueue and MinionWorker.@@ -355,6 +356,7 @@ export function formatJobDetail(job: MinionJob): string {const JOBS_HELP = `gbrain jobs — Minions job queueUSAGE+ gbrain jobs authorize-legacy --ids 12,34 [--expect <snapshot_digest> --yes] [--json]gbrain jobs submit <name> [--params JSON] [--follow] [--priority N][--delay Nms] [--max-attempts N] [--max-stalled N][--max-waiting N]@@ -568,6 +570,16 @@ OPTIONS--follow Keep refreshing (default: on for TTY, off otherwise)--refresh-ms=N Refresh cadence in ms (default 1000). Equals form only —'watch' does not accept a space-separated value.+`,+ 'authorize-legacy': `gbrain jobs authorize-legacy — review old queued work locally++USAGE+ gbrain jobs authorize-legacy --ids 12,34 --json+ gbrain jobs authorize-legacy --ids 12,34 --expect <snapshot_digest> --yes --json++Stop producers and workers and drain active jobs first. The first command only+previews; apply requires the exact reviewed snapshot digest and --yes. Dependencies+are shown but never implicitly authorized. IDs, data, schedule and retries persist.`,prune: `gbrain jobs prune — delete old terminal jobs@@ -645,6 +657,13 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):const queue = new MinionQueue(engine);switch (sub) {+ case 'authorize-legacy': {+ const ids = parseLegacyJobIds(parseFlag(args, '--ids'));+ const preview = args.includes('--dry-run');+ const result = await authorizeLegacyJobs(engine, ids, preview ? undefined : parseFlag(args, '--expect'), !preview && args.includes('--yes'));+ console.log(JSON.stringify(result, null, 2));+ return;+ }case 'submit': {const name = args[1]?.trim();if (!name) {@@ -2144,7 +2163,7 @@ export async function registerBuiltinHandlers(let result;try {result = await performSync(engine, {- repoPath, sourceId, noPull, noEmbed, noExtract,+ repoPath, sourceId, noPull, noEmbed, noExtract, signal: job.signal,concurrency: concurrencyOverride,...(githubItem ? { githubItem } : {}),});@@ -2166,6 +2185,10 @@ export async function registerBuiltinHandlers(throw err;}+ // A cancelled durable job must not complete or schedule follow-up work,+ // even when a direct sync interruption has a resumable partial result.+ if (job.signal?.aborted) throw job.signal.reason ?? new Error('Sync job cancelled');+// v0.40 D22: auto_embed_backfill defaults TRUE when sourceId is set AND// the feature flag is enabled. Submits a child embed-backfill job// (fire-and-forget — D15.1) so stale chunks get embedded async without@@ -2269,7 +2292,7 @@ export async function registerBuiltinHandlers(const target = typeof job.data.dir === 'string' ? job.data.dir : '.';// issue #1678: reuse the worker's live engine for lint's content-sanity// DB lift so it doesn't create + disconnect a competing engine.- const result = await runLintCore({ target, fix: !!job.data.fix, dryRun: !!job.data.dryRun, engine });+ const result = await runLintCore({ target, fix: !!job.data.fix, dryRun: !!job.data.dryRun, engine, signal: job.signal });return result;});@@ -2391,7 +2414,7 @@ export async function registerBuiltinHandlers(const { runLintCore } = await import('./lint.ts');const target = typeof job.data.dir === 'string' ? job.data.dir : '.';// issue #1678: reuse the worker's live engine (see 'lint' handler).- return await runLintCore({ target, fix: true, dryRun: false, engine });+ return await runLintCore({ target, fix: true, dryRun: false, engine, signal: job.signal });});worker.register('integrity-auto', async () => {@@ -2416,7 +2439,10 @@ export async function registerBuiltinHandlers(const importArgs: string[] = [];if (job.data.dir) importArgs.push(String(job.data.dir));if (job.data.noEmbed) importArgs.push('--no-embed');- await runImport(engine, importArgs);+ const result = await runImport(engine, importArgs, { signal: job.signal, sourceId: typeof job.data.sourceId === 'string' ? job.data.sourceId : undefined });+ if (result.errors > 0) {+ throw new Error(`Import failed for ${result.errors} file(s); fix rejected documents and retry the job.`);+ }return { imported: true };});diff --git a/src/commands/lint.ts b/src/commands/lint.tsindex 9f15cda76c..63b7b7ffd5 100644--- a/src/commands/lint.ts+++ b/src/commands/lint.ts@@ -1,3 +1,4 @@+import { readSourceFileSync, writeSourceFileSync, hasSourceFilesystemLock, withSourceFilesystemLock, assertSourceFilesystemActive } from '../core/minions/source-filesystem.ts';/*** gbrain lint — Deterministic brain page quality checker.*@@ -16,7 +17,7 @@* gbrain lint <file.md> # lint single file*/-import { readFileSync, writeFileSync, readdirSync, statSync, lstatSync, existsSync } from 'fs';+import { readdirSync, statSync, lstatSync, existsSync } from 'fs';import { join, relative, dirname } from 'path';import { isAborted } from '../core/abort-check.ts';import { parseMarkdown, type ParseValidationCode } from '../core/markdown.ts';@@ -535,6 +536,10 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {throw new Error(`Not found: ${opts.target}`);}+ if (opts.engine && !hasSourceFilesystemLock(opts.target)) {+ return withSourceFilesystemLock(opts.engine, opts.target, () => runLintCore(opts), { signal: opts.signal });+ }+const isSingleFile = statSync(opts.target).isFile();const pages = isSingleFile ? [opts.target] : collectPages(opts.target, opts.exclude ?? []);opts.onPagesCollected?.(pages.length);@@ -564,6 +569,7 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {let pagesWithIssues = 0;for (let idx = 0; idx < pages.length; idx++) {+ assertSourceFilesystemActive();const page = pages[idx];// #1972: every 200 pages, yield to the event loop and honor abort. The// yield is what lets the abort signal actually fire (the rest of the loop@@ -573,7 +579,7 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {if (isAborted(opts.signal)) break;await new Promise<void>((resolve) => setImmediate(resolve));}- const content = readFileSync(page, 'utf-8');+ const content = readSourceFileSync(page, 'utf-8');const relPath = isSingleFile ? page : relative(opts.target, page);const issues = lintContent(content, relPath, lintOpts);opts.onPageScanned?.();@@ -589,7 +595,8 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {fixCount = issues.filter(i => i.fixable).length;totalFixed += fixCount;if (!opts.dryRun) {- writeFileSync(page, fixed);+ assertSourceFilesystemActive();+ writeSourceFileSync(page, fixed);if (commitFixes) {commitWriteThroughFile(repoProbe, page, relative(repoProbe, page).replace(/\.md$/u, ''));}diff --git a/src/commands/mcp-provision.ts b/src/commands/mcp-provision.tsindex bb45234936..61640e2303 100644--- a/src/commands/mcp-provision.ts+++ b/src/commands/mcp-provision.ts@@ -72,7 +72,7 @@ export async function provisionHarnessGrant(engine: BrainEngine, input: Provisioconst prospective = { clientId: '', clientName: input.name, revision: 0, revoked: false, ...resolved } as ClientGrant;validateClientGrant(prospective, await grantValidationContext(tx));if (input.dryRun) return { grant: prospective, before: null, dry_run: true, credentials: null as HarnessCredentials | null, credential_action: 'none' };- const provider = new GBrainOAuthProvider({ sql });+ const provider = new GBrainOAuthProvider({ sql, transaction: fn => fn(sql) });const registered = await provider.registerClientManual(input.name, ['client_credentials'], prospective.scopes.join(' '), [], sourceId,prospective.federatedRead, 'client_secret_post', {boundTools: prospective.boundTools ?? undefined, boundSourceId: prospective.boundSourceId ?? undefined,diff --git a/src/commands/serve-http-consent.ts b/src/commands/serve-http-consent.tsdeleted file mode 100644index 499d0db9d3..0000000000--- a/src/commands/serve-http-consent.ts+++ /dev/null@@ -1,83 +0,0 @@-import { randomBytes } from 'node:crypto';-import type { Express, Request, Response } from 'express';-import express from 'express';-import type { GBrainOAuthProvider } from '../core/oauth-provider.ts';--type Consent = { session: string; query: string; redirect: string; state?: string; expires: number; approved: boolean };-const escape = (s: string) => s.replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]!));-const page = (body: string) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Connect to GBrain</title></head><body><main>${body}</main></body></html>`;--/** Mount BEFORE the SDK auth router. Nonces bind consent to this admin session- * and the complete authorization request; approving a different request cannot- * authorize this one. The SDK still validates PKCE, redirects and client grants. */-export function mountOAuthOwnerConsent(app: Express, options: {- provider: GBrainOAuthProvider;- sessionValid: (session: string) => boolean;- publicOrigin: string;-}) {- const pending = new Map<string, Consent>();- const session = (req: Request) => typeof req.cookies?.gbrain_admin === 'string' ? req.cookies.gbrain_admin as string : '';- const fail = (res: Response, status: number, error: string) => res.status(status).json({ error, error_description: 'Open the connection again and approve it from an authenticated GBrain admin session.' });- const prune = () => { for (const [id, item] of pending) if (item.expires < Date.now()) pending.delete(id); };-- app.post('/authorize/consent', express.urlencoded({ extended: false }), (req, res) => {- res.set('Cache-Control', 'no-store');- const nonce = typeof req.body?.nonce === 'string' ? req.body.nonce : '';- const item = pending.get(nonce);- const sid = session(req);- if (!item || item.expires < Date.now() || item.session !== sid || !options.sessionValid(sid) || item.approved) return void fail(res, 403, 'consent_expired');- if (req.headers.origin && req.headers.origin !== options.publicOrigin) return void fail(res, 403, 'invalid_origin');- if (req.body?.decision !== 'approve') {- pending.delete(nonce);- const target = new URL(item.redirect);- target.searchParams.set('error', 'access_denied');- if (item.state) target.searchParams.set('state', item.state);- res.redirect(303, target.toString());- return;- }- item.approved = true;- const target = new URLSearchParams(item.query);- target.set('_gbrain_approval', nonce);- res.redirect(303, `/authorize?${target}`);- });-- app.use('/authorize', async (req, res, next) => {- res.set('Cache-Control', 'no-store');- res.set('Referrer-Policy', 'no-referrer');- res.set('X-Frame-Options', 'DENY');- // Only the canonical endpoint is gated here; our consent POST terminated above.- if (req.path !== '/' && req.path !== '') { next(); return; }- if (req.method !== 'GET') { fail(res, 405, 'authorization_requires_browser'); return; }- const sid = session(req);- if (!options.sessionValid(sid)) {- res.status(401).type('html').send(page(`<h1>Sign in to approve this connection</h1><p>Use the admin token from your GBrain server. It is sent only to this server.</p><form id="login"><label>Admin token <input name="token" type="password" required autocomplete="off"></label><button>Sign in</button></form><p id="result" role="status"></p><script>document.getElementById('login').onsubmit=async function(event){event.preventDefault();const response=await fetch('/admin/login',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({token:new FormData(this).get('token')})});if(response.ok)location.reload();else document.getElementById('result').textContent='Sign in failed. Check the admin token.';};</script>`));- return;- }- try {- const params = new URL(req.originalUrl, options.publicOrigin).searchParams;- const approved = params.get('_gbrain_approval');- params.delete('_gbrain_approval');- if (approved) {- const item = pending.get(approved);- pending.delete(approved);- if (!item || !item.approved || item.expires < Date.now() || item.session !== sid || item.query !== params.toString()) { fail(res, 403, 'consent_expired'); return; }- // Strip our transport-only field before the SDK validates the request.- req.url = `/?${params}`;- res.locals.gbrainOwnerApproved = true;- next();- return;- }- const clientId = params.get('client_id');- if (!clientId) { fail(res, 400, 'invalid_client'); return; }- const client = await options.provider.clientsStore.getClient(clientId);- const redirect = params.get('redirect_uri');- if (!client || !redirect || !client.redirect_uris.includes(redirect)) { fail(res, 400, 'invalid_redirect_uri'); return; }- prune();- if (pending.size >= 1000) { fail(res, 429, 'consent_busy'); return; }- const nonce = randomBytes(32).toString('hex');- pending.set(nonce, { session: sid, query: params.toString(), redirect, state: params.get('state') ?? undefined, expires: Date.now() + 300_000, approved: false });- const requested = params.get('scope') || client.scope || '(client defaults)';- res.type('html').send(page(`<h1>Connect ${escape(client.client_name || 'this client')} to GBrain</h1><p>Client: <code>${escape(clientId)}</code></p><p>Requested permissions: <strong>${escape(requested)}</strong>. The registered grant remains the ceiling.</p><p>Return address: ${escape(redirect)}</p><form method="post" action="/authorize/consent"><input type="hidden" name="nonce" value="${nonce}"><button name="decision" value="approve">Approve connection</button> <button name="decision" value="deny">Cancel</button></form>`));- } catch { fail(res, 400, 'invalid_authorization_request'); }- });-}diff --git a/src/commands/serve-http-oauth.ts b/src/commands/serve-http-oauth.tsnew file mode 100644index 0000000000..9f3c171eed--- /dev/null+++ b/src/commands/serve-http-oauth.ts@@ -0,0 +1,145 @@+/** HTTP adapters for owner consent and hash-only confidential client credentials. */+import express, { type Express, type Request, type Response, type RequestHandler } from 'express';+import { createHmac, randomBytes } from 'node:crypto';+import { OAuthError, InvalidClientError, InvalidRequestError } from '@modelcontextprotocol/sdk/server/auth/errors.js';+import { OAuthTokenRevocationRequestSchema } from '@modelcontextprotocol/sdk/shared/auth.js';+import type { GBrainOAuthProvider } from '../core/oauth-provider.ts';+import { OAuthConsentError } from '../core/oauth-grants.ts';+import { safeHexEqual } from '../core/timing-safe.ts';+import { isRetryableError } from '../core/retry-matcher.ts';++function sendOAuthError(res: Response, error: unknown): void {+ if (error instanceof OAuthError) {+ res.status(error instanceof InvalidClientError ? 401 : 400).json(error.toResponseObject());+ return;+ }+ const retryable = isRetryableError(error);+ res.status(retryable ? 503 : 500).json({+ error: retryable ? 'temporarily_unavailable' : 'server_error',+ error_description: retryable ? 'Authorization temporarily unavailable' : 'Authorization failed',+ });+}++function confidentialCredentials(req: Request): { clientId: string; secret: string; basic: boolean } | undefined {+ const clientId = req.body?.client_id;+ const secret = req.body?.client_secret;+ const header = req.headers.authorization ?? '';+ const basic = /^Basic\b/i.test(header);+ if ((clientId !== undefined && typeof clientId !== 'string') || (secret !== undefined && typeof secret !== 'string')+ || (basic && (clientId !== undefined || secret !== undefined))) throw new InvalidRequestError('Malformed or mixed client authentication');+ if (basic) {+ try {+ const encoded = /^Basic\s+([A-Za-z0-9+/]+={0,2})$/i.exec(header)?.[1];+ if (!encoded) throw new Error();+ const decoded = Buffer.from(encoded, 'base64').toString('utf8');+ const separator = decoded.indexOf(':');+ if (separator < 1) throw new Error();+ const id = decodeURIComponent(decoded.slice(0, separator).replace(/\+/g, ' '));+ const password = decodeURIComponent(decoded.slice(separator + 1).replace(/\+/g, ' '));+ if (!password) throw new Error();+ return { clientId: id, secret: password, basic: true };+ } catch { throw new InvalidClientError('Invalid client'); }+ }+ if (typeof secret === 'string') {+ if (!clientId || !secret) throw new InvalidClientError('Invalid client');+ return { clientId, secret, basic: false };+ }+ return undefined;+}++function stringParam(req: Request, name: string, required = false): string | undefined {+ const value = req.body?.[name];+ if (value === undefined && !required) return undefined;+ if (typeof value !== 'string' || (required && !value)) throw new InvalidRequestError(`${name} must be a non-empty string`);+ return value;+}++export function mountConfidentialOAuth(app: Express, provider: GBrainOAuthProvider, rateLimiter: RequestHandler): void {+ app.post('/token', rateLimiter, express.urlencoded({ extended: false }), async (req, res, next) => {+ res.setHeader('Cache-Control', 'no-store');+ res.setHeader('Pragma', 'no-cache');+ try {+ const grant = stringParam(req, 'grant_type');+ const credentials = confidentialCredentials(req);+ if (!credentials) {+ if (grant === 'client_credentials') throw new InvalidClientError('Confidential client authentication required');+ return next(); // SDK public-client path; provider owns PKCE verification.+ }+ const client = await provider.verifyConfidentialClientSecret(credentials.clientId, credentials.secret);+ let resource: URL | undefined;+ const requestedResource = stringParam(req, 'resource');+ if (requestedResource !== undefined) {+ try { resource = new URL(requestedResource); } catch { throw new InvalidRequestError('Invalid resource URL'); }+ }+ const scope = stringParam(req, 'scope');+ if (grant === 'client_credentials') {+ res.json(await provider.exchangeClientCredentials(credentials.clientId, credentials.secret, scope));+ } else if (grant === 'authorization_code') {+ res.json(await provider.exchangeAuthorizationCode(client, stringParam(req, 'code', true)!, stringParam(req, 'code_verifier'), stringParam(req, 'redirect_uri'), resource));+ } else if (grant === 'refresh_token') {+ res.json(await provider.exchangeRefreshToken(client, stringParam(req, 'refresh_token', true)!, scope === undefined ? undefined : scope.split(/\s+/).filter(Boolean), resource));+ } else return next();+ } catch (error) { sendOAuthError(res, error); }+ });++ app.post('/revoke', rateLimiter, express.urlencoded({ extended: false }), async (req, res, next) => {+ res.setHeader('Cache-Control', 'no-store');+ try {+ const credentials = confidentialCredentials(req);+ if (!credentials) return next();+ const parsed = OAuthTokenRevocationRequestSchema.safeParse(req.body);+ if (!parsed.success || !parsed.data.token) throw new InvalidRequestError('Valid token required');+ const client = await provider.verifyConfidentialClientSecret(credentials.clientId, credentials.secret);+ await provider.revokeToken(client, parsed.data);+ res.status(200).end();+ } catch (error) {+ if (error instanceof InvalidClientError && /^Basic\b/i.test(req.headers.authorization ?? '')) res.setHeader('WWW-Authenticate', 'Basic realm="gbrain"');+ sendOAuthError(res, error);+ }+ });+}++export function mountOAuthConsent(app: Express, provider: GBrainOAuthProvider, requireAdmin: RequestHandler, rateLimiter: RequestHandler): void {+ app.use((req, res, next) => {+ if (req.path.startsWith('/admin')) {+ res.setHeader('Referrer-Policy', 'no-referrer');+ res.setHeader('X-Frame-Options', 'DENY');+ }+ next();+ });+ const csrfKey = randomBytes(32);+ const csrfFor = (req: Request, id: string): string => createHmac('sha256', csrfKey)+ .update(String(req.cookies?.gbrain_admin ?? '')).update('\0').update(id).digest('hex');+ const handleError = (res: Response, error: unknown): void => {+ if (error instanceof OAuthConsentError) {+ res.status(error.status).json({ error: error.code, message: error.message });+ } else if (error instanceof InvalidClientError) {+ res.status(409).json({ error: 'client_unavailable', message: 'This client was revoked. Restart the connection from your client.' });+ } else {+ res.status(isRetryableError(error) ? 503 : 500).json({ error: 'authorization_failed', message: 'Approval could not be completed. Restart the connection from your client.' });+ }+ };+ app.get('/admin/api/oauth-requests/:id', requireAdmin, rateLimiter, (req, res) => {+ res.setHeader('Cache-Control', 'no-store');+ try {+ const id = String(req.params.id);+ res.json({ ...provider.grants.details(id), csrf: csrfFor(req, id) });+ } catch (error) { handleError(res, error); }+ });+ app.post('/admin/api/oauth-requests/:id', requireAdmin, rateLimiter, express.json(), async (req, res) => {+ res.setHeader('Cache-Control', 'no-store');+ const id = String(req.params.id);+ const body = req.body;+ if (!body || typeof body !== 'object' || Array.isArray(body)+ || Object.keys(body).some(key => key !== 'decision' && key !== 'csrf')+ || (body.decision !== 'approve' && body.decision !== 'deny')+ || typeof body.csrf !== 'string' || !/^[a-f0-9]{64}$/.test(body.csrf)+ || !safeHexEqual(body.csrf, csrfFor(req, id))) {+ res.status(403).json({ error: 'invalid_consent', message: 'Reload this request and review it again before approving.' });+ return;+ }+ try {+ res.json({ redirectUrl: await provider.grants.decide(id, body.decision === 'approve') });+ } catch (error) { handleError(res, error); }+ });+}diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.tsindex 49d75be184..e86faeac15 100644--- a/src/commands/serve-http.ts+++ b/src/commands/serve-http.ts@@ -27,7 +27,8 @@ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';import { mcpAuthRouter, getOAuthProtectedResourceMetadataUrl } from '@modelcontextprotocol/sdk/server/auth/router.js';import { requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js';-import { OAuthTokenRevocationRequestSchema } from '@modelcontextprotocol/sdk/shared/auth.js';+import { InvalidTokenError } from '@modelcontextprotocol/sdk/server/auth/errors.js';+import { mountConfidentialOAuth, mountOAuthConsent } from './serve-http-oauth.ts';import type { BrainEngine } from '../core/engine.ts';import { operations, OperationError, opAllowedForBoundClient } from '../core/operations.ts';import type { OperationContext, AuthInfo } from '../core/operations.ts';@@ -39,7 +40,6 @@ import { publicHarnessMetadata } from '../core/harness/registry.ts';import { GRANT_PROFILES } from '../core/grants/model.ts';import { provisionHarnessGrant } from './mcp-provision.ts';import { retainCredentialDelivery } from '../core/harness/delivery.ts';-import { mountOAuthOwnerConsent } from './serve-http-consent.ts';import { readClientGrant, rescopeClientGrant } from '../core/grants/service.ts';import { parseAdminGrantRequest, previewNewAdminGrant, grantHttpStatus, GRANT_TOKEN_IMPLICATIONS, mountAdminGrantDiscovery } from './serve-http-grants.ts';import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';@@ -165,7 +165,6 @@ import {} from './auth.ts';import { registerClientNameLockKey } from './agent-register.ts';import { isUndefinedColumnError } from '../core/utils.ts';-import { isRetryableError } from '../core/retry-matcher.ts';import {computeContentHash,validateIngestionEvent,@@ -911,6 +910,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptionconst oauthProvider = new GBrainOAuthProvider({sql,+ transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))),tokenTtl,dcrDisabled: !enableDcr,allowClientCredentialsDcr: enableDcrInsecure === true,@@ -1085,188 +1085,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptionmessage: { error: 'rate_limited', message: 'Too many admin auth attempts. Try again shortly.' },});- app.post('/token', ccRateLimiter, express.urlencoded({ extended: false }), async (req, res, next) => {- if (req.body?.grant_type !== 'client_credentials') {- return next(); // Fall through to confidential-client handler or SDK- }-- try {- const { client_id, client_secret, scope } = req.body;- if (!client_id || !client_secret) {- res.status(400).json({ error: 'invalid_request', error_description: 'client_id and client_secret required' });- return;- }-- const tokens = await oauthProvider.exchangeClientCredentials(client_id, client_secret, scope);- res.json(tokens);- } catch (e) {- const msg = e instanceof Error ? e.message : 'Unknown error';- res.status(400).json({ error: 'invalid_grant', error_description: msg });- }- });-- // ---------------------------------------------------------------------------- // v0.37.7.0 #1166: Custom authorization_code + refresh_token handler for- // CONFIDENTIAL clients. The MCP SDK's clientAuth middleware does plaintext- // `client.client_secret !== presented_secret` compare; we store- // SHA-256 hashes, so the SDK's compare always fails for confidential- // clients. This middleware verifies the secret hash ourselves before- // calling the provider's exchange methods directly.- //- // Public clients (token_endpoint_auth_method='none') fall through to- // the SDK's handler — the v0.34.1.0 PKCE path stays canonical.- // ---------------------------------------------------------------------------- app.post('/token', ccRateLimiter, async (req, res, next) => {- const grantType = req.body?.grant_type;- if (grantType !== 'authorization_code' && grantType !== 'refresh_token') {- return next();- }-- // Detect confidential auth: either client_secret in body- // (client_secret_post) OR Authorization: Basic header- // (client_secret_basic). Public PKCE clients omit both.- const bodySecret: string | undefined = req.body?.client_secret;- let clientId: string | undefined = req.body?.client_id;- let presentedSecret: string | undefined = bodySecret;- const authHeader = (req.headers.authorization ?? '').toString();- if (!presentedSecret && authHeader.startsWith('Basic ')) {- try {- const decoded = Buffer.from(authHeader.slice('Basic '.length), 'base64').toString('utf8');- const idx = decoded.indexOf(':');- if (idx > -1) {- clientId ||= decodeURIComponent(decoded.slice(0, idx));- presentedSecret = decodeURIComponent(decoded.slice(idx + 1));- }- } catch {- // Malformed Basic header → falls through; SDK will reject- }- }- if (!clientId || !presentedSecret) {- return next(); // Public client path; SDK handles.- }-- try {- const client = await oauthProvider.verifyConfidentialClientSecret(clientId, presentedSecret);- let tokens;- if (grantType === 'authorization_code') {- const code = req.body.code;- const redirectUri = req.body.redirect_uri;- const codeVerifier = req.body.code_verifier;- if (!code) {- res.status(400).json({ error: 'invalid_request', error_description: 'code required' });- return;- }- tokens = await oauthProvider.exchangeAuthorizationCode(client, code, codeVerifier, redirectUri,- typeof req.body.resource === 'string' ? new URL(req.body.resource) : undefined);- } else {- const refreshToken = req.body.refresh_token;- const scopeParam = typeof req.body.scope === 'string' ? req.body.scope.split(/\s+/) : undefined;- if (!refreshToken) {- res.status(400).json({ error: 'invalid_request', error_description: 'refresh_token required' });- return;- }- tokens = await oauthProvider.exchangeRefreshToken(client, refreshToken, scopeParam,- typeof req.body.resource === 'string' ? new URL(req.body.resource) : undefined);- }- res.json(tokens);- } catch (e) {- const msg = e instanceof Error ? e.message : 'Unknown error';- // RFC 6749: invalid_client for auth failures, invalid_grant for- // code/token problems. "Invalid client" → 401; everything else 400.- if (msg === 'Invalid client' || msg === 'Client has been revoked') {- res.status(401).json({ error: 'invalid_client', error_description: msg });- } else {- res.status(400).json({ error: 'invalid_grant', error_description: msg });- }- }- });-- // The SDK's /revoke handler compares the presented secret with- // client.client_secret as plaintext. GBrain stores only a SHA-256 hash, so- // confidential clients need the same hash-aware validation used above for- // authorization_code and refresh_token exchanges. Public clients present no- // secret and continue through to the SDK's PKCE-compatible handler.- app.post('/revoke', ccRateLimiter, express.urlencoded({ extended: false }), async (req, res, next) => {- res.setHeader('Cache-Control', 'no-store');-- const rawClientId: unknown = req.body?.client_id;- const rawBodySecret: unknown = req.body?.client_secret;- const authHeader = (req.headers.authorization ?? '').toString();-- // RFC 6749 §2.3: one client-authentication method per request. Reject- // duplicates/arrays from express.urlencoded rather than letting them reach- // hashToken() as non-strings and become a misleading invalid_client error.- const hasBasicAuth = /^Basic\b/i.test(authHeader);- if (- (rawClientId !== undefined && typeof rawClientId !== 'string') ||- (rawBodySecret !== undefined && typeof rawBodySecret !== 'string') ||- (hasBasicAuth && (rawClientId !== undefined || rawBodySecret !== undefined))- ) {- res.status(400).json({ error: 'invalid_request', error_description: 'Malformed or mixed client authentication' });- return;- }-- let clientId = typeof rawClientId === 'string' ? rawClientId : undefined;- let presentedSecret = typeof rawBodySecret === 'string' && rawBodySecret.length > 0- ? rawBodySecret- : undefined;- if (hasBasicAuth) {- try {- const match = authHeader.match(/^Basic\s+([^\s]+)$/i);- if (!match) throw new Error('Malformed Basic authentication');- const decoded = Buffer.from(match[1], 'base64').toString('utf8');- const idx = decoded.indexOf(':');- if (idx < 1) throw new Error('Malformed Basic authentication');- clientId = decodeURIComponent(decoded.slice(0, idx).replace(/\+/g, ' '));- presentedSecret = decodeURIComponent(decoded.slice(idx + 1).replace(/\+/g, ' '));- if (!presentedSecret) throw new Error('Malformed Basic authentication');- } catch {- res.setHeader('WWW-Authenticate', 'Basic realm="gbrain"');- res.status(401).json({ error: 'invalid_client', error_description: 'Invalid client' });- return;- }- }- if (!clientId || !presentedSecret) return next();-- const parsedRequest = OAuthTokenRevocationRequestSchema.safeParse(req.body);- if (!parsedRequest.success || parsedRequest.data.token.length === 0) {- res.status(400).json({ error: 'invalid_request', error_description: 'Valid token required' });- return;- }-- let client;- try {- client = await oauthProvider.verifyConfidentialClientSecret(clientId, presentedSecret);- } catch (e) {- const msg = e instanceof Error ? e.message : '';- if (msg === 'Invalid client' || msg === 'Client has been revoked') {- if (hasBasicAuth) res.setHeader('WWW-Authenticate', 'Basic realm="gbrain"');- res.status(401).json({ error: 'invalid_client', error_description: 'Invalid client' });- return;- }- console.error('[serve-http] revoke client verification failed:', msg || 'Unknown error');- const retryable = isRetryableError(e);- res.status(retryable ? 503 : 500).json({- error: retryable ? 'temporarily_unavailable' : 'server_error',- error_description: retryable ? 'Token revocation temporarily unavailable' : 'Token revocation failed',- });- return;- }-- try {- await oauthProvider.revokeToken(client, parsedRequest.data);- // RFC 7009 §2.2: successful revocation, including an unknown token, is 200.- res.status(200).end();- } catch (e) {- const msg = e instanceof Error ? e.message : 'Unknown error';- console.error('[serve-http] token revocation failed:', msg);- const retryable = isRetryableError(e);- res.status(retryable ? 503 : 500).json({- error: retryable ? 'temporarily_unavailable' : 'server_error',- error_description: retryable ? 'Token revocation temporarily unavailable' : 'Token revocation failed',- });- }- });+ mountConfidentialOAuth(app, oauthProvider, ccRateLimiter);// ---------------------------------------------------------------------------// MCP SDK Auth Router (OAuth endpoints)@@ -1299,6 +1118,17 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption// derived from the same value so the two can never drift apart.const mcpResourceUrl = new URL('/mcp', issuerUrl);const resourceMetadataUrl = getOAuthProtectedResourceMetadataUrl(mcpResourceUrl);+ // The SDK validates expiry/scopes but leaves audience enforcement to us.+ // Legacy grants without a resource retain their existing compatibility.+ const resourceVerifier = {+ async verifyAccessToken(token: string) {+ const auth = await oauthProvider.verifyAccessToken(token);+ if (auth.resource && auth.resource.toString() !== mcpResourceUrl.toString()) {+ throw new InvalidTokenError('Token is bound to a different resource');+ }+ return auth;+ },+ };// F9: cookie `secure` flag honors both the request's TLS state (req.secure// is set when express trust-proxy lands an X-Forwarded-Proto: https) AND@@ -1370,11 +1200,6 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptionnext();});- mountOAuthOwnerConsent(app, {- provider: oauthProvider,- publicOrigin: new URL(mcpResourceUrl).origin,- sessionValid: id => Boolean(id && (adminSessions.get(id) ?? 0) > Date.now()),- });app.use(authRouter);app.get('/.well-known/gbrain', (_req, res) => {res.json({ version: VERSION, protocol: 'mcp', endpoint: mcpResourceUrl.toString(), profiles: GRANT_PROFILES,@@ -1488,7 +1313,9 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptionconst nonce = randomBytes(32).toString('hex');magicLinkNonces.set(nonce, Date.now() + NONCE_TTL_MS);const baseUrl = publicUrl || `http://localhost:${port}`;- res.json({ url: `${baseUrl}/admin/auth/${nonce}`, expires_in: NONCE_TTL_MS / 1000 });+ const pendingId = req.body?.oauth_request;+ const pendingQuery = oauthProvider.grants.hasPending(pendingId) ? `?oauth_request=${pendingId}` : '';+ res.json({ url: `${baseUrl}/admin/auth/${nonce}${pendingQuery}`, expires_in: NONCE_TTL_MS / 1000 });});// GET /admin/auth/:nonce — single-use magic link redemption.@@ -1531,7 +1358,9 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptionadminSessions.set(sessionId, sessionExpiresAt);res.cookie('gbrain_admin', sessionId, adminCookie(req, 7 * 24 * 60 * 60 * 1000));- res.redirect('/admin/');+ const pendingId = req.query.oauth_request;+ res.redirect(oauthProvider.grants.hasPending(pendingId)+ ? `/admin/?oauth_request=${pendingId}#oauth-consent` : '/admin/');});// Admin auth middleware@@ -1550,7 +1379,8 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptionnext();}- // #3893 (reimplemented from @y2688): Prometheus exposition. Admin-gated —+ mountOAuthConsent(app, oauthProvider, requireAdmin, adminAuthRateLimiter);+app.post('/admin/api/grants', requireAdmin, express.json(), async (req, res) => {res.set('Cache-Control', 'no-store');try {@@ -1562,6 +1392,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption}});+ // #3893 (reimplemented from @y2688): Prometheus exposition. Admin-gated —// request/error/latency series profile a personal brain's usage, so this// is not a public surface (the original PR served it unauthenticated).app.get('/metrics', requireAdmin, (_req: Request, res: Response) => {@@ -2259,10 +2090,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptiontry {const { clientId } = req.body;if (!clientId) { res.status(400).json({ error: 'clientId required' }); return; }- // Soft-delete the client- await sql`UPDATE oauth_clients SET deleted_at = now() WHERE client_id = ${clientId} AND deleted_at IS NULL`;- // Revoke all active tokens for this client- await sql`DELETE FROM oauth_tokens WHERE client_id = ${clientId}`;+ await oauthProvider.revokeClient(clientId);res.json({ revoked: true });} catch (e) {res.status(500).json({ error: e instanceof Error ? e.message : 'Revoke failed' });@@ -2331,7 +2159,9 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptionif (req.path !== '/admin') {return next();}- res.redirect('/admin/');+ const pendingId = req.query.oauth_request;+ res.redirect(oauthProvider.grants.hasPending(pendingId)+ ? `/admin/?oauth_request=${pendingId}#oauth-consent` : '/admin/');});app.get('/admin/{*path}', (req: Request, res: Response, next: NextFunction) => {if (req.path.startsWith('/admin/api/') || req.path === '/admin/events' || req.path === '/admin/login') {@@ -2409,7 +2239,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptionres.status(405).json({ jsonrpc: '2.0', error: { code: -32000, message: 'Method not allowed' }, id: null });});- app.post('/mcp', requireBearerAuth({ verifier: oauthProvider, resourceMetadataUrl }), async (req: Request, res: Response) => {+ app.post('/mcp', requireBearerAuth({ verifier: resourceVerifier, resourceMetadataUrl }), async (req: Request, res: Response) => {const startTime = Date.now();const authInfo = (req as any).auth as AuthInfo;@@ -2878,7 +2708,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptionapp.post('/ingest',ingestRateLimiter,- requireBearerAuth({ verifier: oauthProvider, requiredScopes: ['write'], resourceMetadataUrl }),+ requireBearerAuth({ verifier: resourceVerifier, requiredScopes: ['write'], resourceMetadataUrl }),express.raw({ type: '*/*', limit: ingestMaxBytes }),async (req: Request, res: Response) => {const startTime = Date.now();diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex a8eaa94150..0939d30470 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -1,3 +1,5 @@+import { readSourceFileSync, hasSourceFilesystemLock, withSourceFilesystemLock, currentSourceFilesystemSignal, assertSourceFilesystemActive } from '../core/minions/source-filesystem.ts';+import { currentJobSignal } from '../core/minions/submission-authority.ts';import { existsSync, readFileSync, writeFileSync, statSync, lstatSync, realpathSync } from 'fs';import { join, relative, resolve as pathResolve } from 'path';import type { BrainEngine } from '../core/engine.ts';@@ -53,6 +55,7 @@ import {import {withRefreshingLock,LockUnavailableError,+ LockStolenError,syncLockId,} from '../core/db-lock.ts';import {@@ -603,6 +606,48 @@ See also:export { SyncLockBusyError, runBreakLock } from '../core/sync-lock.ts';export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<SyncResult> {+ assertSourceFilesystemActive(true);+ const jobSignal = currentJobSignal();+ if (jobSignal?.aborted) throw jobSignal.reason ?? new Error('Sync job cancelled');+ const finish = (result: SyncResult): SyncResult => {+ assertSourceFilesystemActive(true);+ if (jobSignal?.aborted) throw jobSignal.reason ?? new Error('Sync job cancelled');+ return result;+ };+ const inheritedSignal = currentSourceFilesystemSignal();+ if (inheritedSignal) opts = { ...opts, signal: opts.signal ? AbortSignal.any([opts.signal, inheritedSignal]) : inheritedSignal };+ const interruptedBeforeWork = async (): Promise<SyncResult> => {+ assertSourceFilesystemActive(true);+ const lastCommit = opts.full ? null : await readSyncAnchor(engine, opts.sourceId, 'last_commit');+ return buildPartialResult({+ fromCommit: lastCommit, toCommit: lastCommit ?? '', filesImported: 0,+ pagesAffected: [], chunksCreated: 0, added: 0, modified: 0, deleted: 0, renamed: 0,+ reason: 'timeout',+ });+ };+ // The delegated runner treats interruption as a resumable partial result,+ // including cancellation before acquisition of the new filesystem lock.+ if (opts.signal?.aborted) return finish(await interruptedBeforeWork());+ const filesystemRoot = opts.repoPath || await readSyncAnchor(engine, opts.sourceId, 'repo_path');+ if (filesystemRoot && !hasSourceFilesystemLock(filesystemRoot)) {+ let entered = false;+ let result: SyncResult | undefined;+ try {+ return finish(await withSourceFilesystemLock(engine, filesystemRoot, async () => {+ entered = true;+ return result = await performSync(engine, opts);+ }, { signal: opts.signal }));+ } catch (err) {+ if (err instanceof LockStolenError) throw err;+ const isCallerAbort = err === opts.signal?.reason || (err instanceof Error && err.name === 'AbortError');+ if (opts.signal?.aborted && isCallerAbort && !jobSignal?.aborted) {+ if (result?.status === 'partial') return finish(result);+ if (!entered) return finish(await interruptedBeforeWork());+ }+ if (err instanceof LockUnavailableError) throw new SyncLockBusyError(await formatLockBusyMessage(engine, err.lockId), err.lockId);+ throw err;+ }+ }// v0.22.13 CODEX-2: cross-process writer lock prevents two concurrent// syncs from racing on the same last_commit anchor (last writer wins,// bookmark regresses, silent corruption).@@ -620,7 +665,7 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<// skipLock is reserved for callers that already serialize via another// mechanism (e.g. cycle.ts holds gbrain-cycle for the broader scope).if (opts.skipLock) {- return await performSyncInner(engine, opts);+ return finish(await performSyncInner(engine, opts));}const lockKey = opts.lockId ?? syncLockId(opts.sourceId ?? 'default');@@ -633,7 +678,7 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<// alive (the import loop's event-loop yields ensure the timer fires), and the// heartbeat-aware takeover refuses to steal a live, refreshing holder.try {- return await withRefreshingLock(engine, lockKey, () => performSyncInner(engine, opts));+ return finish(await withRefreshingLock(engine, lockKey, () => performSyncInner(engine, opts)));} catch (err) {if (err instanceof LockUnavailableError) {throw new SyncLockBusyError(await formatLockBusyMessage(engine, lockKey), lockKey);@@ -1056,7 +1101,7 @@ function fallbackSlugsForFile(const st = lstatSync(abs);if (!st.isSymbolicLink()) {if (st.size > MAX_FILE_SIZE) proofIntact = false;- else contents.push(readFileSync(abs, 'utf-8'));+ else contents.push(readSourceFileSync(abs, 'utf-8'));}}// A symlink's own registrable content is its index blob (the target@@ -4031,7 +4076,7 @@ async function performFullSync(const FULL_SYNC_LARGE_MARKER = Number.MAX_SAFE_INTEGER;const fullConcurrency = autoConcurrency(engine, FULL_SYNC_LARGE_MARKER, opts.concurrency);slog(`Running full import of ${syncScopeRoot}${fullConcurrency > 1 ? ` (${fullConcurrency} workers)` : ''}...`);- const { runImport } = await import('./import.ts');+ const { runImport, ImportAbortError } = await import('./import.ts');const importArgs = [syncScopeRoot];if (opts.noEmbed) importArgs.push('--no-embed');if (opts.includeGitignored) importArgs.push('--include-gitignored');@@ -4044,18 +4089,32 @@ async function performFullSync(const _fullImportT0 = Date.now();serr(`[gbrain phase] sync.fullsync.import start strategy=${opts.strategy ?? 'markdown'}`);opts.onProgress?.({ phase: 'full_import' });- const result = await runImport(engine, importArgs, {- commit: headCommit,- strategy: opts.strategy,- sourceId: opts.sourceId,- exclude: opts.exclude,- includeHidden: opts.includeHidden,- includeGitignored: opts.includeGitignored,- slugRoot,- // issue #1939: performFullSync owns the failure ledger + bookmark via the- // shared gate below; don't let runImport double-record or write its own.- managedBookmark: true,- });+ let result: import('./import.ts').RunImportResult;+ try {+ result = await runImport(engine, importArgs, {+ signal: opts.signal,+ commit: headCommit,+ strategy: opts.strategy,+ sourceId: opts.sourceId,+ exclude: opts.exclude,+ includeHidden: opts.includeHidden,+ includeGitignored: opts.includeGitignored,+ slugRoot,+ // issue #1939: performFullSync owns the failure ledger + bookmark via the+ // shared gate below; don't let runImport double-record or write its own.+ managedBookmark: true,+ });+ if (opts.signal?.aborted) throw new ImportAbortError('interrupted', 1, result);+ } catch (error) {+ assertSourceFilesystemActive(true);+ if (!(error instanceof ImportAbortError) || !error.partialResult || !opts.signal?.aborted || currentJobSignal()?.aborted) throw error;+ const partial = error.partialResult;+ return buildPartialResult({+ fromCommit: await readSyncAnchor(engine, opts.sourceId, 'last_commit'), toCommit: headCommit,+ filesImported: partial.imported, pagesAffected: [], chunksCreated: partial.chunksCreated,+ added: partial.imported, modified: 0, deleted: 0, renamed: 0, reason: 'timeout',+ });+ }serr(`[gbrain phase] sync.fullsync.import done ${Date.now() - _fullImportT0}ms ` +`imported=${result.imported} skipped=${result.skipped} errors=${result.errors}`,diff --git a/src/core/capture-content.ts b/src/core/capture-content.tsindex d3b9444c53..3856499013 100644--- a/src/core/capture-content.ts+++ b/src/core/capture-content.ts@@ -7,7 +7,7 @@* no fs, no engine.*/-import matter from 'gray-matter';+import { dataFrontmatter as matter } from './data-frontmatter.ts';import { computeContentHash } from './ingestion/types.ts';/** The subset of capture options the frontmatter/slug helpers consume. */@@ -209,7 +209,7 @@ export function explicitCaptureType(rawBody: string, explicit?: string): stringif (typeof explicit === 'string' && explicit.length > 0) return explicit;const trimmedStart = rawBody.replace(/^/, '');if (!/^---\r?\n/.test(trimmedStart)) return undefined;- let parsed: matter.GrayMatterFile<string>;+ let parsed: ReturnType<typeof matter>;try {parsed = matter(rawBody);} catch {@@ -248,8 +248,15 @@ export function mergeCaptureFrontmatter(rawBody: string, opts: CaptureFrontmatte// Detect frontmatter: leading `---\n` or `---\r\n`, tolerating leading BOM/whitespace.// We do NOT use the more permissive `startsWith('---')` because a body that opens// with a horizontal-rule like `--- separator ---` would false-positive.- const trimmedStart = rawBody.replace(/^/, '');- const hasFrontmatter = /^---\r?\n/.test(trimmedStart);+ // Parse before wrapping: an unsupported language must not be hidden inside+ // a generated heading. Serialization always treats the remaining body opaquely.+ let parsed: ReturnType<typeof matter>;+ try {+ parsed = matter(rawBody);+ } catch (e) {+ throw new Error(`malformed frontmatter in capture input: ${e instanceof Error ? e.message : String(e)}`);+ }+ const hasFrontmatter = parsed.hasFrontmatter;if (!hasFrontmatter) {// No existing frontmatter: stamp a fresh block and (if body lacks markdown@@ -269,14 +276,6 @@ export function mergeCaptureFrontmatter(rawBody: string, opts: CaptureFrontmatte}// Existing frontmatter: parse, merge user-wins, re-emit as a SINGLE block.- let parsed: matter.GrayMatterFile<string>;- try {- parsed = matter(rawBody);- } catch (e) {- throw new Error(- `malformed frontmatter in capture input: ${e instanceof Error ? e.message : String(e)}`,- );- }const userFm = (parsed.data ?? {}) as Record<string, unknown>;const merged: Record<string, unknown> = {// Spread user's declared keys first so 'description', 'tags', etc. pass through.diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 06104a471d..3e60ae5125 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -27,9 +27,9 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--compile', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--fast', '--file', '--flag', '--force', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--isolated', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-embedding', '--no-hooks', '--no-verify', '--once', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push', '--push-only', '--quiet', '--rebase', '--remove', '--repair', '--scope', '--scopes', '--set', '--short', '--show', '--show-toplevel', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--token-ttl', '--unset-all', '--url', '--user-hooks', '--verify', '--version', '--visibility', '--workspace', '--yes'],'brainstorm': ['--all', '--brain', '--chunker-debug', '--code', '--compile', '--exclude', '--fast', '--file', '--fix', '--force', '--force-rechunk', '--force-resume', '--from-pages', '--full', '--help', '--http', '--json', '--judge-model', '--lang', '--limit', '--list-runs', '--markdown', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--model', '--no-embed', '--no-embedding', '--no-save', '--path', '--resume', '--retry-failed', '--retry-judge', '--save', '--source', '--stale', '--strict-budget', '--surface', '--timeout', '--token-ttl', '--yes'],'cache': ['--brain', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--source', '--surface', '--token-ttl', '--yes'],- 'calibration': ['--ab', '--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--by-mention', '--content', '--date', '--days', '--dry-run', '--entities', '--explain', '--federated', '--file', '--follow', '--full', '--help', '--holder', '--http', '--image', '--json', '--key-prefix', '--kind', '--lang', '--limit', '--markdown', '--max-usd', '--mode', '--multimodal', '--near-symbol', '--no-federated', '--offset', '--page', '--path', '--phase', '--progress-interval', '--progress-json', '--quiet', '--recency', '--regenerate', '--repo', '--restore-only', '--salience', '--save', '--scrub-gstack', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--stale', '--stale-ok', '--stats', '--stdin', '--surface', '--symbol-kind', '--thin', '--trusted-extraction', '--types', '--undo-wave', '--url', '--walk-depth', '--with-calibration', '--with-db', '--yes'],+ 'calibration': ['--ab', '--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--by-mention', '--content', '--date', '--days', '--dry-run', '--entities', '--explain', '--federated', '--file', '--full', '--help', '--holder', '--http', '--image', '--json', '--key-prefix', '--kind', '--lang', '--limit', '--markdown', '--max-usd', '--mode', '--multimodal', '--near-symbol', '--no-federated', '--offset', '--page', '--path', '--phase', '--progress-interval', '--progress-json', '--quiet', '--recency', '--regenerate', '--repo', '--restore-only', '--salience', '--save', '--scrub-gstack', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--stale', '--stale-ok', '--stats', '--stdin', '--surface', '--symbol-kind', '--thin', '--trusted-extraction', '--types', '--undo-wave', '--url', '--walk-depth', '--with-calibration', '--with-db', '--yes'],'call': ['--brain', '--federated', '--help', '--http', '--json', '--no-federated', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--stale', '--timeout'],- 'capture': ['--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--by-mention', '--content', '--date', '--days', '--depth', '--entities', '--exclude', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-federated', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--repo', '--restore-only', '--salience', '--save', '--scopes', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--stale-ok', '--stats', '--stdin', '--surface', '--token-ttl', '--trusted-extraction', '--type', '--types', '--url', '--walk-depth', '--what', '--where', '--who', '--with-db', '--yes'],+ 'capture': ['--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--by-mention', '--content', '--date', '--days', '--depth', '--entities', '--exclude', '--fast', '--federated', '--file', '--force', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-federated', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--repo', '--restore-only', '--salience', '--save', '--scopes', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--stale-ok', '--stats', '--stdin', '--surface', '--token-ttl', '--trusted-extraction', '--type', '--types', '--url', '--walk-depth', '--what', '--where', '--who', '--with-db', '--yes'],'check-backlinks': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dir', '--dry-run', '--explain', '--follow', '--help', '--include-frontmatter', '--json', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout', '--type'],'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],'check-update': ['--all', '--brain', '--check', '--dim', '--ff-only', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--version', '--yes'],@@ -57,7 +57,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'extract-conversation-facts': ['--all', '--all-sources', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--by-mention', '--check', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--dim', '--dir', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--federated', '--fix', '--follow', '--force', '--force-break-lock', '--help', '--json', '--judge-model', '--kind', '--limit', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--name', '--no', '--no-embed', '--no-embedding', '--no-federated', '--older-than', '--override-disabled', '--path', '--pglite', '--print', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--segment-limit', '--session', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--version', '--workers', '--yes'],'features': ['--all', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--explain', '--from-meetings', '--help', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--ner', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--progress-json', '--quiet', '--rebuild', '--refresh', '--repo', '--run-id', '--since', '--since-created', '--slugs', '--source', '--source-id', '--stale', '--target', '--type', '--verbose', '--workers'],'files': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dry-run', '--exclude', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--help', '--http', '--json', '--no-embedding', '--no-federated', '--no-pointer', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--retry-failed', '--save', '--source', '--source-guard', '--stale', '--surface', '--timeout', '--token-ttl', '--type', '--yes'],- 'forget': ['--access', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-federated', '--offset', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--recency', '--repo', '--restore-only', '--rollup', '--salience', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--stale-ok', '--stats', '--stdin', '--supersessions', '--surface', '--today', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--watch', '--with-db', '--yes'],+ 'forget': ['--access', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--force', '--from-pages', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-federated', '--offset', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--recency', '--repo', '--restore-only', '--rollup', '--salience', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--stale-ok', '--stats', '--stdin', '--supersessions', '--surface', '--today', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--watch', '--with-db', '--yes'],'founder': ['--brain', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--mcp-only', '--no-embedding', '--since', '--source', '--surface', '--token-ttl', '--until'],'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--redact', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],'frontmatter': ['--allow-catch-all', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude', '--exclude-standard', '--fast', '--fix', '--force', '--from-pages', '--full', '--get', '--help', '--http', '--include-catch-all', '--include-hidden', '--json', '--name-only', '--name-status', '--no-embedding', '--no-verify', '--others', '--source', '--strategy', '--surface', '--timeout', '--token-ttl', '--uninstall', '--write-back'],@@ -68,7 +68,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'init': ['--all', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--ctx-size', '--dim', '--embedding-dimensions', '--embedding-model', '--embeddings', '--entity', '--exclude', '--expansion-model', '--fast', '--flag', '--force', '--from-pages', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--judge-model', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--prefer-postgres', '--print', '--probe', '--provenance', '--quiet', '--reranking', '--reset', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--token-ttl', '--touchpoint', '--url', '--version', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--embeddings', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--overwrite', '--refresh', '--reranking', '--source', '--surface', '--target', '--token-ttl'],'integrity': ['--auto', '--backend', '--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--confidence', '--cost', '--dry-run', '--exclude', '--explain', '--fast', '--follow', '--force', '--fresh', '--from-pages', '--help', '--http', '--json', '--limit', '--no-embedding', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--stale', '--supabase', '--surface', '--timeout', '--token-ttl', '--type', '--url'],- 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-protected', '--allow-shell-jobs', '--apply', '--asof', '--auto', '--auto-with-prompt', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-usd', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--cluster', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--content', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--federated-read', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--full-history', '--hard-deadline', '--health-interval', '--held-out', '--help', '--http', '--idempotency-key', '--image', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lang', '--limit', '--lock', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-runtime', '--max-runtime-min', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--name-status', '--near-symbol', '--ner', '--nice', '--no', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-federate', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-max-cost', '--no-mutate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--offset', '--older-than', '--once', '--order', '--orphan', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--phase', '--pid-file', '--print', '--priority', '--progress-interval', '--progress-json', '--queue', '--quiet', '--rebuild', '--recency', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--remediate', '--repo', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--run-id', '--salience', '--save', '--segment-limit', '--serial', '--session', '--session-id', '--short', '--show-toplevel', '--sigkill-rescue', '--since', '--since-created', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stale-ok', '--stats', '--status', '--stdin', '--strategy', '--surface', '--swap-only', '--symbol-kind', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--token-ttl', '--trusted-extraction', '--type', '--types', '--uninstall', '--unsafe-bypass-dream-guard', '--url', '--user', '--verbose', '--verify', '--version', '--walk-depth', '--watch', '--wedge-rescue', '--with-db', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-protected', '--allow-shell-jobs', '--apply', '--asof', '--auto', '--auto-with-prompt', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-usd', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--cluster', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--content', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--fast', '--federated', '--federated-read', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--full-history', '--hard-deadline', '--health-interval', '--held-out', '--help', '--http', '--idempotency-key', '--ids', '--image', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lang', '--limit', '--lock', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-runtime', '--max-runtime-min', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--name-status', '--near-symbol', '--ner', '--nice', '--no', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-federate', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-max-cost', '--no-mutate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--offset', '--older-than', '--once', '--order', '--orphan', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--phase', '--pid-file', '--print', '--priority', '--progress-interval', '--progress-json', '--queue', '--quiet', '--rebuild', '--recency', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--remediate', '--repo', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--run-id', '--salience', '--save', '--segment-limit', '--serial', '--session', '--session-id', '--short', '--show-toplevel', '--sigkill-rescue', '--since', '--since-created', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stale-ok', '--stats', '--status', '--stdin', '--strategy', '--surface', '--swap-only', '--symbol-kind', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--token-ttl', '--trusted-extraction', '--type', '--types', '--uninstall', '--unsafe-bypass-dream-guard', '--url', '--user', '--verbose', '--verify', '--version', '--walk-depth', '--watch', '--wedge-rescue', '--with-db', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--abort', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--branch', '--cached', '--check', '--compile', '--dry-run', '--exclude', '--explain', '--fast', '--file', '--fix', '--follow', '--force', '--from-pages', '--full', '--get', '--git-dir', '--git-path', '--help', '--http', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-cron', '--no-embedding', '--no-verify', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push-only', '--quiet', '--rebase', '--remediate', '--short', '--show-toplevel', '--source', '--stale', '--surface', '--timeout', '--token-ttl', '--unset-all'],'loops': ['--all', '--brain', '--federated-read', '--help', '--http', '--json', '--source', '--source-guard', '--stale-ok', '--status', '--timeout', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--retry-judge', '--save', '--source', '--strict-budget', '--yes'],@@ -78,16 +78,16 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'models': ['--brain', '--detail', '--dim', '--drain', '--embedding-dimensions', '--embedding-model', '--embeddings', '--help', '--json', '--judge-model', '--model', '--multimodal', '--no', '--no-embed', '--print', '--recency', '--reranking', '--reset', '--skip', '--source', '--to', '--version'],'mounts': ['--alias', '--brain', '--cache', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--explain', '--help', '--id', '--json', '--lang', '--lock', '--markdown', '--mcp-url', '--multimodal', '--near-symbol', '--path', '--restore-only', '--skills-dir', '--source', '--stale', '--symbol-kind', '--thin', '--verbose'],'notability-eval': ['--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--model', '--multimodal', '--no', '--no-embed', '--out', '--print', '--repo', '--skip-llm', '--source', '--target-high', '--target-low', '--target-medium', '--to', '--version'],- 'onboard': ['--access', '--all', '--allow-empty', '--allow-protected', '--apply', '--asof', '--auto', '--auto-with-prompt', '--bound-slug-prefixes', '--brain', '--by-mention', '--check', '--content', '--date', '--days', '--entities', '--explain', '--federated', '--file', '--follow', '--from-pages', '--full', '--help', '--history', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--near-symbol', '--offset', '--page', '--params', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--remediate', '--remediation-plan', '--resume', '--salience', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale-ok', '--stats', '--stdin', '--surface', '--target-score', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],+ 'onboard': ['--access', '--all', '--allow-empty', '--allow-protected', '--apply', '--asof', '--auto', '--auto-with-prompt', '--bound-slug-prefixes', '--brain', '--by-mention', '--check', '--content', '--date', '--days', '--entities', '--explain', '--federated', '--file', '--from-pages', '--full', '--help', '--history', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--near-symbol', '--offset', '--page', '--params', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--remediate', '--remediation-plan', '--resume', '--salience', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale-ok', '--stats', '--stdin', '--surface', '--target-score', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],'orphans': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--mode', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout'],'pages': ['--brain', '--dry-run', '--help', '--json', '--older-than', '--source'],'pglite-repair': ['--brain', '--break-lock', '--dry-rnu', '--dry-run', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--path', '--quiet', '--source', '--surface', '--token-ttl', '--yes'],'post-upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--code', '--compile', '--concurrency', '--cost-estimate', '--detail', '--dim', '--embedding-dimensions', '--embedding-model', '--exclude', '--fast', '--ff-only', '--flag', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--from-pages', '--help', '--host-dir', '--http', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--model', '--multimodal', '--name-only', '--no', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pglite', '--print', '--quiet', '--recency', '--repo', '--require-db', '--reset', '--since', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--surface', '--swap-only', '--target', '--timeout', '--to', '--token-ttl', '--uninstall', '--user', '--verbose', '--verify', '--version', '--workers', '--yes'],- 'protocol': ['--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--salience', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale-ok', '--stats', '--stdin', '--surface', '--synthesize', '--target', '--timeout', '--token', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],+ 'protocol': ['--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--force', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--salience', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale-ok', '--stats', '--stdin', '--surface', '--synthesize', '--target', '--timeout', '--token', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],'providers': ['--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--embeddings', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--print', '--reranking', '--reset', '--source', '--surface', '--to', '--token-ttl', '--touchpoint', '--version', '--yes'],'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],'quarantine': ['--apply', '--brain', '--code', '--compile', '--exclude', '--fast', '--fix', '--force', '--force-rechunk', '--from-pages', '--help', '--http', '--include-flagged', '--json', '--lang', '--limit', '--markdown', '--no-embed', '--no-embedding', '--source', '--source-id', '--stale', '--surface', '--token-ttl'],- 'recall': ['--access', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-federated', '--offset', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--recency', '--repo', '--restore-only', '--rollup', '--salience', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--stale-ok', '--stats', '--stdin', '--supersessions', '--surface', '--today', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--watch', '--with-db', '--yes'],+ 'recall': ['--access', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--force', '--from-pages', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-federated', '--offset', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--recency', '--repo', '--restore-only', '--rollup', '--salience', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--stale-ok', '--stats', '--stdin', '--supersessions', '--surface', '--today', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--watch', '--with-db', '--yes'],'reconcile-links': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dry-run', '--explain', '--follow', '--full', '--help', '--include-frontmatter', '--include-hidden', '--json', '--name-status', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--strategy', '--timeout', '--type'],'reindex': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--check', '--code', '--compile', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exclude', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--from-pages', '--help', '--http', '--json', '--lang', '--limit', '--markdown', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--older-than', '--path', '--pglite', '--print', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--type', '--version', '--workers', '--yes'],'reindex-code': ['--abi', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--chunker-debug', '--code', '--compile', '--concurrency', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fix', '--follow', '--force', '--force-rechunk', '--help', '--json', '--judge-model', '--lang', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--no', '--no-embed', '--older-than', '--print', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--serial', '--source', '--stale', '--timeout', '--to', '--version', '--workers', '--yes'],@@ -114,13 +114,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--dir', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--full-history', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lock', '--max-age', '--max-rss', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--name-status', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--orphan', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--retry-failed', '--section', '--serial', '--short', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--surface', '--timeout', '--token-ttl', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--federated', '--fix', '--help', '--json', '--no-federated', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--to'],'sweep': ['--all', '--background', '--batch-limit', '--brain', '--brain-wide-max-cost-usd', '--budget-ms', '--check', '--delete-brain', '--explain', '--federated', '--follow', '--help', '--home', '--json', '--name', '--no-delegate', '--no-federated', '--once', '--parallel', '--path', '--prefix', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--source', '--source-guard', '--stale', '--stats', '--timeout'],- 'sync': ['--abbrev-ref', '--abi', '--abort', '--account', '--all', '--all-sources', '--allow-empty', '--apply', '--apply-rewrites', '--asof', '--auto', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--clone-dir', '--code', '--column', '--compile', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--ff-only', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--lock', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--object-format', '--older-than', '--orphan', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--rebuild-rollup', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--reset', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--run-id', '--save', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--since-created', '--skills-dir', '--skip-failed', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token-env', '--token-ttl', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--abi', '--abort', '--account', '--all', '--all-sources', '--allow-empty', '--apply', '--apply-rewrites', '--asof', '--auto', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--clone-dir', '--code', '--column', '--compile', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--ff-only', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--ids', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--lock', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--object-format', '--older-than', '--orphan', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--rebuild-rollup', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--reset', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--run-id', '--save', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--since-created', '--skills-dir', '--skip-failed', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token-env', '--token-ttl', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--accept', '--all', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--exclude', '--expired', '--fast', '--federated', '--file', '--force', '--from-pages', '--help', '--holder', '--http', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--no-federated', '--offset', '--outcome', '--path', '--pglite', '--print', '--quality', '--reject', '--repo', '--restore-only', '--row', '--semantic', '--serial', '--since', '--slugs', '--sort', '--source', '--source-guard', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--token-ttl', '--unit', '--until', '--value', '--version', '--weight', '--who', '--yes'],'think': ['--all', '--anchor', '--bind', '--bound-slug-prefixes', '--brain', '--calibration-holder', '--compile', '--enable-dcr', '--enable-dcr-insecure', '--exclude', '--explain', '--fast', '--federated', '--federated-read', '--force', '--from-pages', '--help', '--http', '--json', '--log-full-params', '--max-usd', '--mcp-only', '--model', '--name', '--no-embed', '--no-embedding', '--no-federated', '--no-hard-deadline', '--once', '--parallel', '--path', '--port', '--prefix', '--print-admin-token', '--public-url', '--repo', '--restore-only', '--rounds', '--save', '--serial', '--since', '--source', '--source-guard', '--stale', '--stdio-idle-timeout', '--suppress', '--suppress-bootstrap-token', '--surface', '--take', '--timeout', '--token-ttl', '--until', '--with-calibration', '--yes'],'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--check', '--code', '--compile', '--days', '--dry-run', '--embed', '--exclude', '--explain', '--facts', '--fast', '--federated', '--follow', '--force', '--format', '--from-pages', '--full', '--help', '--http', '--include-self', '--json', '--limit', '--markdown', '--max-bytes', '--max-cost-usd', '--no-embedding', '--no-federated', '--path', '--print', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--since', '--since-last', '--slug', '--source', '--source-guard', '--source-id', '--stale', '--surface', '--timeout', '--token-ttl'],'upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--code', '--compile', '--concurrency', '--cost-estimate', '--detail', '--dim', '--embedding-dimensions', '--embedding-model', '--exclude', '--fast', '--ff-only', '--flag', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--from-pages', '--help', '--host-dir', '--http', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--model', '--multimodal', '--name-only', '--no', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pglite', '--print', '--quiet', '--recency', '--repo', '--require-db', '--reset', '--since', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--surface', '--swap-only', '--target', '--timeout', '--to', '--token-ttl', '--uninstall', '--user', '--verbose', '--verify', '--version', '--workers', '--yes'],'waiting': ['--all', '--brain', '--federated-read', '--help', '--http', '--json', '--source', '--source-guard', '--stale-ok', '--status', '--timeout', '--top', '--type'],'watch': ['--brain', '--exclude', '--fast', '--federated', '--force', '--from-pages', '--help', '--http', '--json', '--max-pages', '--min-confidence', '--no-embedding', '--no-federated', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--stats', '--surface', '--token-ttl', '--window-turns'],- 'whoknows': ['--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--by-mention', '--content', '--date', '--days', '--detail', '--entities', '--exclude', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--salience', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale-ok', '--stats', '--stdin', '--surface', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],+ 'whoknows': ['--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--by-mention', '--content', '--date', '--days', '--detail', '--entities', '--exclude', '--explain', '--fast', '--federated', '--file', '--force', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--salience', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale-ok', '--stats', '--stdin', '--surface', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],'ze-switch': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--confirm-reembed', '--dim', '--dry-run', '--explain', '--follow', '--force', '--force-sunset-target', '--help', '--ignore-env-override', '--ignore-missing-key', '--json', '--markdown', '--non-interactive', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reranker', '--reset', '--resume', '--source', '--stale', '--timeout', '--to', '--undo', '--yes'],};diff --git a/src/core/data-frontmatter.ts b/src/core/data-frontmatter.tsnew file mode 100644index 0000000000..f4d9001091--- /dev/null+++ b/src/core/data-frontmatter.ts@@ -0,0 +1,62 @@+import { safeLoad, safeDump } from 'js-yaml';++export interface DataFrontmatter {+ data: Record<string, unknown>;+ content: string;+ hasFrontmatter: boolean;+}++export class FrontmatterLanguageError extends Error {+ constructor() {+ super('Unsupported frontmatter language; only YAML and JSON are allowed');+ this.name = 'FrontmatterLanguageError';+ }+}++/** Parse data only. There is deliberately no pluggable engine or evaluator. */+export function parseDataFrontmatter(input: string): DataFrontmatter {+ const original = input.replace(/^\uFEFF/, '');+ // Preserve ordinary body whitespace; lift leading blank lines only for a fence.+ const lifted = original.replace(/^(?:[\t ]*\r?\n)+(?=---)/, '');+ const opening = /^---([^\r\n]*)(?:\r?\n|$)/.exec(lifted);+ if (!opening || opening[1]!.startsWith('-') || opening[1]!.trimEnd().endsWith('---')) {+ return { data: {}, content: original, hasFrontmatter: false };+ }+ const language = opening[1]!.trim().toLowerCase();+ if (language !== '' && language !== 'yaml' && language !== 'yml' && language !== 'json') {+ throw new FrontmatterLanguageError();+ }+ const rest = lifted.slice(opening[0].length);+ const closing = /^---[\t ]*(?:\r?\n|$)/m.exec(rest);+ // Match the established parser's missing-close behavior: parse the remaining+ // block and let the higher-level markdown validator report MISSING_CLOSE.+ const block = closing ? rest.slice(0, closing.index) : rest;+ let value: unknown;+ try {+ value = block.trim() === '' ? {} : language === 'json' ? JSON.parse(block) : safeLoad(block);+ } catch (error) {+ // Parser messages can contain the document itself. Report only location,+ // so request/job diagnostics never copy private frontmatter into logs.+ const line = (error as { mark?: { line?: number } })?.mark?.line;+ throw new Error(`Malformed ${language === 'json' ? 'JSON' : 'YAML'} frontmatter${typeof line === 'number' ? ` at line ${line + 2}` : ''}`);+ }+ if (value !== undefined && value !== null && (typeof value !== 'object' || Array.isArray(value))) {+ throw new Error('Frontmatter must be a YAML or JSON object');+ }+ return {+ data: (value ?? {}) as Record<string, unknown>,+ content: closing ? rest.slice(closing.index + closing[0].length) : '',+ hasFrontmatter: true,+ };+}++/** Serialize metadata without ever interpreting the body as frontmatter. */+export function stringifyDataFrontmatter(content: string, data: Record<string, unknown>): string {+ const yaml = safeDump(data).trim();+ const header = yaml === '{}' ? '' : `---\n${yaml}\n---\n`;+ return header + (content.endsWith('\n') ? content : content + '\n');+}++// Small compatibility surface for callers that parse and serialize together.+// Unlike the removed dependency, stringify never parses its content argument.+export const dataFrontmatter = Object.assign(parseDataFrontmatter, { stringify: stringifyDataFrontmatter });diff --git a/src/core/db-lock.ts b/src/core/db-lock.tsindex a647ae0dc8..aba8f2b04b 100644--- a/src/core/db-lock.ts+++ b/src/core/db-lock.ts@@ -951,6 +951,8 @@ export interface WithRefreshingLockOpts {ttlMinutes?: number;/** Heartbeat-fail threshold in ms — abort if SELECT 1 takes longer. Default 30000. */heartbeatTimeoutMs?: number;+ /** Opt-in cooperative cancellation when ownership is lost or renewal misses the TTL. */+ onLockLost?: (reason: Error) => void;}/**@@ -973,6 +975,20 @@ export async function withRefreshingLock<T>(const handle = await tryAcquireDbLock(engine, lockId, ttlMinutes);if (!handle) throw new LockUnavailableError(lockId);+ let lost = false;+ let expiryTimer: ReturnType<typeof setTimeout> | undefined;+ const notifyLoss = () => {+ if (lost) return;+ lost = true;+ opts.onLockLost?.(new LockStolenError(lockId));+ };+ const renewDeadline = () => {+ if (!opts.onLockLost || lost) return;+ clearTimeout(expiryTimer);+ expiryTimer = setTimeout(notifyLoss, ttlMinutes * 60_000);+ expiryTimer.unref?.();+ };+ renewDeadline();let healthOk = true;// Re-entrancy guard: with a 15s minimum cadence and a 30s default timeout,// two ticks can overlap on a slow pool — one refresh in flight at a time.@@ -1019,10 +1035,12 @@ export async function withRefreshingLock<T>(// but mutual exclusion is GONE and the degraded-heartbeat exit// message names it.clearInterval(interval);+ notifyLoss();healthOk = false;process.stderr.write(`[lock-refresh] ${lockId}: ${new LockStolenError(lockId).message} — heartbeat stopped, mutual exclusion lost\n`);return;}+ renewDeadline();healthOk = true;} catch (err) {const msg = err instanceof Error ? err.message : String(err);@@ -1042,6 +1060,7 @@ export async function withRefreshingLock<T>(return await work();} finally {clearInterval(interval);+ clearTimeout(expiryTimer);try { await handle.release(); } catch { /* idempotent */ }if (!healthOk) {// Surface that the heartbeat detected backend trouble — caller candiff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.tsindex e05306c05c..a894d7e718 100644--- a/src/core/facts/fence-write.ts+++ b/src/core/facts/fence-write.ts@@ -44,6 +44,7 @@ import { inferTypeFromPack, parseMarkdown } from '../markdown.ts';import { sanitizeText } from '../batch-rows.ts';import { loadActivePackBestEffort } from '../schema-pack/best-effort.ts';import { withPageLock } from '../page-lock.ts';+import { assertSourceFilesystemActive, hasSourceFilesystemLock, withSourceFilesystemLock } from '../minions/source-filesystem.ts';import { gbrainPath } from '../config.ts';import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';import { isDurabilityHardened, commitWriteThroughFile } from '../brain-repo-durability.ts';@@ -308,6 +309,9 @@ export async function writeFactsToFence(return { inserted: 0, ids: [], targetUnresolvable: true };}const { filePath, writeRoot } = resolved;+ if (!hasSourceFilesystemLock(writeRoot)) {+ return withSourceFilesystemLock(engine, writeRoot, () => writeFactsToFence(engine, target, facts));+ }const tmpPath = `${filePath}.tmp`;const durabilityEnabled = isDurabilityHardened(writeRoot);@@ -450,6 +454,7 @@ export async function writeFactsToFence(: 'clean';// 3. Atomic write: .tmp first, then parse-validate, then rename.+ assertSourceFilesystemActive();writeFileSync(tmpPath, body, 'utf-8');// 4. Parse-before-rename: re-read the .tmp content and verify thediff --git a/src/core/facts/forget.ts b/src/core/facts/forget.tsindex 7b6edde10b..fe90b6400e 100644--- a/src/core/facts/forget.ts+++ b/src/core/facts/forget.ts@@ -14,6 +14,7 @@ import { existsSync, readFileSync, writeFileSync, renameSync } from 'node:fs';import type { BrainEngine } from '../engine.ts';import { withPageLock } from '../page-lock.ts';+import { assertSourceFilesystemActive, hasSourceFilesystemLock, withSourceFilesystemLock } from '../minions/source-filesystem.ts';import { resolvePageWriteTarget } from '../write-through.ts';import { parseFactsFence, renderFactsTable, type ParsedFact } from '../facts-fence.ts';import { parseMarkdown } from '../markdown.ts';@@ -203,66 +204,75 @@ export async function forgetFactInFence(// fence keeps the live row for the next absorb to resurrect.const resolved = await resolvePageWriteTarget(engine, slug, row.source_id);if (!resolved.ok) return legacyExpire();- const filePath = resolved.filePath;- const tmpPath = `${filePath}.tmp`;+ // Continue this accepted withdrawal under the source lock. Restarting the+ // whole operation here would observe the expiry we just committed and skip+ // its filesystem mirror as an already-forgotten request.+ const mirrorWithdrawal = async (): Promise<ForgetFactResult> => {+ const filePath = resolved.filePath;+ const tmpPath = `${filePath}.tmp`;- if (!existsSync(filePath)) {- // File deleted out from under us — only the DB has the row.- // Legacy path is the safe behavior; the operator can fix the- // tree mismatch separately.- return legacyExpire();- }-- return withPageLock(slug, async () => {- const body = readFileSync(filePath, 'utf-8');- // Fence missing the row (DB drifted from markdown) or its markers (race /- // corruption): fall through to legacy expire so the user's intent- // succeeds; doctor surfaces the drift separately.- const newBody = strikeFenceRow(body, targetRowNum, reason, today);- if (newBody === null) return legacyExpire(true);-- // Atomic .tmp + parse-validate + rename.- writeFileSync(tmpPath, newBody, 'utf-8');- const tmpBody = readFileSync(tmpPath, 'utf-8');- const validate = parseFactsFence(tmpBody);- if (validate.warnings.length > 0) {- // Quarantine .tmp; leave the canonical file alone; fall back to- // DB expire so the user's forget intent still succeeds.- return legacyExpire(true);+ if (!existsSync(filePath)) {+ // File deleted out from under us — only the DB has the row.+ // Legacy path is the safe behavior; the operator can fix the+ // tree mismatch separately.+ return legacyExpire();}- renameSync(tmpPath, filePath);- // Stamp the DB to match: valid_until = today, expired_at = now().- // This keeps DB query patterns (active facts WHERE expired_at IS NULL)- // accurate the moment the forget commits, without waiting for the- // next extract_facts cycle phase to reconcile.- await engine.executeRaw(- `UPDATE facts SET valid_until = $1, expired_at = now()- WHERE id = $2 AND expired_at IS NULL`,- [today, factId],- );+ return withPageLock(slug, async () => {+ const body = readFileSync(filePath, 'utf-8');+ // Fence missing the row (DB drifted from markdown) or its markers (race /+ // corruption): fall through to legacy expire so the user's intent+ // succeeds; doctor surfaces the drift separately.+ const newBody = strikeFenceRow(body, targetRowNum, reason, today);+ if (newBody === null) return legacyExpire(true);- // #4696: mirror the rewritten file into the DB body, or the reconcile- // (which reads pages.compiled_truth) resurrects the claim before the- // next sync absorbs the file — and sync is commit-anchored, so that- // window lasts until the user commits. Parse + sanitize the FILE bytes- // as import-file.ts does. Body-only: content_chunks still carry the- // live claim, so the row KEEPS its old content_hash and the next sync- // re-imports + re-chunks. Stamping the importer's hash here made sync- // skip the page and the struck claim kept surfacing in chunk search.- // Never persist an EMPTY hash: a row that had none gets a row-shaped- // hash of its pre-mirror content, which the rewritten file can't match.- // Best-effort — file + facts row are already correct.- try {- const reparsed = parseMarkdown(tmpBody, `${slug}.md`);- const page = await engine.getPage(slug, { sourceId: row.source_id });- if (page) {- await engine.refreshPageBody(slug, row.source_id,- sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline),- page.content_hash || contentHash(page));+ // Atomic .tmp + parse-validate + rename.+ assertSourceFilesystemActive();+ writeFileSync(tmpPath, newBody, 'utf-8');+ const tmpBody = readFileSync(tmpPath, 'utf-8');+ const validate = parseFactsFence(tmpBody);+ if (validate.warnings.length > 0) {+ // Quarantine .tmp; leave the canonical file alone; fall back to+ // DB expire so the user's forget intent still succeeds.+ return legacyExpire(true);}- } catch { /* degrades to the pre-#4696 window (stale until the next sync) */ }+ renameSync(tmpPath, filePath);- return { ok: true, path: 'fence', reason };- }, { timeoutMs: 5_000 });+ // Stamp the DB to match: valid_until = today, expired_at = now().+ // This keeps DB query patterns (active facts WHERE expired_at IS NULL)+ // accurate the moment the forget commits, without waiting for the+ // next extract_facts cycle phase to reconcile.+ await engine.executeRaw(+ `UPDATE facts SET valid_until = $1, expired_at = now()+ WHERE id = $2 AND expired_at IS NULL`,+ [today, factId],+ );++ // #4696: mirror the rewritten file into the DB body, or the reconcile+ // (which reads pages.compiled_truth) resurrects the claim before the+ // next sync absorbs the file — and sync is commit-anchored, so that+ // window lasts until the user commits. Parse + sanitize the FILE bytes+ // as import-file.ts does. Body-only: content_chunks still carry the+ // live claim, so the row KEEPS its old content_hash and the next sync+ // re-imports + re-chunks. Stamping the importer's hash here made sync+ // skip the page and the struck claim kept surfacing in chunk search.+ // Never persist an EMPTY hash: a row that had none gets a row-shaped+ // hash of its pre-mirror content, which the rewritten file can't match.+ // Best-effort — file + facts row are already correct.+ try {+ const reparsed = parseMarkdown(tmpBody, `${slug}.md`);+ const page = await engine.getPage(slug, { sourceId: row.source_id });+ if (page) {+ await engine.refreshPageBody(slug, row.source_id,+ sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline),+ page.content_hash || contentHash(page));+ }+ } catch { /* degrades to the pre-#4696 window (stale until the next sync) */ }++ return { ok: true, path: 'fence', reason };+ }, { timeoutMs: 5_000 });+ };+ return hasSourceFilesystemLock(resolved.writeRoot)+ ? mirrorWithdrawal()+ : withSourceFilesystemLock(engine, resolved.writeRoot, mirrorWithdrawal);}diff --git a/src/core/guarded-http.ts b/src/core/guarded-http.tsnew file mode 100644index 0000000000..eddfbdf6e2--- /dev/null+++ b/src/core/guarded-http.ts@@ -0,0 +1,133 @@+/**+ * The only network adapter for untrusted URLs. The caller has already checked+ * every DNS answer; connect to that literal while preserving the HTTP authority+ * and TLS identity. Bun >= 1.3.11 is required for explicit TLS serverName.+ *+ * Bun's native fetch and node:http wrapper cannot reliably disable environment+ * proxies per request. Fail closed in that environment: a proxy could resolve+ * the original hostname again. Never mutate process-wide proxy settings.+ */+import { Readable } from 'node:stream';+import { createBrotliDecompress, createGunzip, createInflate } from 'node:zlib';+import type { ReadableStream as NodeReadableStream } from 'node:stream/web';+import { assertSupportedBun } from './runtime-version.ts';++export interface PinnedHttpTarget {+ resolvedUrl: string;+ resolvedIp: string;+ originalHost: string;+ ipv6: boolean;+}++export interface PinnedHttpRequest {+ method: string;+ headers: Headers;+ body?: string;+ signal: AbortSignal;+}++export type PinnedHttpFetch = (+ target: PinnedHttpTarget,+ originalUrl: URL,+ init: PinnedHttpRequest,+) => Promise<Response>;++const PROXY_VARIABLES = ['HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'];+const hasAmbientProxy = () => PROXY_VARIABLES.some(key => Boolean(process.env[key]?.trim()));+// Also remember the import-time state because runtimes may cache proxy settings.+const ambientProxyAtImport = hasAmbientProxy();++export class HttpProxyError extends Error {+ readonly code = 'PROXY_NOT_SUPPORTED';+ constructor() {+ super('Guarded URL requests require a direct connection. Remove HTTP_PROXY, HTTPS_PROXY and ALL_PROXY (including lowercase variants), then restart GBrain.');+ this.name = 'HttpProxyError';+ }+}++/** @internal Inject only the raw fetch in hermetic TLS tests. */+export function createPinnedHttpFetch(fetchImpl: typeof fetch): PinnedHttpFetch {+ return async (target, originalUrl, init) => {+ assertSupportedBun();+ if (ambientProxyAtImport || hasAmbientProxy()) throw new HttpProxyError();+ const headers = new Headers(init.headers);+ // Never accept caller-controlled routing headers. Keep non-default ports.+ headers.set('host', originalUrl.host);+ headers.set('connection', 'close');+ headers.set('accept-encoding', 'gzip, deflate, br');+ return fetchImpl(target.resolvedUrl, {+ method: init.method,+ headers,+ body: init.body,+ signal: init.signal,+ redirect: 'manual',+ keepalive: false,+ // Decode ourselves, with a cap on the decoded stream.+ decompress: false,+ ...(originalUrl.protocol === 'https:' ? {+ tls: {+ rejectUnauthorized: true,+ ...(target.originalHost ? { serverName: target.originalHost } : {}),+ },+ } : {}),+ });+ };+}++export const fetchPinnedHttp: PinnedHttpFetch = (...args) => createPinnedHttpFetch(fetch)(...args);++export class HttpBodyError extends Error {+ constructor(readonly code: 'BODY_TOO_LARGE' | 'UNSUPPORTED_ENCODING', message: string) {+ super(message);+ this.name = 'HttpBodyError';+ }+}++/** Consume a finite decoded body, destroying both network and decoder on error. */+export async function readBoundedHttpBody(res: Response, maxBytes: number, signal: AbortSignal): Promise<Buffer> {+ const encoding = (res.headers.get('content-encoding') ?? 'identity').trim().toLowerCase();+ if (!['identity', 'gzip', 'deflate', 'br'].includes(encoding)) {+ await res.body?.cancel();+ throw new HttpBodyError('UNSUPPORTED_ENCODING', 'Unsupported HTTP Content-Encoding');+ }+ // Compressed Content-Length is not the decoded size. The stream limit below+ // remains authoritative for missing, misleading, and compressed lengths.+ const length = res.headers.get('content-length');+ if (encoding === 'identity' && length && /^\d+$/.test(length) && Number(length) > maxBytes) {+ await res.body?.cancel();+ throw new HttpBodyError('BODY_TOO_LARGE', `Response body exceeds ${maxBytes} bytes`);+ }+ if (!res.body) return Buffer.alloc(0);++ const source = Readable.fromWeb(res.body as unknown as NodeReadableStream<Uint8Array>);+ const decoder = encoding === 'gzip' ? createGunzip()+ : encoding === 'deflate' ? createInflate()+ : encoding === 'br' ? createBrotliDecompress() : undefined;+ const stream = decoder ? source.pipe(decoder) : source;+ // pipe() does not forward source errors to the destination.+ const onSourceError = (err: Error) => decoder?.destroy(err);+ source.on('error', onSourceError);+ const abort = () => {+ const err = signal.reason instanceof Error ? signal.reason : new DOMException('Request aborted', 'AbortError');+ source.destroy(err);+ decoder?.destroy(err);+ };+ signal.addEventListener('abort', abort, { once: true });+ const chunks: Buffer[] = [];+ let size = 0;+ try {+ if (signal.aborted) abort();+ for await (const chunk of stream) {+ size += chunk.length;+ if (size > maxBytes) throw new HttpBodyError('BODY_TOO_LARGE', `Response body exceeds ${maxBytes} decoded bytes`);+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));+ }+ signal.throwIfAborted();+ return Buffer.concat(chunks, size);+ } finally {+ signal.removeEventListener('abort', abort);+ source.unpipe(decoder);+ source.destroy();+ decoder?.destroy();+ }+}diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex d7e8442327..e9d70e838c 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -1,3 +1,4 @@+import { readSourceFileSync } from './minions/source-filesystem.ts';import { readFileSync, statSync, lstatSync } from 'fs';import { basename, extname } from 'path';import { createHash } from 'crypto';@@ -1255,7 +1256,7 @@ export async function importFromFile(return { slug: relativePath, status: 'skipped', chunks: 0, error: `File too large (${stat.size} bytes)` };}- let content = readFileSync(filePath, 'utf-8').replace(/^\uFEFF/, ''); // #4798: a BOM is encoding noise, not content+ let content = readSourceFileSync(filePath, 'utf-8').replace(/^\uFEFF/, ''); // #4798: a BOM is encoding noise, not content// Defense-in-depth for callers that bypass the sync/import classifiers// (direct importFromFile, reindex, capture paths): a malformed filename is@@ -2102,7 +2103,7 @@ export async function importImageFile(const linkOpts = opts.sourceId? { fromSourceId: opts.sourceId, toSourceId: opts.sourceId, originSourceId: opts.sourceId }: undefined;- const buf = readFileSync(filePath);+ const buf = readSourceFileSync(filePath);const hash = createHash('sha256').update(buf).digest('hex');const existing = await engine.getPage(imageSlug, sourceOpts);diff --git a/src/core/ingestion/sources/markdown-greenfield.ts b/src/core/ingestion/sources/markdown-greenfield.tsindex 640e892ad6..f1733b9772 100644--- a/src/core/ingestion/sources/markdown-greenfield.ts+++ b/src/core/ingestion/sources/markdown-greenfield.ts@@ -46,7 +46,7 @@import { readFileSync, readdirSync, existsSync, statSync, appendFileSync, mkdirSync } from 'node:fs';import { join, relative, dirname } from 'node:path';import { homedir } from 'node:os';-import matter from 'gray-matter';+import { dataFrontmatter as matter } from '../../data-frontmatter.ts';import { computeContentHash } from '../types.ts';import type {IngestionSource,diff --git a/src/core/markdown.ts b/src/core/markdown.tsindex d17e79eb67..712b30380c 100644--- a/src/core/markdown.ts+++ b/src/core/markdown.ts@@ -1,4 +1,4 @@-import matter from 'gray-matter';+import { dataFrontmatter as matter, FrontmatterLanguageError } from './data-frontmatter.ts';import { safeLoad as yamlSafeLoad } from 'js-yaml';import type { Page, PageType } from './types.ts';import { slugifyPath } from './sync.ts';@@ -260,6 +260,7 @@ export function parseMarkdown(try {parsed = matter(safeContent);} catch (e) {+ if (e instanceof FrontmatterLanguageError && !opts?.validate) throw e;yamlParseError = e as Error;}@@ -269,6 +270,11 @@ export function parseMarkdown(expectedSlug: opts.expectedSlug,parsedFrontmatter: parsed?.data ?? {},});+ // Language selectors do not look like the plain YAML fence expected by+ // structural validation. Keep their rejection visible to ingestion callers.+ if (yamlParseError instanceof FrontmatterLanguageError && !errors.some(error => error.code === 'YAML_PARSE')) {+ errors.push({ code: 'YAML_PARSE', line: 1, message: `YAML parse failed: ${yamlParseError.message}` });+ }}// When YAML parsing failed (rare; gray-matter is forgiving), fall back to@@ -371,7 +377,7 @@ function collectValidationErrors(});return;}- if (lines[firstNonEmpty].trim() !== '---') {+ if (!/^---(?:\s*(?:yaml|yml|json))?\s*$/i.test(lines[firstNonEmpty].trim())) {errors.push({code: 'MISSING_OPEN',message: 'Frontmatter must start with --- on the first non-empty line',diff --git a/src/core/migrate.ts b/src/core/migrate.tsindex a4c9bcf582..0d2a84f04b 100644--- a/src/core/migrate.ts+++ b/src/core/migrate.ts@@ -6516,6 +6516,41 @@ export const MIGRATIONS: Migration[] = [idempotent: true,sql: FACT_WITHDRAWAL_SCHEMA_SQL + FACT_WITHDRAWAL_BACKFILL_SQL,},+ {+ version: 149,+ name: 'minion_submission_authority',+ // NULL preserves unknown legacy provenance; only reviewed local work may backfill it.+ sql: `+ LOCK TABLE minion_jobs IN ACCESS EXCLUSIVE MODE;+ DO $cutover$ BEGIN+ IF EXISTS (SELECT 1 FROM minion_jobs WHERE status = 'active') THEN+ RAISE EXCEPTION 'Drain or cancel active minion jobs and stop all producers/workers before the authority cutover';+ END IF;+ END $cutover$;+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS submission_authority JSONB;+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS claim_generation BIGINT NOT NULL DEFAULT 0;++CREATE OR REPLACE FUNCTION enforce_minion_queue_protocol() RETURNS trigger SET search_path = pg_catalog, public AS $protocol$+BEGIN+ IF TG_OP = 'INSERT' THEN+ IF NEW.submission_authority IS NULL OR NEW.claim_generation <> 0 THEN+ RAISE EXCEPTION 'Minion queue protocol 1 required: upgrade every producer and worker before restart';+ END IF;+ ELSIF NEW.status = 'active' AND (OLD.status <> 'active' OR NEW.lock_token IS DISTINCT FROM OLD.lock_token) THEN+ IF NEW.submission_authority IS NULL OR NEW.claim_generation IS DISTINCT FROM OLD.claim_generation + 1 THEN+ RAISE EXCEPTION 'Minion queue protocol 1 required: old workers cannot claim upgraded queue jobs';+ END IF;+ ELSIF NEW.claim_generation IS DISTINCT FROM OLD.claim_generation THEN+ RAISE EXCEPTION 'Minion queue claim generation may advance only with a claim';+ END IF;+ RETURN NEW;+END;+$protocol$ LANGUAGE plpgsql;+DROP TRIGGER IF EXISTS minion_queue_protocol ON minion_jobs;+CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON minion_jobs+ FOR EACH ROW EXECUTE FUNCTION enforce_minion_queue_protocol();+ `,+ },];export const LATEST_VERSION = MIGRATIONS.length > 0diff --git a/src/core/minions/authorize-legacy.ts b/src/core/minions/authorize-legacy.tsnew file mode 100644index 0000000000..184fe0653d--- /dev/null+++ b/src/core/minions/authorize-legacy.ts@@ -0,0 +1,80 @@+/** Local-only, explicit preview/CAS authorization of pre-cutover job rows. */+import type { BrainEngine } from '../engine.ts';+import { APPLICATION_AUTHORITY, authorityDigest, parseSubmissionAuthority } from './submission-authority.ts';++export function parseLegacyJobIds(raw: string | undefined): number[] {+ if (!raw || !/^\d+(,\d+)*$/.test(raw)) throw new Error('authorize-legacy requires --ids <id,id,...>; implicit/all-job approval is unavailable');+ const ids = [...new Set(raw.split(',').map(Number))].sort((a, b) => a - b);+ if (ids.some(id => !Number.isSafeInteger(id) || id <= 0)) throw new Error('job ids must be positive safe integers');+ return ids;+}++async function snapshot(engine: BrainEngine, ids: number[], lock: boolean) {+ // The controlled cutover normally has no producers. Lock the graph table on+ // apply as well so a descendant insertion/reparent cannot race the CAS.+ if (lock) {+ await engine.executeRaw('LOCK TABLE minion_jobs IN SHARE ROW EXCLUSIVE MODE');+ await engine.executeRaw('LOCK TABLE sources IN SHARE MODE');+ }+ const jobs = await engine.executeRaw<Record<string, unknown>>(+ `SELECT *, submission_authority IS NULL AS legacy_authority_is_null+ FROM minion_jobs WHERE id = ANY($1::int[]) ORDER BY id${lock ? ' FOR UPDATE' : ''}`, [ids]);+ if (jobs.length !== ids.length) throw new Error('One or more selected jobs no longer exist');+ // JSONB null also decodes to JS null. Only the SQL NULL left by the cutover+ // represents historical provenance; never downgrade unknown/versioned authority.+ if (jobs.some(job => job.legacy_authority_is_null !== true)) {+ throw new Error('Every selected job must have SQL NULL submission authority. For unsupported non-NULL authority, use matching application/database versions or explicitly cancel the job locally.');+ }+ const [active] = await engine.executeRaw<{ count: string }>("SELECT count(*)::text AS count FROM minion_jobs WHERE status = 'active'");+ // The controlled upgrade drains before review. Recovery decisions belong to+ // the local operator, never an implicit status/retry rewrite in this command.+ if (Number(active?.count ?? 0)) throw new Error('Drain or cancel all active jobs and stop producers/workers before authorizing legacy jobs');+ const graph = await engine.executeRaw<Record<string, unknown>>(+ `WITH RECURSIVE connected(id) AS (+ SELECT id FROM minion_jobs WHERE id = ANY($1::int[])+ UNION+ SELECT adjacent.id FROM minion_jobs adjacent+ JOIN minion_jobs edge ON adjacent.parent_job_id = edge.id OR adjacent.id = edge.parent_job_id+ JOIN connected c ON edge.id = c.id+ ) SELECT * FROM minion_jobs WHERE id IN (SELECT id FROM connected) ORDER BY id`, [ids]);+ const dependencies = graph.filter(job => !ids.includes(Number(job.id)));+ // Include source registration state in CAS without assuming old payload source+ // fields prove authority. The operator is approving the actual historical work.+ const sources = await engine.executeRaw<Record<string, unknown>>('SELECT id, local_path, config, archived, created_at FROM sources ORDER BY id');+ const version = await engine.getConfig('version');+ const digest = authorityDigest({ preview_version: 1, authority_version: 1, version, jobs, dependencies, sources });+ return {+ preview_version: 1 as const, authority_version: 1 as const, snapshot_digest: digest,+ jobs: jobs.map(job => ({+ id: job.id, name: job.name, status: job.status, data: job.data, previous_authority: job.submission_authority,+ data_digest: authorityDigest(job.data), parent_job_id: job.parent_job_id,+ delay_until: job.delay_until, attempts_made: job.attempts_made,+ })),+ // Full recursive graph, including payload and failure policy, makes downstream+ // cancellation/release effects reviewable. Only the explicitly selected IDs+ // gain authority; graph rows participate in the CAS without being rewritten.+ dependencies: dependencies.map((row): Record<string, unknown> => ({ ...row, claim_generation: String(row.claim_generation) })),+ effects: { implicitly_authorized_ids: [],+ startup_blocking_dependency_ids: dependencies.filter(row =>+ ['waiting', 'active', 'delayed', 'waiting-children', 'paused'].includes(String(row.status)) &&+ !parseSubmissionAuthority(row.submission_authority)).map(row => row.id),+ note: 'Parent completion/failure/cancellation keeps the existing graph policies shown in dependencies.' },+ // No dependency is implicitly authorized; unselected nonterminal legacy rows+ // continue to block worker startup until separately reviewed or cancelled.+ };+}++export async function authorizeLegacyJobs(engine: BrainEngine, ids: number[], expected?: string, yes = false) {+ if (ids.length === 0 || ids.some(id => !Number.isSafeInteger(id) || id <= 0)) throw new Error('Explicit positive job ids required');+ if (!yes && expected === undefined) return { ...(await snapshot(engine, ids, false)), applied: false, authorized: 0 };+ if (!yes || !expected || !/^[a-f0-9]{64}$/.test(expected)) throw new Error('Apply requires BOTH --expect <preview snapshot_digest> and --yes');+ return engine.transaction(async tx => {+ const preview = await snapshot(tx, ids, true);+ if (preview.snapshot_digest !== expected) throw new Error('Legacy authorization snapshot changed; preview and review again');+ const changed = await tx.executeRaw<{ id: number }>(+ `UPDATE minion_jobs SET submission_authority = $2::jsonb+ WHERE id = ANY($1::int[]) AND submission_authority IS NULL RETURNING id`, [ids, APPLICATION_AUTHORITY]);+ if (changed.length !== ids.length) throw new Error('Legacy authorization CAS failed; no jobs authorized');+ return { ...preview, applied: true, authorized: changed.length };+ });+}diff --git a/src/core/minions/delegated-admission.ts b/src/core/minions/delegated-admission.tsindex 9a85fc5cb9..2237e47b07 100644--- a/src/core/minions/delegated-admission.ts+++ b/src/core/minions/delegated-admission.ts@@ -25,7 +25,7 @@ export async function admitDelegatedRetry(tx: BrainEngine, id: number): Promise<if (!rows.length) return false;const { clientId } = prepareDelegatedReplay(rows[0].name, rows[0].data);if (!clientId) return true;- const limit = await lockDelegatedSubmission(tx, clientId, rows[0].name, rows[0].data);+ const limit = await lockDelegatedSubmission(tx, clientId, rows[0].name, rows[0].data, id);// Another retry may have won while this transaction waited for the client.const current = await tx.executeRaw("SELECT id FROM minion_jobs WHERE id=$1 AND status IN ('failed','dead')", [id]);if (!current.length) return false;@@ -34,13 +34,13 @@ export async function admitDelegatedRetry(tx: BrainEngine, id: number): Promise<}/** Caller holds this transaction through any coalescing and the final INSERT. */-export async function lockDelegatedSubmission(tx: BrainEngine, clientId: string | undefined, name: string, data?: Record<string, unknown>): Promise<number | null> {+export async function lockDelegatedSubmission(tx: BrainEngine, clientId: string | undefined, name: string, data?: Record<string, unknown>, jobId?: number): Promise<number | null> {if (!clientId) return null;if (name !== 'subagent' || data?.__owner_client_id !== clientId) throw new Error('invalid delegated submission owner');await tx.executeRaw('SELECT client_id FROM oauth_clients WHERE client_id = $1 FOR UPDATE', [clientId]);const submitted = snapshotFromJob(data);if (!submitted) throw new DelegationDeniedError(['snapshot_missing']);- return (await effectiveDelegation(tx, submitted)).maxConcurrent;+ return (await effectiveDelegation(tx, submitted, jobId)).maxConcurrent;}/** Across every queue and nonterminal state; coalesced existing work adds no slot. */diff --git a/src/core/minions/delegated-policy.ts b/src/core/minions/delegated-policy.tsindex 17aa330295..493dd7e707 100644--- a/src/core/minions/delegated-policy.ts+++ b/src/core/minions/delegated-policy.ts@@ -3,7 +3,7 @@ import { readClientGrant, grantValidationContext, delegationReasons, type Clientimport { validGrantPrefixes, normalizeGrantBrain } from '../grants/model.ts';import { hasScope } from '../scope.ts';import { normalizeSlugPrefix } from '../ops/context.ts';-import { UnrecoverableError } from './types.ts';+import { UnrecoverableError } from './errors.ts';/** Immutable submission ceiling. Current grants may narrow it, never enlarge it. */export interface DelegationSnapshot {diff --git a/src/core/minions/errors.ts b/src/core/minions/errors.tsnew file mode 100644index 0000000000..80bc7884ea--- /dev/null+++ b/src/core/minions/errors.ts@@ -0,0 +1,9 @@+/** Dependency-free handler errors, shared by policy and worker entrypoints. */++/** Throw this from a handler to skip all retry logic and go straight to 'dead'. */+export class UnrecoverableError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'UnrecoverableError';+ }+}diff --git a/src/core/minions/handlers/subagent.ts b/src/core/minions/handlers/subagent.tsindex 827b3b321c..423d6180bc 100644--- a/src/core/minions/handlers/subagent.ts+++ b/src/core/minions/handlers/subagent.ts@@ -37,7 +37,7 @@ import type {import type { BrainEngine } from '../../engine.ts';import type { GBrainConfig } from '../../config.ts';import { loadConfig, isConfigTruthy } from '../../config.ts';-import { buildBrainTools, filterAllowedTools } from '../tools/brain-allowlist.ts';+import { buildBrainTools, selectAllowedTools } from '../tools/brain-allowlist.ts';import {acquireLease,releaseLease,@@ -474,9 +474,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {// #1586: cycle-resolved source scope for tool-call OperationContexts.sourceId: data.source_id,});- const selectedTools = data.allowed_tools !== undefined- ? filterAllowedTools(registry, data.allowed_tools)- : registry;+ const selectedTools = selectAllowedTools(registry, data.allowed_tools);const guardTools = (tools: ToolDef[], deferEmbeds = false) => guardDelegatedTools(engine, config, submitted, ctx.id, tools, deps.toolRegistry !== undefined, deferEmbeds);const toolDefs = guardTools(selectedTools);@@ -546,9 +544,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {// that scoped its job read-only must not gain write capability by// setting mode: oneshot (put_page filtered out → no_put_page_tool// fallback → the equally-filtered loop).- const oneshotSelectedTools = data.allowed_tools !== undefined- ? filterAllowedTools(oneshotRegistry, data.allowed_tools)- : oneshotRegistry;+ const oneshotSelectedTools = selectAllowedTools(oneshotRegistry, data.allowed_tools);const oneshotTools = guardTools(oneshotSelectedTools, true);const outcome = await runSubagentOneshot({engine,diff --git a/src/core/minions/job-context.ts b/src/core/minions/job-context.tsindex 8f982a6291..66dc4efb64 100644--- a/src/core/minions/job-context.ts+++ b/src/core/minions/job-context.ts@@ -28,6 +28,7 @@ export function buildJobContext(id: job.id,name: job.name,data: job.data,+ submission_authority: job.submission_authority,attempts_made: job.attempts_made,signal,deadlineAtMs: job.timeout_at != null ? job.timeout_at.getTime() : null,diff --git a/src/core/minions/plugin-loader.ts b/src/core/minions/plugin-loader.tsindex 665891f879..251e992401 100644--- a/src/core/minions/plugin-loader.ts+++ b/src/core/minions/plugin-loader.ts@@ -32,7 +32,7 @@import * as fs from 'node:fs';import * as path from 'node:path';-import matter from 'gray-matter';+import { dataFrontmatter as matter } from '../data-frontmatter.ts';export const SUPPORTED_PLUGIN_VERSION = 'gbrain-plugin-v1';diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.tsindex 6a3c2546d1..33b178f2e6 100644--- a/src/core/minions/queue.ts+++ b/src/core/minions/queue.ts@@ -8,6 +8,7 @@* await queue.prune({ olderThan: new Date(Date.now() - 30 * 86400000) });*/+import { APPLICATION_AUTHORITY, assertSameAuthority, assertNoUnreviewedJobs, authorizeJobExecution, currentSubmissionAuthority, parseSubmissionAuthority, type SubmissionAuthority } from './submission-authority.ts';import type { BrainEngine } from '../engine.ts';import type {MinionJob, MinionJobInput, MinionJobStatus, InboxMessage, TokenUpdate,@@ -40,6 +41,7 @@ import {} from '../audit/batch-retry-audit.ts';/** Trusted 4th argument, kept outside user-spread job options. */export interface TrustedSubmitOpts {+ submissionAuthority?: SubmissionAuthority;/** Allow PROTECTED_JOB_NAMES; CLI or operation-local callers only. */allowProtectedSubmit?: boolean;/** Allow PGLite embed-backfill only for an explicit inline-worker caller. */@@ -164,7 +166,9 @@ function coalesceReturn(row: Record<string, unknown>,audit: Omit<CoalesceAuditEvent, 'returned_job_id'>,sink: (ev: CoalesceAuditEvent) => void,+ authority: SubmissionAuthority,): MinionJob {+ assertSameAuthority(row.submission_authority, authority);const coalesced = rowToMinionJob(row);coalesced.coalesced = true;sink({ ...audit, returned_job_id: coalesced.id });@@ -212,7 +216,15 @@ export class MinionQueue {// Normalize first so the protected-name check and the insert use the same// canonical form. Without the trim-before-check, `queue.add(' shell ', ...)`// would evade the guard and insert a job literally named 'shell'.+ if (currentSubmissionAuthority() && currentSubmissionAuthority()!.kind !== 'application') throw new Error('Remote jobs cannot submit descendant jobs');+ const authority = parseSubmissionAuthority(trusted?.submissionAuthority ?? APPLICATION_AUTHORITY);+ if (!authority) throw new Error('Unsupported submission authority');+ const delegatedClientId = authority.kind === 'remote_agent' ? authority.principal.id : trusted?.delegatedClientId;+ if (authority.kind === 'remote_agent' && trusted?.delegatedClientId !== undefined && trusted.delegatedClientId !== delegatedClientId) {+ throw new Error('Delegated submission identity differs from its authority');+ }const jobName = (name || '').trim();+ if (authority.kind !== 'application') await authorizeJobExecution(this.engine, { name: jobName, data: data ?? {}, submission_authority: authority });if (jobName.length === 0) {throw new Error('Job name cannot be empty');}@@ -289,6 +301,7 @@ export class MinionQueue {// then insert fresh and run the work twice (adversarial-review finding).const hashablePayload = Object.keys(data ?? {}).some(k => !PARAM_HASH_EXCLUDED_KEYS.has(k));const coalesceActive =+ authority.kind === 'application' &&(opts?.coalesce_params ?? policy.coalesceParams) &&!opts?.parent_job_id &&!opts?.idempotency_key &&@@ -325,7 +338,7 @@ export class MinionQueue {const result = await this.engine.transaction(async (tx) => {// Client lock spans grant validation, capacity check and insertion.- const delegatedLimit = await lockDelegatedSubmission(tx, trusted?.delegatedClientId, jobName, data);+ const delegatedLimit = await lockDelegatedSubmission(tx, delegatedClientId, jobName, data);// 1. Idempotency fast path — if a row already exists for this key, return it// without doing any other work. The unique partial index guarantees// no second row can be inserted with the same non-null key.@@ -341,6 +354,7 @@ export class MinionQueue {);if (existing.length > 0) {const existingJob = rowToMinionJob(existing[0]);+ assertSameAuthority(existingJob.submission_authority, authority);if (existingJob.status === 'dead' || existingJob.status === 'cancelled') {await tx.executeRaw(`UPDATE minion_jobs SET idempotency_key = NULL WHERE id = $1`,@@ -393,11 +407,11 @@ export class MinionQueue {queue: admissionQueue,name: jobName,param_hash: paramHash,- }, ev => { coalesceAudit = ev; });+ }, ev => { coalesceAudit = ev; }, authority);}}- await checkDelegatedCapacity(tx, trusted?.delegatedClientId, delegatedLimit);+ await checkDelegatedCapacity(tx, delegatedClientId, delegatedLimit);// 1a2. Name-global waiting quota (admission; config-only, no shipped// default — user decision D2C). Counts the name across ALL queues:@@ -503,7 +517,7 @@ export class MinionQueue {name: jobName,pending_count: pendingCount,max_pending: maxPending,- }, ev => { coalesceAudit = ev; });+ }, ev => { coalesceAudit = ev; }, authority);}}}@@ -533,7 +547,7 @@ export class MinionQueue {name: jobName,waiting_count: waitingCount,max_waiting: maxWaiting,- }, ev => { coalesceAudit = ev; });+ }, ev => { coalesceAudit = ev; }, authority);}}}@@ -550,6 +564,7 @@ export class MinionQueue {throw new Error(`parent_job_id ${opts.parent_job_id} not found`);}const parent = rowToMinionJob(parentRows[0]);+ if (parent.submission_authority && parent.submission_authority.kind !== 'application') throw new Error('Remote jobs cannot have descendants');depth = parent.depth + 1;if (depth > maxSpawnDepth) {@@ -594,11 +609,11 @@ export class MinionQueue {const baseCols = `name, queue, status, priority, data, max_attempts, backoff_type,backoff_delay, backoff_jitter, delay_until, parent_job_id, on_child_fail,depth, max_children, timeout_ms, lock_duration_ms, remove_on_complete, remove_on_fail, idempotency_key,- quiet_hours, stagger_key, private_queue_owner_job_id, private_queue_owner_token, private_queue_lease_until`;+ quiet_hours, stagger_key, private_queue_owner_job_id, private_queue_owner_token, private_queue_lease_until, submission_authority`;const baseVals = `$1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20::jsonb, $21`;- const baseValsWithOwner = `${baseVals}, $22, $23, $24`;+ const baseValsWithOwner = `${baseVals}, $22, $23, $24, $25::jsonb`;const cols = hasMaxStalled ? `${baseCols}, max_stalled` : baseCols;- const vals = hasMaxStalled ? `${baseValsWithOwner}, $25` : baseValsWithOwner;+ const vals = hasMaxStalled ? `${baseValsWithOwner}, $26` : baseValsWithOwner;const insertSql = opts?.idempotency_key? `INSERT INTO minion_jobs (${cols})@@ -644,6 +659,7 @@ export class MinionQueue {opts?.private_queue_owner_job_id ?? null,opts?.private_queue_owner_token ?? null,privateQueueLeaseUntil,+ authority,];if (hasMaxStalled) params.push(clampedMaxStalled);@@ -660,6 +676,7 @@ export class MinionQueue {throw new Error(`idempotency_key ${opts.idempotency_key} insert returned no row and no existing row found`);}const raced = rowToMinionJob(existing[0]);+ assertSameAuthority(raced.submission_authority, authority);raced.coalesced = true; // third coalesce path: lost the insert racereturn raced;}@@ -885,6 +902,7 @@ export class MinionQueue {reason?: string;maxQueues?: number;} = {}): Promise<PrivateQueueRecoveryResult> {+ await assertNoUnreviewedJobs(this.engine);const result: PrivateQueueRecoveryResult = {scanned_queues: 0,cancelled_queues: 0,@@ -1151,6 +1169,7 @@ export class MinionQueue {* (the channel where the notice prints); this method just sweeps.*/async handleWaitingTTL(opts?: { maxPerTick?: number }): Promise<{ cancelled: number; by_name: Record<string, number> }> {+ await assertNoUnreviewedJobs(this.engine);const maxPerTick = Math.max(1, Math.floor(opts?.maxPerTick ?? 500));const ttlNames = await resolveTtlNames(this.engine);const by_name: Record<string, number> = {};@@ -1217,6 +1236,9 @@ export class MinionQueue {*/async retryJob(id: number): Promise<MinionJob | null> {return this.engine.transaction(async tx => {+ const [prior] = await tx.executeRaw<Record<string, unknown>>('SELECT * FROM minion_jobs WHERE id = $1', [id]);+ if (!prior) return null;+ await authorizeJobExecution(tx, rowToMinionJob(prior));if (!await admitDelegatedRetry(tx, id)) return null;const rows = await tx.executeRaw<Record<string, unknown>>(`UPDATE minion_jobs SET status = 'waiting', error_text = NULL,@@ -1435,6 +1457,7 @@ export class MinionQueue {*/async claim(lockToken: string, lockDurationMs: number, queue: string, registeredNames: string[]): Promise<MinionJob | null> {if (registeredNames.length === 0) return null;+ await assertNoUnreviewedJobs(this.engine);// Direct (session-mode) pool: claim opens the lock that renewLock then// heartbeats. Both must live on a connection the transaction-mode pooler@@ -1454,6 +1477,7 @@ export class MinionQueue {const rows = await this.engine.executeRawDirect<Record<string, unknown>>(`UPDATE minion_jobs SETstatus = 'active',+ claim_generation = claim_generation + 1,lock_token = $1,lock_until = now() + ((CASE WHEN COALESCE(lock_duration_ms, ($6::jsonb ->> name)::int) IS NULL THEN $2ELSE LEAST(GREATEST(COALESCE(lock_duration_ms, ($6::jsonb ->> name)::int), 5000), 3600000) END)::double precision * interval '1 millisecond'),@@ -1468,7 +1492,7 @@ export class MinionQueue {updated_at = now()WHERE id = (SELECT id FROM minion_jobs- WHERE queue = $3 AND status = 'waiting' AND name = ANY($4)+ WHERE queue = $3 AND status = 'waiting' AND submission_authority IS NOT NULL AND name = ANY($4)ORDER BY priority ASC, created_at ASCFOR UPDATE SKIP LOCKEDLIMIT 1@@ -1492,6 +1516,7 @@ export class MinionQueue {* but will be caught the next one (after re-claim). Never double-handled.*/async handleTimeouts(): Promise<MinionJob[]> {+ await assertNoUnreviewedJobs(this.engine);return this.engine.transaction(async (tx) => {// #1737: count the timed-out run as a spent attempt (terminal, no retry).// Safe against double-count: the worker sweep runs handleStalled ->@@ -1631,6 +1656,7 @@ export class MinionQueue {* timeout_ms null -> 2 * lockDurationMs * max_stalled*/async handleWallClockTimeouts(lockDurationMs: number): Promise<MinionJob[]> {+ await assertNoUnreviewedJobs(this.engine);return this.engine.transaction(async (tx) => {// W0 (D5.12): same parents-first discover/lock/kill shape as// handleTimeouts; shared tail in killJobs().@@ -2047,6 +2073,7 @@ export class MinionQueue {/** Promote delayed jobs whose delay_until has passed. Returns promoted jobs. */async promoteDelayed(): Promise<MinionJob[]> {+ await assertNoUnreviewedJobs(this.engine);const rows = await this.lockRetry(() => this.engine.executeRaw<Record<string, unknown>>(`UPDATE minion_jobs SET status = 'waiting', delay_until = NULL,started_at = NULL,@@ -2059,6 +2086,7 @@ export class MinionQueue {/** Detect and handle stalled jobs. Single CTE, no off-by-one. Returns affected jobs. */async handleStalled(graceMsOverride?: number): Promise<{ requeued: MinionJob[]; dead: MinionJob[] }> {+ await assertNoUnreviewedJobs(this.engine);// W0 fix-wave (Tier-1 #4): the dead-letter branch previously emitted NO// child_done and never unblocked aggregator parents — a child that died// via max-stall stranded its parent in 'waiting-children' forever (the@@ -2197,6 +2225,9 @@ export class MinionQueue {/** Resume a paused job back to waiting. */async resumeJob(id: number): Promise<MinionJob | null> {+ const prior = await this.getJob(id);+ if (!prior) return null;+ await authorizeJobExecution(this.engine, prior);const rows = await this.engine.executeRaw<Record<string, unknown>>(`UPDATE minion_jobs SET status = 'waiting',lock_token = NULL, lock_until = NULL, updated_at = now()@@ -2266,6 +2297,8 @@ export class MinionQueue {const source = await this.getJob(id);if (!source) return null;if (!['completed', 'failed', 'dead'].includes(source.status)) return null;+ const authority = await authorizeJobExecution(this.engine, source);+ if (authority.kind !== 'application' && dataOverrides && Object.keys(dataOverrides).length) throw new Error('Remote job replay cannot override accepted data; submit a new job');const { data, clientId } = prepareDelegatedReplay(source.name, source.data, dataOverrides);@@ -2276,7 +2309,8 @@ export class MinionQueue {backoff_type: source.backoff_type,backoff_delay: source.backoff_delay,backoff_jitter: source.backoff_jitter,- }, clientId ? { allowProtectedSubmit: true, delegatedClientId: clientId } : undefined);+ }, { submissionAuthority: authority, delegatedClientId: clientId,+ allowProtectedSubmit: authority.kind === 'remote_agent' || (authority.kind === 'application' && isProtectedJobName(source.name)) });}/** Remove a child's dependency on its parent. */diff --git a/src/core/minions/run-child.ts b/src/core/minions/run-child.tsindex ecc872e1be..e2e2b60fa4 100644--- a/src/core/minions/run-child.ts+++ b/src/core/minions/run-child.ts@@ -1,3 +1,4 @@+import { authorizeJobExecution, withSubmissionAuthority } from './submission-authority.ts';/*** `gbrain jobs run-child` core (issue #5 — per-job process isolation).*@@ -152,7 +153,8 @@ export async function runChildJobEntry(try {// #4218: same phase attribution as the in-process worker path — the// isolated child runs its own gateway, so the wrap must live here too.- const result = await withChatPhase(`job:${job.name}`, () => handler(context));+ const authority = await authorizeJobExecution(engine, job);+ const result = await withSubmissionAuthority(authority, () => withChatPhase(`job:${job.name}`, () => handler(context)), abort.signal);// completeJob's {value: x} wrap decision must run BEFORE JSON// serialization: a JSON round-trip changes typeof for Date /// toJSON-bearing results (object → string), which would flip the wrapdiff --git a/src/core/minions/source-filesystem.ts b/src/core/minions/source-filesystem.tsnew file mode 100644index 0000000000..4225600f26--- /dev/null+++ b/src/core/minions/source-filesystem.ts@@ -0,0 +1,137 @@+/** Filesystem boundary for the four generic remote jobs; not an OS sandbox.+ * Trust model excludes hostile concurrent same-UID or cross-brain writers.+ * Cooperating writers in this brain share the canonical worktree lock.+ */+import { AsyncLocalStorage } from 'node:async_hooks';+import { setTimeout as delay } from 'node:timers/promises';+import { closeSync, constants, fstatSync, ftruncateSync, lstatSync, openSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';+import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { LockStolenError, LockUnavailableError, withRefreshingLock } from '../db-lock.ts';+import { discoverGitRoot } from '../sync-git.ts';+import { authorityDigest, currentRemoteJobAuthority, currentJobSignal } from './submission-authority.ts';++const heldRoots = new AsyncLocalStorage<ReadonlySet<string>>();+const filesystemSignal = new AsyncLocalStorage<AbortSignal>();+const filesystemLeases = new AsyncLocalStorage<Array<{ key: string; lost: boolean }>>();+export function currentSourceFilesystemSignal(): AbortSignal | undefined {+ const local = filesystemSignal.getStore(), job = currentJobSignal();+ return local && job && local !== job ? AbortSignal.any([local, job]) : local ?? job;+}+export function assertSourceFilesystemActive(allowCallerAbort = false): void {+ // Lease ownership is independent of caller cancellation: a timeout racing a+ // later lease loss must never hide the loss behind a resumable partial result.+ for (const lease of filesystemLeases.getStore() ?? []) if (lease.lost) throw new LockStolenError(lease.key);+ if (allowCallerAbort) return;+ const signal = currentSourceFilesystemSignal();+ // Some Bun versions drop an asynchronously created AbortSignal reason.+ if (signal?.aborted) throw signal.reason ?? new DOMException('Source filesystem work cancelled or lock lease lost', 'AbortError');+}+function lockRoot(path: string): string {+ let canonical = resolve(path);+ try { canonical = realpathSync(canonical); } catch { /* local initialization may create it */ }+ try { if (statSync(canonical).isFile()) canonical = dirname(canonical); } catch { /* nonexistent local target */ }+ try { return realpathSync(discoverGitRoot(canonical)); } catch { return canonical; }+}+function encloses(root: string, path: string): boolean {+ const rel = relative(root, path);+ return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);+}+export function hasSourceFilesystemLock(path: string): boolean {+ const canonical = lockRoot(path);+ return [...heldRoots.getStore() ?? []].some(root => encloses(root, canonical));+}+async function registeredLockRoot(engine: BrainEngine, path: string): Promise<string> {+ let root = lockRoot(path);+ const sources = await engine.executeRaw<{ local_path: string }>(`SELECT local_path FROM sources WHERE local_path IS NOT NULL AND local_path <> ''`);+ // A registered non-Git parent can contain a Git source. Canonicalize every+ // registered source through the same worktree rule, then choose the outermost+ // ancestor so overlapping sources agree regardless of which one starts first.+ for (const source of sources) {+ const candidate = lockRoot(source.local_path);+ if (encloses(candidate, root)) root = candidate;+ }+ return root;+}+export async function withSourceFilesystemLock<T>(engine: BrainEngine, path: string, fn: () => Promise<T>, opts: { signal?: AbortSignal; waitMs?: number } = {}): Promise<T> {+ assertSourceFilesystemActive();+ if (hasSourceFilesystemLock(path)) return fn();+ const root = await registeredLockRoot(engine, path);+ const held = new Set(heldRoots.getStore() ?? []);+ held.add(root);+ const key = `gbrain-fs:${authorityDigest(root)}`;+ const inheritedSignal = currentSourceFilesystemSignal();+ const signal = opts.signal && inheritedSignal ? AbortSignal.any([opts.signal, inheritedSignal]) : opts.signal ?? inheritedSignal;+ const deadline = Date.now() + (opts.waitMs ?? 5000);+ for (;;) {+ signal?.throwIfAborted();+ let entered = false;+ try {+ const lost = new AbortController();+ const lease = { key, lost: false };+ const activeSignal = signal ? AbortSignal.any([signal, lost.signal]) : lost.signal;+ return await withRefreshingLock(engine, key, () => {+ entered = true;+ return heldRoots.run(held, () => filesystemLeases.run([...(filesystemLeases.getStore() ?? []), lease], () => filesystemSignal.run(activeSignal, async () => {+ assertSourceFilesystemActive();+ const result = await fn();+ assertSourceFilesystemActive();+ return result;+ })));+ }, { onLockLost: reason => { lease.lost = true; lost.abort(reason); } });+ } catch (err) {+ // Retry acquisition only: never rerun a partially executed callback.+ if (entered || !(err instanceof LockUnavailableError) || err.lockId !== key || Date.now() >= deadline) throw err;+ await delay(Math.min(50, Math.max(1, deadline - Date.now())), undefined, { signal });+ }+ }+}++export function assertSourceFilePath(path: string): string {+ assertSourceFilesystemActive();+ const authority = currentRemoteJobAuthority();+ if (!authority) return path;+ const root = authority.grant.canonicalRoot;+ if (realpathSync(root) !== root) throw new Error('Source root changed during job');+ const absolute = resolve(path);+ const rel = relative(root, absolute);+ if (!rel || isAbsolute(rel) || rel === '..' || rel.startsWith(`..${sep}`)) throw new Error('Source file escapes registered root');+ let component = root;+ for (const part of rel.split(sep)) {+ component = resolve(component, part);+ if (lstatSync(component).isSymbolicLink()) throw new Error('Remote source jobs do not follow symlinks');+ }+ const real = realpathSync(absolute);+ const realRel = relative(root, real);+ if (isAbsolute(realRel) || realRel === '..' || realRel.startsWith(`..${sep}`)) throw new Error('Source file escapes registered root');+ return real;+}++function openSourceFile(path: string, write: boolean): number {+ const real = assertSourceFilePath(path);+ if (constants.O_NOFOLLOW === undefined) throw new Error('Remote filesystem jobs require O_NOFOLLOW support');+ const fd = openSync(real, (write ? constants.O_WRONLY : constants.O_RDONLY) | constants.O_NOFOLLOW);+ try {+ if (!fstatSync(fd).isFile()) throw new Error('Source path must identify a regular file');+ // Parent-directory checks and final-descriptor checks are complementary;+ // the descriptor is retained through I/O rather than reopening the path.+ assertSourceFilePath(real);+ return fd;+ } catch (err) { closeSync(fd); throw err; }+}+export function readSourceFileSync(path: string): Buffer;+export function readSourceFileSync(path: string, encoding: BufferEncoding): string;+export function readSourceFileSync(path: string, encoding?: BufferEncoding): Buffer | string {+ assertSourceFilesystemActive();+ if (!currentRemoteJobAuthority()) return encoding ? readFileSync(path, encoding) : readFileSync(path);+ const fd = openSourceFile(path, false);+ try { return encoding ? readFileSync(fd, encoding) : readFileSync(fd); }+ finally { closeSync(fd); }+}+export function writeSourceFileSync(path: string, content: string): void {+ assertSourceFilesystemActive();+ if (!currentRemoteJobAuthority()) { writeFileSync(path, content); return; }+ const fd = openSourceFile(path, true);+ try { assertSourceFilesystemActive(); ftruncateSync(fd, 0); writeFileSync(fd, content); }+ finally { closeSync(fd); }+}diff --git a/src/core/minions/submission-authority.ts b/src/core/minions/submission-authority.tsnew file mode 100644index 0000000000..e33b27fd59--- /dev/null+++ b/src/core/minions/submission-authority.ts@@ -0,0 +1,274 @@+/** Durable authority for queued work. Payloads and caller-spread options are never authority. */+import { AsyncLocalStorage } from 'node:async_hooks';+import { createHash } from 'node:crypto';+import { realpathSync, statSync } from 'node:fs';+import type { BrainEngine } from '../engine.ts';+import type { AuthInfo, OperationContext } from '../ops/contract.ts';+import { OperationError } from '../ops/contract.ts';+import { normalizeSlugPrefix } from '../ops/context.ts';+import { hasScope } from '../scope.ts';+import { coerceLegacyPermissions, normalizeTokenScopes, parseLegacyTokenScope } from '../legacy-token-scope.ts';+import { isValidSourceId } from '../source-id.ts';+import { discoverGitRoot } from '../sync-git.ts';+import type { MinionJob } from './types.ts';+import { effectiveDelegation, snapshotFromJob } from './delegated-policy.ts';++export const REMOTE_JOB_NAMES = ['sync', 'import', 'lint', 'lint-fix'] as const;+export type RemoteJobName = typeof REMOTE_JOB_NAMES[number];+export type SubmissionAuthority = { version: 1; kind: 'application' } | RemoteJobAuthority | RemoteAgentAuthority;+export interface RemoteAgentAuthority {+ version: 1;+ kind: 'remote_agent';+ principal: { kind: 'oauth_client'; id: string };+ grant: { scopes: string[]; sourceId: string; sourceCreatedAt: string; allowedTools: string[]; allowedSlugPrefixes: string[] };+ payloadHash: string;+}+export interface RemoteJobAuthority {+ version: 1;+ kind: 'remote_generic';+ principal: NonNullable<AuthInfo['principal']>;+ grant: {+ scopes: string[];+ sourceId: string;+ sourceCreatedAt: string;+ canonicalRoot: string;+ worktreeRoot: string | null;+ jobName: RemoteJobName;+ allowedOperations?: string[] | null;+ };+ payloadHash: string;+}+export const APPLICATION_AUTHORITY: SubmissionAuthority = Object.freeze({ version: 1, kind: 'application' });+const executionAuthority = new AsyncLocalStorage<{ authority: SubmissionAuthority; signal?: AbortSignal }>();+export function currentSubmissionAuthority(): SubmissionAuthority | undefined { return executionAuthority.getStore()?.authority; }+export function currentRemoteJobAuthority(): RemoteJobAuthority | undefined {+ const a = executionAuthority.getStore()?.authority;+ return a?.kind === 'remote_generic' ? a : undefined;+}+export function currentJobSignal(): AbortSignal | undefined { return executionAuthority.getStore()?.signal; }+export function withSubmissionAuthority<T>(authority: SubmissionAuthority, fn: () => T, signal?: AbortSignal): T {+ return executionAuthority.run({ authority, signal }, fn);+}+function deny(message: string): never {+ throw new OperationError('permission_denied', `Queued job authorization: ${message}`);+}+function record(value: unknown): Record<string, unknown> | undefined {+ return value !== null && typeof value === 'object' && !Array.isArray(value)+ ? value as Record<string, unknown> : undefined;+}+/** Stable digest also used by local legacy-review CAS; no credentials are hashed into payloads. */+export function authorityDigest(value: unknown): string {+ const stable = (v: unknown): unknown => Array.isArray(v) ? v.map(stable)+ : typeof v === 'bigint' ? v.toString()+ : v instanceof Date ? v.toISOString()+ : record(v) ? Object.fromEntries(Object.keys(v as object).sort().map(k => [k, stable((v as Record<string, unknown>)[k])]))+ : v;+ return createHash('sha256').update(JSON.stringify(stable(value))).digest('hex');+}+export function parseSubmissionAuthority(value: unknown): SubmissionAuthority | null {+ if (typeof value === 'string') { try { value = JSON.parse(value); } catch { return null; } }+ const a = record(value);+ if (a?.version !== 1) return null;+ if (a.kind === 'application') return APPLICATION_AUTHORITY;+ const p = record(a.principal), g = record(a.grant);+ if (a.kind === 'remote_agent') {+ if (p?.kind !== 'oauth_client' || typeof p.id !== 'string' || !p.id || !g ||+ !Array.isArray(g.scopes) || !g.scopes.every(v => typeof v === 'string') ||+ typeof g.sourceId !== 'string' || !isValidSourceId(g.sourceId) || typeof g.sourceCreatedAt !== 'string' ||+ !Array.isArray(g.allowedTools) || !g.allowedTools.length || !g.allowedTools.every(v => typeof v === 'string' && v.length) ||+ !Array.isArray(g.allowedSlugPrefixes) || !g.allowedSlugPrefixes.every(v => typeof v === 'string') ||+ typeof a.payloadHash !== 'string' || !/^[a-f0-9]{64}$/.test(a.payloadHash)) return null;+ return structuredClone(a) as unknown as RemoteAgentAuthority;+ }+ if (a.kind !== 'remote_generic' || !p || !g ||+ !['oauth_client', 'legacy_token'].includes(String(p.kind)) || typeof p.id !== 'string' || !p.id ||+ !Array.isArray(g.scopes) || !g.scopes.every(s => typeof s === 'string') ||+ (g.allowedOperations !== undefined && g.allowedOperations !== null &&+ (!Array.isArray(g.allowedOperations) || !g.allowedOperations.every(op => typeof op === 'string' && op.length))) ||+ typeof g.sourceId !== 'string' || !isValidSourceId(g.sourceId) ||+ typeof g.sourceCreatedAt !== 'string' || typeof g.canonicalRoot !== 'string' || !g.canonicalRoot ||+ !(g.worktreeRoot === null || typeof g.worktreeRoot === 'string') ||+ !REMOTE_JOB_NAMES.includes(g.jobName as RemoteJobName) || typeof a.payloadHash !== 'string' ||+ !/^[a-f0-9]{64}$/.test(a.payloadHash)) return null;+ return structuredClone(a) as unknown as RemoteJobAuthority;+}+export function assertSameAuthority(actual: unknown, expected: SubmissionAuthority): void {+ const parsed = parseSubmissionAuthority(actual);+ if (!parsed || authorityDigest(parsed) !== authorityDigest(expected)) deny('coalescing across submission authorities is forbidden');+}++async function sourceBoundary(engine: BrainEngine, sourceId: string, jobName: RemoteJobName) {+ const [source] = await engine.executeRaw<Record<string, unknown>>(+ 'SELECT id, local_path, config, archived, created_at FROM sources WHERE id = $1', [sourceId]);+ if (!source || source.archived !== false || typeof source.local_path !== 'string' || !source.local_path) {+ deny('an active source with a registered filesystem root is required');+ }+ let config = source.config;+ if (typeof config === 'string') { try { config = JSON.parse(config); } catch { deny('malformed source config'); } }+ if (!record(config) || record(config)!.kind != null) deny('generic filesystem jobs require an ordinary filesystem source; use the dedicated connector endpoint');+ let canonicalRoot: string;+ try {+ canonicalRoot = realpathSync(source.local_path);+ if (!statSync(canonicalRoot).isDirectory()) deny('registered source root must be a directory');+ } catch { deny('registered source root is unavailable or is not a directory'); }+ let worktreeRoot: string | null = null;+ try { worktreeRoot = realpathSync(discoverGitRoot(canonicalRoot)); }+ catch { if (jobName === 'sync') deny('remote sync requires an existing Git working tree; initialize or restore it locally'); }+ return { canonicalRoot, worktreeRoot, sourceCreatedAt: new Date(source.created_at as string).toISOString() };+}++async function assertCurrentPrincipal(engine: BrainEngine, authority: RemoteJobAuthority): Promise<void> {+ const { principal, grant } = authority;+ let scopes: string[], sourceId: string | undefined;+ if (principal.kind === 'oauth_client') {+ // No fallback projections: an incomplete auth schema cannot authorize background work.+ const [row] = await engine.executeRaw<Record<string, unknown>>(+ 'SELECT client_id, deleted_at, scope, source_id, bound_slug_prefixes, surface, allowed_operations FROM oauth_clients WHERE client_id = $1', [principal.id]);+ if (!row || row.deleted_at != null) deny('OAuth client is missing or revoked');+ scopes = typeof row.scope === 'string' ? row.scope.split(/\s+/).filter(Boolean) : [];+ sourceId = typeof row.source_id === 'string' ? row.source_id : undefined;+ if (row.bound_slug_prefixes != null) deny('bulk filesystem jobs are unavailable to slug-bound clients');+ if (row.surface != null && row.surface !== 'full') deny('current client surface does not permit generic jobs');+ for (const operations of [grant.allowedOperations, row.allowed_operations]) {+ if (operations != null && (!Array.isArray(operations) || !operations.every(op => typeof op === 'string') || !operations.includes('submit_job'))) {+ deny('original and current operation grants must authorize submit_job');+ }+ }+ } else {+ const [row] = await engine.executeRaw<Record<string, unknown>>(+ 'SELECT id, revoked_at, scopes, permissions FROM access_tokens WHERE id = $1', [principal.id]);+ if (!row || row.revoked_at != null) deny('legacy token is missing or revoked');+ scopes = normalizeTokenScopes(row.scopes) ?? ['read', 'write', 'admin'];+ if (row.permissions != null && !coerceLegacyPermissions(row.permissions)) deny('malformed token permissions');+ sourceId = parseLegacyTokenScope(coerceLegacyPermissions(row.permissions)?.source_id).sourceId;+ }+ if (!hasScope(grant.scopes, 'admin') || !hasScope(scopes, 'admin') || sourceId !== grant.sourceId) {+ deny('the original grant and current principal must both authorize this source and admin operation');+ }+}++export async function prepareRemoteJob(+ ctx: OperationContext, name: string, input: unknown,+): Promise<{ data: Record<string, unknown>; authority: RemoteJobAuthority }> {+ if (!REMOTE_JOB_NAMES.includes(name as RemoteJobName)) deny('unsupported remote job; only sync, import, lint and lint-fix are available through remote submit_job');+ const principal = ctx.auth?.principal;+ const sourceId = ctx.auth?.sourceId;+ if (!principal || !sourceId || !isValidSourceId(sourceId) || ctx.sourceId !== sourceId || !hasScope(ctx.auth?.scopes ?? [], 'admin')) {+ deny('an authenticated persistent principal and scalar write source are required; use local CLI or a dedicated operation');+ }+ if (ctx.auth?.boundSlugPrefixes !== undefined || ctx.auth?.fenceProjectionDegraded) deny('bulk filesystem jobs require an unrestricted source grant');+ const raw = input === undefined ? {} : record(input);+ if (!raw) deny('job data must be an object');+ const allowed = name === 'sync' ? ['pull', 'noPull'] : [];+ for (const key of Object.keys(raw)) if (!allowed.includes(key)) deny('unsupported remote job parameter');+ for (const key of allowed) if (raw[key] !== undefined && typeof raw[key] !== 'boolean') deny(`${key} must be a boolean`);+ if (raw.pull !== undefined && raw.noPull !== undefined) deny('supply only one of pull and noPull');+ const boundary = await sourceBoundary(ctx.engine, sourceId, name as RemoteJobName);+ const wholeWorktree = boundary.canonicalRoot === boundary.worktreeRoot;+ const pull = raw.pull ?? (raw.noPull !== undefined ? !raw.noPull : wholeWorktree);+ if (name === 'sync' && pull && !wholeWorktree) deny('pull is unavailable for a source nested inside another Git working tree');+ const data: Record<string, unknown> = name === 'sync'+ ? { repoPath: boundary.canonicalRoot, sourceId, noPull: !pull, noEmbed: true, noExtract: true, auto_embed_backfill: false }+ : { dir: boundary.canonicalRoot, sourceId, ...(name === 'import' ? { noEmbed: true } : {}) };+ const authority: RemoteJobAuthority = {+ version: 1, kind: 'remote_generic', principal: { ...principal },+ grant: { scopes: [...ctx.auth!.scopes], sourceId, ...boundary, jobName: name as RemoteJobName,+ allowedOperations: ctx.auth?.allowedOperations == null ? null : [...ctx.auth.allowedOperations] },+ payloadHash: authorityDigest(data),+ };+ await assertCurrentPrincipal(ctx.engine, authority);+ return { data, authority };+}++const toolName = (name: string) => name.replace(/^(?:brain_|mcp__gbrain__)/, '');++async function assertCurrentAgent(engine: BrainEngine, a: RemoteAgentAuthority, data: Record<string, unknown>, jobId?: number): Promise<void> {+ const [source] = await engine.executeRaw<Record<string, unknown>>('SELECT archived, created_at FROM sources WHERE id = $1', [a.grant.sourceId]);+ if (!source || source.archived !== false || new Date(source.created_at as string).toISOString() !== a.grant.sourceCreatedAt) deny('agent source is missing, archived, or was replaced');+ if (data.__delegation_grant !== undefined) {+ const submitted = snapshotFromJob(data);+ if (!submitted || submitted.clientId !== a.principal.id || submitted.sourceId !== a.grant.sourceId+ || authorityDigest(submitted.tools) !== authorityDigest(a.grant.allowedTools)+ || authorityDigest(submitted.slugPrefixes) !== authorityDigest(a.grant.allowedSlugPrefixes)+ || !hasScope(a.grant.scopes, 'agent')) deny('delegation snapshot differs from its accepted authority');+ // Direct and delegated namespaces are independent. The current grant may+ // narrow tools/paths, while the submitted snapshot remains the ceiling.+ await effectiveDelegation(engine, submitted, jobId);+ return;+ }+ // Preserve the older explicit authority shape for already accepted jobs.+ const [row] = await engine.executeRaw<Record<string, unknown>>(+ 'SELECT deleted_at, scope, source_id, bound_tools, bound_source_id, bound_slug_prefixes FROM oauth_clients WHERE client_id = $1', [a.principal.id]);+ if (!row || row.deleted_at != null) deny('agent owner is missing or revoked');+ const scopes = typeof row.scope === 'string' ? row.scope.split(/\s+/) : [];+ if (!hasScope(a.grant.scopes, 'agent') || !hasScope(scopes, 'agent')) deny('original and current grants must include agent scope');+ if (row.source_id !== a.grant.sourceId || (row.bound_source_id != null && row.bound_source_id !== a.grant.sourceId)) deny('agent source grant changed');+ if (!Array.isArray(row.bound_tools) || !row.bound_tools.length ||+ !row.bound_tools.every(t => typeof t === 'string' && t.length && !['file_list', 'file_url'].includes(toolName(t)))) deny('current agent tool binding is empty or unsupported');+ const tools = row.bound_tools.map(t => toolName(t as string));+ if (a.grant.allowedTools.some(t => !tools.includes(toolName(t)))) deny('accepted agent tools are outside the current binding');+ const prefixes = row.bound_slug_prefixes;+ if (prefixes != null) {+ if (!Array.isArray(prefixes) || !prefixes.length || !prefixes.every(p => typeof p === 'string' && p.length) || !a.grant.allowedSlugPrefixes.length) deny('agent slug binding changed');+ for (const granted of a.grant.allowedSlugPrefixes) {+ const requested = normalizeSlugPrefix(granted);+ if (!prefixes.some(p => { const base = normalizeSlugPrefix(p as string); return base && (base.endsWith('/') ? requested.startsWith(base) : requested === base || requested.startsWith(`${base}/`)); })) deny('accepted agent slug grant is outside the current binding');+ }+ }+}++export async function prepareRemoteAgent(ctx: OperationContext, data: Record<string, unknown>): Promise<RemoteAgentAuthority> {+ const principal = ctx.auth?.principal;+ if (principal?.kind !== 'oauth_client' || principal.id !== ctx.auth?.clientId || !hasScope(ctx.auth?.scopes ?? [], 'agent') ||+ typeof data.source_id !== 'string' || data.source_id !== ctx.auth?.sourceId || !isValidSourceId(data.source_id)) deny('submit_agent requires a verified OAuth principal and scalar source grant');+ const [source] = await ctx.engine.executeRaw<Record<string, unknown>>('SELECT archived, created_at FROM sources WHERE id = $1', [data.source_id]);+ if (!source || source.archived !== false) deny('agent source must be active');+ const authority: RemoteAgentAuthority = {+ version: 1, kind: 'remote_agent', principal: { kind: 'oauth_client', id: principal.id },+ grant: { scopes: [...ctx.auth!.scopes], sourceId: data.source_id, sourceCreatedAt: new Date(source.created_at as string).toISOString(),+ allowedTools: [...data.allowed_tools as string[]], allowedSlugPrefixes: [...data.allowed_slug_prefixes as string[]] },+ payloadHash: authorityDigest(data),+ };+ if (!parseSubmissionAuthority(authority)) deny('invalid agent grant');+ await assertCurrentAgent(ctx.engine, authority, data);+ return authority;+}++/** Runs in BOTH inline and isolated workers, immediately before the handler. */+export async function authorizeJobExecution(engine: BrainEngine, job: Pick<MinionJob, 'name' | 'data' | 'submission_authority'> & Partial<Pick<MinionJob, 'id'>>): Promise<SubmissionAuthority> {+ const a = parseSubmissionAuthority(job.submission_authority);+ if (!a) deny('missing or unsupported submission authority; review locally with jobs authorize-legacy');+ if (a.kind === 'application') return a;+ if (a.kind === 'remote_agent') {+ if (job.name !== 'subagent' || authorityDigest(job.data) !== a.payloadHash) deny('agent payload differs from its accepted grant');+ await assertCurrentAgent(engine, a, job.data, job.id);+ return a;+ }+ if (job.name !== a.grant.jobName || authorityDigest(job.data) !== a.payloadHash) deny('job data or name differs from its accepted grant');+ await assertCurrentPrincipal(engine, a);+ const boundary = await sourceBoundary(engine, a.grant.sourceId, a.grant.jobName);+ for (const key of ['canonicalRoot', 'worktreeRoot', 'sourceCreatedAt'] as const) {+ if (boundary[key] !== a.grant[key]) deny('source registration or filesystem root changed; submit a new job');+ }+ return a;+}++export async function assertRemoteJobControl(ctx: OperationContext, job: MinionJob, overrides?: unknown): Promise<void> {+ if (ctx.remote === false) return;+ const a = parseSubmissionAuthority(job.submission_authority);+ if (!a || a.kind === 'application' || !ctx.auth?.principal ||+ authorityDigest(a.principal) !== authorityDigest(ctx.auth.principal)) deny('only the submitting principal may restart a generic remote job');+ if (overrides !== undefined && (!record(overrides) || Object.keys(overrides as object).length)) deny('replay overrides are unavailable remotely; submit a new job');+ if (!hasScope(ctx.auth.scopes, 'admin') || ctx.auth.sourceId !== a.grant.sourceId) deny('current request is outside the original grant');+ await authorizeJobExecution(ctx.engine, job);+}++/** Startup and claim gate: do not let sweeps silently destroy unresolved legacy dependency graphs. */+export async function assertNoUnreviewedJobs(engine: BrainEngine): Promise<void> {+ const rows = await engine.executeRaw<{ id: number; submission_authority: unknown }>(+ `SELECT id, submission_authority FROM minion_jobs+ WHERE status IN ('waiting','active','delayed','waiting-children','paused')+ AND submission_authority IS DISTINCT FROM '{"version":1,"kind":"application"}'::jsonb`);+ const invalid = rows.filter(row => !parseSubmissionAuthority(row.submission_authority));+ if (invalid.length) deny(`${invalid.length} legacy jobs have missing or unsupported authority; stop producers/workers. Review SQL NULL rows with jobs authorize-legacy --ids ...; unsupported non-NULL authority requires matching application/database versions or explicit local cancellation before workers start`);+}diff --git a/src/core/minions/tools/brain-allowlist.ts b/src/core/minions/tools/brain-allowlist.tsindex 6de0036eaa..9b2efe755a 100644--- a/src/core/minions/tools/brain-allowlist.ts+++ b/src/core/minions/tools/brain-allowlist.ts@@ -37,7 +37,7 @@ import type { ToolCtx, ToolDef } from '../types.ts';* Knowledge Runtime).** Read-only (all safe):- * query, search, get_page, list_pages, file_list, file_url,+ * query, search, get_page, list_pages,* get_backlinks, traverse_graph, resolve_slugs, get_ingest_log** Conditional write:@@ -52,8 +52,6 @@ export const BRAIN_TOOL_ALLOWLIST: ReadonlySet<string> = new Set(['search','get_page','list_pages',- 'file_list',- 'file_url','get_backlinks','traverse_graph',// v114 (#1941): read-only provenance discovery. Edge-WRITE ops (add_link /@@ -97,8 +95,6 @@ export const BRAIN_TOOL_USAGE_HINTS: Readonly<Record<string, string>> = {search: 'Use for hybrid keyword + vector search returning ranked page hits. Use over `query` when you want page-level not chunk-level results (e.g. "find pages about X").',get_page: 'Read a brain page by its slug. Returns the full markdown body + frontmatter + linked pages.',list_pages: 'List pages by type or slug-prefix filter. Use when you need to enumerate (e.g. "list all `people/` pages") instead of search.',- file_list: 'List uploaded files (attachments) by slug-prefix or content type. NOT the local filesystem — only files the brain has stored.',- file_url: 'Get a presigned URL for a brain-stored file. Read-only; expires.',get_backlinks: 'List every page that links TO the given slug. Use for "what references this".',traverse_graph: 'Walk the typed-edge graph starting from a slug (e.g. `works_at`, `founded`, `invested_in`). Use for relationship queries.',list_link_sources: 'List the distinct link provenances in the brain with edge counts (e.g. `citation-graph`, `manual`). Use to discover which edge-writers have populated the graph.',@@ -271,7 +267,7 @@ function buildOpContext(deps: OpContextDeps): OperationContext {export function buildBrainTools(opts: BuildBrainToolsOpts): ToolDef[] {const filter = opts.allowedNames ?? BRAIN_TOOL_ALLOWLIST;const picked: Operation[] = operations.filter(- op => BRAIN_TOOL_ALLOWLIST.has(op.name) && filter.has(op.name),+ op => !op.localOnly && BRAIN_TOOL_ALLOWLIST.has(op.name) && filter.has(op.name),);// #1586: fail fast on a malformed source id before any tool executes@@ -300,6 +296,7 @@ export function buildBrainTools(opts: BuildBrainToolsOpts): ToolDef[] {// Keyed by the unprefixed op name. Undefined when no hint is registered.usage_hint: BRAIN_TOOL_USAGE_HINTS[op.name],async execute(input: unknown, ctx: ToolCtx): Promise<unknown> {+ if (op.localOnly) throw new Error(`${toolName}: local-only operations cannot be delegated`);const opCtx = buildOpContext({engine: ctx.engine,config: opts.config,@@ -357,6 +354,15 @@ export function filterAllowedTools(registry: ToolDef[], allowedToolNames: stringreturn picked;}+/** An absent trusted binding uses the registry; an explicit empty binding grants nothing. */+export function selectAllowedTools(registry: ToolDef[], allowed: unknown): ToolDef[] {+ if (allowed === undefined) return registry;+ if (!Array.isArray(allowed) || allowed.some(name => typeof name !== 'string' || name.trim() === '')) {+ throw new Error('subagent allowed_tools must be an array of nonempty tool names');+ }+ return filterAllowedTools(registry, allowed);+}+/** Exported for unit tests (stable surface). */export const __testing = {sanitizeToolName,diff --git a/src/core/minions/types.ts b/src/core/minions/types.tsindex 1038e1d1f7..cb065c36a1 100644--- a/src/core/minions/types.ts+++ b/src/core/minions/types.ts@@ -1,3 +1,4 @@+import { parseSubmissionAuthority, type SubmissionAuthority } from './submission-authority.ts';/*** Minions — BullMQ-inspired Postgres-native job queue for GBrain.*@@ -39,6 +40,8 @@ export interface MinionJob {status: MinionJobStatus;priority: number;data: Record<string, unknown>;+ /** Internal authority column; never accepted from job data or remote options. */+ submission_authority?: SubmissionAuthority | null;// Retrymax_attempts: number;@@ -264,6 +267,8 @@ export interface MinionJobContext {id: number;name: string;data: Record<string, unknown>;+ /** Internal authority column; never accepted from job data or remote options. */+ submission_authority?: SubmissionAuthority | null;attempts_made: number;/** AbortSignal for cooperative cancellation (fires on timeout, cancel, pause, or lock loss). */signal: AbortSignal;@@ -426,13 +431,7 @@ export const ABORT_REASON_TIMEOUT = 'timeout';// --- Errors ----/** Throw this from a handler to skip all retry logic and go straight to 'dead'. */-export class UnrecoverableError extends Error {- constructor(message: string) {- super(message);- this.name = 'UnrecoverableError';- }-}+export { UnrecoverableError } from './errors.ts';// --- Row Mapping ---@@ -443,6 +442,7 @@ export function rowToMinionJob(row: Record<string, unknown>): MinionJob {queue: row.queue as string,status: row.status as MinionJobStatus,priority: row.priority as number,+ submission_authority: parseSubmissionAuthority(row.submission_authority),data: (typeof row.data === 'string' ? JSON.parse(row.data) : row.data ?? {}) as Record<string, unknown>,max_attempts: row.max_attempts as number,attempts_made: row.attempts_made as number,diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.tsindex 9064861279..1823d92439 100644--- a/src/core/minions/worker.ts+++ b/src/core/minions/worker.ts@@ -1,3 +1,4 @@+import { assertNoUnreviewedJobs, authorizeJobExecution, withSubmissionAuthority } from './submission-authority.ts';/*** MinionWorker — Concurrent in-process job worker with BullMQ-inspired patterns.*@@ -381,6 +382,7 @@ export class MinionWorker extends EventEmitter {}await this.queue.ensureSchema();+ await assertNoUnreviewedJobs(this.engine);this.running = true;// R2-9 lifecycle: (re-)enable the event-loop-delay histogram for this// run; stop() disables it so embedding hosts / test suites that cycle@@ -1304,6 +1306,7 @@ export class MinionWorker extends EventEmitter {);try {+ const authority = await authorizeJobExecution(this.engine, job);const result = isolated? await runJobInChild({jobId: job.id,@@ -1316,7 +1319,7 @@ export class MinionWorker extends EventEmitter {})// #4218: attribute every gateway.chat() the handler makes to this// job so chat_usage_log rows carry `phase = 'job:<name>'`.- : await withChatPhase(`job:${job.name}`, () => handler(context as MinionJobContext));+ : await withSubmissionAuthority(authority, () => withChatPhase(`job:${job.name}`, () => handler(context as MinionJobContext)), abort.signal);// The child spawned and ran — the spawn path is healthy again.this._consecutiveChildSpawnFailures = 0;diff --git a/src/core/oauth-grants.ts b/src/core/oauth-grants.tsnew file mode 100644index 0000000000..9ec9b0814c--- /dev/null+++ b/src/core/oauth-grants.ts@@ -0,0 +1,275 @@+/** OAuth grant lifecycle. Every grant mutation locks the same client row. */+import { createHash } from 'node:crypto';+import { redirectUriMatches } from '@modelcontextprotocol/sdk/server/auth/handlers/authorize.js';+import type { AuthorizationParams } from '@modelcontextprotocol/sdk/server/auth/provider.js';+import type { OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';+import { InvalidClientError, InvalidGrantError, InvalidRequestError, ServerError, TooManyRequestsError } from '@modelcontextprotocol/sdk/server/auth/errors.js';+import type { SqlQuery } from './sql-query.ts';+import { generateToken, hashToken } from './utils.ts';+import { hasScope, parseScopeString } from './scope.ts';+import { intersectGrantedScopes } from './grants/model.ts';+import { safeHexEqual } from './timing-safe.ts';++export type OAuthTransaction = <T>(fn: (sql: SqlQuery) => Promise<T>) => Promise<T>;+type ClientRow = Record<string, unknown>;+export function oauthPgArray(values: string[]): string {+ return `{${values.map(s => `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`).join(',')}}`;+}++function assertActive(row: ClientRow | undefined): asserts row is ClientRow {+ if (!row || row.deleted_at != null) throw new InvalidClientError('Invalid client or client has been revoked');+}++function grantScopes(row: ClientRow, requested?: string[]): string[] {+ const allowed = parseScopeString(row.scope as string | undefined);+ return (requested?.length ? requested : allowed).filter(scope => hasScope(allowed, scope));+}++/** Compare policy, not a mutable reference or only the display name. */+function policyDigest(row: ClientRow): string {+ const fields = ['client_id', 'client_name', 'redirect_uris', 'grant_types', 'scope',+ 'client_secret_hash', 'token_endpoint_auth_method', 'client_secret_expires_at',+ 'source_id', 'federated_read', 'bound_tools', 'bound_source_id', 'bound_brain_id',+ 'bound_slug_prefixes', 'bound_max_concurrent', 'budget_usd_per_day', 'surface', 'token_ttl',+ 'allowed_operations', 'delegated_slug_prefixes', 'delegated_namespace', 'grant_profile',+ 'grant_revision', 'grant_repair_reasons'];+ return hashToken(JSON.stringify(fields.map(field => row[field] ?? null)));+}++export interface OAuthConsentDetails {+ id: string;+ clientId: string;+ clientName: string;+ redirectUri: string;+ scopes: string[];+ sourceId: string | null;+ allowedSources: string[];+ resource: string | null;+ allowedOperations: string[] | null;+ boundSlugPrefixes: string[] | null;+ delegatedTools: string[] | null;+ delegatedSlugPrefixes: string[] | null;+ delegatedNamespace: string | null;+ expiresAt: number;+}+interface PendingAuthorization {+ details: OAuthConsentDetails;+ params: AuthorizationParams;+ policy: string;+ status: 'pending' | 'processing' | 'approved' | 'denied' | 'failed';+}++export class OAuthConsentError extends Error {+ constructor(readonly status: number, readonly code: string, message: string) { super(message); }+}++export class OAuthGrants {+ private readonly pending = new Map<string, PendingAuthorization>();+ constructor(private readonly options: {+ sql: SqlQuery;+ transaction?: OAuthTransaction;+ tokenTtl: number;+ refreshTtl: number;+ now?: () => number;+ }) {}++ private now(): number { return (this.options.now ?? Date.now)(); }+ private async locked<T>(clientId: string, fn: (sql: SqlQuery, row: ClientRow) => Promise<T>): Promise<T> {+ if (!this.options.transaction) throw new ServerError('OAuth grant transactions are unavailable');+ return this.options.transaction(async sql => {+ const [row] = await sql`SELECT * FROM oauth_clients WHERE client_id = ${clientId} FOR UPDATE`;+ assertActive(row);+ return fn(sql, row);+ });+ }++ private prune(): void {+ const now = this.now();+ for (const [id, pending] of this.pending) {+ if (pending.details.expiresAt <= now) this.pending.delete(id);+ }+ }++ async begin(clientId: string, params: AuthorizationParams): Promise<string> {+ this.prune();+ if (this.pending.size >= 1000) throw new TooManyRequestsError('Too many pending requests. Try again shortly.');+ if (!/^[A-Za-z0-9_-]{43}$/.test(params.codeChallenge)) throw new InvalidRequestError('S256 PKCE challenge required');+ const [row] = await this.options.sql`SELECT * FROM oauth_clients WHERE client_id = ${clientId}`;+ assertActive(row);+ if (!Array.isArray(row.grant_types) || !row.grant_types.includes('authorization_code')) {+ throw new InvalidClientError('Authorization code grant not authorized for this client');+ }+ if (!Array.isArray(row.redirect_uris) || !row.redirect_uris.some(uri => typeof uri === 'string' && redirectUriMatches(params.redirectUri, uri))) {+ throw new InvalidRequestError('Redirect URI does not match registered client');+ }+ // No await between the capacity check and insert: concurrent DB reads cannot overfill the store.+ this.prune();+ if (this.pending.size >= 1000) throw new TooManyRequestsError('Too many pending requests. Try again shortly.');+ const id = generateToken('');+ const details: OAuthConsentDetails = {+ id, clientId, clientName: typeof row.client_name === 'string' ? row.client_name : clientId,+ redirectUri: params.redirectUri, scopes: grantScopes(row, params.scopes),+ sourceId: typeof row.source_id === 'string' ? row.source_id : null,+ allowedSources: Array.isArray(row.federated_read) ? [...row.federated_read] as string[] : [],+ allowedOperations: Array.isArray(row.allowed_operations) ? [...row.allowed_operations] as string[] : null,+ boundSlugPrefixes: Array.isArray(row.bound_slug_prefixes) ? [...row.bound_slug_prefixes] as string[] : null,+ delegatedTools: Array.isArray(row.bound_tools) ? [...row.bound_tools] as string[] : null,+ delegatedSlugPrefixes: Array.isArray(row.delegated_slug_prefixes) ? [...row.delegated_slug_prefixes] as string[] : null,+ delegatedNamespace: typeof row.delegated_namespace === 'string' ? row.delegated_namespace : null,+ resource: params.resource?.toString() ?? null, expiresAt: this.now() + 10 * 60_000,+ };+ this.pending.set(id, {+ details, params: { ...params, scopes: [...details.scopes], resource: params.resource ? new URL(params.resource) : undefined },+ policy: policyDigest(row), status: 'pending',+ });+ return id;+ }++ details(id: string): OAuthConsentDetails {+ this.prune();+ const pending = this.pending.get(id);+ if (!pending || pending.status !== 'pending') {+ throw new OAuthConsentError(410, 'authorization_unavailable', 'This request expired, was completed, or the server restarted. Restart the connection from your client.');+ }+ return structuredClone(pending.details);+ }++ hasPending(id: unknown): id is string {+ if (typeof id !== 'string' || !/^[a-f0-9]{64}$/.test(id)) return false;+ try { this.details(id); return true; } catch { return false; }+ }++ async decide(id: string, approve: boolean): Promise<string> {+ this.details(id);+ const pending = this.pending.get(id)!;+ pending.status = 'processing'; // claim synchronously before the first await+ const redirect = new URL(pending.params.redirectUri);+ if (pending.params.state) redirect.searchParams.set('state', pending.params.state);+ if (!approve) {+ pending.status = 'denied';+ redirect.searchParams.set('error', 'access_denied');+ return redirect.toString();+ }+ try {+ const code = await this.locked(pending.details.clientId, async (sql, row) => {+ if (pending.details.expiresAt <= this.now()) throw new OAuthConsentError(410, 'authorization_expired', 'This request expired. Restart the connection from your client.');+ if (policyDigest(row) !== pending.policy) throw new OAuthConsentError(409, 'client_policy_changed', 'Client permissions changed. Restart the connection and review the new request.');+ const code = generateToken('gbrain_code_');+ await sql`+ INSERT INTO oauth_codes (code_hash, client_id, scopes, code_challenge,+ code_challenge_method, redirect_uri, state, resource, expires_at)+ VALUES (${hashToken(code)}, ${pending.details.clientId}, ${oauthPgArray(pending.details.scopes)},+ ${pending.params.codeChallenge}, ${'S256'}, ${pending.params.redirectUri},+ ${pending.params.state ?? null}, ${pending.details.resource}, ${Math.floor(this.now() / 1000) + 600})+ `;+ return code;+ });+ pending.status = 'approved';+ redirect.searchParams.set('code', code);+ return redirect.toString();+ } catch (error) {+ pending.status = 'failed'; // uncertain commit is terminal; never retry this request+ throw error;+ }+ }++ async exchangeCode(clientId: string, code: string, verifier?: string, redirectUri?: string, resource?: URL, secretHash?: string): Promise<OAuthTokens> {+ return this.locked(clientId, async (sql, client) => {+ this.assertCredentialPolicy(client, secretHash);+ const [row] = await sql`SELECT * FROM oauth_codes WHERE code_hash = ${hashToken(code)} AND client_id = ${clientId} FOR UPDATE`;+ if (!row || !Number.isFinite(Number(row.expires_at)) || Number(row.expires_at) <= Math.floor(this.now() / 1000) || row.expires_at == null) throw new InvalidGrantError('Authorization code not found or expired');+ if (redirectUri === undefined || redirectUri !== row.redirect_uri) throw new InvalidGrantError('Redirect URI does not match authorization code');+ if (typeof verifier !== 'string' || !/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)+ || row.code_challenge_method !== 'S256'+ || createHash('sha256').update(verifier).digest('base64url') !== row.code_challenge) {+ throw new InvalidGrantError('Invalid S256 PKCE verifier');+ }+ const target = this.resource(row.resource, resource);+ const scopes = this.currentScopes(client, row.scopes as string[]);+ await sql`DELETE FROM oauth_codes WHERE code_hash = ${hashToken(code)} AND client_id = ${clientId}`;+ return this.issue(sql, client, scopes, target, true);+ });+ }++ async refresh(clientId: string, token: string, requested?: string[], resource?: URL, secretHash?: string): Promise<OAuthTokens> {+ return this.locked(clientId, async (sql, client) => {+ this.assertCredentialPolicy(client, secretHash);+ const [row] = await sql`SELECT * FROM oauth_tokens WHERE token_hash = ${hashToken(token)} AND token_type = 'refresh' AND client_id = ${clientId} FOR UPDATE`;+ if (!row) throw new InvalidGrantError('Refresh token not found');+ if (row.expires_at == null || !Number.isFinite(Number(row.expires_at)) || Number(row.expires_at) <= Math.floor(this.now() / 1000)) throw new InvalidGrantError('Refresh token expired');+ const original = Array.isArray(row.scopes) ? row.scopes as string[] : [];+ if (requested?.some(scope => !hasScope(original, scope))) throw new InvalidGrantError('Requested scope exceeds refresh token grant');+ if (requested?.some(scope => !hasScope(parseScopeString(client.scope as string | undefined), scope))) throw new InvalidGrantError('Requested scope exceeds current client grant');+ const scopes = this.currentScopes(client, requested ?? original);+ const target = this.resource(row.resource, resource);+ await sql`DELETE FROM oauth_tokens WHERE token_hash = ${hashToken(token)} AND token_type = 'refresh' AND client_id = ${clientId}`;+ return this.issue(sql, client, scopes, target, true);+ });+ }++ private currentScopes(client: ClientRow, original: string[]): string[] {+ const allowed = parseScopeString(client.scope as string | undefined);+ return intersectGrantedScopes(original ?? [], allowed);+ }++ private assertCredentialPolicy(client: ClientRow, secretHash?: string): void {+ if ((client.client_secret_hash ?? undefined) !== secretHash) throw new InvalidClientError('Client credentials changed; authenticate again');+ const expires = Number(client.client_secret_expires_at);+ if (secretHash && expires > 0 && expires <= Math.floor(this.now() / 1000)) throw new InvalidClientError('Client credentials expired');+ }++ private resource(stored: unknown, requested?: URL): URL | undefined {+ if (typeof stored === 'string' && stored) {+ if (requested && requested.toString() !== stored) throw new InvalidGrantError('Requested resource exceeds the approved grant');+ return new URL(stored);+ }+ return requested; // pre-resource grants remain valid on upgrade+ }++ async clientCredentials(clientId: string, secret: string, requested?: string): Promise<OAuthTokens> {+ return this.locked(clientId, async (sql, client) => {+ if (!Array.isArray(client.grant_types) || !client.grant_types.includes('client_credentials')) throw new InvalidGrantError('Client credentials grant not authorized for this client');+ if (typeof client.client_secret_hash !== 'string' || !/^[a-f0-9]{64}$/i.test(client.client_secret_hash) || !safeHexEqual(client.client_secret_hash, hashToken(secret))) throw new InvalidClientError('Invalid client secret');+ this.assertCredentialPolicy(client, client.client_secret_hash);+ return this.issue(sql, client, grantScopes(client, requested ? parseScopeString(requested) : undefined), undefined, false);+ });+ }++ async revokeToken(clientId: string, token: string, secretHash?: string): Promise<void> {+ await this.locked(clientId, async (sql, client) => {+ this.assertCredentialPolicy(client, secretHash);+ await sql`DELETE FROM oauth_tokens WHERE token_hash = ${hashToken(token)} AND client_id = ${clientId}`;+ });+ }++ async revokeClient(clientId: string): Promise<void> {+ if (!this.options.transaction) throw new ServerError('OAuth grant transactions are unavailable');+ await this.options.transaction(async sql => {+ const [row] = await sql`SELECT * FROM oauth_clients WHERE client_id = ${clientId} FOR UPDATE`;+ if (!row) return;+ // Inspect optional schema before the statement; catching a missing column inside a PG transaction aborts it.+ if ('deleted_at' in row) await sql`UPDATE oauth_clients SET deleted_at = now() WHERE client_id = ${clientId}`;+ else await sql`DELETE FROM oauth_clients WHERE client_id = ${clientId}`;+ await sql`DELETE FROM oauth_codes WHERE client_id = ${clientId}`;+ await sql`DELETE FROM oauth_tokens WHERE client_id = ${clientId}`;+ });+ }++ private async issue(sql: SqlQuery, client: ClientRow, scopes: string[], resource: URL | undefined, refresh: boolean): Promise<OAuthTokens> {+ const clientId = client.client_id as string;+ const override = Number(client.token_ttl);+ const ttl = Number.isFinite(override) && override > 0 ? override : this.options.tokenTtl;+ const now = Math.floor(this.now() / 1000);+ const access = generateToken('gbrain_at_');+ await sql`INSERT INTO oauth_tokens (token_hash, token_type, client_id, scopes, expires_at, resource)+ VALUES (${hashToken(access)}, ${'access'}, ${clientId}, ${oauthPgArray(scopes)}, ${now + ttl}, ${resource?.toString() ?? null})`;+ const result: OAuthTokens = { access_token: access, token_type: 'bearer', expires_in: ttl, scope: scopes.join(' ') };+ if (refresh) {+ const token = generateToken('gbrain_rt_');+ await sql`INSERT INTO oauth_tokens (token_hash, token_type, client_id, scopes, expires_at, resource)+ VALUES (${hashToken(token)}, ${'refresh'}, ${clientId}, ${oauthPgArray(scopes)}, ${now + this.options.refreshTtl}, ${resource?.toString() ?? null})`;+ result.refresh_token = token;+ }+ return result;+ }+}diff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.tsindex d7fe16cbdc..d1d349352c 100644--- a/src/core/oauth-provider.ts+++ b/src/core/oauth-provider.ts@@ -13,6 +13,8 @@* - Legacy access_tokens fallback for backward compat*/+import { OAuthGrants, type OAuthTransaction } from './oauth-grants.ts';+import { safeHexEqual } from './timing-safe.ts';import { AsyncLocalStorage } from 'node:async_hooks';import type { Response } from 'express';import type {@@ -23,7 +25,7 @@ import type {import type { OAuthServerProvider, AuthorizationParams } from '@modelcontextprotocol/sdk/server/auth/provider.js';import type { OAuthRegisteredClientsStore } from '@modelcontextprotocol/sdk/server/auth/clients.js';import type { AuthInfo as SdkAuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';-import { InvalidTokenError, InvalidClientMetadataError, InvalidGrantError } from '@modelcontextprotocol/sdk/server/auth/errors.js';+import { InvalidTokenError, InvalidClientMetadataError, InvalidClientError, InvalidGrantError } from '@modelcontextprotocol/sdk/server/auth/errors.js';import { hashToken, generateToken, isUndefinedColumnError } from './utils.ts';import {hasScope,@@ -68,19 +70,6 @@ export interface AgentClientBindings {// Types// ----------------------------------------------------------------------------/**- * Convert a JS array to a PostgreSQL array literal for PGLite compat.- *- * PGLite's `db.query(sql, params)` rejects JS arrays bound directly to TEXT[]- * columns ("insufficient data left in message"), so we hand-build the array- * literal `{...}` and let Postgres parse it on insert.- *- * SECURITY: every element is wrapped in double quotes with `"` and `\`- * escaped. Without this, an element containing a comma (e.g., a malicious- * `redirect_uri` containing `,`) would be parsed by Postgres as MULTIPLE- * array elements, smuggling values past validation. See CSO finding #5.- */-/*** Allow-list of RFC 7591 §2 `token_endpoint_auth_method` values gbrain* accepts at registration. Three values, chosen because the SDK's@@ -233,6 +222,8 @@ export function coerceTimestamp(value: unknown): number | undefined {interface GBrainOAuthProviderOptions {sql: SqlQuery;+ /** Required for grant issuance/rotation/revocation; registration and verification need only sql. */+ transaction?: OAuthTransaction;/** Default token TTL in seconds (default: 3600 = 1 hour) */tokenTtl?: number;/** Default refresh token TTL in seconds (default: 30 days) */@@ -333,6 +324,7 @@ class GBrainClientsStore implements OAuthRegisteredClientsStore {grant_types, scope, token_endpoint_auth_method,client_id_issued_at, client_secret_expires_atFROM oauth_clients WHERE client_id = ${clientId}+ AND (to_jsonb(oauth_clients)->>'deleted_at') IS NULL`;if (rows.length === 0) return undefined;const r = rows[0];@@ -561,12 +553,14 @@ export class GBrainOAuthProvider implements OAuthServerProvider {private readonly dcrDisabled: boolean;private tokenTtl: number;private refreshTtl: number;+ readonly grants: OAuthGrants;constructor(options: GBrainOAuthProviderOptions) {this.sql = options.sql;this.dcrDisabled = options.dcrDisabled === true;this.tokenTtl = options.tokenTtl || 3600;this.refreshTtl = options.refreshTtl || 30 * 24 * 3600;+ this.grants = new OAuthGrants({ sql: this.sql, transaction: options.transaction, tokenTtl: this.tokenTtl, refreshTtl: this.refreshTtl });// #2179 fail-closed: an unset DCR max is bounded by the operator's own// token TTL — never a fixed permissive ceiling — so a self-registering// client cannot elect a longer-lived token than the server default@@ -604,46 +598,8 @@ export class GBrainOAuthProvider implements OAuthServerProvider {params: AuthorizationParams,res: Response,): Promise<void> {- const code = generateToken('gbrain_code_');- const codeHash = hashToken(code);- const expiresAt = Math.floor(Date.now() / 1000) + 600; // 10 minute TTL-- // Scope clamp (RFC 6749 §3.3): the SDK's authorize handler splits- // `?scope=...` verbatim and forwards the raw list to the provider, so- // the provider MUST clamp against the client's registered grant. Without- // this, a `read`-registered client requesting `?scope=admin` would have- // `['admin']` stored in oauth_codes and returned by exchangeAuthorizationCode- // as a fully-admin access token. Mirrors the filter pattern already used- // by exchangeClientCredentials (this file) and exchangeRefreshToken's F3- // subset enforcement (RFC 6749 §6) so all three grant entry points clamp- // consistently. When the client requests NO scope, RFC 6749 §3.3 lets the- // server fall back to a default — we default to the client's full- // registered scope (matching exchangeClientCredentials, which already does- // `requestedScope ? ... : allowedScopes`). Previously an omitted request- // granted the empty set, which then propagated into the access+refresh- // tokens and never self-healed: every op failed `insufficient_scope` even- // though the client was registered with `read write`. Clients that omit- // `scope` on /authorize (e.g. some MCP connectors) hit this. Still clamped- // to the allowed set, so an explicit over-broad request can't escalate.- const allowedScopes = parseScopeString(client.scope);- const requestedScopes = (params.scopes && params.scopes.length) ? params.scopes : allowedScopes;- const grantedScopes = requestedScopes.filter(s => hasScope(allowedScopes, s));-- await this.sql`- INSERT INTO oauth_codes (code_hash, client_id, scopes, code_challenge,- code_challenge_method, redirect_uri, state, resource, expires_at)- VALUES (${codeHash}, ${client.client_id},- ${pgArray(grantedScopes)},- ${params.codeChallenge}, ${'S256'},- ${params.redirectUri}, ${params.state || null},- ${params.resource?.toString() || null}, ${expiresAt})- `;-- // Redirect back with the code- const redirectUrl = new URL(params.redirectUri);- redirectUrl.searchParams.set('code', code);- if (params.state) redirectUrl.searchParams.set('state', params.state);- res.redirect(redirectUrl.toString());+ const id = await this.grants.begin(client.client_id, params);+ res.redirect(`/admin/?oauth_request=${id}#oauth-consent`);}async challengeForAuthorizationCode(@@ -656,11 +612,13 @@ export class GBrainOAuthProvider implements OAuthServerProvider {// client_id at all.const rows = await this.sql`SELECT code_challenge FROM oauth_codes- WHERE code_hash = ${codeHash}- AND client_id = ${client.client_id}- AND expires_at > ${Math.floor(Date.now() / 1000)}+ JOIN oauth_clients ON oauth_clients.client_id = oauth_codes.client_id+ WHERE (to_jsonb(oauth_clients)->>'deleted_at') IS NULL+ AND code_hash = ${codeHash}+ AND oauth_codes.client_id = ${client.client_id}+ AND oauth_codes.expires_at > ${Math.floor(Date.now() / 1000)}`;- if (rows.length === 0) throw new Error('Authorization code not found or expired');+ if (rows.length === 0) throw new InvalidGrantError('Authorization code not found or expired');return rows[0].code_challenge as string;}@@ -671,60 +629,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {redirectUri?: string,resource?: URL,): Promise<OAuthTokens> {- const codeHash = hashToken(authorizationCode);- const now = Math.floor(Date.now() / 1000);- const pending = await this.sql`SELECT code_challenge, code_challenge_method, resource- FROM oauth_codes WHERE code_hash = ${codeHash} AND client_id = ${client.client_id} AND expires_at > ${now}`;- if (!pending.length) throw new InvalidGrantError('Authorization code not found or expired');- const challenge = typeof codeVerifier === 'string' && /^[A-Za-z0-9._~-]{43,128}$/.test(codeVerifier)- ? Buffer.from(hashToken(codeVerifier), 'hex').toString('base64url') : null;- if (pending[0].code_challenge_method !== 'S256' || challenge === null || challenge !== pending[0].code_challenge) {- throw new InvalidGrantError('Invalid PKCE code verifier');- }- const boundResource = typeof pending[0].resource === 'string' ? pending[0].resource : null;- if (resource !== undefined && resource.toString() !== boundResource) throw new InvalidGrantError('Authorization code resource mismatch');- const effectiveResource = boundResource ? new URL(boundResource) : undefined;-- // F1 + F7c hardening: bind client_id AND redirect_uri atomically into the- // DELETE WHERE clause. RFC 6749 §10.5 requires auth codes be single-use;- // RFC 6749 §4.1.3 requires the token endpoint validate redirect_uri- // matches the value sent at /authorize. The previous SELECT-then-compare- // pattern (a) burned the code on the wrong-client path so the legitimate- // client could not retry, and (b) ignored redirect_uri on exchange- // entirely. With RETURNING, the second request — or any wrong-client /- // wrong-redirect-uri attempt — gets zero rows back and fails cleanly.- // The legitimate client's code stays available for one valid redemption.- //- // Use `redirectUri !== undefined` rather than truthy — an attacker- // submitting `redirect_uri=""` (empty string) at /token would otherwise- // hit the falsy branch and bypass the binding entirely.- const rows = redirectUri !== undefined- ? await this.sql`- DELETE FROM oauth_codes- WHERE code_hash = ${codeHash}- AND client_id = ${client.client_id}- AND redirect_uri = ${redirectUri}- AND expires_at > ${now}- AND code_challenge = ${challenge}- AND resource IS NOT DISTINCT FROM ${boundResource}- RETURNING client_id, scopes, resource- `- : await this.sql`- DELETE FROM oauth_codes- WHERE code_hash = ${codeHash}- AND client_id = ${client.client_id}- AND expires_at > ${now}- AND code_challenge = ${challenge}- AND resource IS NOT DISTINCT FROM ${boundResource}- RETURNING client_id, scopes, resource- `;- if (rows.length === 0) throw new Error('Authorization code not found or expired');-- const codeRow = rows[0];-- // Issue tokens- const scopes = (codeRow.scopes as string[]) || [];- return this.issueTokens(client.client_id, scopes, effectiveResource, true);+ return this.grants.exchangeCode(client.client_id, authorizationCode, codeVerifier, redirectUri, resource, client.client_secret);}// -------------------------------------------------------------------------@@ -737,63 +642,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {scopes?: string[],resource?: URL,): Promise<OAuthTokens> {- const tokenHash = hashToken(refreshToken);- const now = Math.floor(Date.now() / 1000);-- // F2 hardening: bind client_id atomically into the DELETE WHERE clause.- // RFC 6749 §10.4 detection of stolen refresh tokens depends on second-use- // failure. The previous SELECT-then-DELETE pattern + post-hoc client- // compare let an attacker who guessed/stole a refresh token burn it on- // the wrong-client path, defeating the stolen-token signal for the- // legitimate client. With the predicate in the DELETE, wrong-client- // attempts get zero rows back; the legitimate client retains the row- // for one valid rotation.- const rows = await this.sql`- DELETE FROM oauth_tokens- WHERE token_hash = ${tokenHash}- AND token_type = 'refresh'- AND client_id = ${client.client_id}- AND (${resource === undefined} OR resource IS NOT DISTINCT FROM ${resource?.toString() ?? null})- RETURNING client_id, scopes, expires_at, resource- `;- // #4532: InvalidGrantError (not bare Error) — the SDK's token handler maps- // OAuthError subclasses to their RFC 6749 wire shape (400 invalid_grant)- // and everything else to a 500 Internal Server Error. A refresh with a- // rotated/expired token is a routine client condition (RFC 6749 §5.2- // invalid_grant), and the 500 made well-behaved MCP clients treat it as a- // server outage instead of re-running the authorization flow.- if (rows.length === 0) throw new InvalidGrantError('Refresh token not found');-- const row = rows[0];- // NULL expires_at is treated as expired (fail-closed). Schema permits NULL- // even though issueTokens always sets it, so a corrupt or hand-modified row- // can't ride past validation.- const expiresAt = coerceTimestamp(row.expires_at);- if (expiresAt === undefined || expiresAt < now) throw new InvalidGrantError('Refresh token expired');-- // F3 hardening: requested scopes on refresh MUST be a subset of the- // original grant on this refresh token's row. RFC 6749 §6: "the scope of- // the access token … MUST NOT include any scope not originally granted by- // the resource owner." Scope is checked against the row's scopes (the- // grant), NOT against the client's currently-allowed scopes (which can- // expand later). Omitted scope (`undefined`) inherits the original grant- // verbatim and stays distinct from an explicit empty array.- //- // v0.28: hasScope replaces exact-string-match so an `admin` grant CAN- // refresh down to `sources_admin` (admin implies all). Without this,- // gstack /setup-gbrain Path 4 — which mints a sources_admin-scoped- // refresh — would fail when the brain admin's bootstrap token was- // issued at the `admin` tier.- const grantedScopes = (row.scopes as string[]) || [];- if (scopes && scopes.some(s => !hasScope(grantedScopes, s))) {- throw new Error('Requested scope exceeds refresh token grant');- }- const current = await this._clientsStore.getClient(client.client_id);- if (!current) throw new InvalidGrantError('Client no longer exists');- const liveGrant = parseScopeString(current.scope);- if (scopes && scopes.some(scope => !hasScope(liveGrant, scope))) throw new InvalidGrantError('Requested scope exceeds current client grant');- const tokenScopes = intersectGrantedScopes(scopes ?? grantedScopes, liveGrant);- return this.issueTokens(client.client_id, tokenScopes, typeof row.resource === 'string' ? new URL(row.resource) : undefined, true);+ return this.grants.refresh(client.client_id, refreshToken, scopes, resource, client.client_secret);}// -------------------------------------------------------------------------@@ -829,6 +678,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {FROM oauth_tokens tLEFT JOIN oauth_clients c ON c.client_id = t.client_idWHERE t.token_hash = ${tokenHash} AND t.token_type = 'access'+ AND c.client_id IS NOT NULL AND (to_jsonb(c)->>'deleted_at') IS NULL`;} catch (err) {// Degrade ladder for brains that haven't run apply-migrations yet:@@ -873,6 +723,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {FROM oauth_tokens tLEFT JOIN oauth_clients c ON c.client_id = t.client_idWHERE t.token_hash = ${tokenHash} AND t.token_type = 'access'+ AND c.client_id IS NOT NULL AND (to_jsonb(c)->>'deleted_at') IS NULL`;} catch (errS) {if (!missingOAuthColumn(errS)) throw errS;@@ -889,6 +740,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {FROM oauth_tokens tLEFT JOIN oauth_clients c ON c.client_id = t.client_idWHERE t.token_hash = ${tokenHash} AND t.token_type = 'access'+ AND c.client_id IS NOT NULL AND (to_jsonb(c)->>'deleted_at') IS NULL`;} catch (err2) {if (!missingOAuthColumn(err2)) throw err2;@@ -904,6 +756,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {FROM oauth_tokens tLEFT JOIN oauth_clients c ON c.client_id = t.client_idWHERE t.token_hash = ${tokenHash} AND t.token_type = 'access'+ AND c.client_id IS NOT NULL AND (to_jsonb(c)->>'deleted_at') IS NULL`;} catch (err3) {if (!missingOAuthColumn(err3)) throw err3;@@ -918,6 +771,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {FROM oauth_tokens tLEFT JOIN oauth_clients c ON c.client_id = t.client_idWHERE t.token_hash = ${tokenHash} AND t.token_type = 'access'+ AND c.client_id IS NOT NULL AND (to_jsonb(c)->>'deleted_at') IS NULL`;}}@@ -1000,6 +854,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {return {token,clientId: row.client_id as string,+ principal: { kind: 'oauth_client', id: row.client_id as string },clientName: (row.client_name as string | null) ?? undefined,scopes: effectiveScopes,issuedScopes,@@ -1042,7 +897,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {let legacyRows: Record<string, unknown>[];try {legacyRows = await this.sql`- SELECT name, permissions, scopes FROM access_tokens+ SELECT id, name, permissions, scopes FROM access_tokensWHERE token_hash = ${tokenHash} AND revoked_at IS NULL`;} catch (err) {@@ -1056,13 +911,13 @@ export class GBrainOAuthProvider implements OAuthServerProvider {// name-only — and that brain predates scoped minting entirely.try {legacyRows = await this.sql`- SELECT name, scopes FROM access_tokens+ SELECT id, name, scopes FROM access_tokensWHERE token_hash = ${tokenHash} AND revoked_at IS NULL`;} catch (err2) {if (!isUndefinedColumnError(err2, 'scopes')) throw err2;legacyRows = await this.sql`- SELECT name FROM access_tokens+ SELECT id, name FROM access_tokensWHERE token_hash = ${tokenHash} AND revoked_at IS NULL`;}@@ -1102,6 +957,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {return {token,clientId: name,+ principal: { kind: 'legacy_token', id: String(legacyRows[0].id) },clientName: name,scopes: grantedScopes ?? ['read', 'write', 'admin'],expiresAt: Math.floor(Date.now() / 1000) + 365 * 24 * 3600, // Legacy tokens never expire — set 1yr future@@ -1128,18 +984,12 @@ export class GBrainOAuthProvider implements OAuthServerProvider {client: OAuthClientInformationFull,request: OAuthTokenRevocationRequest,): Promise<void> {- const tokenHash = hashToken(request.token);- // F4 hardening: bind client_id so a client can only revoke its own- // tokens. RFC 7009 §2.1: "The authorization server first validates the- // client credentials … and then verifies whether the token was issued- // to the client making the revocation request." Pre-fix, any- // authenticated client that knew (or guessed) another client's token- // hash could revoke it.- await this.sql`- DELETE FROM oauth_tokens- WHERE token_hash = ${tokenHash}- AND client_id = ${client.client_id}- `;+ await this.grants.revokeToken(client.client_id, request.token, client.client_secret);+ }++ /** Owner-triggered revocation serializes with every grant path. */+ async revokeClient(clientId: string): Promise<void> {+ await this.grants.revokeClient(clientId);}// -------------------------------------------------------------------------@@ -1164,25 +1014,8 @@ export class GBrainOAuthProvider implements OAuthServerProvider {presentedSecret: string,): Promise<OAuthClientInformationFull> {const client = await this._clientsStore.getClient(clientId);- if (!client) throw new Error('Invalid client');- // Public client — refuse to use this hash-compare path.- if (client.client_secret === undefined) {- throw new Error('Invalid client');- }- const presentedHash = hashToken(presentedSecret);- // client.client_secret is the stored SHA-256 hash (getClient returns- // it as the `client_secret` field per the v0.34.1.0 normalization).- // Compare via SHA-256-then-equals; constant-time compare a follow-up.- if (client.client_secret !== presentedHash) {- throw new Error('Invalid client');- }- // Soft-delete probe — same shape as exchangeClientCredentials.- try {- const [revoked] = await this.sql`SELECT deleted_at FROM oauth_clients WHERE client_id = ${clientId} AND deleted_at IS NOT NULL`;- if (revoked) throw new Error('Client has been revoked');- } catch (e) {- if (e instanceof Error && e.message === 'Client has been revoked') throw e;- if (!isUndefinedColumnError(e, 'deleted_at')) throw e;+ if (!client || typeof client.client_secret !== 'string' || !/^[a-f0-9]{64}$/i.test(client.client_secret) || !safeHexEqual(client.client_secret, hashToken(presentedSecret))) {+ throw new InvalidClientError('Invalid client or client has been revoked');}return client;}@@ -1192,47 +1025,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {clientSecret: string,requestedScope?: string,): Promise<OAuthTokens> {- const client = await this._clientsStore.getClient(clientId);- if (!client) throw new Error('Client not found');-- // Check if client has been revoked (soft-deleted). The deleted_at column- // is recent — pre-migration brains don't have it, so the probe must- // tolerate that one specific failure mode without swallowing real errors- // (lock timeouts, network blips, auth failures).- try {- const [revoked] = await this.sql`SELECT deleted_at FROM oauth_clients WHERE client_id = ${clientId} AND deleted_at IS NOT NULL`;- if (revoked) throw new Error('Client has been revoked');- } catch (e) {- // F5 hardening: surface anything that ISN'T a missing-column error.- // Bare `catch {}` masked DB outages as "client not revoked" — fail-open- // posture in a security-sensitive code path.- if (e instanceof Error && e.message === 'Client has been revoked') throw e;- if (!isUndefinedColumnError(e, 'deleted_at')) throw e;- }-- // Check grant type first (before verifying secret)- const grants = (client.grant_types as string[]) || [];- if (!grants.includes('client_credentials')) {- throw new Error('Client credentials grant not authorized for this client');- }-- // Verify secret- const secretHash = hashToken(clientSecret);- if (client.client_secret !== secretHash) throw new Error('Invalid client secret');-- // Determine scopes. v0.28 swaps exact-string-match for hasScope so a- // client whose grant is `admin` can mint tokens that include implied- // scopes like `sources_admin` (admin implies all). Tokens are still- // capped by what the client was registered for — this only changes how- // the cap is computed.- const allowedScopes = parseScopeString(client.scope);- const requestedScopes = requestedScope ? parseScopeString(requestedScope) : allowedScopes;- const grantedScopes = requestedScopes.filter(s => hasScope(allowedScopes, s));-- // Client credentials: access token only, NO refresh token (RFC 6749 4.4.3)- // Per-client TTL (oauth_clients.token_ttl) is applied inside issueTokens- // so all three grant paths honor it (#2179).- return this.issueTokens(clientId, grantedScopes, undefined, false);+ return this.grants.clientCredentials(clientId, clientSecret, requestedScope);}// -------------------------------------------------------------------------@@ -1279,6 +1072,9 @@ export class GBrainOAuthProvider implements OAuthServerProvider {// `startsWith` true for every slug — a binding that looks set in// `auth list` and the admin UI while fencing nothing. Reject at// registration, the same way source ids are validated.+ if (agentBindings?.boundTools && (agentBindings.boundTools.length === 0 || agentBindings.boundTools.some(tool => typeof tool !== 'string' || !tool.trim()))) {+ throw new Error('--bound-tools requires at least one non-empty tool name');+ }if (agentBindings?.boundSlugPrefixes) {// Same rule as rescopeClient: an empty list is ambiguous. It registers// as deny-all for every direct write while printing an empty binding@@ -1436,72 +1232,4 @@ export class GBrainOAuthProvider implements OAuthServerProvider {return rescopeOAuthClient(this.sql, clientId, opts);}- // -------------------------------------------------------------------------- // Internal: Issue access + optional refresh tokens- // --------------------------------------------------------------------------- /**- * Per-client TTL override lookup (oauth_clients.token_ttl). Set by the- * admin API, the CLI, or a DCR `token_ttl_seconds` request (#2179).- * Column may not exist on older schemas — graceful fallback to undefined.- */- private async lookupClientTokenTtl(clientId: string): Promise<number | undefined> {- try {- const ttlRows = await this.sql`SELECT token_ttl FROM oauth_clients WHERE client_id = ${clientId}`;- if (ttlRows.length > 0 && ttlRows[0].token_ttl) return Number(ttlRows[0].token_ttl);- } catch (e) {- // F5 hardening posture: only the "column doesn't exist" path is a- // non-fatal fall-through.- if (!isUndefinedColumnError(e, 'token_ttl')) throw e;- }- return undefined;- }-- private async issueTokens(- clientId: string,- scopes: string[],- resource: URL | undefined,- includeRefresh: boolean,- ): Promise<OAuthTokens> {- const currentClient = await this._clientsStore.getClient(clientId);- if (!currentClient) throw new InvalidGrantError('Client no longer exists');- scopes = intersectGrantedScopes(scopes, parseScopeString(currentClient.scope));- const accessToken = generateToken('gbrain_at_');- const accessHash = hashToken(accessToken);- const now = Math.floor(Date.now() / 1000);- // #2179: the per-client override lives here (not in individual grant- // handlers) so client_credentials, authorization_code AND refresh- // issuance all honor oauth_clients.token_ttl consistently.- const effectiveTtl = (await this.lookupClientTokenTtl(clientId)) || this.tokenTtl;- const accessExpiry = now + effectiveTtl;-- await this.sql`- INSERT INTO oauth_tokens (token_hash, token_type, client_id, scopes, expires_at, resource)- VALUES (${accessHash}, ${'access'}, ${clientId},- ${pgArray(scopes)}, ${accessExpiry}, ${resource?.toString() || null})- `;-- const result: OAuthTokens = {- access_token: accessToken,- token_type: 'bearer',- expires_in: effectiveTtl,- scope: scopes.join(' '),- };-- if (includeRefresh) {- const refreshToken = generateToken('gbrain_rt_');- const refreshHash = hashToken(refreshToken);- const refreshExpiry = now + this.refreshTtl;-- await this.sql`- INSERT INTO oauth_tokens (token_hash, token_type, client_id, scopes, expires_at, resource)- VALUES (${refreshHash}, ${'refresh'}, ${clientId},- ${pgArray(scopes)}, ${refreshExpiry}, ${resource?.toString() || null})- `;-- result.refresh_token = refreshToken;- }-- return result;- }}diff --git a/src/core/ops/context.ts b/src/core/ops/context.tsindex 45f3d156e8..6ca1625c17 100644--- a/src/core/ops/context.ts+++ b/src/core/ops/context.ts@@ -559,14 +559,14 @@ export function resolveRequestedScope(return ctx.remote === false ? {} : sourceScopeOpts(ctx);}if (sourceIdParam !== undefined) {- const allowed = ctx.auth?.allowedSources;- // An explicit empty federated set retains only the legacy scalar floor.- // It must never turn a caller-supplied source into unrestricted access.- const granted = allowed?.length ? allowed : ctx.sourceId ? [ctx.sourceId] : [];- if (ctx.remote !== false && allowed !== undefined && !granted.includes(sourceIdParam)) {+ const scope = sourceScopeOpts(ctx);+ const granted = scope.sourceIds !== undefined+ ? scope.sourceIds.includes(sourceIdParam)+ : scope.sourceId === sourceIdParam;+ if (ctx.remote !== false && !granted) {throw new OperationError('permission_denied',- `source '${sourceIdParam}' is outside your granted sources`,+ 'Requested source is outside your granted sources','Request access to this source, or omit source_id to search within your grant.',);}diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex 3eecf9bd9d..6dd032bd53 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -137,6 +137,8 @@ export interface Logger {export interface AuthInfo {token: string;clientId: string;+ /** Durable, verifier-derived identity. Never infer this from a display name or request data. */+ principal?: { kind: 'oauth_client' | 'legacy_token'; id: string };/*** Human-readable agent name resolved at token-verification time.* For OAuth clients this is `oauth_clients.client_name`; for legacydiff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex a20f32a614..166400f8f8 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -829,7 +829,11 @@ const forget_fact: Operation = {const id = p.id as number;const reason = typeof p.reason === 'string' ? p.reason : undefined;const { forgetFactInFence } = await import('../facts/forget.ts');- const result = await forgetFactInFence(ctx.engine, id, { reason });+ const result = await forgetFactInFence(ctx.engine, id, {+ reason,+ sourceId: ctx.sourceId ?? 'default',+ worldOnly: ctx.remote !== false,+ });if (!result.ok && result.path === 'not_found') {throw new OperationError('fact_not_found', `Fact id ${id} not found.`);}diff --git a/src/core/ops/jobs.ts b/src/core/ops/jobs.tsindex 0244fa89aa..3ae0db2293 100644--- a/src/core/ops/jobs.ts+++ b/src/core/ops/jobs.ts@@ -1,3 +1,11 @@+import { prepareRemoteJob, prepareRemoteAgent, assertRemoteJobControl } from '../minions/submission-authority.ts';+import type { MinionJob } from '../minions/types.ts';++function publicJob(job: MinionJob) {+ const { submission_authority: _authority, ...visible } = job;+ return { ...visible, private_queue_owner_token: job.private_queue_owner_token == null ? null : '[redacted]' };+}+/*** Jobs (Minions) operation cluster — pure move from operations.ts (v0.46.x* tranche 2). Op consts stay module-private; `jobsOperations` below lists@@ -9,7 +17,6 @@import type { Operation, OperationContext } from './contract.ts';import { OperationError } from './contract.ts';-import { normalizeSlugPrefix } from './context.ts';import { hasScope } from '../scope.ts';import {assertEmbedBackfillQueueAdmission,@@ -72,10 +79,10 @@ async function assertJobOwned(ctx: OperationContext, id: number, owner: string):const submit_job: Operation = {name: 'submit_job',- description: 'Submit a background job to the Minions queue. Built-in types are registered by registerBuiltinHandlers (src/commands/jobs.ts) — e.g. sync, embed, lint, import, extract, backlinks, autopilot-cycle, subagent, and more; submitting an unknown name with --follow prints the full list. The `shell` type is CLI-only and rejected over MCP.',+ description: 'Submit a background job. Remote callers may submit sync, import, lint or lint-fix for their authenticated filesystem source. Other kinds require local CLI or a dedicated operation.',params: {- name: { type: 'string', required: true, description: 'Job type (e.g. sync, embed, lint, import, extract, backlinks, autopilot-cycle; shell is CLI-only). Full registry: registerBuiltinHandlers in src/commands/jobs.ts.' },- data: { type: 'object', description: 'Job payload (JSON)' },+ name: { type: 'string', required: true, description: 'Remote job type: sync, import, lint, or lint-fix. Local CLI also supports other registered types.' },+ data: { type: 'object', description: 'Remote sync accepts optional pull/noPull (one boolean); other remote jobs accept no parameters. Source and paths are derived from the grant.' },queue: { type: 'string', description: 'Queue name (default: "default")' },priority: { type: 'number', description: 'Priority (0 = highest, default: 0)' },max_attempts: { type: 'number', description: 'Max retry attempts (default: 3)' },@@ -87,27 +94,9 @@ const submit_job: Operation = {scope: 'admin',handler: async (ctx, p) => {const name = typeof p.name === 'string' ? p.name.trim() : '';- const jobData = { ...((p.data as Record<string, unknown>) || {}) };- // Derived-identity fence for `data.client_id` (same posture as- // send_job_message's sender fence): it is a spend-attribution identity —- // handlers settle LLM/embedding spend against it via getJobClientId →- // recordMinionJobSpend (minion-spend.ts), charging that OAuth client's- // mcp_spend_log / daily cap. A remote caller must NEVER pick it- // (spoofing another client's bill/cap): overwrite with the- // AUTHENTICATED client id — the same identity source run_onboard's A23- // stamping uses — or strip the key when no authenticated identity- // exists (spend then records clientId=null, global accounting only).- // Trusted local callers (ctx.remote === false) pass through unchanged.- if (ctx.remote !== false) {- delete jobData.__owner_client_id;- delete jobData.__delegation_grant;- const authClientId = ctx.auth?.clientId;- if (typeof authClientId === 'string' && authClientId.length > 0) {- jobData.client_id = authClientId;- } else {- delete jobData.client_id;- }- }+ let jobData = { ...((p.data as Record<string, unknown>) || {}) };+ const remoteSubmission = ctx.remote !== false ? await prepareRemoteJob(ctx, name, p.data) : undefined;+ if (remoteSubmission) jobData = remoteSubmission.data;const translateAdmissionError = (e: unknown): never => {if (e instanceof InvalidEmbedBackfillSourceIdError) {throw new OperationError('invalid_params', e.message);@@ -149,7 +138,9 @@ const submit_job: Operation = {const queue = new MinionQueue(ctx.engine);// Trusted flag fires ONLY for an explicit local CLI submission of a protected// name. Strict `=== false` so an untyped/cast context can't escalate.- const trusted = ctx.remote === false && isProtectedJobName(name) ? { allowProtectedSubmit: true } : undefined;+ const trusted = remoteSubmission+ ? { submissionAuthority: remoteSubmission.authority }+ : ctx.remote === false && isProtectedJobName(name) ? { allowProtectedSubmit: true } : undefined;// v0.35.8.0: pre-enqueue shell-job validation, parity with the CLI submit// path. Closes the bug class where shell.ts handler-time validation ran@@ -211,7 +202,7 @@ const submit_job: Operation = {// Amendments 24/25: post-enqueue queue-state probe (time-bounded,// fail-open). The job is already persisted; a probe failure degrades to// {probe_failed: true}, never an error on a successful submission.- return { ...job, private_queue_owner_token: job.private_queue_owner_token == null ? null : '[redacted]', queue_state: await probeQueueStateSafe(ctx, job.queue, [name]) };+ return { ...publicJob(job), queue_state: await probeQueueStateSafe(ctx, job.queue, [name]) };},};@@ -309,6 +300,13 @@ const submit_agent: Operation = {const budgetCapText = snapshot.budgetUsdPerDay;const requestedTools = snapshot.tools;const requestedSlugPrefixes = snapshot.slugPrefixes;+ const jobData: Record<string, unknown> = {+ prompt: p.prompt, max_turns: maxTurns, model: resolvedModel,+ allowed_tools: requestedTools, allowed_slug_prefixes: requestedSlugPrefixes,+ source_id: snapshot.sourceId, __owner_client_id: clientId,+ __delegation_grant: snapshot,+ };+ const authority = await prepareRemoteAgent(ctx, jobData);if (ctx.dryRun) {return {dry_run: true, action: 'submit_agent', client_id: clientId,@@ -321,17 +319,11 @@ const submit_agent: Operation = {}const { MinionQueue } = await import('../minions/queue.ts');const queue = new MinionQueue(ctx.engine);- const jobData: Record<string, unknown> = {- prompt: p.prompt, max_turns: maxTurns, model: resolvedModel,- allowed_tools: requestedTools, allowed_slug_prefixes: requestedSlugPrefixes,- source_id: snapshot.sourceId, __owner_client_id: clientId,- __delegation_grant: snapshot,- };let job;try {job = await queue.add('subagent', jobData,{ queue: (p.queue as string) || 'default' },- { allowProtectedSubmit: true, delegatedClientId: clientId });+ { allowProtectedSubmit: true, delegatedClientId: clientId, submissionAuthority: authority });} catch (error) {const { isQueueQuotaExceededError } = await import('../minions/admission.ts');if (isQueueQuotaExceededError(error)) throw new OperationError('rate_limited', error.message, 'Retry after existing work completes.');@@ -495,7 +487,7 @@ const get_job: Operation = {if (!job) throw new OperationError('invalid_params', `Job not found: ${p.id}`);// private_queue_owner_token is a capability credential (lease renewal /// attach), not job data — never expose it over MCP envelopes.- return { ...job, private_queue_owner_token: job.private_queue_owner_token == null ? null : '[redacted]' };+ return publicJob(job);},};@@ -524,7 +516,7 @@ const list_jobs: Operation = {} as Parameters<typeof queue.getJobs>[0]);// private_queue_owner_token is a capability credential (lease renewal /// attach), not job data — never expose it over MCP envelopes.- return jobs.map(j => ({ ...j, private_queue_owner_token: j.private_queue_owner_token == null ? null : '[redacted]' }));+ return jobs.map(publicJob);},};@@ -549,7 +541,7 @@ const cancel_job: Operation = {if (!cancelled) throw new OperationError('invalid_params', `Cannot cancel job ${p.id} (may already be in terminal status)`);// private_queue_owner_token is a capability credential (lease renewal /// attach), not job data — never expose it over MCP envelopes.- return { ...cancelled, private_queue_owner_token: cancelled.private_queue_owner_token == null ? null : '[redacted]' };+ return publicJob(cancelled);},};@@ -565,11 +557,14 @@ const retry_job: Operation = {if (ctx.dryRun) return { dry_run: true, action: 'retry_job', id: p.id };const { MinionQueue } = await import('../minions/queue.ts');const queue = new MinionQueue(ctx.engine);+ const prior = await queue.getJob(p.id as number);+ if (!prior) throw new OperationError('invalid_params', 'Job not found');+ await assertRemoteJobControl(ctx, prior);const retried = await queue.retryJob(p.id as number);if (!retried) throw new OperationError('invalid_params', `Cannot retry job ${p.id} (must be failed or dead)`);// private_queue_owner_token is a capability credential (lease renewal /// attach), not job data — never expose it over MCP envelopes.- return { ...retried, private_queue_owner_token: retried.private_queue_owner_token == null ? null : '[redacted]' };+ return publicJob(retried);},};@@ -622,6 +617,9 @@ const resume_job: Operation = {if (ctx.dryRun) return { dry_run: true, action: 'resume_job', id: p.id };const { MinionQueue } = await import('../minions/queue.ts');const queue = new MinionQueue(ctx.engine);+ const prior = await queue.getJob(p.id as number);+ if (!prior) throw new OperationError('invalid_params', 'Job not found');+ await assertRemoteJobControl(ctx, prior);const job = await queue.resumeJob(p.id as number);if (!job) throw new OperationError('invalid_params', `Job not found or not paused: ${p.id}`);return { id: job.id, status: job.status };@@ -641,6 +639,9 @@ const replay_job: Operation = {if (ctx.dryRun) return { dry_run: true, action: 'replay_job', id: p.id };const { MinionQueue } = await import('../minions/queue.ts');const queue = new MinionQueue(ctx.engine);+ const prior = await queue.getJob(p.id as number);+ if (!prior) throw new OperationError('invalid_params', 'Job not found');+ await assertRemoteJobControl(ctx, prior, p.data_overrides);const job = await queue.replayJob(p.id as number, p.data_overrides as Record<string, unknown> | undefined);if (!job) throw new OperationError('invalid_params', `Job not found or not in terminal state: ${p.id}`);return { id: job.id, name: job.name, status: job.status, source_id: p.id };diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex e0a8efbf97..7457de9882 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -1177,7 +1177,11 @@ export class PGLiteEngine implements BrainEngine {EXISTS (SELECT 1 FROM information_schema.columnsWHERE table_schema='public' AND table_name='minion_jobs' AND column_name='private_queue_owner_token') AS minion_jobs_pq_token_exists,EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema='public' AND table_name='minion_jobs' AND column_name='private_queue_lease_until') AS minion_jobs_pq_lease_exists+ WHERE table_schema='public' AND table_name='minion_jobs' AND column_name='private_queue_lease_until') AS minion_jobs_pq_lease_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema='public' AND table_name='minion_jobs' AND column_name='submission_authority') AS minion_jobs_submission_authority_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema='public' AND table_name='minion_jobs' AND column_name='claim_generation') AS minion_jobs_claim_generation_exists`);const probe = rows[0] as {pages_exists: boolean;@@ -1231,6 +1235,8 @@ export class PGLiteEngine implements BrainEngine {minion_jobs_pq_owner_exists: boolean;minion_jobs_pq_token_exists: boolean;minion_jobs_pq_lease_exists: boolean;+ minion_jobs_submission_authority_exists: boolean;+ minion_jobs_claim_generation_exists: boolean;};const needsPagesBootstrap = probe.pages_exists && !probe.source_id_exists;@@ -1328,6 +1334,10 @@ export class PGLiteEngine implements BrainEngine {const needsMinionJobsPrivateQueue = probe.minion_jobs_exists&& (!probe.minion_jobs_pq_owner_exists || !probe.minion_jobs_pq_token_exists|| !probe.minion_jobs_pq_lease_exists);+ // v149: the schema-blob queue protocol references both fields. Repair+ // partial upgrades too; historical authority remains NULL until reviewed.+ const needsMinionJobsAuthority = probe.minion_jobs_exists+ && (!probe.minion_jobs_submission_authority_exists || !probe.minion_jobs_claim_generation_exists);// Fresh installs (no tables yet) and modern brains both no-op.if (!needsPagesBootstrap && !needsLinksBootstrap && !needsChunksBootstrap@@ -1343,7 +1353,7 @@ export class PGLiteEngine implements BrainEngine {&& !needsPagesLinksExtractedAt&& !needsTimelineEventPageId&& !needsMinionJobsTimeoutAt && !needsMinionJobsIdempotencyKey- && !needsMinionJobsPrivateQueue) return;+ && !needsMinionJobsPrivateQueue && !needsMinionJobsAuthority) return;process.stderr.write(' Schema forward-reference gap detected, applying bootstrap\n');@@ -1638,6 +1648,14 @@ export class PGLiteEngine implements BrainEngine {ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_lease_until TIMESTAMPTZ;`);}+ if (needsMinionJobsAuthority) {+ // Metadata only. Never assign authority to existing jobs here; the+ // migration owns the cutover guard and explicit review authorizes rows.+ await this.db.exec(`+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS submission_authority JSONB;+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS claim_generation BIGINT NOT NULL DEFAULT 0;+ `);+ }}async withReservedConnection<T>(fn: (conn: ReservedConnection) => Promise<T>): Promise<T> {diff --git a/src/core/pglite-schema.ts b/src/core/pglite-schema.tsindex 7f54e9a612..3bcc5251aa 100644--- a/src/core/pglite-schema.ts+++ b/src/core/pglite-schema.ts@@ -448,6 +448,8 @@ CREATE TABLE IF NOT EXISTS minion_jobs (queue TEXT NOT NULL DEFAULT 'default',status TEXT NOT NULL DEFAULT 'waiting',priority INTEGER NOT NULL DEFAULT 0,+ submission_authority JSONB, -- Unreviewed legacy provenance stays NULL.+ claim_generation BIGINT NOT NULL DEFAULT 0,data JSONB NOT NULL DEFAULT '{}',max_attempts INTEGER NOT NULL DEFAULT 3,attempts_made INTEGER NOT NULL DEFAULT 0,@@ -496,6 +498,26 @@ CREATE TABLE IF NOT EXISTS minion_jobs (CONSTRAINT chk_lock_duration_positive CHECK (lock_duration_ms IS NULL OR (lock_duration_ms >= 5000 AND lock_duration_ms <= 3600000)));+CREATE OR REPLACE FUNCTION enforce_minion_queue_protocol() RETURNS trigger SET search_path = pg_catalog, public AS $protocol$+BEGIN+ IF TG_OP = 'INSERT' THEN+ IF NEW.submission_authority IS NULL OR NEW.claim_generation <> 0 THEN+ RAISE EXCEPTION 'Minion queue protocol 1 required: upgrade every producer and worker before restart';+ END IF;+ ELSIF NEW.status = 'active' AND (OLD.status <> 'active' OR NEW.lock_token IS DISTINCT FROM OLD.lock_token) THEN+ IF NEW.submission_authority IS NULL OR NEW.claim_generation IS DISTINCT FROM OLD.claim_generation + 1 THEN+ RAISE EXCEPTION 'Minion queue protocol 1 required: old workers cannot claim upgraded queue jobs';+ END IF;+ ELSIF NEW.claim_generation IS DISTINCT FROM OLD.claim_generation THEN+ RAISE EXCEPTION 'Minion queue claim generation may advance only with a claim';+ END IF;+ RETURN NEW;+END;+$protocol$ LANGUAGE plpgsql;+DROP TRIGGER IF EXISTS minion_queue_protocol ON minion_jobs;+CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON minion_jobs+ FOR EACH ROW EXECUTE FUNCTION enforce_minion_queue_protocol();+CREATE INDEX IF NOT EXISTS idx_minion_jobs_claim ON minion_jobs (queue, priority ASC, created_at ASC) WHERE status = 'waiting';CREATE INDEX IF NOT EXISTS idx_minion_jobs_status ON minion_jobs(status);CREATE INDEX IF NOT EXISTS idx_minion_jobs_stalled ON minion_jobs (lock_until) WHERE status = 'active';diff --git a/src/core/postgres-engine/forward-reference-bootstrap.ts b/src/core/postgres-engine/forward-reference-bootstrap.tsindex 216ebec6c4..7f8697f19f 100644--- a/src/core/postgres-engine/forward-reference-bootstrap.ts+++ b/src/core/postgres-engine/forward-reference-bootstrap.ts@@ -20,6 +20,7 @@// convergence cases).import type postgres from 'postgres';+import { GRANT_COLUMNS_SQL } from '../grants/schema.ts';/*** Probe + patch every forward-reference target the embedded schema blob@@ -64,6 +65,7 @@ const probeRows = await conn<{oauth_clients_federated_read_exists: boolean;oauth_clients_surface_exists: boolean;oauth_clients_surface_set_by_exists: boolean;+ oauth_client_grants_exist: boolean;sources_exists: boolean;sources_archived_exists: boolean;sources_archived_at_exists: boolean;@@ -124,6 +126,9 @@ const probeRows = await conn<{WHERE table_schema = current_schema() AND table_name = 'oauth_clients' AND column_name = 'surface') AS oauth_clients_surface_exists,EXISTS (SELECT 1 FROM information_schema.columnsWHERE table_schema = current_schema() AND table_name = 'oauth_clients' AND column_name = 'surface_set_by') AS oauth_clients_surface_set_by_exists,+ (SELECT COUNT(*) = 6 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'oauth_clients'+ AND column_name IN ('allowed_operations', 'delegated_slug_prefixes', 'delegated_namespace', 'grant_profile', 'grant_revision', 'grant_repair_reasons')) AS oauth_client_grants_exist,EXISTS (SELECT 1 FROM information_schema.tablesWHERE table_schema = current_schema() AND table_name = 'sources') AS sources_exists,EXISTS (SELECT 1 FROM information_schema.columns@@ -172,6 +177,10 @@ const probeRows = await conn<{WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'private_queue_owner_token') AS minion_jobs_pq_token_exists,EXISTS (SELECT 1 FROM information_schema.columnsWHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'private_queue_lease_until') AS minion_jobs_pq_lease_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'submission_authority') AS minion_jobs_submission_authority_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'claim_generation') AS minion_jobs_claim_generation_exists,EXISTS (SELECT 1 FROM information_schema.tablesWHERE table_schema = current_schema() AND table_name = 'dream_verdicts') AS dream_verdicts_exists,EXISTS (SELECT 1 FROM information_schema.columns@@ -225,6 +234,7 @@ const probeSurface = probe as {};const needsOauthClientsSurface = probe.oauth_clients_exists&& (!probeSurface.oauth_clients_surface_exists || !probeSurface.oauth_clients_surface_set_by_exists);+const needsOauthClientGrants = probe.oauth_clients_exists && !probe.oauth_client_grants_exist;// v0.26.5 (v34): sources.archived + archived_at + archive_expires_at added// for soft-delete lifecycle. SCHEMA_SQL's `CREATE TABLE IF NOT EXISTS sources`// is a no-op on pre-existing sources tables (won't add columns), so the@@ -271,6 +281,8 @@ const probeCr = probe as {minion_jobs_pq_owner_exists?: boolean;minion_jobs_pq_token_exists?: boolean;minion_jobs_pq_lease_exists?: boolean;+ minion_jobs_submission_authority_exists?: boolean;+ minion_jobs_claim_generation_exists?: boolean;};const needsContextualRetrievalColumns = (probe.pages_exists&& (!probeCr.pages_cr_mode_exists || !probeCr.pages_corpus_generation_exists))@@ -306,6 +318,10 @@ const needsMinionJobsIdempotencyKey = probeCr.minion_jobs_exists === trueconst needsMinionJobsPrivateQueue = probeCr.minion_jobs_exists === true&& (!probeCr.minion_jobs_pq_owner_exists || !probeCr.minion_jobs_pq_token_exists|| !probeCr.minion_jobs_pq_lease_exists);+// v149: the schema-blob queue protocol references both fields. Repair either+// missing field without assigning authority to historical work.+const needsMinionJobsAuthority = probeCr.minion_jobs_exists === true+ && (!probeCr.minion_jobs_submission_authority_exists || !probeCr.minion_jobs_claim_generation_exists);// v143 (dream_verdicts_ttl, #4657): blob index dream_verdicts_expires_idx// references expires_at, but the column only lands via migration v143 — a// Postgres brain at schema v30-v142 (dream_verdicts exists since v30)@@ -318,7 +334,7 @@ if (!needsPagesBootstrap && !needsLinksBootstrap && !needsChunksBootstrap&& !needsPagesDeletedAt && !needsMcpLogBootstrap && !needsSubagentProviderId&& !needsChunksEmbeddingImage && !needsPagesRecency&& !needsIngestLogSourceId && !needsFilesBootstrap- && !needsOauthClientsBootstrap && !needsOauthClientsSurface+ && !needsOauthClientsBootstrap && !needsOauthClientsSurface && !needsOauthClientGrants&& !needsSourcesArchive&& !needsPagesLastRetrievedAt&& !needsPagesProvenance@@ -327,7 +343,7 @@ if (!needsPagesBootstrap && !needsLinksBootstrap && !needsChunksBootstrap&& !needsPagesLinksExtractedAt&& !needsTimelineEventPageId&& !needsMinionJobsTimeoutAt && !needsMinionJobsIdempotencyKey- && !needsMinionJobsPrivateQueue+ && !needsMinionJobsPrivateQueue && !needsMinionJobsAuthority&& !needsDreamVerdictsExpiresAt) return;process.stderr.write(' Schema forward-reference gap detected, applying bootstrap\n');@@ -492,6 +508,10 @@ if (needsOauthClientsBootstrap) {`);}+// Mirror the PGLite bootstrap, including partially installed grant columns.+// Numbered migration 147 owns policy repair and its constraints.+if (needsOauthClientGrants) await conn.unsafe(GRANT_COLUMNS_SQL);+if (needsOauthClientsSurface) {// WP4 (v127): per-client MCP tool surface + operator-lock marker.// Nullable TEXT, no index — bootstrap mirrors the v127 column shape so@@ -639,4 +659,12 @@ if (needsMinionJobsPrivateQueue) {ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_lease_until TIMESTAMPTZ;`);}+if (needsMinionJobsAuthority) {+ // Metadata only. Migration v149 owns the cutover guard; local explicit+ // review is the only path that may assign authority to historical rows.+ await conn.unsafe(`+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS submission_authority JSONB;+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS claim_generation BIGINT NOT NULL DEFAULT 0;+ `);+}}diff --git a/src/core/resolvers/builtin/url-reachable.ts b/src/core/resolvers/builtin/url-reachable.tsindex 528ac9c739..489fc8f5a6 100644--- a/src/core/resolvers/builtin/url-reachable.ts+++ b/src/core/resolvers/builtin/url-reachable.ts@@ -10,8 +10,7 @@* and we genuinely don't know.** Security:- * - SSRF guard reuses isInternalUrl() from src/commands/integrations.ts- * (same wave-3 hardening that protects recipe health_checks).+ * - SSRF guard pins every validated DNS target and preserves its TLS identity.* - Redirect chain is followed manually (max 5 hops) with per-hop* re-validation; matches the integrations.ts pattern so no new SSRF* bypass surface.@@ -19,12 +18,7 @@* Abort token threads through both.*/-import { promises as dns } from 'dns';-import {- isInternalUrl,- hostnameToOctets,- isPrivateIpv4,-} from '../../../commands/integrations.ts';+import { fetchWithSSRFGuard, HttpProxyError, SSRFError, validateAndResolveUrl } from '../../ssrf-validate.ts';import type {Resolver,ResolverContext,@@ -84,156 +78,43 @@ export const urlReachableResolver: Resolver<UrlReachableInput, UrlReachableOutputhrow new ResolverError('schema', 'url_reachable: url must be a non-empty string', 'url_reachable');}- // SSRF gate — refuse to probe internal/private/metadata endpoints (by hostname string).- if (isInternalUrl(url)) {+ try {+ const resp = await fetchWithSSRFGuard(url, {+ method: 'HEAD',+ headerOnly: true,+ headFallback: true,+ maxRedirects: MAX_REDIRECTS,+ timeoutMs,+ signal,+ });+ const missingLocation = resp.status >= 300 && resp.status < 400 && !resp.headers.get('location');+ const reachable = resp.status >= 200 && resp.status < 400 && !missingLocation;return {value: {- reachable: false,- reason: 'blocked: internal/private/metadata hostname or non-http(s) scheme',- },- confidence: 1,- source: 'head-check',- fetchedAt: new Date(),- };- }-- // DNS rebinding defense: resolve the hostname NOW and validate the resolved- // IP against private ranges. Prevents attacker-controlled domains whose DNS- // returns a public IP at string-validation time and `169.254.169.254` at- // fetch time. We check the A/AAAA records; if any of them is private, we- // refuse the whole URL rather than trying to pin a specific IP (node's- // fetch doesn't expose a lookup hook cleanly, and pinning would break SNI- // on some CDNs).- const rebindCheck = await checkDnsRebinding(url);- if (rebindCheck) {- return {- value: {- reachable: false,- reason: rebindCheck,+ reachable,+ status: resp.status,+ finalUrl: resp.url !== url ? resp.url : undefined,+ reason: missingLocation ? 'redirect without Location header' : reachable ? undefined : `HTTP ${resp.status}`,},confidence: 1,source: 'head-check',fetchedAt: new Date(),};- }-- let currentUrl = url;- let status: number | undefined;- let usedMethod: 'HEAD' | 'GET' = 'HEAD';-- for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {- const combinedSignal = composeSignals(signal, timeoutMs);- let resp: Response;- try {- resp = await fetch(currentUrl, {- method: usedMethod,- redirect: 'manual',- signal: combinedSignal,- });- } catch (err: unknown) {- if (isAbortError(err)) {- throw new ResolverError('aborted', `url_reachable aborted (${currentUrl})`, 'url_reachable', err);- }- // fetch threw (DNS, connection refused, timeout). Not reachable, no status.- return {- value: {- reachable: false,- reason: `fetch error: ${errMessage(err).slice(0, 200)}`,- },- confidence: 1,- source: 'head-check',- fetchedAt: new Date(),- };+ } catch (err) {+ if (err instanceof SSRFError && ['REQUEST_ABORTED', 'REQUEST_TIMEOUT'].includes(err.code)) {+ throw new ResolverError('aborted', 'url_reachable aborted', 'url_reachable', err);}-- status = resp.status;-- // Some servers reject HEAD with 405 / 501. Retry once as GET (same hop).- if (usedMethod === 'HEAD' && (status === 405 || status === 501)) {- usedMethod = 'GET';- continue;- }-- // Redirect handling- if (status >= 300 && status < 400) {- const location = resp.headers.get('location');- if (!location) {- return {- value: {- reachable: false,- status,- finalUrl: currentUrl !== url ? currentUrl : undefined,- reason: 'redirect without Location header',- },- confidence: 1,- source: 'head-check',- fetchedAt: new Date(),- };- }- const nextUrl = new URL(location, currentUrl).toString();- // Re-validate each hop against SSRF (hostname string).- if (isInternalUrl(nextUrl)) {- return {- value: {- reachable: false,- status,- finalUrl: currentUrl,- reason: `redirect to blocked hostname: ${nextUrl}`,- },- confidence: 1,- source: 'head-check',- fetchedAt: new Date(),- };- }- // DNS rebinding defense on redirect target too.- const rebindOnRedirect = await checkDnsRebinding(nextUrl);- if (rebindOnRedirect) {- return {- value: {- reachable: false,- status,- finalUrl: currentUrl,- reason: `redirect blocked by DNS check: ${rebindOnRedirect}`,- },- confidence: 1,- source: 'head-check',- fetchedAt: new Date(),- };- }- currentUrl = nextUrl;- usedMethod = 'HEAD'; // reset to HEAD for the new hop- continue;- }-- // Terminal status. 2xx/4xx both count as deterministic answers:- // 2xx = reachable, 4xx = reachable-but-dead-at-this-path.- // We flag 4xx/5xx as unreachable for integrity purposes.- const reachable = status >= 200 && status < 400;return {value: {- reachable,- status,- finalUrl: currentUrl !== url ? currentUrl : undefined,- reason: reachable ? undefined : `HTTP ${status}`,+ reachable: false,+ reason: err instanceof SSRFError || err instanceof HttpProxyError+ ? `blocked: ${err.message}` : 'fetch error: request failed',},confidence: 1,source: 'head-check',fetchedAt: new Date(),};}-- // Ran out of redirect budget- return {- value: {- reachable: false,- status,- finalUrl: currentUrl,- reason: `exceeded ${MAX_REDIRECTS} redirects`,- },- confidence: 1,- source: 'head-check',- fetchedAt: new Date(),- };},};@@ -246,87 +127,12 @@ function errMessage(err: unknown): string {return String(err);}-/**- * Resolve the URL's hostname via DNS and check every A/AAAA result against- * the private-IP ranges. Returns a reason string when the resolution includes- * a private target (attacker DNS rebinding); returns null when safe.- *- * Hostnames that are already IP literals skip this check — isInternalUrl()- * handles them directly at the string level.- *- * If DNS resolution fails (network glitch, NXDOMAIN), we return null and let- * the main fetch attempt surface a real error. Blocking on ambiguous DNS- * would create a false-positive storm when the user has network issues.- *- * Exported for testability.- */+/** Compatibility helper; the shared validator is the only address policy. */export async function checkDnsRebinding(urlStr: string): Promise<string | null> {- let parsed: URL;- try { parsed = new URL(urlStr); } catch { return null; }- let host = parsed.hostname.toLowerCase();- if (host.startsWith('[') && host.endsWith(']')) host = host.slice(1, -1);-- // IP literal? isInternalUrl already rejected private ones; skip DNS.- if (hostnameToOctets(host)) return null;- if (host.includes(':')) return null; // IPv6 literal-- let addrs: { address: string; family: number }[];try {- // all: true returns both A and AAAA records.- addrs = await dns.lookup(host, { all: true });- } catch {- return null; // let fetch surface the error- }-- for (const a of addrs) {- if (a.family === 4) {- const octets = a.address.split('.').map(s => parseInt(s, 10));- if (octets.length === 4 && octets.every(o => Number.isFinite(o)) && isPrivateIpv4(octets)) {- return `DNS resolution of ${host} yielded private IPv4 ${a.address} (rebinding defense)`;- }- } else if (a.family === 6) {- // Minimal v6 private-range checks: loopback, link-local, unique-local, IPv4-mapped.- const v6 = a.address.toLowerCase();- if (v6 === '::1' || v6 === '::' ) return `DNS resolution of ${host} yielded IPv6 loopback ${v6}`;- if (v6.startsWith('fe80:') || v6.startsWith('fc') || v6.startsWith('fd')) {- return `DNS resolution of ${host} yielded private/link-local IPv6 ${v6}`;- }- if (v6.startsWith('::ffff:')) {- const tail = v6.slice(7);- const octets = tail.split('.').map(s => parseInt(s, 10));- if (octets.length === 4 && octets.every(o => Number.isFinite(o)) && isPrivateIpv4(octets)) {- return `DNS resolution of ${host} yielded IPv4-mapped private IPv6 ${v6}`;- }- }- }- }- return null;-}--function isAbortError(err: unknown): boolean {- return !!err && typeof err === 'object' &&- 'name' in err && (err as { name: string }).name === 'AbortError';-}--/**- * Combine a caller-provided AbortSignal with a per-request timeout. If the- * caller's signal fires OR the timeout elapses, the combined signal aborts.- * Uses AbortSignal.any when available (Bun 1.1+, Node 22+); falls back to- * a manual controller for older runtimes.- */-function composeSignals(outer: AbortSignal | undefined, timeoutMs: number): AbortSignal {- const timeoutSignal = AbortSignal.timeout(timeoutMs);- if (!outer) return timeoutSignal;- // Bun supports AbortSignal.any since 1.0.26- if (typeof (AbortSignal as { any?: (signals: AbortSignal[]) => AbortSignal }).any === 'function') {- return (AbortSignal as unknown as { any: (signals: AbortSignal[]) => AbortSignal }).any([outer, timeoutSignal]);+ await validateAndResolveUrl(urlStr);+ return null;+ } catch (err) {+ return errMessage(err);}- // Fallback: manual propagation- const controller = new AbortController();- const onAbort = () => controller.abort();- if (outer.aborted) controller.abort();- else outer.addEventListener('abort', onAbort, { once: true });- if (timeoutSignal.aborted) controller.abort();- else timeoutSignal.addEventListener('abort', onAbort, { once: true });- return controller.signal;}diff --git a/src/core/runtime-version.ts b/src/core/runtime-version.tsnew file mode 100644index 0000000000..7336bba4cf--- /dev/null+++ b/src/core/runtime-version.ts@@ -0,0 +1,10 @@+/** Required for the guarded transport's TLS identity and connection behavior. */+export const MINIMUM_BUN_VERSION = '1.3.11';++export function assertSupportedBun(version = typeof Bun === 'undefined' ? '' : Bun.version): void {+ if (!/^\d+\.\d+\.\d+(?:\+.*)?$/.test(version) || !Bun.semver.satisfies(version, `>=${MINIMUM_BUN_VERSION}`)) {+ const error = new Error(`GBrain requires Bun ${MINIMUM_BUN_VERSION} or newer. Run bun upgrade, then restart GBrain.`);+ Object.assign(error, { code: 'UNSUPPORTED_RUNTIME' });+ throw error;+ }+}diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex f4a128ac96..31b94f375c 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -1049,6 +1049,8 @@ CREATE TABLE IF NOT EXISTS minion_jobs (queue TEXT NOT NULL DEFAULT 'default',status TEXT NOT NULL DEFAULT 'waiting',priority INTEGER NOT NULL DEFAULT 0,+ submission_authority JSONB, -- NULL legacy rows require local authorization before workers start+ claim_generation BIGINT NOT NULL DEFAULT 0, -- advanced atomically by protocol-aware claimsdata JSONB NOT NULL DEFAULT '{}',max_attempts INTEGER NOT NULL DEFAULT 3,attempts_made INTEGER NOT NULL DEFAULT 0,@@ -1576,6 +1578,28 @@ CREATE TABLE IF NOT EXISTS think_ab_results (CREATE INDEX IF NOT EXISTS think_ab_results_recent_idxON think_ab_results (source_id, ran_at DESC);+-- Reject pre-upgrade producers/claims; old reapers must still be stopped during cutover.++CREATE OR REPLACE FUNCTION enforce_minion_queue_protocol() RETURNS trigger SET search_path = pg_catalog, public AS \$protocol\$+BEGIN+ IF TG_OP = 'INSERT' THEN+ IF NEW.submission_authority IS NULL OR NEW.claim_generation <> 0 THEN+ RAISE EXCEPTION 'Minion queue protocol 1 required: upgrade every producer and worker before restart';+ END IF;+ ELSIF NEW.status = 'active' AND (OLD.status <> 'active' OR NEW.lock_token IS DISTINCT FROM OLD.lock_token) THEN+ IF NEW.submission_authority IS NULL OR NEW.claim_generation IS DISTINCT FROM OLD.claim_generation + 1 THEN+ RAISE EXCEPTION 'Minion queue protocol 1 required: old workers cannot claim upgraded queue jobs';+ END IF;+ ELSIF NEW.claim_generation IS DISTINCT FROM OLD.claim_generation THEN+ RAISE EXCEPTION 'Minion queue claim generation may advance only with a claim';+ END IF;+ RETURN NEW;+END;+\$protocol\$ LANGUAGE plpgsql;+DROP TRIGGER IF EXISTS minion_queue_protocol ON minion_jobs;+CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON minion_jobs+ FOR EACH ROW EXECUTE FUNCTION enforce_minion_queue_protocol();+-- NOTIFY trigger for real-time job events (Postgres only, not PGLite)CREATE OR REPLACE FUNCTION notify_minion_job_change() RETURNS trigger SET search_path = pg_catalog, public AS \$\$BEGINdiff --git a/src/core/search/image-loader.ts b/src/core/search/image-loader.tsindex e057d032ec..533b3d44ee 100644--- a/src/core/search/image-loader.ts+++ b/src/core/search/image-loader.ts@@ -29,7 +29,7 @@import { readFile } from 'node:fs/promises';import { isAbsolute } from 'node:path';-import { SSRFError, fetchWithSSRFGuard } from '../ssrf-validate.ts';+import { SSRFError, HttpBodyError, HttpProxyError, fetchWithSSRFGuard, type GuardedHttpResponse } from '../ssrf-validate.ts';/** Max bytes for input image. Configurable via `search.image_query.max_bytes`. */export const DEFAULT_IMAGE_MAX_BYTES = 10 * 1024 * 1024;@@ -163,48 +163,40 @@ async function loadHttpUrl(url: string,opts: { maxBytes: number; timeoutMs: number; maxRedirects: number },): Promise<LoadedImage> {- let res: Response;+ let res: GuardedHttpResponse;try {res = await fetchWithSSRFGuard(url, {maxRedirects: opts.maxRedirects,timeoutMs: opts.timeoutMs,+ maxBytes: opts.maxBytes,});} catch (err) {+ if (err instanceof HttpBodyError && err.code === 'BODY_TOO_LARGE') {+ throw new ImageLoadError('OVERSIZED', err.message);+ }if (err instanceof SSRFError) {+ if (err.code === 'REQUEST_TIMEOUT' || err.code === 'REQUEST_ABORTED') {+ throw new ImageLoadError('TIMEOUT', `Fetch timeout (${opts.timeoutMs}ms)`);+ }throw new ImageLoadError('SSRF_BLOCKED', `SSRF: ${err.message}`);}+ if (err instanceof HttpProxyError || err instanceof HttpBodyError) {+ throw new ImageLoadError('FETCH_FAILED', err.message);+ }const msg = err instanceof Error ? err.message : String(err);if (msg.includes('abort')) {- throw new ImageLoadError('TIMEOUT', `Fetch timeout (${opts.timeoutMs}ms): ${url}`);+ throw new ImageLoadError('TIMEOUT', `Fetch timeout (${opts.timeoutMs}ms)`);}- throw new ImageLoadError('FETCH_FAILED', `Fetch failed: ${msg}`);+ throw new ImageLoadError('FETCH_FAILED', 'Fetch failed: request failed');}if (!res.ok) {throw new ImageLoadError('FETCH_FAILED',- `Fetch returned HTTP ${res.status}: ${res.statusText || ''}`,- );- }- // Pre-flight: reject oversized responses before reading the body.- const contentLengthHeader = res.headers.get('content-length');- if (contentLengthHeader) {- const declared = parseInt(contentLengthHeader, 10);- if (Number.isFinite(declared) && declared > opts.maxBytes) {- throw new ImageLoadError(- 'OVERSIZED',- `Response Content-Length ${declared} exceeds cap ${opts.maxBytes}`,- );- }- }- // Read the body; second guard against lying Content-Length.- const arrayBuf = await res.arrayBuffer();- const bytes = Buffer.from(arrayBuf);- if (bytes.length > opts.maxBytes) {- throw new ImageLoadError(- 'OVERSIZED',- `Response body is ${bytes.length} bytes; cap is ${opts.maxBytes} (lying Content-Length?)`,+ `Fetch returned HTTP ${res.status}`,);}+ // The transport already bounded the decoded stream under the same deadline.+ const bytes = res.body;const contentType = sniffContentType(bytes);return finalize(bytes, contentType);}diff --git a/src/core/ssrf-validate.ts b/src/core/ssrf-validate.tsindex cbf3203aa8..f8fb314c73 100644--- a/src/core/ssrf-validate.ts+++ b/src/core/ssrf-validate.ts@@ -23,7 +23,10 @@*/import { lookup as nodeDnsLookup } from 'node:dns/promises';-import { isInternalUrl, isPrivateIpv4, hostnameToOctets } from './url-safety.ts';+import { isIP } from 'node:net';+import { isInternalUrl, hostnameToOctets } from './url-safety.ts';+import { fetchPinnedHttp, readBoundedHttpBody, type PinnedHttpFetch } from './guarded-http.ts';+export { HttpBodyError, HttpProxyError } from './guarded-http.ts';// Module-level seam so tests can swap DNS resolution without `mock.module`// (which is banned in non-serial unit tests per scripts/check-test-isolation.sh R2).@@ -63,7 +66,9 @@ export type SSRFErrorCode =| 'DNS_RESOLUTION_FAILED'| 'DNS_RESOLVED_INTERNAL'| 'SSRF_REDIRECT_DENIED'- | 'SSRF_HOP_LIMIT';+ | 'SSRF_HOP_LIMIT'+ | 'REQUEST_TIMEOUT'+ | 'REQUEST_ABORTED';/*** Validate a URL against SSRF policy and resolve its hostname to an IP.@@ -83,11 +88,11 @@ export async function validateAndResolveUrl(urlStr: string): Promise<ResolvedTartry {url = new URL(urlStr);} catch {- throw new SSRFError('INVALID_URL', `Malformed URL: ${truncate(urlStr)}`);+ throw new SSRFError('INVALID_URL', 'Malformed HTTP URL');}if (url.protocol !== 'http:' && url.protocol !== 'https:') {- throw new SSRFError('INVALID_SCHEME', `Unsupported scheme ${url.protocol}; only http(s) allowed`);+ throw new SSRFError('INVALID_SCHEME', 'Unsupported URL scheme; only http(s) allowed');}if (url.username || url.password) {@@ -97,7 +102,7 @@ export async function validateAndResolveUrl(urlStr: string): Promise<ResolvedTar// Layer 1: static check covers IPv4 hex/octal/single-int, IPv6 ULA + link-local,// metadata hostnames, CGNAT, IPv4-mapped IPv6.if (isInternalUrl(urlStr)) {- throw new SSRFError('INTERNAL_HOST', `URL targets internal/private network: ${truncate(urlStr)}`);+ throw new SSRFError('INTERNAL_HOST', 'URL targets an internal, private, or otherwise nonpublic network');}let host = url.hostname;@@ -119,22 +124,22 @@ export async function validateAndResolveUrl(urlStr: string): Promise<ResolvedTarlet addrs: Array<{ address: string; family: number }>;try {addrs = await _dnsLookup(host, { all: true, family: 0 });- } catch (err) {+ } catch {throw new SSRFError('DNS_RESOLUTION_FAILED',- `Failed to resolve ${host}: ${err instanceof Error ? err.message : String(err)}`,+ 'DNS resolution failed for the requested destination',);}if (addrs.length === 0) {- throw new SSRFError('DNS_RESOLUTION_FAILED', `No DNS records for ${host}`);+ throw new SSRFError('DNS_RESOLUTION_FAILED', 'No DNS records for the requested destination');}for (const a of addrs) {if (isAddressInternal(a.address, a.family)) {throw new SSRFError('DNS_RESOLVED_INTERNAL',- `${host} resolves to internal address ${a.address} (DNS rebinding attempt?)`,+ 'DNS returned a nonpublic or invalid address',);}}@@ -164,95 +169,152 @@ function isIpLiteral(host: string): boolean {}function isAddressInternal(addr: string, family: number): boolean {- if (family === 4) {- const octets = hostnameToOctets(addr);- return octets ? isPrivateIpv4(octets) : true; // fail-closed on parse failure- }- if (family === 6) {- const lower = addr.toLowerCase();- if (lower === '::1' || lower === '::') return true;- if (/^f[cd][0-9a-f]{2}:/.test(lower)) return true; // ULA fc00::/7- if (/^fe[89ab][0-9a-f]:/.test(lower)) return true; // link-local fe80::/10- if (lower.startsWith('::ffff:')) {- const tail = lower.slice(7);- const dotted = hostnameToOctets(tail);- if (dotted && isPrivateIpv4(dotted)) return true;- }- return false;- }- return true; // unknown family — fail-closed+ // WHATWG URL canonicalization compresses IPv6 and converts mapped dotted+ // addresses to hextets. Reuse the same classifier as literal URL inputs.+ if ((family !== 4 && family !== 6) || isIP(addr) !== family) return true;+ return isInternalUrl(`http://${family === 6 ? `[${addr}]` : addr}/`);+}++export interface GuardedHttpOptions {+ method?: string;+ headers?: HeadersInit;+ body?: string;+ signal?: AbortSignal | null;+ maxRedirects?: number;+ timeoutMs?: number;+ /** Header-only probes destroy the body immediately, including GET fallback. */+ headerOnly?: boolean;+ /** Required for body reads; counts decoded bytes, not Content-Length. */+ maxBytes?: number;+ /** Recipe-configured headers/auth/body must never cross an origin. */+ sameOrigin?: boolean;+ /** HEAD probes retry 405/501 once with GET without resetting their budget. */+ headFallback?: boolean;+}++export interface GuardedHttpResponse {+ status: number;+ statusText: string;+ ok: boolean;+ headers: Headers;+ url: string;+ body: Buffer;+}++/** @internal Dependency injection keeps transport tests off real DNS/targets. */+export interface GuardedHttpDependencies {+ resolve?: typeof validateAndResolveUrl;+ fetch?: PinnedHttpFetch;}+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);+const PUBLIC_HEADERS = new Set(['accept', 'accept-language', 'user-agent']);+/**- * Fetch a URL with full SSRF protection including per-redirect-hop validation.- *- * On every Location response header, the new URL is re-validated via- * `validateAndResolveUrl` — fresh DNS resolution per hop defeats rebinding- * across the redirect chain. Max 3 hops by default.- *- * Returns the final Response. Caller is responsible for body size limits- * (use `init.signal` to abort, or check `Content-Length` before consuming).+ * Validate -> pin -> request, repeated for every redirect. One abort deadline+ * covers DNS, TLS, redirects and bounded decoded-body consumption. There is no+ * unrestricted Response escaping this boundary.*/export async function fetchWithSSRFGuard(urlStr: string,- init: RequestInit & {- maxRedirects?: number;- timeoutMs?: number;- } = {},-): Promise<Response> {+ init: GuardedHttpOptions = {},+ deps: GuardedHttpDependencies = {},+): Promise<GuardedHttpResponse> {const maxRedirects = init.maxRedirects ?? 3;const timeoutMs = init.timeoutMs ?? 5000;-+ if (!Number.isInteger(maxRedirects) || maxRedirects < 0 || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {+ throw new TypeError('Invalid HTTP redirect limit or timeout');+ }+ if (!init.headerOnly && (!Number.isSafeInteger(init.maxBytes) || init.maxBytes! <= 0)) {+ throw new TypeError('A positive maxBytes is required when reading an HTTP body');+ }+ const initialMethod = (init.method ?? 'GET').toUpperCase();+ if (!/^[!#$%&'*+.^_`|~0-9A-Z-]+$/.test(initialMethod) || ['CONNECT', 'TRACE', 'TRACK'].includes(initialMethod)) {+ throw new TypeError('Unsupported HTTP method');+ }+ if (init.body !== undefined && (typeof init.body !== 'string' || ['GET', 'HEAD'].includes(initialMethod))) {+ throw new TypeError('HTTP bodies must be strings on a method other than GET/HEAD');+ }+ const headers = new Headers(init.headers);+ const sameOrigin = init.sameOrigin || !['GET', 'HEAD'].includes(initialMethod) || init.body !== undefined+ || [...headers.keys()].some(key => !PUBLIC_HEADERS.has(key));const controller = new AbortController();const externalSignal = init.signal;- const onAbort = () => controller.abort();+ const onAbort = () => controller.abort(new SSRFError('REQUEST_ABORTED', 'HTTP request aborted'));if (externalSignal) {- if (externalSignal.aborted) controller.abort();+ if (externalSignal.aborted) onAbort();else externalSignal.addEventListener('abort', onAbort, { once: true });}- const timer = setTimeout(() => controller.abort(), timeoutMs);+ const timer = setTimeout(() => controller.abort(new SSRFError('REQUEST_TIMEOUT', 'HTTP request timeout')), timeoutMs);+ const resolve = deps.resolve ?? validateAndResolveUrl;+ const request = deps.fetch ?? fetchPinnedHttp;try {let currentUrl = urlStr;let hops = 0;+ let method = initialMethod;while (true) {- const target = await validateAndResolveUrl(currentUrl);- const fetchInit: RequestInit = {- ...init,- redirect: 'manual',- signal: controller.signal,- };- // Set Host header to the original hostname so SNI/TLS works correctly- // (we're fetching by resolved IP but the server expects the real host).- const headers = new Headers(init.headers || {});- if (target.originalHost) {- headers.set('Host', target.originalHost);- }- fetchInit.headers = headers;- const res = await fetch(target.resolvedUrl, fetchInit);- // Redirect status codes- if ([301, 302, 303, 307, 308].includes(res.status)) {- if (hops >= maxRedirects) {- throw new SSRFError('SSRF_HOP_LIMIT', `Exceeded ${maxRedirects} redirect hops`);+ controller.signal.throwIfAborted();+ const target = await abortable(resolve(currentUrl), controller.signal);+ controller.signal.throwIfAborted();+ const url = new URL(currentUrl);+ const hop = new AbortController();+ const abortHop = () => hop.abort(controller.signal.reason);+ controller.signal.addEventListener('abort', abortHop, { once: true });+ try {+ const res = await abortable(request(target, url, { method, headers, body: init.body, signal: hop.signal }), controller.signal);+ if (init.headFallback && method === 'HEAD' && [405, 501].includes(res.status)) {+ await res.body?.cancel();+ method = 'GET';+ continue;}const location = res.headers.get('location');- if (!location) {- return res; // redirect with no Location — return as-is, caller decides+ if (REDIRECT_STATUSES.has(res.status) && location) {+ await res.body?.cancel();+ if (hops >= maxRedirects) {+ throw new SSRFError('SSRF_HOP_LIMIT', `Exceeded ${maxRedirects} redirect hops`);+ }+ let next: URL;+ try {+ next = new URL(location, url);+ } catch {+ throw new SSRFError('SSRF_REDIRECT_DENIED', 'Malformed redirect Location');+ }+ if ((url.protocol === 'https:' && next.protocol !== 'https:') || (sameOrigin && next.origin !== url.origin)) {+ throw new SSRFError('SSRF_REDIRECT_DENIED', 'Redirect would downgrade TLS or cross a protected origin');+ }+ currentUrl = next.toString();+ method = initialMethod;+ hops++;+ continue;}- // Resolve relative location against current URL- const next = new URL(location, currentUrl).toString();- currentUrl = next;- hops++;- continue;+ let body: Buffer = Buffer.alloc(0);+ if (init.headerOnly || method === 'HEAD' || !res.ok) await res.body?.cancel();+ else body = await readBoundedHttpBody(res, init.maxBytes!, controller.signal);+ controller.signal.throwIfAborted();+ return { status: res.status, statusText: res.statusText, ok: res.ok, headers: res.headers, url: currentUrl, body };+ } finally {+ // Bun body cancellation alone does not reliably close the connection.+ // Abort every completed/redirected/failed request, keeping the overall+ // deadline independent so the next permitted hop can still run.+ hop.abort();+ controller.signal.removeEventListener('abort', abortHop);}- return res;}+ } catch (err) {+ if (controller.signal.aborted) throw controller.signal.reason;+ throw err;} finally {clearTimeout(timer);if (externalSignal) externalSignal.removeEventListener('abort', onAbort);}}-function truncate(s: string, n = 200): string {- return s.length > n ? s.slice(0, n) + '...' : s;+function abortable<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {+ return new Promise((resolve, reject) => {+ const abort = () => reject(signal.reason);+ signal.addEventListener('abort', abort, { once: true });+ if (signal.aborted) abort();+ pending.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));+ });}diff --git a/src/core/timeline-write-through.ts b/src/core/timeline-write-through.tsindex f24e64e70e..ba139fe613 100644--- a/src/core/timeline-write-through.ts+++ b/src/core/timeline-write-through.ts@@ -57,6 +57,7 @@ import {type WriteThroughResult,} from './write-through.ts';import { withPageLock } from './page-lock.ts';+import { assertSourceFilesystemActive, hasSourceFilesystemLock, withSourceFilesystemLock } from './minions/source-filesystem.ts';import { findTimelineSplitIndex } from './markdown.ts';import {isDurabilityHardened, commitWriteThroughFile, currentBranch, getLastPushOutcome,@@ -333,6 +334,9 @@ export async function writeTimelineEntryThrough(return { handled: false, skipped: target.skipped };}const { filePath, writeRoot } = target;+ if (!hasSourceFilesystemLock(writeRoot)) {+ return await withSourceFilesystemLock(engine, writeRoot, () => writeTimelineEntryThrough(engine, slug, sourceId, entry, opts));+ }const page = await engine.getPage(slug, { sourceId });if (!page) {@@ -391,6 +395,7 @@ export async function writeTimelineEntryThrough(// convention). Clean the temp up on failure — never leak a stray.const tmpPath = `${filePath}.tmp.${process.pid}.${randomBytes(4).toString('hex')}`;try {+ assertSourceFilesystemActive();writeFileSync(tmpPath, afterText, 'utf8');renameSync(tmpPath, filePath);} catch (writeErr) {diff --git a/src/core/url-safety.ts b/src/core/url-safety.tsindex 1755c9e367..c9898a6456 100644--- a/src/core/url-safety.ts+++ b/src/core/url-safety.ts@@ -57,9 +57,10 @@ export function hostnameToOctets(hostname: string): number[] | null {return null;}-/** Classify an IPv4 address as internal/private/reserved. */+/** Classify an IPv4 address as nonpublic, including reserved and multicast ranges. */export function isPrivateIpv4(octets: number[]): boolean {- const [a, b] = octets;+ if (octets.length !== 4 || !octets.every(o => Number.isInteger(o) && o >= 0 && o <= 255)) return true;+ const [a, b, c, d] = octets;if (a === 127) return true; // 127.0.0.0/8 loopbackif (a === 10) return true; // 10.0.0.0/8 RFC1918if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12 RFC1918@@ -67,6 +68,51 @@ export function isPrivateIpv4(octets: number[]): boolean {if (a === 169 && b === 254) return true; // 169.254.0.0/16 link-local (incl. AWS metadata)if (a === 100 && b >= 64 && b <= 127) return true; // 100.64.0.0/10 CGNAT (Tailscale)if (a === 0) return true; // 0.0.0.0/8 unspecified+ if (a >= 224) return true; // Multicast, reserved, and limited broadcast+ // https://www.iana.org/assignments/iana-ipv4-special-registry/+ // Preserve the two globally reachable anycast exceptions in 192.0.0.0/24.+ if (a === 192 && b === 0 && c === 0) return d !== 9 && d !== 10;+ if (a === 192 && b === 0 && c === 2) return true; // Documentation+ if (a === 192 && b === 88 && c === 99) return true; // Deprecated 6to4 relay+ if (a === 198 && (b === 18 || b === 19)) return true; // Benchmarking+ if (a === 198 && b === 51 && c === 100) return true; // Documentation+ if (a === 203 && b === 0 && c === 113) return true; // Documentation+ return false;+}++/** The URL parser has already canonicalized IPv6, including any dotted IPv4 tail. */+function isNonpublicIpv6(host: string): boolean {+ const parts = host.split('::');+ if (parts.length > 2) return true;+ const left = parts[0] ? parts[0].split(':') : [];+ const right = parts[1] ? parts[1].split(':') : [];+ const omitted = 8 - left.length - right.length;+ if ((parts.length === 1 && omitted !== 0) || (parts.length === 2 && omitted < 1)) return true;+ const tuples = [...left, ...Array(omitted).fill('0'), ...right];+ if (tuples.length !== 8 || !tuples.every(t => /^[0-9a-f]{1,4}$/.test(t))) return true;+ const words = tuples.map(t => parseInt(t, 16));+ const embeddedV4 = [words[6] >>> 8, words[6] & 0xff, words[7] >>> 8, words[7] & 0xff];+ // Mapped addresses and the globally routed NAT64 well-known prefix inherit+ // the embedded IPv4 policy, so alternate encodings cannot reach private IPv4.+ if (words.slice(0, 5).every(w => w === 0) && words[5] === 0xffff) return isPrivateIpv4(embeddedV4);+ if (words[0] === 0x64 && words[1] === 0xff9b && words.slice(2, 6).every(w => w === 0)) return isPrivateIpv4(embeddedV4);++ // Current global unicast allocation is 2000::/3. This excludes unspecified,+ // discard, local translation, ULA, link/site-local, multicast, and reserved space.+ // https://www.iana.org/assignments/ipv6-address-space/+ if ((words[0] & 0xe000) !== 0x2000) return true;+ // https://www.iana.org/assignments/iana-ipv6-special-registry/+ if (words[0] === 0x2001 && words[1] < 0x200) {+ // The IETF protocol block is nonpublic except these globally reachable+ // anycast, AMT, AS112, ORCHIDv2, and drone-identifier allocations.+ if (words[1] === 1 && words.slice(2, 7).every(w => w === 0) && words[7] >= 1 && words[7] <= 3) return false;+ if (words[1] === 3 || (words[1] === 4 && words[2] === 0x112)) return false;+ if (words[1] >= 0x20 && words[1] <= 0x3f) return false;+ return true;+ }+ if (words[0] === 0x2001 && words[1] === 0xdb8) return true; // Documentation+ if (words[0] === 0x2002) return true; // Deprecated 6to4; embedded destinations are not confined+ if (words[0] === 0x3fff && words[1] < 0x1000) return true; // Documentation 3fff::/20return false;}@@ -80,7 +126,7 @@ export function isInternalUrl(urlStr: string): boolean {}if (url.protocol !== 'http:' && url.protocol !== 'https:') return true;- let host = url.hostname.toLowerCase();+ let host = url.hostname.toLowerCase().replace(/\.$/, '');const metadataHostnames = new Set(['metadata.google.internal',@@ -95,39 +141,10 @@ export function isInternalUrl(urlStr: string): boolean {if (host.startsWith('[') && host.endsWith(']')) host = host.slice(1, -1);- if (host === '::1' || host === '::') return true;-- // v0.28.1 codex finding (HIGH): also block IPv6 ULA fc00::/7 (private- // unique-local addresses) and link-local fe80::/10. Without this, an- // attacker who controls a hostname's AAAA record can target internal- // IPv6 services even though IPv4 internal-classification fires.- // ULA: first hex tuple matches /^fc[0-9a-f]{2}/ or /^fd[0-9a-f]{2}/- // Link-local: first hex tuple matches /^fe[89ab][0-9a-f]/- if (/^f[cd][0-9a-f]{2}:/i.test(host) || /^fe[89ab][0-9a-f]:/i.test(host)) {- return true;- }-- if (host.startsWith('::ffff:')) {- const tail = host.slice(7);- const dotted = hostnameToOctets(tail);- if (dotted && isPrivateIpv4(dotted)) return true;- const hextets = tail.split(':');- if (hextets.length === 2 && hextets.every(h => /^[0-9a-f]{1,4}$/.test(h))) {- const hi = parseInt(hextets[0], 16);- const lo = parseInt(hextets[1], 16);- const octets = [(hi >> 8) & 0xff, hi & 0xff, (lo >> 8) & 0xff, lo & 0xff];- if (isPrivateIpv4(octets)) return true;- }- }+ if (host.includes(':')) return isNonpublicIpv6(host);const octets = hostnameToOctets(host);if (octets && isPrivateIpv4(octets)) return true;- if (host.endsWith('.')) {- const stripped = host.slice(0, -1);- const strippedOctets = hostnameToOctets(stripped);- if (strippedOctets && isPrivateIpv4(strippedOctets)) return true;- }-return false;}diff --git a/src/core/write-through.ts b/src/core/write-through.tsindex 7b77d086b3..7eef1adc4b 100644--- a/src/core/write-through.ts+++ b/src/core/write-through.ts@@ -1,3 +1,4 @@+import { hasSourceFilesystemLock, withSourceFilesystemLock, assertSourceFilesystemActive } from './minions/source-filesystem.ts';/*** Shared disk write-through for the canonical ingestion path.*@@ -374,6 +375,9 @@ export async function writePageThrough(return { written: false, skipped: target.skipped };}const { filePath, writeRoot, sourcePathToBind } = target;+ if (!hasSourceFilesystemLock(writeRoot)) {+ return await withSourceFilesystemLock(engine, writeRoot, () => writePageThrough(engine, slug, opts));+ }const writtenPage = await engine.getPage(slug, { sourceId });if (!writtenPage) {@@ -413,6 +417,7 @@ export async function writePageThrough(// EEXIST when the directory already exists (POSIX no-ops it). That aborts// the put_page / enrich / capture write-through whenever the prefix dir// already exists, silently leaving the DB and the .md file plane out of sync.+ assertSourceFilesystemActive();if (!existsSync(dir)) mkdirSync(dir, { recursive: true });// Atomic write: unique temp sibling + rename. Unique name (pid + random)@@ -462,6 +467,7 @@ export async function writePageThrough(let pushed: 'pending' | undefined;let lastPushStatus: PushLogOutcome | undefined;try {+ assertSourceFilesystemActive();if (isDurabilityHardened(writeRoot)) {committed = commitWriteThroughFile(writeRoot, filePath, slug);if (committed) {@@ -539,11 +545,15 @@ export async function deletePageThrough(const target = opts.target ?? await resolvePageWriteTarget(engine, slug, sourceId);if (!target.ok) return { removed: false, skipped: target.skipped };const { filePath } = target;+ if (!hasSourceFilesystemLock(target.writeRoot)) {+ return await withSourceFilesystemLock(engine, target.writeRoot, () => deletePageThrough(engine, slug, opts));+ }if (!existsSync(filePath)) {return { removed: false, path: filePath, skipped: 'file_not_present' };}+ assertSourceFilesystemActive();unlinkSync(filePath);return { removed: true, path: filePath };} catch (e) {diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.tsindex 116664fa69..9a55362219 100644--- a/src/mcp/http-transport.ts+++ b/src/mcp/http-transport.ts@@ -26,11 +26,12 @@*/import { createHash } from 'crypto';+import { hasScope } from '../core/scope.ts';import type { BrainEngine } from '../core/engine.ts';import { buildToolDefs } from './tool-defs.ts';import { resolveMcpInstructions } from './instructions.ts';import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';-import { operations } from '../core/operations.ts';+import { operations, operationsByName } from '../core/operations.ts';import type { AuthInfo } from '../core/operations.ts';import { VERSION } from '../version.ts';import { dispatchToolCall, requestLogStatusForResult } from './dispatch.ts';@@ -44,7 +45,7 @@ import { degradedLastError, isEngineDegraded } from '../core/degraded-marker.ts'import { classifyPgAccessError } from '../core/pg-access-classify.ts';import { redactConnectionInfo } from '../core/audit/redact-connection-info.ts';import { redactUrlsInText } from '../core/url-redact.ts';-import { parseLegacyTokenScope, parseTakesHoldersAllowList, coerceLegacyPermissions } from '../core/legacy-token-scope.ts';+import { normalizeTokenScopes, parseLegacyTokenScope, parseTakesHoldersAllowList, coerceLegacyPermissions } from '../core/legacy-token-scope.ts';export { parseLegacyTokenScope };const DEFAULT_BODY_CAP = 1024 * 1024; // 1 MiB@@ -249,7 +250,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {const hash = hashToken(token);try {const [row] = await sql`- SELECT id, name, permissions FROM access_tokens+ SELECT id, name, permissions, scopes FROM access_tokensWHERE token_hash = ${hash} AND revoked_at IS NULL`;if (!row) return { ok: false };@@ -276,8 +277,9 @@ export async function startHttpTransport(opts: HttpTransportOptions) {const auth: AuthInfo = {token,clientId: rowId,+ principal: { kind: 'legacy_token', id: rowId },clientName: rowName,- scopes: [],+ scopes: normalizeTokenScopes(row.scopes) ?? ['read', 'write', 'admin'],sourceId,...(allowedSources ? { allowedSources } : {}),};@@ -422,8 +424,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {// Ambient writeback (opt-in, default off): resolved per initialize —// fail-closed with a per-engine last-known-good bundle, so a config// read failure serves the previous bundle (or the base string), never- // a wrong posture. This transport carries no per-token scopes- // (OV-A5 is the OAuth lane's concern) but it DOES clamp surfaces —+ // a wrong posture. The advertised writeback also respects token scopes —// extract_facts is advertised only when the resolved surface can// actually call it (OV2-14; a verbs/starter-pinned serve must not// order agents to call a tool dispatch will deny).@@ -437,8 +438,8 @@ export async function startHttpTransport(opts: HttpTransportOptions) {// #4748: contract (+ opt-in writeback section) + deployment identity.instructions: resolveMcpInstructions(fileConfig, process.env, {writeback: ambientOptsFrom(writeback, {- remember: surfaceAllowedOps ? surfaceAllowedOps.has('remember') : true,- extractFacts: surfaceAllowedOps ? surfaceAllowedOps.has('extract_facts') : true,+ remember: hasScope(auth.auth!.scopes, 'write') && (!surfaceAllowedOps || surfaceAllowedOps.has('remember')),+ extractFacts: hasScope(auth.auth!.scopes, 'write') && (!surfaceAllowedOps || surfaceAllowedOps.has('extract_facts')),}),}),},@@ -467,9 +468,11 @@ export async function startHttpTransport(opts: HttpTransportOptions) {// unconditionally, so gates-off served the exact listed-but-denied// catalog lie E5 (test/truthful-catalog.e2e-lite.test.ts) pins out.const gateDisabled = await disabledOpsForPublishGates(engine, fileConfig);- const visibleTools = gateDisabled.size === 0- ? tools- : tools.filter(t => !gateDisabled.has(t.name));+ const visibleTools = tools.filter(t => {+ const op = operationsByName[t.name];+ return op && !gateDisabled.has(t.name) && (hasScope(auth.auth!.scopes, op.scope ?? 'read')+ || (op.agentCallable === true && hasScope(auth.auth!.scopes, 'agent')));+ });logRequest(auth.tokenName!, 'tools/list', 'success', Date.now() - startedMs);return Response.json({ result: { tools: visibleTools }, jsonrpc: '2.0', id },@@ -481,6 +484,14 @@ export async function startHttpTransport(opts: HttpTransportOptions) {if (method === 'tools/call') {const toolName: string = params?.name ?? 'unknown';const args: Record<string, unknown> = params?.arguments ?? {};+ const op = operationsByName[toolName];+ if (op && !op.localOnly && !hasScope(auth.auth!.scopes, op.scope ?? 'read') &&+ !(op.agentCallable === true && hasScope(auth.auth!.scopes, 'agent'))) {+ logRequest(auth.tokenName!, `tools/call:${toolName}`, 'denied_after_list', Date.now() - startedMs);+ return Response.json({ jsonrpc: '2.0', id, result: { isError: true, content: [{ type: 'text',+ text: JSON.stringify({ error: 'permission_denied', message: `Tool requires ${op.scope ?? 'read'} scope` }) }] } },+ { headers: corsHeaders(origin) });+ }// v0.28: thread per-token takes-holder allow-list so takes_list /// takes_search / query (when it returns takes) can server-side filter.// v0.34.1 (#861): thread source-isolation scope. Legacy access_tokensdiff --git a/src/schema.sql b/src/schema.sqlindex b9f331e0d6..cb4da594fc 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -1045,6 +1045,8 @@ CREATE TABLE IF NOT EXISTS minion_jobs (queue TEXT NOT NULL DEFAULT 'default',status TEXT NOT NULL DEFAULT 'waiting',priority INTEGER NOT NULL DEFAULT 0,+ submission_authority JSONB, -- NULL legacy rows require local authorization before workers start+ claim_generation BIGINT NOT NULL DEFAULT 0, -- advanced atomically by protocol-aware claimsdata JSONB NOT NULL DEFAULT '{}',max_attempts INTEGER NOT NULL DEFAULT 3,attempts_made INTEGER NOT NULL DEFAULT 0,@@ -1572,6 +1574,28 @@ CREATE TABLE IF NOT EXISTS think_ab_results (CREATE INDEX IF NOT EXISTS think_ab_results_recent_idxON think_ab_results (source_id, ran_at DESC);+-- Reject pre-upgrade producers/claims; old reapers must still be stopped during cutover.++CREATE OR REPLACE FUNCTION enforce_minion_queue_protocol() RETURNS trigger SET search_path = pg_catalog, public AS $protocol$+BEGIN+ IF TG_OP = 'INSERT' THEN+ IF NEW.submission_authority IS NULL OR NEW.claim_generation <> 0 THEN+ RAISE EXCEPTION 'Minion queue protocol 1 required: upgrade every producer and worker before restart';+ END IF;+ ELSIF NEW.status = 'active' AND (OLD.status <> 'active' OR NEW.lock_token IS DISTINCT FROM OLD.lock_token) THEN+ IF NEW.submission_authority IS NULL OR NEW.claim_generation IS DISTINCT FROM OLD.claim_generation + 1 THEN+ RAISE EXCEPTION 'Minion queue protocol 1 required: old workers cannot claim upgraded queue jobs';+ END IF;+ ELSIF NEW.claim_generation IS DISTINCT FROM OLD.claim_generation THEN+ RAISE EXCEPTION 'Minion queue claim generation may advance only with a claim';+ END IF;+ RETURN NEW;+END;+$protocol$ LANGUAGE plpgsql;+DROP TRIGGER IF EXISTS minion_queue_protocol ON minion_jobs;+CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON minion_jobs+ FOR EACH ROW EXECUTE FUNCTION enforce_minion_queue_protocol();+-- NOTIFY trigger for real-time job events (Postgres only, not PGLite)CREATE OR REPLACE FUNCTION notify_minion_job_change() RETURNS trigger SET search_path = pg_catalog, public AS $$BEGINdiff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex f17032585f..a823214a90 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.49.0.0 -->+<!-- gbrain-template-stamp: 0.50.0.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/admin-agents-spend.test.ts b/test/admin-agents-spend.test.tsindex e475f1548d..7adfc38867 100644--- a/test/admin-agents-spend.test.ts+++ b/test/admin-agents-spend.test.ts@@ -260,8 +260,8 @@ describe('queryAgentClientSpend (v0.38 Slice 4 — /admin/api/agents/spend SQL)'// 1 active + 1 waiting + 1 waiting-children + 1 completed (excluded)for (const status of ['active', 'waiting', 'waiting-children', 'delayed', 'paused', 'completed']) {await engine.executeRaw(- `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at)- VALUES ('subagent', $1, $2::jsonb, 'default', 0, now())`,+ `INSERT INTO minion_jobs (submission_authority, name, status, data, queue, priority, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', $1, $2::jsonb, 'default', 0, now())`,[status, JSON.stringify({ prompt: 'x', __owner_client_id: 'busy-client' })],);}@@ -272,8 +272,8 @@ describe('queryAgentClientSpend (v0.38 Slice 4 — /admin/api/agents/spend SQL)'it('only counts subagent jobs (not shell/other minion jobs)', async () => {await seedClient({ id: 'shell-too', scope: 'read agent' });await engine.executeRaw(- `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at)- VALUES ('shell', 'active', $1::jsonb, 'default', 0, now())`,+ `INSERT INTO minion_jobs (submission_authority, name, status, data, queue, priority, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'shell', 'active', $1::jsonb, 'default', 0, now())`,[JSON.stringify({ cmd: 'echo', __owner_client_id: 'shell-too' })],);const rows = await queryAgentClientSpend(engine);@@ -309,8 +309,8 @@ describe('queryAgentClientSpend (v0.38 Slice 4 — /admin/api/agents/spend SQL)'[future],);await engine.executeRaw(- `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at)- VALUES ('subagent', 'active', $1::jsonb, 'default', 0, now())`,+ `INSERT INTO minion_jobs (submission_authority, name, status, data, queue, priority, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'active', $1::jsonb, 'default', 0, now())`,[JSON.stringify({ prompt: 'x', __owner_client_id: 'full-data' })],);const rows = await queryAgentClientSpend(engine);diff --git a/test/agent-install-backup.serial.test.ts b/test/agent-install-backup.serial.test.tsindex a65ea7cd52..a562eda0b8 100644--- a/test/agent-install-backup.serial.test.ts+++ b/test/agent-install-backup.serial.test.ts@@ -11,6 +11,7 @@ import { readInstallReceipt, writeInstallReceipt } from '../src/core/agent-instaimport { createPgliteBackup, rebaseManagedConfig, restorePgliteBackup } from '../src/core/backup/snapshot.ts';import { writeBackupArchive } from '../src/core/backup/archive.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';import { acquireLock, releaseLock, PgliteBusyError } from '../src/core/pglite-lock.ts';import { withEnv } from './helpers/with-env.ts';@@ -55,7 +56,16 @@ beforeAll(async () => {await withEnv({ DATABASE_URL: 'postgres://wrong.invalid/foreign', GBRAIN_DATABASE_URL: 'postgres://wrong.invalid/foreign', OPENAI_API_KEY: 'must-not-persist', GBRAIN_BRAIN_ID: 'foreign', GBRAIN_SOURCE: 'foreign' }, () => setupInAgent({ root, harness: 'grok-bot', bundle, sourceRef }));await withBrain(root, async engine => {await engine.executeRaw(`INSERT INTO facts (fact, source, source_id) VALUES ($1, 'fixture', 'default')`, ['unique DB-only durable fact']);- await engine.executeRaw(`INSERT INTO minion_jobs (name, status, data) VALUES ('subagent', 'waiting', '{}'), ('subagent', 'active', '{}'), ('subagent', 'delayed', '{}'), ('subagent', 'waiting-children', '{}'), ('subagent', 'paused', '{}'), ('subagent', 'completed', '{}')`);+ const queue = new MinionQueue(engine);+ for (const status of ['waiting', 'active', 'delayed', 'waiting-children', 'paused', 'completed']) {+ // Current application submission stamps durable authority. Model each+ // lifecycle state without executing work; active represents one claim.+ const job = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });+ if (status !== 'waiting') await engine.executeRaw(+ "UPDATE minion_jobs SET status=$1, claim_generation=claim_generation+CASE WHEN $1='active' THEN 1 ELSE 0 END WHERE id=$2",+ [status, job.id],+ );+ }await engine.executeRaw(`INSERT INTO sources (id, name, local_path) VALUES ('external', 'External fixture', $1)`, [join(temporary, 'outside')]);await engine.executeRaw(`INSERT INTO pages (slug, type, title, compiled_truth, timeline, frontmatter, content_hash, source_id, source_path) VALUES ('recovery-note', 'note', 'Recovery fixture', '', '', '{}', 'fixture', 'default', $1)`, [join(root, 'memory', 'note.md')]);});@@ -152,19 +162,24 @@ process.exit(await child.exited);});test('existing database files after an interrupted init do not certify unfinished schema migrations', async () => {- const receipt = readInstallReceipt(root)!;- const schema = await withBrain(root, async engine => {+ // This setup recovery has no running work. The separate backup fixture keeps+ // its active jobs for the restore-quarantine assertions below.+ const interruptedRoot = join(temporary, 'interrupted-root');+ await setupInAgent({ root: interruptedRoot, harness: 'grok-bot', bundle, sourceRef });+ const receipt = readInstallReceipt(interruptedRoot)!;+ const schema = await withBrain(interruptedRoot, async engine => {+ await engine.executeRaw("INSERT INTO facts (fact, source, source_id) VALUES ('interrupted init durable fact', 'fixture', 'default')");const current = Number(await engine.getConfig('version'));await engine.setConfig('version', String(current - 1));return current;});receipt.initialized = false; receipt.state = 'installing';writeInstallReceipt(receipt);- const repaired = await setupInAgent({ root, harness: 'grok-bot', bundle, sourceRef });+ const repaired = await setupInAgent({ root: interruptedRoot, harness: 'grok-bot', bundle, sourceRef });expect(repaired.status).toBe('repaired');- expect(readInstallReceipt(root)!.schema_version).toBe(schema);- expect(readInstallReceipt(root)!.pending_runtime_migration).toBe(false);- expect(await withBrain(root, e => e.executeRaw('SELECT fact FROM facts'))).toContainEqual({ fact: 'unique DB-only durable fact' });+ expect(readInstallReceipt(interruptedRoot)!.schema_version).toBe(schema);+ expect(readInstallReceipt(interruptedRoot)!.pending_runtime_migration).toBe(false);+ expect(await withBrain(interruptedRoot, e => e.executeRaw('SELECT fact FROM facts'))).toContainEqual({ fact: 'interrupted init durable fact' });});test('separate installed CLI processes remember, recall and forget despite hostile routing', async () => {diff --git a/test/agent-register-guards.serial.test.ts b/test/agent-register-guards.serial.test.tsindex 13278cfcc2..369c753f61 100644--- a/test/agent-register-guards.serial.test.ts+++ b/test/agent-register-guards.serial.test.ts@@ -98,6 +98,21 @@ describe('agent register live-serve + duplicate-name refusals (real PGLite brainexpect(firstDoc.ok).toBe(true);expect(firstDoc.client_id).toMatch(/^gbrain_cl_/);+ // Reissue must also mint through a fresh transaction after rotating the+ // client secret; returning a client row alone does not wire the harness.+ const reissue = Bun.spawn([+ 'bun', '--no-env-file', 'run', 'src/cli.ts', 'agent', 'register',+ '--reissue', firstDoc.client_id, '--harness', 'codex',+ '--url', 'http://localhost:19139/mcp', '--json',+ ], { cwd: REPO, env, stdout: 'pipe', stderr: 'pipe' });+ const [reissueOut] = await Promise.all([+ new Response(reissue.stdout).text(), new Response(reissue.stderr).text(),+ ]);+ expect(await reissue.exited).toBe(0);+ const reissueDoc = JSON.parse(reissueOut.trim());+ expect(reissueDoc.ok).toBe(true);+ expect(reissueDoc.client_id).toBe(firstDoc.client_id);+// Second register with the SAME name → duplicate_name envelope, exit 1,// message carries the existing client id + the --reissue hint.const dup = register(env);diff --git a/test/agent-register.test.ts b/test/agent-register.test.tsindex 88ac4a6c01..71fb24096c 100644--- a/test/agent-register.test.ts+++ b/test/agent-register.test.ts@@ -326,7 +326,7 @@ describe('PGLite integration (pre-flight → tx → audit → exchange)', () =>// Exchange on the OUTER engine (tx sql is dead after commit) — the// 3600s-default regression pin: expires_in must reflect the 30d column.- const provider = new GBrainOAuthProvider({ sql });+ const provider = new GBrainOAuthProvider({ sql, transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });const tokens = await provider.exchangeClientCredentials(registered.clientId, registered.clientSecret!);expect(tokens.expires_in).toBe(REGISTER_DEFAULT_TOKEN_TTL_SECONDS);@@ -365,7 +365,7 @@ describe('PGLite integration (pre-flight → tx → audit → exchange)', () =>registered = await registerScopedClient(sqlQueryForEngine(tx), 'itest-rotate', baseRegisterArgs(), {});});const oldSecret = registered.clientSecret!;- const provider = new GBrainOAuthProvider({ sql });+ const provider = new GBrainOAuthProvider({ sql, transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });await provider.exchangeClientCredentials(registered.clientId, oldSecret); // sanity: works pre-rotationconst newSecret = await rotateClientSecret(engine, registered.clientId, 'itest-rotate');diff --git a/test/all-sources-sentinel.test.ts b/test/all-sources-sentinel.test.tsindex bde089101b..7284b216da 100644--- a/test/all-sources-sentinel.test.ts+++ b/test/all-sources-sentinel.test.ts@@ -160,7 +160,9 @@ describe('__all__ is never narrower than an unqualified read', () => {expect(federatedSearchScope(ctx, '__all__')).toEqual({sourceIds: ['default', 'src-a', 'src-b'],});- expect(federatedSearchScope(ctx, 'src-a')).toEqual({ sourceId: 'src-a' });+ // Transport federation preserves unqualified reads; it does not grant an+ // arbitrary explicit source to a caller without a durable source grant.+ expect(() => federatedSearchScope(ctx, 'src-a')).toThrow('outside your granted sources');});test('remote scalar scope stays pinned when no transport federation exists', () => {diff --git a/test/authorization-boundaries.test.ts b/test/authorization-boundaries.test.tsnew file mode 100644index 0000000000..b9e43e3416--- /dev/null+++ b/test/authorization-boundaries.test.ts@@ -0,0 +1,47 @@+import { describe, expect, test } from 'bun:test';+import { operations, resolveRequestedScope, type OperationContext } from '../src/core/operations.ts';+import { BRAIN_TOOL_ALLOWLIST, buildBrainTools } from '../src/core/minions/tools/brain-allowlist.ts';++function context(overrides: Partial<OperationContext> = {}): OperationContext {+ return { engine: {} as any, config: {} as any, logger: console as any, dryRun: false,+ remote: true, sourceId: 'source-a', ...overrides };+}++describe('operation authorization boundaries', () => {+ test('scalar and empty-array remote grants reject an explicit foreign source', () => {+ for (const remote of [true, undefined]) {+ for (const allowedSources of [undefined, []]) {+ const ctx = context({ remote, auth: { allowedSources } as any });+ expect(() => resolveRequestedScope(ctx, 'source-b')).toThrow(/granted sources/);+ expect(resolveRequestedScope(ctx, 'source-a')).toEqual({ sourceId: 'source-a' });+ }+ }+ });++ test('unqualified reads retain the scalar default and local explicit routing', () => {+ expect(resolveRequestedScope(context(), undefined)).toEqual({ sourceId: 'source-a' });+ expect(resolveRequestedScope(context({ remote: false }), 'source-b')).toEqual({ sourceId: 'source-b' });+ });++ test('forget_fact cannot expire a foreign or private fact', async () => {+ const op = operations.find(op => op.name === 'forget_fact')!;+ for (const [source_id, visibility] of [['source-b', 'world'], ['source-a', 'private']]) {+ let expired = false;+ const engine = {+ executeRaw: async () => [{ id: '7', source_id, visibility, expired_at: null,+ entity_slug: null, row_num: null, source_markdown_slug: null }],+ expireFact: async () => { expired = true; },+ };+ await expect(op.handler(context({ engine: engine as any }), { id: 7 })).rejects.toThrow(/not found/);+ expect(expired).toBe(false);+ }+ });++ test('delegated registry contains no attachments or local-only operations', () => {+ const tools = buildBrainTools({ engine: {} as any, config: {} as any, subagentId: 7 });+ expect(tools.some(tool => ['brain_file_list', 'brain_file_url'].includes(tool.name))).toBe(false);+ for (const op of operations.filter(op => BRAIN_TOOL_ALLOWLIST.has(op.name))) {+ expect(op.localOnly).not.toBe(true);+ }+ });+});diff --git a/test/autopilot-failure-cooldown.test.ts b/test/autopilot-failure-cooldown.test.tsindex 3b9ed9151a..edcb93e9c7 100644--- a/test/autopilot-failure-cooldown.test.ts+++ b/test/autopilot-failure-cooldown.test.ts@@ -95,7 +95,7 @@ describe('readRecentSourceFailures + isSourceInCooldown (PGLite)', () => {const finished = new Date(Date.now() - finishedMinAgo * 60_000).toISOString();const data = sourceId === null ? {} : { source_id: sourceId };await engine.executeRaw(- `INSERT INTO minion_jobs (name, status, data, finished_at) VALUES ('autopilot-cycle', $1, $2, $3)`,+ `INSERT INTO minion_jobs (submission_authority, name, status, data, finished_at) VALUES ('{"version":1,"kind":"application"}'::jsonb, 'autopilot-cycle', $1, $2, $3)`,[status, data, finished],);}diff --git a/test/bootstrap.test.ts b/test/bootstrap.test.tsindex fa308cdc1d..d0f7d69c8d 100644--- a/test/bootstrap.test.ts+++ b/test/bootstrap.test.ts@@ -31,6 +31,57 @@ import { LATEST_VERSION } from '../src/core/migrate.ts';delete process.env.GBRAIN_PGLITE_SNAPSHOT;describe('PGLiteEngine#applyForwardReferenceBootstrap', () => {+ test('queue bootstrap preserves legacy jobs without authorizing them and repairs either missing column', async () => {+ const engine = new PGLiteEngine();+ await engine.connect({});+ try {+ await engine.initSchema();+ const db = (engine as any).db;+ await db.exec(`+ DROP TRIGGER IF EXISTS minion_queue_protocol ON minion_jobs;+ ALTER TABLE minion_jobs DROP COLUMN submission_authority;+ ALTER TABLE minion_jobs DROP COLUMN claim_generation;+ INSERT INTO minion_jobs (name, status, data, attempts_made, attempts_started, delay_until)+ VALUES ('sync', 'delayed', '{"sourceId":"default"}', 1, 2, '2026-09-01T00:00:00Z'),+ ('lint', 'completed', '{}', 0, 1, NULL);+ `);+ const original = await engine.executeRaw(`+ SELECT id, name, status, data, attempts_made, attempts_started, delay_until FROM minion_jobs ORDER BY id+ `);+ await (engine as any).applyForwardReferenceBootstrap();+ await (engine as any).applyForwardReferenceBootstrap();+ const columns = await engine.executeRaw<{ column_name: string; is_nullable: string; column_default: string | null }>(`+ SELECT column_name, is_nullable, column_default FROM information_schema.columns+ WHERE table_name = 'minion_jobs' AND column_name IN ('submission_authority', 'claim_generation')+ ORDER BY column_name+ `);+ expect(columns).toEqual([+ { column_name: 'claim_generation', is_nullable: 'NO', column_default: '0' },+ { column_name: 'submission_authority', is_nullable: 'YES', column_default: null },+ ]);+ expect(await engine.executeRaw(`+ SELECT id, name, status, data, attempts_made, attempts_started, delay_until FROM minion_jobs ORDER BY id+ `)).toEqual(original);+ expect(await engine.executeRaw(`+ SELECT submission_authority, claim_generation::int FROM minion_jobs ORDER BY id+ `)).toEqual([{ submission_authority: null, claim_generation: 0 }, { submission_authority: null, claim_generation: 0 }]);++ // Partial upgrades must repair either field without overwriting the other.+ await db.exec(`ALTER TABLE minion_jobs DROP COLUMN submission_authority;+ UPDATE minion_jobs SET claim_generation = 7 WHERE name = 'lint';`);+ await (engine as any).applyForwardReferenceBootstrap();+ expect(await engine.executeRaw(`SELECT submission_authority, claim_generation::int FROM minion_jobs WHERE name = 'lint'`))+ .toEqual([{ submission_authority: null, claim_generation: 7 }]);+ await db.exec(`ALTER TABLE minion_jobs DROP COLUMN claim_generation;+ UPDATE minion_jobs SET submission_authority = '{"version":1,"kind":"application"}' WHERE name = 'lint';`);+ await (engine as any).applyForwardReferenceBootstrap();+ expect(await engine.executeRaw(`SELECT submission_authority, claim_generation::int FROM minion_jobs WHERE name = 'lint'`))+ .toEqual([{ submission_authority: { version: 1, kind: 'application' }, claim_generation: 0 }]);+ } finally {+ await engine.disconnect();+ }+ }, 30000);+test('no-op on fresh install (no pages or links table)', async () => {const engine = new PGLiteEngine();await engine.connect({});diff --git a/test/brain-allowlist.serial.test.ts b/test/brain-allowlist.serial.test.tsindex d6c11b11b7..378397abbb 100644--- a/test/brain-allowlist.serial.test.ts+++ b/test/brain-allowlist.serial.test.ts@@ -45,7 +45,7 @@ describe('BRAIN_TOOL_ALLOWLIST', () => {expect(missing).toEqual([]);});- test('contains the v0.15 read-only 10 + put_page + v0.29 salience pair + v114 list_link_sources', () => {+ test('contains delegated page tools and excludes local-only attachments', () => {// v0.29 added get_recent_salience + find_anomalies (read-only).// get_recent_transcripts is deliberately excluded — subagent calls always// have ctx.remote=true, and the v0.29 trust gate rejects remote callers.@@ -53,7 +53,9 @@ describe('BRAIN_TOOL_ALLOWLIST', () => {// the edge-WRITE ops add_link/remove_link stay out (separate trust call).// #2778 added add_timeline_entry (write, fenced like put_page via// operations.ts:enforceSubagentSlugFence).- expect(BRAIN_TOOL_ALLOWLIST.size).toBe(15);+ expect(BRAIN_TOOL_ALLOWLIST.size).toBe(13);+ expect(BRAIN_TOOL_ALLOWLIST.has('file_list')).toBe(false);+ expect(BRAIN_TOOL_ALLOWLIST.has('file_url')).toBe(false);expect(BRAIN_TOOL_ALLOWLIST.has('add_timeline_entry')).toBe(true);expect(BRAIN_TOOL_ALLOWLIST.has('query')).toBe(true);expect(BRAIN_TOOL_ALLOWLIST.has('search')).toBe(true);diff --git a/test/budget-tracker.test.ts b/test/budget-tracker.test.tsindex 81afa54780..f1d07d51d0 100644--- a/test/budget-tracker.test.ts+++ b/test/budget-tracker.test.ts@@ -185,7 +185,7 @@ describe('haltBudgetSubtree', () => {await inheritBudgetOwner(engine, c1.id, owner.id);// Move c1 to 'active' to simulate in-flight.await engine.executeRaw(- `UPDATE minion_jobs SET status = 'active', lock_token = 'lock', lock_until = now() + interval '1 minute' WHERE id = $1`,+ `UPDATE minion_jobs SET status = 'active', claim_generation = claim_generation + 1, lock_token = 'lock', lock_until = now() + interval '1 minute' WHERE id = $1`,[c1.id],);diff --git a/test/capture-build-content.test.ts b/test/capture-build-content.test.tsindex f71ae1e5c9..2b0aad9dc4 100644--- a/test/capture-build-content.test.ts+++ b/test/capture-build-content.test.ts@@ -12,7 +12,7 @@*/import { describe, test, expect } from 'bun:test';-import matter from 'gray-matter';+import { dataFrontmatter as matter } from '../src/core/data-frontmatter.ts';import { __testing as captureTesting } from '../src/commands/capture.ts';const { mergeCaptureFrontmatter, deriveTitle } = captureTesting;diff --git a/test/chronicle-capture.test.ts b/test/chronicle-capture.test.tsindex 8530428598..8546e4a836 100644--- a/test/chronicle-capture.test.ts+++ b/test/chronicle-capture.test.ts@@ -4,7 +4,7 @@* frontmatter sugar. No engine needed.*/import { describe, test, expect } from 'bun:test';-import matter from 'gray-matter';+import { dataFrontmatter as matter } from '../src/core/data-frontmatter.ts';import { __testing } from '../src/commands/capture.ts';const { defaultSlug, mergeCaptureFrontmatter } = __testing;diff --git a/test/client-grants.test.ts b/test/client-grants.test.tsindex 8a3f9f4dc3..9835ac8227 100644--- a/test/client-grants.test.ts+++ b/test/client-grants.test.ts@@ -1,3 +1,4 @@+import { authorizeAsOwner } from './helpers/oauth.ts';import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';@@ -20,7 +21,7 @@ beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();- provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine) });+ provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });}, 60_000);afterAll(async () => { await engine?.disconnect(); }, 15_000);@@ -256,7 +257,8 @@ describe('client capability grants', () => {resolveGrantProfile({ profile: 'delegating-agent', sourceId: 'default', boundTools: ['search'] }));await rescopeClientGrant(engine, created.clientId, { budgetUsdPerDay: '2.50', boundMaxConcurrent: 2 }, { actor: 'test' });const data = JSON.stringify({ __owner_client_id: created.clientId, allowed_tools: ['search'], source_id: 'default' });- const [job] = await engine.executeRaw("INSERT INTO minion_jobs (name, status, data) VALUES ('subagent', 'paused', $1::text::jsonb) RETURNING id", [data]);+ const [job] = await engine.executeRaw("INSERT INTO minion_jobs (name, status, data, submission_authority) VALUES ('subagent', 'paused', $1::text::jsonb, '{\"version\":1,\"kind\":\"application\"}'::jsonb) RETURNING id", [data]);+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = NULL WHERE id = $1', [job.id]);await rescopeClientGrant(engine, created.clientId, { budgetUsdPerDay: null, boundMaxConcurrent: 9 }, { actor: 'test' });const [row] = await engine.executeRaw('SELECT data FROM minion_jobs WHERE id = $1', [job.id]);const frozen = (row.data as any).__delegation_grant;@@ -314,7 +316,7 @@ describe('OAuth code and refresh grant boundaries', () => {const created = await provider.registerClientManual(`pkce-${authMethod}-example`, ['authorization_code', 'refresh_token'], 'read write', [redirect], 'default', undefined, authMethod);const client = (await provider.clientsStore.getClient(created.clientId))!;let destination = '';- await provider.authorize(client, { redirectUri: redirect, codeChallenge: challenge, scopes: ['read', 'write'], resource }, { redirect(url: string) { destination = url; } } as Response);+ await authorizeAsOwner(provider, client, { redirectUri: redirect, codeChallenge: challenge, scopes: ['read', 'write'], resource }, { redirect(url: string) { destination = url; } } as Response);return { client, code: new URL(destination).searchParams.get('code')! };}@@ -322,7 +324,7 @@ describe('OAuth code and refresh grant boundaries', () => {test(`${method}: invalid PKCE or resource preserves code; valid exchange binds audience`, async () => {const { client, code } = await authorization(method);await expect(provider.exchangeAuthorizationCode(client, code, 'x'.repeat(64), redirect, resource)).rejects.toThrow('PKCE');- await expect(provider.exchangeAuthorizationCode(client, code, verifier, redirect, new URL('https://other.example/mcp'))).rejects.toThrow('resource mismatch');+ await expect(provider.exchangeAuthorizationCode(client, code, verifier, redirect, new URL('https://other.example/mcp'))).rejects.toThrow('resource');const tokens = await provider.exchangeAuthorizationCode(client, code, verifier, redirect);expect((await provider.verifyAccessToken(tokens.access_token)).resource?.toString()).toBe(resource.toString());await expect(provider.exchangeAuthorizationCode(client, code, verifier, redirect)).rejects.toThrow('not found');diff --git a/test/commands/capture.test.ts b/test/commands/capture.test.tsindex 2ff93bd25a..a6f354a580 100644--- a/test/commands/capture.test.ts+++ b/test/commands/capture.test.ts@@ -14,7 +14,7 @@ import * as path from 'node:path';import * as os from 'node:os';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import { resetPgliteState } from '../helpers/reset-pglite.ts';-import matter from 'gray-matter';+import { dataFrontmatter as matter } from '../../src/core/data-frontmatter.ts';import { runCapture, __testing } from '../../src/commands/capture.ts';import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';diff --git a/test/cross-modal-phase2.test.ts b/test/cross-modal-phase2.test.tsindex 4fd28a720d..13d46933aa 100644--- a/test/cross-modal-phase2.test.ts+++ b/test/cross-modal-phase2.test.ts@@ -13,9 +13,12 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';import { mkdtempSync, writeFileSync, mkdirSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';+import { gzipSync } from 'node:zlib';import {ImageLoadError,loadImageInput,+ DEFAULT_IMAGE_MAX_BYTES,+ DEFAULT_REMOTE_IMAGE_MAX_BYTES,} from '../src/core/search/image-loader.ts';import { __setDnsLookupForTests } from '../src/core/ssrf-validate.ts';@@ -151,6 +154,7 @@ describe('loadImageInput — invalid input shapes', () => {});describe('loadImageInput — http(s) URL with SSRF defense', () => {+ const originalFetch = globalThis.fetch;let stubAddrs: Map<string, Array<{ address: string; family: number }>>;beforeEach(() => {@@ -165,6 +169,57 @@ describe('loadImageInput — http(s) URL with SSRF defense', () => {return recs;}) as any);});+ afterEach(() => { globalThis.fetch = originalFetch; });++ test('loads compressed PNG using the decoded body and preserves remote/local limits', async () => {+ stubAddrs.set('images.example.test', [{ address: '8.8.8.8', family: 4 }]);+ globalThis.fetch = (async () => new Response(new Uint8Array(gzipSync(PNG_BYTES)), {+ headers: { 'content-encoding': 'gzip', 'content-type': 'image/png' },+ })) as unknown as typeof fetch;+ const image = await loadImageInput('https://images.example.test/image.png');+ expect(image.bytes).toEqual(PNG_BYTES);+ expect(image.contentType).toBe('image/png');+ expect(DEFAULT_REMOTE_IMAGE_MAX_BYTES).toBe(2 * 1024 * 1024);+ expect(DEFAULT_IMAGE_MAX_BYTES).toBe(10 * 1024 * 1024);++ const compressed = new Uint8Array(gzipSync(Buffer.concat([PNG_BYTES, Buffer.alloc(DEFAULT_REMOTE_IMAGE_MAX_BYTES)])));+ globalThis.fetch = (async () => new Response(compressed, { headers: { 'content-encoding': 'gzip' } })) as unknown as typeof fetch;+ await expect(loadImageInput('https://images.example.test/image.png', { maxBytes: DEFAULT_REMOTE_IMAGE_MAX_BYTES }))+ .rejects.toMatchObject({ code: 'OVERSIZED' });+ });++ test('a stalled image body retains the total timeout after headers arrive', async () => {+ stubAddrs.set('images.example.test', [{ address: '8.8.8.8', family: 4 }]);+ let cancelled = false;+ globalThis.fetch = (async () => new Response(new ReadableStream({+ start(controller) { controller.enqueue(PNG_BYTES); },+ cancel() { cancelled = true; },+ }))) as unknown as typeof fetch;+ await expect(loadImageInput('https://images.example.test/image.png', { timeoutMs: 20 }))+ .rejects.toMatchObject({ code: 'TIMEOUT' });+ expect(cancelled).toBe(true);+ });++ test('image error diagnostics exclude signed URLs, transport errors and HTTP reason text', async () => {+ const url = 'https://images.example.test/private-document?signature=private-value';+ stubAddrs.set('images.example.test', [{ address: '8.8.8.8', family: 4 }]);+ globalThis.fetch = (async () => new Response(new ReadableStream())) as unknown as typeof fetch;+ const timedOut = await loadImageInput(url, { timeoutMs: 20 }).catch(error => error);+ expect(timedOut).toBeInstanceOf(ImageLoadError);+ expect(timedOut.code).toBe('TIMEOUT');+ expect(timedOut.message).not.toContain('private-');++ globalThis.fetch = (async () => { throw new Error('TLS failure private-document private-value'); }) as unknown as typeof fetch;+ const failed = await loadImageInput(url).catch(error => error);+ expect(failed.code).toBe('FETCH_FAILED');+ expect(failed.message).not.toContain('private-');++ globalThis.fetch = (async () => new Response(null, { status: 400, statusText: 'private-document private-value' })) as unknown as typeof fetch;+ const rejected = await loadImageInput(url).catch(error => error);+ expect(rejected.code).toBe('FETCH_FAILED');+ expect(rejected.message).toContain('400');+ expect(rejected.message).not.toContain('private-');+ });test('rejects URL whose hostname resolves internal (DNS rebinding)', async () => {stubAddrs.set('attacker.com', [{ address: '127.0.0.1', family: 4 }]);diff --git a/test/cycle-patterns-source-scope.test.ts b/test/cycle-patterns-source-scope.test.tsindex 1ff1a309e5..d7cf56f062 100644--- a/test/cycle-patterns-source-scope.test.ts+++ b/test/cycle-patterns-source-scope.test.ts@@ -46,8 +46,8 @@ beforeAll(async () => {ON CONFLICT (id) DO NOTHING;`);await db.exec(`- INSERT INTO minion_jobs (id, queue, name, data, status)- VALUES (2001, 'default', 'subagent', '{}'::jsonb, 'completed')+ INSERT INTO minion_jobs (submission_authority, id, queue, name, data, status)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 2001, 'default', 'subagent', '{}'::jsonb, 'completed')ON CONFLICT (id) DO NOTHING;`);await db.query(diff --git a/test/cycle-synthesize-daily-cap.test.ts b/test/cycle-synthesize-daily-cap.test.tsindex 46c50608da..c587251340 100644--- a/test/cycle-synthesize-daily-cap.test.ts+++ b/test/cycle-synthesize-daily-cap.test.ts@@ -119,8 +119,8 @@ async function seedPassingFile(rig: Rig, name: string): Promise<string> {/** Seed a recent (or old) synth-v2 submission row for the cap counter. */async function seedSubmissionRow(rig: Rig, opts: { ageHours?: number; status?: string; sourceId?: string; tag: string }): Promise<void> {await rig.engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, data, idempotency_key, created_at)- VALUES ('subagent', 'dream-inline-old-run', $1,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, idempotency_key, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'dream-inline-old-run', $1,jsonb_build_object('source_id', $2::text),$3,now() - ($4 || ' hours')::interval)`,@@ -225,9 +225,9 @@ describe('daily cap — engaged', () => {return `dream:synth-v2:default:filename:${name}:${hash16}`;};await rig.engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, data, idempotency_key, created_at, finished_at)- VALUES ('subagent', 'dream-inline-old-run', 'completed', '{"source_id":"default"}'::jsonb, $1, now() - interval '2 days', now() - interval '2 days'),- ('subagent', 'dream-inline-old-run', 'cancelled', '{"source_id":"default"}'::jsonb, $2, now() - interval '2 days', now() - interval '2 days')`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, idempotency_key, created_at, finished_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'dream-inline-old-run', 'completed', '{"source_id":"default"}'::jsonb, $1, now() - interval '2 days', now() - interval '2 days'),+ ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'dream-inline-old-run', 'cancelled', '{"source_id":"default"}'::jsonb, $2, now() - interval '2 days', now() - interval '2 days')`,[key('2026-08-05-done.txt'), key('2026-08-06-redo.txt')],);const details = await runPhase(rig);@@ -253,10 +253,10 @@ describe('daily cap — engaged', () => {// full: c0of2 + c1of2 completed (a whole set). partial: only c0of3 —// the transcript would ship with holes, so it must be re-synthesized.await rig.engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, data, idempotency_key, created_at, finished_at)- VALUES ('subagent', 'dream-inline-old-run', 'completed', '{"source_id":"default"}'::jsonb, $1, now() - interval '2 days', now() - interval '2 days'),- ('subagent', 'dream-inline-old-run', 'completed', '{"source_id":"default"}'::jsonb, $2, now() - interval '2 days', now() - interval '2 days'),- ('subagent', 'dream-inline-old-run', 'completed', '{"source_id":"default"}'::jsonb, $3, now() - interval '2 days', now() - interval '2 days')`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, idempotency_key, created_at, finished_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'dream-inline-old-run', 'completed', '{"source_id":"default"}'::jsonb, $1, now() - interval '2 days', now() - interval '2 days'),+ ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'dream-inline-old-run', 'completed', '{"source_id":"default"}'::jsonb, $2, now() - interval '2 days', now() - interval '2 days'),+ ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'dream-inline-old-run', 'completed', '{"source_id":"default"}'::jsonb, $3, now() - interval '2 days', now() - interval '2 days')`,[chunkKey('2026-08-07-chunked-full.txt', 0, 2),chunkKey('2026-08-07-chunked-full.txt', 1, 2),@@ -365,8 +365,8 @@ describe('daily cap — engaged', () => {const hash16 = createHash('sha256').update(content, 'utf8').digest('hex').slice(0, 16);const key = `dream:synth-v2:default:filename:${encodeURIComponent('2026-08-09-retry.txt')}:${hash16}`;await rig.engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, data, idempotency_key)- VALUES ('subagent', 'dream-inline-1700000000000-deadbeef', 'waiting', '{}'::jsonb, $1)`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, idempotency_key)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'dream-inline-1700000000000-deadbeef', 'waiting', '{}'::jsonb, $1)`,[key],);const details = await runPhase(rig, { excludeQueue: 'dream-inline-1700000000000-deadbeef' });diff --git a/test/cycle-synthesize-slug-collection.test.ts b/test/cycle-synthesize-slug-collection.test.tsindex 8c19d0a703..4baa82a32b 100644--- a/test/cycle-synthesize-slug-collection.test.ts+++ b/test/cycle-synthesize-slug-collection.test.ts@@ -35,11 +35,11 @@ beforeAll(async () => {// The function only reads tool_executions; minion_jobs just needs to exist.const db = (engine as any).db;await db.exec(`- INSERT INTO minion_jobs (id, queue, name, data, status)+ INSERT INTO minion_jobs (submission_authority, id, queue, name, data, status)VALUES- (1001, 'default', 'subagent', '{}'::jsonb, 'completed'),- (1002, 'default', 'subagent', '{}'::jsonb, 'completed'),- (1003, 'default', 'subagent', '{}'::jsonb, 'completed')+ ('{"version":1,"kind":"application"}'::jsonb, 1001, 'default', 'subagent', '{}'::jsonb, 'completed'),+ ('{"version":1,"kind":"application"}'::jsonb, 1002, 'default', 'subagent', '{}'::jsonb, 'completed'),+ ('{"version":1,"kind":"application"}'::jsonb, 1003, 'default', 'subagent', '{}'::jsonb, 'completed')ON CONFLICT (id) DO NOTHING;`);});diff --git a/test/data-frontmatter.test.ts b/test/data-frontmatter.test.tsnew file mode 100644index 0000000000..2b6b9eec82--- /dev/null+++ b/test/data-frontmatter.test.ts@@ -0,0 +1,51 @@+import { describe, expect, test } from 'bun:test';+import { parseDataFrontmatter, stringifyDataFrontmatter } from '../src/core/data-frontmatter.ts';+import { parseMarkdown } from '../src/core/markdown.ts';++describe('frontmatter data and serialization compatibility', () => {+ test('preserves independently specified field order, scalar types and quoting', () => {+ const data = { title: 'A title', count: 3, enabled: true, date: new Date('2024-06-01'), code: '001', multiline: 'one\ntwo\n' };+ const expected = "---\ntitle: A title\ncount: 3\nenabled: true\ndate: 2024-06-01T00:00:00.000Z\ncode: '001'\nmultiline: |\n one\n two\n---\n# Body\n\n---\nend\n";+ expect(stringifyDataFrontmatter('# Body\n\n---\nend', data)).toBe(expected);+ const parsed = parseDataFrontmatter(expected);+ expect(parsed.data).toEqual(data);+ expect(parsed.content).toBe('# Body\n\n---\nend\n');+ });++ test('preserves empty metadata/body and final-newline conventions', () => {+ expect(stringifyDataFrontmatter('', {})).toBe('\n');+ expect(stringifyDataFrontmatter('body\n\n', {})).toBe('body\n\n');+ expect(stringifyDataFrontmatter('body', { title: 'foo: bar' })).toBe("---\ntitle: 'foo: bar'\n---\nbody\n");+ });++ test('body text is opaque, including apparent executable frontmatter', () => {+ const body = '---javascript\n({title: "example"})\n---\n# Body';+ expect(stringifyDataFrontmatter(body, { type: 'note' })).toBe('---\ntype: note\n---\n' + body + '\n');+ });++ test('recognizes BOM, leading blank lines, CRLF and explicit data languages', () => {+ for (const prefix of ['', '\uFEFF', '\n \n', '\uFEFF\r\n']) {+ for (const language of ['', 'yaml', 'yml', 'json']) {+ const block = language === 'json' ? '{"title":"Example","count":3}' : 'title: Example\r\ncount: 3';+ const input = prefix + '---' + language + '\r\n' + block + '\r\n---\r\nbody\r\n';+ expect(parseDataFrontmatter(input).data).toEqual({ title: 'Example', count: 3 });+ expect(parseDataFrontmatter(input).content).toBe('body\r\n');+ expect(parseMarkdown(input, 'notes/example.md', { validate: true }).errors).toEqual([]);+ }+ }+ });++ test('safe YAML aliases and merge keys retain their ordinary meaning', () => {+ const parsed = parseDataFrontmatter('---\ndefaults: &defaults\n enabled: true\ncopy:\n <<: *defaults\n---\nbody');+ expect(parsed.data.copy).toEqual({ enabled: true });+ });++ test('rejects unknown engines and YAML executable tags without echoing content', () => {+ for (const language of ['javascript', 'js', 'toml', 'unknown']) {+ expect(() => parseDataFrontmatter(`---${language}\n{}\n---\nbody`)).toThrow(/Unsupported frontmatter language/);+ }+ expect(() => parseDataFrontmatter('---\nvalue: !!js/function "private-marker"\n---\nbody')).toThrow('Malformed YAML frontmatter');+ try { parseDataFrontmatter('---\ntitle: [private-marker\n---\nbody'); }+ catch (error) { expect((error as Error).message).not.toContain('private-marker'); }+ });+});diff --git a/test/doctor-queue-divergence.test.ts b/test/doctor-queue-divergence.test.tsindex 69794d577a..3d49cc41e1 100644--- a/test/doctor-queue-divergence.test.ts+++ b/test/doctor-queue-divergence.test.ts@@ -47,8 +47,8 @@ async function seed(extra: { createdAtSql?: string; finishedAtSql?: string; errorText?: string } = {},): Promise<void> {await base.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, error_text, created_at, updated_at, finished_at)- VALUES ($1, $2, $3, $4, ${extra.createdAtSql ?? 'now()'}, now(), ${extra.finishedAtSql ?? 'NULL'})`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, error_text, created_at, updated_at, finished_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, $1, $2, $3, $4, ${extra.createdAtSql ?? 'now()'}, now(), ${extra.finishedAtSql ?? 'NULL'})`,[name, queue, status, extra.errorText ?? null],);}diff --git a/test/doctor-subagent-health.test.ts b/test/doctor-subagent-health.test.tsindex 247837760a..d72523f187 100644--- a/test/doctor-subagent-health.test.ts+++ b/test/doctor-subagent-health.test.ts@@ -66,9 +66,9 @@ describe('doctor subagent_health (v0.41 Bug 2 / Eng D8)', () => {for (let i = 0; i < 3; i++) {await engine.executeRaw(`INSERT INTO minion_jobs- (name, queue, status, attempts_made, attempts_started,+ (submission_authority, name, queue, status, attempts_made, attempts_started,finished_at, started_at, max_attempts)- VALUES ('subagent', 'default', 'completed', 1, 1,+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'default', 'completed', 1, 1,now(), now() - interval '1 second', 3)`,);}diff --git a/test/doctor-wedged-queue.test.ts b/test/doctor-wedged-queue.test.tsindex 63d83112a3..afa36b604c 100644--- a/test/doctor-wedged-queue.test.ts+++ b/test/doctor-wedged-queue.test.ts@@ -51,8 +51,8 @@ async function seed(extra: { lockUntilSql?: string; updatedAtSql?: string; createdAtSql?: string } = {},): Promise<void> {await base.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, lock_until, updated_at, created_at)- VALUES ($1, $2, $3, ${extra.lockUntilSql ?? 'NULL'}, ${extra.updatedAtSql ?? 'now()'}, ${extra.createdAtSql ?? 'now()'})`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, lock_until, updated_at, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, $1, $2, $3, ${extra.lockUntilSql ?? 'NULL'}, ${extra.updatedAtSql ?? 'now()'}, ${extra.createdAtSql ?? 'now()'})`,[name, queue, status],);}@@ -284,12 +284,12 @@ describe('orphaned private dream queues', () => {// Terminal owner + expired lease → the classifier verdict is 'orphan':// auto-recovery cancels it at the next worker spawn / cycle start.await base.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, created_at) VALUES ('parent', 'cycle', 'completed', now() - interval '3 hours')`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, created_at) VALUES ('{"version":1,"kind":"application"}'::jsonb, 'parent', 'cycle', 'completed', now() - interval '3 hours')`,);const owner = await base.executeRaw<{ id: number }>(`SELECT max(id)::int AS id FROM minion_jobs`);await base.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, created_at, updated_at, private_queue_owner_job_id, private_queue_owner_token, private_queue_lease_until)- VALUES ('child', 'dream-inline-owned-dead', 'waiting', now() - interval '2 hours', now() - interval '2 hours', $1, 'tok', now() - interval '1 hour')`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, created_at, updated_at, private_queue_owner_job_id, private_queue_owner_token, private_queue_lease_until)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'child', 'dream-inline-owned-dead', 'waiting', now() - interval '2 hours', now() - interval '2 hours', $1, 'tok', now() - interval '1 hour')`,[owner[0].id],);const check = await computeOrphanedPrivateQueueCheck(pgLike);@@ -300,8 +300,8 @@ describe('orphaned private dream queues', () => {it('suppresses a queue whose owner lease is still in the future (live, never flagged)', async () => {await base.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, created_at, private_queue_owner_token, private_queue_lease_until)- VALUES ('child', 'dream-inline-leased', 'waiting', now() - interval '2 hours', 'tok', now() + interval '30 min')`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, created_at, private_queue_owner_token, private_queue_lease_until)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'child', 'dream-inline-leased', 'waiting', now() - interval '2 hours', 'tok', now() + interval '30 min')`,);const check = await computeOrphanedPrivateQueueCheck(pgLike);expect(check.status).toBe('ok');@@ -317,8 +317,8 @@ describe('orphaned private dream queues — cycle-lock liveness + ownership corrextra: { createdAtSql?: string } = {},): Promise<void> {await base.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, data, created_at)- VALUES ($1, $2, $3, $4::text::jsonb, ${extra.createdAtSql ?? 'now()'})`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, $1, $2, $3, $4::text::jsonb, ${extra.createdAtSql ?? 'now()'})`,['subagent', queue, status, JSON.stringify(dataJson)],);}@@ -440,8 +440,8 @@ describe('orphaned private dream queues — classify cap, buckets, flagged-only// 101 metadata-backed orphan candidates (aged, waiting, expired lease —// classifier verdict 'orphan'), one row per queue for speed.await base.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, created_at, updated_at, private_queue_lease_until)- SELECT 'subagent', 'dream-inline-cap-' || i, 'waiting',+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, created_at, updated_at, private_queue_lease_until)+ SELECT '{"version":1,"kind":"application"}'::jsonb, 'subagent', 'dream-inline-cap-' || i, 'waiting',now() - interval '2 hours', now() - interval '2 hours', now() - interval '1 hour'FROM generate_series(1, 101) AS i`,);@@ -457,8 +457,8 @@ describe('orphaned private dream queues — classify cap, buckets, flagged-only// the 101st never gets classified. Status stays ok but the message and// details must still surface the unclassified remainder.await base.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, created_at, updated_at, private_queue_lease_until)- SELECT 'subagent', 'dream-inline-live-' || i, 'waiting',+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, created_at, updated_at, private_queue_lease_until)+ SELECT '{"version":1,"kind":"application"}'::jsonb, 'subagent', 'dream-inline-live-' || i, 'waiting',now() - interval '2 hours', now(), now() + interval '30 minutes'FROM generate_series(1, 101) AS i`,);@@ -473,12 +473,12 @@ describe('orphaned private dream queues — classify cap, buckets, flagged-only// Owner job still waiting (not claimed, no lock) → verdict not_orphan:// doctor must say "inspect the owner", never advertise cancellation.await base.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, created_at) VALUES ('dream-cycle', 'default', 'waiting', now() - interval '3 hours')`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, created_at) VALUES ('{"version":1,"kind":"application"}'::jsonb, 'dream-cycle', 'default', 'waiting', now() - interval '3 hours')`,);const owner = await base.executeRaw<{ id: number }>(`SELECT max(id)::int AS id FROM minion_jobs`);await base.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, created_at, updated_at, private_queue_owner_job_id, private_queue_owner_token)- VALUES ('subagent', 'dream-inline-owner-pending', 'waiting', now() - interval '2 hours', now() - interval '2 hours', $1, 'tok')`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, created_at, updated_at, private_queue_owner_job_id, private_queue_owner_token)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'dream-inline-owner-pending', 'waiting', now() - interval '2 hours', now() - interval '2 hours', $1, 'tok')`,[owner[0].id],);const check = await computeOrphanedPrivateQueueCheck(pgLike);@@ -497,12 +497,12 @@ describe('orphaned private dream queues — classify cap, buckets, flagged-only// the engine-aware remediation must name the dream trigger (a supervisor// command is impossible advice — no worker process can ever run there).await base.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, created_at) VALUES ('dream-cycle', 'default', 'completed', now() - interval '3 hours')`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, created_at) VALUES ('{"version":1,"kind":"application"}'::jsonb, 'dream-cycle', 'default', 'completed', now() - interval '3 hours')`,);const owner = await base.executeRaw<{ id: number }>(`SELECT max(id)::int AS id FROM minion_jobs`);await base.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, created_at, updated_at, private_queue_owner_job_id, private_queue_owner_token, private_queue_lease_until)- VALUES ('subagent', 'dream-inline-pglite-recoverable', 'waiting', now() - interval '2 hours', now() - interval '2 hours', $1, 'tok', now() - interval '1 hour')`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, created_at, updated_at, private_queue_owner_job_id, private_queue_owner_token, private_queue_lease_until)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'dream-inline-pglite-recoverable', 'waiting', now() - interval '2 hours', now() - interval '2 hours', $1, 'tok', now() - interval '1 hour')`,[owner[0].id],);const check = await computeOrphanedPrivateQueueCheck(base as unknown as BrainEngine);@@ -515,12 +515,12 @@ describe('orphaned private dream queues — classify cap, buckets, flagged-onlyit('waiting_jobs counts FLAGGED queues only — live-lease-suppressed waiting rows are excluded (749a7dcb)', async () => {// Recoverable orphan with 3 waiting rows (terminal owner, expired lease).await base.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, created_at) VALUES ('dream-cycle', 'default', 'completed', now() - interval '3 hours')`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, created_at) VALUES ('{"version":1,"kind":"application"}'::jsonb, 'dream-cycle', 'default', 'completed', now() - interval '3 hours')`,);const owner = await base.executeRaw<{ id: number }>(`SELECT max(id)::int AS id FROM minion_jobs`);await base.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, created_at, updated_at, private_queue_owner_job_id, private_queue_owner_token, private_queue_lease_until)- SELECT 'subagent', 'dream-inline-orphan-n', 'waiting',+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, created_at, updated_at, private_queue_owner_job_id, private_queue_owner_token, private_queue_lease_until)+ SELECT '{"version":1,"kind":"application"}'::jsonb, 'subagent', 'dream-inline-orphan-n', 'waiting',now() - interval '2 hours', now() - interval '2 hours', $1, 'tok', now() - interval '1 hour'FROM generate_series(1, 3)`,[owner[0].id],@@ -528,8 +528,8 @@ describe('orphaned private dream queues — classify cap, buckets, flagged-only// Aged candidate suppressed by a live lease, carrying 2 waiting rows that// must NOT leak into waiting_jobs (pre-fix it summed N+M during the scan).await base.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, created_at, updated_at, private_queue_lease_until)- SELECT 'subagent', 'dream-inline-lively-m', 'waiting',+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, created_at, updated_at, private_queue_lease_until)+ SELECT '{"version":1,"kind":"application"}'::jsonb, 'subagent', 'dream-inline-lively-m', 'waiting',now() - interval '2 hours', now() - interval '2 hours', now() + interval '30 minutes'FROM generate_series(1, 2)`,);diff --git a/test/doctor.test.ts b/test/doctor.test.tsindex 6afa480b07..6ae40cf3d8 100644--- a/test/doctor.test.ts+++ b/test/doctor.test.ts@@ -418,7 +418,7 @@ describe('doctor command', () => {// the pre-#2375 damage class) and one LEGITIMATE string scalar// (persistToolExec binds pre-serialized string payloads as-is).await engine.executeRaw(- `INSERT INTO minion_jobs (id, name, data, status) VALUES (990001, 'doctor-jsonb-test', '{}'::jsonb, 'completed')`,+ `INSERT INTO minion_jobs (submission_authority, id, name, data, status) VALUES ('{"version":1,"kind":"application"}'::jsonb, 990001, 'doctor-jsonb-test', '{}'::jsonb, 'completed')`,);await engine.executeRaw(`INSERT INTO subagent_messages (job_id, message_idx, role, content_blocks)diff --git a/test/dream-retriage.test.ts b/test/dream-retriage.test.tsindex 8d4907bd0a..6438d3afca 100644--- a/test/dream-retriage.test.ts+++ b/test/dream-retriage.test.ts@@ -96,8 +96,8 @@ async function seedJob(rig: Rig, opts: {sourceId?: string;}): Promise<number> {const rows = await rig.engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, queue, status, data, idempotency_key)- VALUES ('subagent', $1, $2, jsonb_build_object('source_id', $3::text), $4)+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, idempotency_key)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', $1, $2, jsonb_build_object('source_id', $3::text), $4)RETURNING id`,[opts.queue ?? 'dream-inline-1700000000000-deadbeef', opts.status ?? 'waiting', opts.sourceId ?? 'default', opts.key],);diff --git a/test/e2e/autopilot-cooldown-parity.test.ts b/test/e2e/autopilot-cooldown-parity.test.tsindex b99c837b1b..4361bcb919 100644--- a/test/e2e/autopilot-cooldown-parity.test.ts+++ b/test/e2e/autopilot-cooldown-parity.test.ts@@ -27,7 +27,7 @@ async function seed(engine: BrainEngine): Promise<void> {];for (const [status, data, minAgo] of rows) {await engine.executeRaw(- `INSERT INTO minion_jobs (name, status, data, finished_at) VALUES ('autopilot-cycle', $1, $2, $3)`,+ `INSERT INTO minion_jobs (submission_authority, name, status, data, finished_at) VALUES ('{"version":1,"kind":"application"}'::jsonb, 'autopilot-cycle', $1, $2, $3)`,[status, data, new Date(Date.now() - minAgo * 60_000).toISOString()],);}diff --git a/test/e2e/autopilot-fanout-postgres.test.ts b/test/e2e/autopilot-fanout-postgres.test.tsindex 657d10a62a..fcfcb9390a 100644--- a/test/e2e/autopilot-fanout-postgres.test.ts+++ b/test/e2e/autopilot-fanout-postgres.test.ts@@ -154,7 +154,7 @@ describeIfDB('autopilot fan-out — Postgres E2E', () => {const r1 = await dispatchPerSource(engine, queue, mkOpts('slot-A'));expect(r1.dispatched).toEqual(['stuck']);await engine.executeRaw(- `UPDATE minion_jobs SET status = 'active', lock_token = 'stuck-worker',+ `UPDATE minion_jobs SET status = 'active', claim_generation = claim_generation + 1, lock_token = 'stuck-worker',lock_until = now() + interval '5 minutes', started_at = now()WHERE name = 'autopilot-cycle'`,);diff --git a/test/e2e/bench-vs-openclaw/durability.bench.ts b/test/e2e/bench-vs-openclaw/durability.bench.tsindex 4561be0a80..e52bc9977b 100644--- a/test/e2e/bench-vs-openclaw/durability.bench.ts+++ b/test/e2e/bench-vs-openclaw/durability.bench.ts@@ -75,12 +75,12 @@ describeBench('Bench: Durability (SIGKILL mid-flight)', () => {// then got SIGKILLed (status=active, lock_until in the past).const seeded = await conn.unsafe<{ id: number }[]>(`INSERT INTO minion_jobs- (name, queue, status, priority, data, max_attempts, attempts_made, attempts_started,+ (submission_authority, name, queue, status, priority, data, max_attempts, attempts_made, attempts_started,backoff_type, backoff_delay, backoff_jitter, stalled_counter, max_stalled,lock_token, lock_until, on_child_fail, depth, remove_on_complete, remove_on_fail,started_at)SELECT- 'bench-rescue', 'default', 'active', 0, '{}'::jsonb, 3, 1, 1,+ '{"version":1,"kind":"application"}'::jsonb, 'bench-rescue', 'default', 'active', 0, '{}'::jsonb, 3, 1, 1,'exponential', 1000, 0.2, 0, 3,'killed-worker:' || gs::text, now() - interval '10 seconds', 'fail_parent', 0, false, false,now() - interval '1 minute'diff --git a/test/e2e/client-grants.test.ts b/test/e2e/client-grants.test.tsindex eb3cdfff24..4352c995bc 100644--- a/test/e2e/client-grants.test.ts+++ b/test/e2e/client-grants.test.ts@@ -60,7 +60,8 @@ suite('client capability grants — Postgres and admin HTTP', () => {{ ...resolveGrantProfile({ profile: 'delegating-agent', sourceId: 'default', boundTools: ['search'] }), budgetUsdPerDay: '3.00', boundMaxConcurrent: 2 });clients.push(client.clientId);const data = JSON.stringify({ __owner_client_id: client.clientId, source_id: 'default', allowed_tools: ['search'] });- const [job] = await engine.executeRaw("INSERT INTO minion_jobs (name, status, data) VALUES ('subagent', 'waiting', $1::text::jsonb) RETURNING id", [data]); jobs.push(Number(job.id));+ const [job] = await engine.executeRaw("INSERT INTO minion_jobs (name, status, data, submission_authority) VALUES ('subagent', 'waiting', $1::text::jsonb, '{\"version\":1,\"kind\":\"application\"}'::jsonb) RETURNING id", [data]);+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = NULL WHERE id = $1', [job.id]); jobs.push(Number(job.id));const attempts = await Promise.allSettled([1, 2].map(() => rescopeClientGrant(engine, client.clientId, { budgetUsdPerDay: null, boundMaxConcurrent: 8 }, { actor: 'pg-test', expectedRevision: 1 })));expect(attempts.filter(a => a.status === 'fulfilled')).toHaveLength(1);expect(attempts.filter(a => a.status === 'rejected')).toHaveLength(1);@@ -146,13 +147,17 @@ suite('client capability grants — Postgres and admin HTTP', () => {const query = new URLSearchParams({ client_id: created.clientId, redirect_uri: redirectUri, response_type: 'code', scope: 'read write', state: 'state-example',code_challenge: createHash('sha256').update(verifier).digest('base64url'), code_challenge_method: 'S256', resource: base + '/mcp' });const authorizeUrl = base + '/authorize?' + query;- expect((await fetch(authorizeUrl, { redirect: 'manual' })).status).toBe(401);- const consent = await fetch(authorizeUrl, { headers: { Cookie: cookie }, redirect: 'manual' }); expect(consent.status).toBe(200);- const nonce = (await consent.text()).match(/name="nonce" value="([a-f0-9]+)"/)?.[1]; expect(nonce).toBeTruthy();- const approval = await fetch(base + '/authorize/consent', { method: 'POST', redirect: 'manual', headers: { Cookie: cookie, Origin: base, 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ nonce: nonce!, decision: 'approve' }) });- expect(approval.status).toBe(303);- const issued = await fetch(base + approval.headers.get('location'), { headers: { Cookie: cookie }, redirect: 'manual' }); expect(issued.status).toBe(302);- const location = new URL(issued.headers.get('location')!); expect(location.searchParams.get('state')).toBe('state-example');+ const consent = await fetch(authorizeUrl, { redirect: 'manual' }); expect(consent.status).toBe(302);+ const pending = new URL(consent.headers.get('location')!, base).searchParams.get('oauth_request');+ expect(pending).toBeTruthy();+ expect((await fetch(base + '/admin/api/oauth-requests/' + pending)).status).toBe(401);+ const detailsResponse = await fetch(base + '/admin/api/oauth-requests/' + pending, { headers: { Cookie: cookie } });+ expect(detailsResponse.status).toBe(200);+ const details = await detailsResponse.json() as any;+ expect(details.allowedOperations).toContain('remember');+ const approval = await post('/admin/api/oauth-requests/' + pending, { csrf: details.csrf, decision: 'approve' });+ expect(approval.status).toBe(200);+ const location = new URL((await approval.json() as any).redirectUrl); expect(location.searchParams.get('state')).toBe('state-example');const code = location.searchParams.get('code'); expect(code).toBeTruthy();const tokenRequest = (values: Record<string, string>) => fetch(base + '/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },body: new URLSearchParams({ client_id: created.clientId, ...(created.clientSecret ? { client_secret: created.clientSecret } : {}), ...values }) });diff --git a/test/e2e/dream-synthesize-chunking.test.ts b/test/e2e/dream-synthesize-chunking.test.tsindex c7e73042b4..5699c02b34 100644--- a/test/e2e/dream-synthesize-chunking.test.ts+++ b/test/e2e/dream-synthesize-chunking.test.ts@@ -207,9 +207,9 @@ describe('E2E synthesize chunking — D8 legacy-key migration', () => {const legacyKey = `dream:synth:${oldFilePath}:${contentHash.slice(0, 16)}`;await rig.engine.executeRaw(`INSERT INTO minion_jobs- (name, queue, status, data, result, idempotency_key, finished_at)+ (submission_authority, name, queue, status, data, result, idempotency_key, finished_at)VALUES- ('subagent', 'default', 'completed', '{}'::jsonb,+ ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'default', 'completed', '{}'::jsonb,'{"stop_reason":"end_turn"}'::jsonb, $1, now())`,[legacyKey],);@@ -271,9 +271,9 @@ describe('E2E synthesize chunking — D8 legacy-key migration', () => {for (const key of legacyKeys) {await rig.engine.executeRaw(`INSERT INTO minion_jobs- (name, queue, status, data, result, idempotency_key, finished_at)+ (submission_authority, name, queue, status, data, result, idempotency_key, finished_at)VALUES- ('subagent', 'default', 'completed', '{}'::jsonb,+ ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'default', 'completed', '{}'::jsonb,'{"stop_reason":"end_turn"}'::jsonb, $1, now())`,[key],);@@ -328,9 +328,9 @@ describe('E2E synthesize chunking — D8 legacy-key migration', () => {const legacyKey = `dream:synth:${filePath}:${contentHash.slice(0, 16)}`;await rig.engine.executeRaw(`INSERT INTO minion_jobs- (name, queue, status, data, result, idempotency_key, finished_at)+ (submission_authority, name, queue, status, data, result, idempotency_key, finished_at)VALUES- ('subagent', 'default', 'completed', '{}'::jsonb,+ ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'default', 'completed', '{}'::jsonb,to_jsonb('{"stop_reason":"end_turn"}'::text), $1, now())`,[legacyKey],);@@ -559,8 +559,8 @@ describe('E2E synthesize — fan-out self-heal for stranded coalesced rows (#415// (Nov 2023) is far past the CX1 liveness grace, so the self-heal may// legally cancel it.const stranded = await rig.engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, queue, status, data, idempotency_key)- VALUES ('subagent', 'dream-inline-1700000000000-deadbeef', 'waiting', '{}'::jsonb, $1)+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, idempotency_key)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'dream-inline-1700000000000-deadbeef', 'waiting', '{}'::jsonb, $1)RETURNING id`,[key],);@@ -619,8 +619,8 @@ describe('E2E synthesize — fan-out self-heal for stranded coalesced rows (#415// concurrently running cycle. The self-heal must leave it alone.const liveQueue = `dream-inline-${Date.now()}-0abc1234`;const seeded = await rig.engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, queue, status, data, idempotency_key)- VALUES ('subagent', $2, 'waiting', '{}'::jsonb, $1)+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, idempotency_key)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', $2, 'waiting', '{}'::jsonb, $1)RETURNING id`,[key, liveQueue],);diff --git a/test/e2e/helpers.ts b/test/e2e/helpers.tsindex 9676692b0c..84ead5e7b5 100644--- a/test/e2e/helpers.ts+++ b/test/e2e/helpers.ts@@ -15,9 +15,9 @@ import { importFromContent } from '../../src/core/import-file.ts';import { parseMarkdown } from '../../src/core/markdown.ts';import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';-// Load .env.testing if present+// Local opt-in configuration; container CI must not import developer credentials.const envPath = resolve(import.meta.dir, '../../.env.testing');-if (existsSync(envPath)) {+if (process.env.GBRAIN_CI_DISABLE_TEST_ENV_FILE !== '1' && existsSync(envPath)) {const lines = readFileSync(envPath, 'utf-8').split('\n');for (const line of lines) {const trimmed = line.trim();diff --git a/test/e2e/jobs-watch-readsnapshot.test.ts b/test/e2e/jobs-watch-readsnapshot.test.tsindex 47b04a6799..1cef03c3d8 100644--- a/test/e2e/jobs-watch-readsnapshot.test.ts+++ b/test/e2e/jobs-watch-readsnapshot.test.ts@@ -59,9 +59,9 @@ describe('v0.41 jobs-watch readSnapshot E2E', () => {}// 2 dead jobs with classifiable errors.await engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, attempts_made, attempts_started, max_attempts, error_text, finished_at, updated_at)- VALUES ('subagent', 'default', 'dead', 1, 1, 1, 'rate lease "anthropic:messages" full (8/8)', now(), now()),- ('subagent', 'default', 'dead', 1, 1, 1, 'prompt is too long: 2M tokens', now(), now())`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, attempts_made, attempts_started, max_attempts, error_text, finished_at, updated_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'default', 'dead', 1, 1, 1, 'rate lease "anthropic:messages" full (8/8)', now(), now()),+ ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'default', 'dead', 1, 1, 1, 'prompt is too long: 2M tokens', now(), now())`,);// One budget-bearing owner with cents.const budgetOwner = await queue.add('subagent', {}, {}, { allowProtectedSubmit: true });diff --git a/test/e2e/minions-authority-parity.test.ts b/test/e2e/minions-authority-parity.test.tsnew file mode 100644index 0000000000..f98cd108a5--- /dev/null+++ b/test/e2e/minions-authority-parity.test.ts@@ -0,0 +1,80 @@+/** Real Postgres backstop for JSONB authority and atomic legacy review. */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, mkdirSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { execFileSync } from 'node:child_process';+import { hasDatabase, setupDB, teardownDB, getEngine } from './helpers.ts';+import { runMigrations } from '../../src/core/migrate.ts';+import { MinionQueue } from '../../src/core/minions/queue.ts';+import { prepareRemoteJob, authorizeJobExecution, assertNoUnreviewedJobs } from '../../src/core/minions/submission-authority.ts';+import { authorizeLegacyJobs } from '../../src/core/minions/authorize-legacy.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { withEnv } from '../helpers/with-env.ts';++const suite = hasDatabase() ? describe : describe.skip;+suite('Postgres queued authority parity', () => {+ let sandbox: string, root: string, queue: MinionQueue;+ const ctx = (): OperationContext => ({+ engine: getEngine(), config: {} as OperationContext['config'], remote: true, sourceId: 'default', dryRun: false,+ logger: { info() {}, warn() {}, error() {} },+ auth: { token: 'test-only', clientId: 'authority-test-client', principal: { kind: 'oauth_client', id: 'authority-test-client' }, scopes: ['admin'], sourceId: 'default' },+ });+ beforeAll(async () => {+ sandbox = mkdtempSync(join(tmpdir(), 'gbrain-pg-job-authority-'));+ root = join(sandbox, 'repo'); mkdirSync(root); execFileSync('git', ['init', '-q', root]);+ await withEnv({ GBRAIN_HOME: sandbox }, async () => { await setupDB(); await runMigrations(getEngine()); });+ queue = new MinionQueue(getEngine());+ }, 120_000);+ afterAll(async () => { await teardownDB(); if (sandbox) rmSync(sandbox, { recursive: true, force: true }); });+ beforeEach(async () => {+ await getEngine().executeRaw('DELETE FROM minion_jobs');+ await getEngine().executeRaw("DELETE FROM oauth_clients WHERE client_id = 'authority-test-client'");+ await getEngine().executeRaw("UPDATE sources SET local_path = $1, config = '{}'::jsonb, archived = false WHERE id = 'default'", [root]);+ await getEngine().executeRaw("INSERT INTO oauth_clients (client_id, client_secret_hash, client_name, scope, source_id) VALUES ('authority-test-client', 'fixture-hash', 'example-client', 'admin', 'default')");+ });+ test('controlled queue protocol cutover matches PGLite', async () => {+ const { rehearseMinionAuthorityUpgrade } = await import('../helpers/minion-authority-upgrade.ts');+ await rehearseMinionAuthorityUpgrade(getEngine());+ });+ test('authority is a JSON object on PostgreSQL and survives replay without promotion', async () => {+ const accepted = await prepareRemoteJob(ctx(), 'lint', {});+ const job = await queue.add('lint', accepted.data, {}, { submissionAuthority: accepted.authority });+ const [raw] = await getEngine().executeRaw<{ kind: string }>('SELECT jsonb_typeof(submission_authority) AS kind FROM minion_jobs WHERE id = $1', [job.id]);+ expect(raw.kind).toBe('object');+ await authorizeJobExecution(getEngine(), (await queue.getJob(job.id))!);+ await getEngine().executeRaw("UPDATE minion_jobs SET status = 'completed' WHERE id = $1", [job.id]);+ expect((await queue.replayJob(job.id))?.submission_authority).toEqual(accepted.authority);+ await getEngine().executeRaw("UPDATE oauth_clients SET deleted_at = now() WHERE client_id = 'authority-test-client'");+ await expect(queue.replayJob(job.id)).rejects.toThrow('revoked');+ });+ test('legacy CAS rollback, NULL cutover gate, and raw-object stamp match PGLite', async () => {+ const job = await queue.add('maintenance', { example: true });+ await getEngine().executeRaw('UPDATE minion_jobs SET submission_authority = NULL WHERE id = $1', [job.id]);+ await expect(assertNoUnreviewedJobs(getEngine())).rejects.toThrow('legacy jobs');+ const preview = await authorizeLegacyJobs(getEngine(), [job.id]);+ await expect(authorizeLegacyJobs(getEngine(), [job.id], 'a'.repeat(64), true)).rejects.toThrow('snapshot changed');+ expect((await queue.getJob(job.id))?.submission_authority).toBeNull();+ await authorizeLegacyJobs(getEngine(), [job.id], preview.snapshot_digest, true);+ expect((await queue.getJob(job.id))?.submission_authority).toEqual({ version: 1, kind: 'application' });+ await assertNoUnreviewedJobs(getEngine());+ });+ test('future authority and JSON null cannot enter the SQL-NULL legacy approval path', async () => {+ const job = await queue.add('maintenance', {});+ await getEngine().executeRaw('UPDATE minion_jobs SET submission_authority = NULL WHERE id = $1', [job.id]);+ const preview = await authorizeLegacyJobs(getEngine(), [job.id]);+ for (const value of [{ version: 2, kind: 'application' }, null]) {+ if (value === null) {+ await getEngine().executeRaw("UPDATE minion_jobs SET submission_authority = 'null'::jsonb WHERE id = $1", [job.id]);+ } else {+ await getEngine().executeRaw('UPDATE minion_jobs SET submission_authority = $1::jsonb WHERE id = $2', [value, job.id]);+ }+ const [before] = await getEngine().executeRaw<{ authority: string }>('SELECT submission_authority::text AS authority FROM minion_jobs WHERE id = $1', [job.id]);+ await expect(authorizeLegacyJobs(getEngine(), [job.id])).rejects.toThrow('SQL NULL');+ await expect(authorizeLegacyJobs(getEngine(), [job.id], preview.snapshot_digest, true)).rejects.toThrow('SQL NULL');+ await expect(assertNoUnreviewedJobs(getEngine())).rejects.toThrow('unsupported authority');+ const [after] = await getEngine().executeRaw<{ authority: string }>('SELECT submission_authority::text AS authority FROM minion_jobs WHERE id = $1', [job.id]);+ expect(after.authority).toBe(before.authority);+ }+ });+});diff --git a/test/e2e/minions-controller-bounce-only.test.ts b/test/e2e/minions-controller-bounce-only.test.tsindex ee77af9ae0..5670b2d4c1 100644--- a/test/e2e/minions-controller-bounce-only.test.ts+++ b/test/e2e/minions-controller-bounce-only.test.ts@@ -84,8 +84,8 @@ describe('v0.41 lease-cap controller E2E (Eng D6 corrected sign)', () => {// Insert dead jobs whose error_text matches the 429 classifier path.for (let i = 0; i < 10; i++) {await engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, attempts_made, attempts_started, max_attempts, error_text, finished_at)- VALUES ('subagent-test', 'default', 'failed', 1, 1, 1, '429 Too Many Requests', now())`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, attempts_made, attempts_started, max_attempts, error_text, finished_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent-test', 'default', 'failed', 1, 1, 1, '429 Too Many Requests', now())`,);}diff --git a/test/e2e/minions-resilience.test.ts b/test/e2e/minions-resilience.test.tsindex 7281f6707c..6d699ef2a7 100644--- a/test/e2e/minions-resilience.test.ts+++ b/test/e2e/minions-resilience.test.ts@@ -166,12 +166,12 @@ describeE2E('E2E: Minions resilience (OpenClaw real-world patterns)', () => {// leaves behind — status='active', lock_token set, lock_until in past.const inserted = await conn.unsafe<{ id: number }[]>(`INSERT INTO minion_jobs- (name, queue, status, priority, data, max_attempts, attempts_made, attempts_started,+ (submission_authority, name, queue, status, priority, data, max_attempts, attempts_made, attempts_started,backoff_type, backoff_delay, backoff_jitter, stalled_counter, max_stalled,lock_token, lock_until, on_child_fail, depth, remove_on_complete, remove_on_fail,started_at)VALUES- ('rescue-me', 'default', 'active', 0, '{}'::jsonb, 3, 1, 1,+ ('{"version":1,"kind":"application"}'::jsonb, 'rescue-me', 'default', 'active', 0, '{}'::jsonb, 3, 1, 1,'exponential', 1000, 0.2, 0, 3,'crashed-worker:123', now() - interval '30 seconds', 'fail_parent', 0, false, false,now() - interval '1 minute')diff --git a/test/e2e/minions-shell.test.ts b/test/e2e/minions-shell.test.tsindex 62da5cf7d0..a916aeeff9 100644--- a/test/e2e/minions-shell.test.ts+++ b/test/e2e/minions-shell.test.ts@@ -125,7 +125,7 @@ describeE2E('E2E: Minions shell handler', () => {{ engine, remote: true, dryRun: false } as any,{ name: 'shell', data: { cmd: 'echo hi', cwd: '/tmp' } },),- ).rejects.toThrow(/permission_denied|cannot be submitted over MCP/i);+ ).rejects.toMatchObject({ code: 'permission_denied' });} finally {await engine.disconnect();}diff --git a/test/e2e/oauth-grant-transactions.test.ts b/test/e2e/oauth-grant-transactions.test.tsnew file mode 100644index 0000000000..8228081fdd--- /dev/null+++ b/test/e2e/oauth-grant-transactions.test.ts@@ -0,0 +1,101 @@+/** Real Postgres row-lock order and rollback; synthetic clients only. */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { setupDB, teardownDB, hasDatabase } from './helpers.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { sqlQueryForEngine, type SqlQuery } from '../../src/core/sql-query.ts';+import { GBrainOAuthProvider } from '../../src/core/oauth-provider.ts';+import { hashToken } from '../../src/core/utils.ts';+import { TEST_PKCE_CHALLENGE, TEST_PKCE_VERIFIER } from '../helpers/oauth.ts';++const suite = hasDatabase() ? describe : describe.skip;+suite('OAuth grant transactions on Postgres', () => {+ let engine: BrainEngine;+ let sql: SqlQuery;+ let provider: GBrainOAuthProvider;+ const clients: string[] = [];+ beforeAll(async () => {+ engine = await setupDB();+ sql = sqlQueryForEngine(engine);+ provider = makeProvider();+ }, 60_000);+ afterAll(async () => {+ if (sql) for (const id of clients) await sql`DELETE FROM oauth_clients WHERE client_id = ${id}`;+ await teardownDB();+ });+ function makeProvider(intercept?: (query: string, run: () => Promise<Record<string, unknown>[]>) => Promise<Record<string, unknown>[]>): GBrainOAuthProvider {+ return new GBrainOAuthProvider({ sql, transaction: fn => engine.transaction(tx => {+ const txSql = sqlQueryForEngine(tx);+ return fn(intercept ? (strings, ...values) => intercept(strings.join('?'), () => txSql(strings, ...values)) : txSql);+ }) });+ }+ async function register() {+ const result = await provider.registerClientManual('synthetic transaction client', ['client_credentials', 'authorization_code', 'refresh_token'], 'read', ['https://client.example/callback']);+ clients.push(result.clientId);+ return result;+ }+ function latch() {+ let release!: () => void;+ const promise = new Promise<void>(resolve => { release = resolve; });+ return { promise, release };+ }+ for (const first of ['issuance', 'revocation'] as const) {+ test(`${first} obtains the client row first; revocation leaves no usable token`, async () => {+ const client = await register();+ const locked = latch();+ const release = latch();+ const attempted = latch();+ const firstProvider = makeProvider(async (query, run) => {+ const result = await run();+ if (query.includes('SELECT * FROM oauth_clients') && query.includes('FOR UPDATE')) {+ locked.release();+ await release.promise;+ }+ return result;+ });+ const secondProvider = makeProvider(async (query, run) => {+ if (query.includes('SELECT * FROM oauth_clients') && query.includes('FOR UPDATE')) attempted.release();+ return run();+ });+ const issue = (p: GBrainOAuthProvider) => p.exchangeClientCredentials(client.clientId, client.clientSecret!, 'read');+ const firstResult = first === 'issuance' ? issue(firstProvider) : firstProvider.revokeClient(client.clientId);+ await locked.promise;+ const secondResult = first === 'issuance' ? secondProvider.revokeClient(client.clientId) : issue(secondProvider);+ // Attach rejection handling before releasing the first transaction.+ const outcomes = Promise.allSettled([firstResult, secondResult]);+ await attempted.promise;+ release.release();+ const results = await outcomes;+ expect(results[0].status).toBe('fulfilled');+ expect(results[1].status).toBe(first === 'issuance' ? 'fulfilled' : 'rejected');+ expect(await sql`SELECT * FROM oauth_tokens WHERE client_id = ${client.clientId}`).toHaveLength(0);+ expect(await provider.clientsStore.getClient(client.clientId)).toBeUndefined();+ }, 15_000);+ }++ test('code and refresh consumption roll back when the second token insert fails', async () => {+ const registered = await register();+ const client = (await provider.clientsStore.getClient(registered.clientId))!;+ const request = await provider.grants.begin(client.client_id, { codeChallenge: TEST_PKCE_CHALLENGE, redirectUri: client.redirect_uris![0], resource: new URL('https://brain.example/mcp') });+ const redirect = await provider.grants.decide(request, true);+ const code = new URL(redirect).searchParams.get('code')!;+ let inserts = 0;+ const failing = makeProvider(async (query, run) => {+ const rows = await run();+ if (query.includes('INSERT INTO oauth_tokens') && ++inserts % 2 === 0) {+ throw new Error('synthetic failure after both token inserts');+ }+ return rows;+ });+ await expect(failing.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER, client.redirect_uris![0])).rejects.toThrow('synthetic failure');+ expect(await sql`SELECT * FROM oauth_codes WHERE code_hash = ${hashToken(code)}`).toHaveLength(1);+ expect(await sql`SELECT * FROM oauth_tokens WHERE client_id = ${client.client_id}`).toHaveLength(0);+ const tokens = await provider.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER, client.redirect_uris![0]);+ await expect(failing.exchangeRefreshToken(client, tokens.refresh_token!)).rejects.toThrow('synthetic failure');+ expect(await sql`SELECT * FROM oauth_tokens WHERE token_hash = ${hashToken(tokens.refresh_token!)}`).toHaveLength(1);+ const outcomes = await Promise.allSettled([provider.exchangeRefreshToken(client, tokens.refresh_token!), provider.exchangeRefreshToken(client, tokens.refresh_token!)]);+ expect(outcomes.filter(result => result.status === 'fulfilled')).toHaveLength(1);+ const succeeded = outcomes.find(result => result.status === 'fulfilled');+ if (succeeded?.status !== 'fulfilled') throw new Error('Expected successful rotation');+ expect((await provider.verifyAccessToken(succeeded.value.access_token)).resource?.toString()).toBe('https://brain.example/mcp');+ });+});diff --git a/test/e2e/openrouter-anthropic-subagent-replay.live.test.ts b/test/e2e/openrouter-anthropic-subagent-replay.live.test.tsindex d4a0a4764e..1e8c61bbe8 100644--- a/test/e2e/openrouter-anthropic-subagent-replay.live.test.ts+++ b/test/e2e/openrouter-anthropic-subagent-replay.live.test.ts@@ -79,8 +79,8 @@ function makeCtx(async function makeJob(prompt: string): Promise<{ jobId: number }> {const rows = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at)- VALUES ('subagent', 'active', $1::jsonb, 'default', 0, now())+ `INSERT INTO minion_jobs (submission_authority, name, status, data, queue, priority, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'active', $1::jsonb, 'default', 0, now())RETURNING id`,[JSON.stringify({ prompt, model: MODEL, max_turns: 4, system: SYSTEM })],);diff --git a/test/e2e/openrouter-deepseek-subagent-replay.live.test.ts b/test/e2e/openrouter-deepseek-subagent-replay.live.test.tsindex cbd4d7d49f..132e8ea8c4 100644--- a/test/e2e/openrouter-deepseek-subagent-replay.live.test.ts+++ b/test/e2e/openrouter-deepseek-subagent-replay.live.test.ts@@ -79,8 +79,8 @@ function makeCtx(async function makeJob(prompt: string): Promise<{ jobId: number }> {const rows = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at)- VALUES ('subagent', 'active', $1::jsonb, 'default', 0, now())+ `INSERT INTO minion_jobs (submission_authority, name, status, data, queue, priority, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'active', $1::jsonb, 'default', 0, now())RETURNING id`,[JSON.stringify({ prompt, model: MODEL, max_turns: 4, system: SYSTEM })],);diff --git a/test/e2e/postgres-bootstrap.test.ts b/test/e2e/postgres-bootstrap.test.tsindex f9ec98201b..1563726be9 100644--- a/test/e2e/postgres-bootstrap.test.ts+++ b/test/e2e/postgres-bootstrap.test.ts@@ -26,6 +26,7 @@ import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PostgresEngine } from '../../src/core/postgres-engine.ts';import { LATEST_VERSION } from '../../src/core/migrate.ts';import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { applyPostgresForwardReferenceBootstrap } from '../../src/core/postgres-engine/forward-reference-bootstrap.ts';const DATABASE_URL = process.env.DATABASE_URL;const skip = !DATABASE_URL;@@ -43,6 +44,71 @@ describe.skipIf(skip)('PostgresEngine forward-reference bootstrap (E2E)', () =>await engine.disconnect();});+ test('grant bootstrap repairs a partial installation without changing existing client policy', async () => {+ await engine.initSchema();+ const conn = await (engine as any).sql.reserve();+ try {+ await conn.unsafe('SELECT pg_advisory_lock(42)');+ await conn.unsafe(`+ INSERT INTO oauth_clients (client_id, client_name, scope, grant_revision)+ VALUES ('fixture-bootstrap-client', 'fixture client', 'read', 4);+ ALTER TABLE oauth_clients DROP COLUMN grant_profile;+ ALTER TABLE oauth_clients DROP COLUMN allowed_operations;+ `);+ await expect((async () => { await conn.unsafe('SELECT grant_profile FROM oauth_clients LIMIT 1'); })())+ .rejects.toThrow('does not exist');+ await applyPostgresForwardReferenceBootstrap(conn);+ await applyPostgresForwardReferenceBootstrap(conn);+ expect(await conn.unsafe(`+ SELECT scope, grant_revision, grant_profile, allowed_operations+ FROM oauth_clients WHERE client_id = 'fixture-bootstrap-client'+ `)).toEqual([{ scope: 'read', grant_revision: 4, grant_profile: null, allowed_operations: null }]);+ } finally {+ await applyPostgresForwardReferenceBootstrap(conn);+ await conn.unsafe("DELETE FROM oauth_clients WHERE client_id = 'fixture-bootstrap-client'");+ await conn.unsafe('SELECT pg_advisory_unlock(42)');+ conn.release();+ }+ }, 30_000);++ test('queue bootstrap preserves historical NULL authority and repairs either missing protocol column', async () => {+ await engine.initSchema();+ const conn = await (engine as any).sql.reserve();+ try {+ await conn.unsafe('SELECT pg_advisory_lock(42)');+ await conn.unsafe(`+ TRUNCATE minion_jobs RESTART IDENTITY CASCADE;+ DROP TRIGGER IF EXISTS minion_queue_protocol ON minion_jobs;+ ALTER TABLE minion_jobs DROP COLUMN submission_authority;+ ALTER TABLE minion_jobs DROP COLUMN claim_generation;+ INSERT INTO minion_jobs (name, status, data, attempts_made, attempts_started, delay_until)+ VALUES ('sync', 'delayed', '{"sourceId":"default"}', 1, 2, '2026-09-01T00:00:00Z'),+ ('lint', 'completed', '{}', 0, 1, NULL);+ `);+ const snapshotSql = 'SELECT id, name, status, data, attempts_made, attempts_started, delay_until FROM minion_jobs ORDER BY id';+ const original = await conn.unsafe(snapshotSql);+ await applyPostgresForwardReferenceBootstrap(conn);+ await applyPostgresForwardReferenceBootstrap(conn);+ expect(await conn.unsafe(snapshotSql)).toEqual(original);+ expect(await conn.unsafe('SELECT submission_authority, claim_generation::int FROM minion_jobs ORDER BY id'))+ .toEqual([{ submission_authority: null, claim_generation: 0 }, { submission_authority: null, claim_generation: 0 }]);+ await conn.unsafe(`ALTER TABLE minion_jobs DROP COLUMN submission_authority;+ UPDATE minion_jobs SET claim_generation = 7 WHERE name = 'lint';`);+ await applyPostgresForwardReferenceBootstrap(conn);+ expect(await conn.unsafe("SELECT submission_authority, claim_generation::int FROM minion_jobs WHERE name = 'lint'"))+ .toEqual([{ submission_authority: null, claim_generation: 7 }]);+ await conn.unsafe(`ALTER TABLE minion_jobs DROP COLUMN claim_generation;+ UPDATE minion_jobs SET submission_authority = '{"version":1,"kind":"application"}' WHERE name = 'lint';`);+ await applyPostgresForwardReferenceBootstrap(conn);+ expect(await conn.unsafe("SELECT submission_authority, claim_generation::int FROM minion_jobs WHERE name = 'lint'"))+ .toEqual([{ submission_authority: { version: 1, kind: 'application' }, claim_generation: 0 }]);+ } finally {+ await conn.unsafe('SELECT pg_advisory_unlock(42)');+ conn.release();+ }+ await engine.initSchema();+ }, 30_000);+test('PostgresEngine.initSchema applies bootstrap → SCHEMA_SQL → migrations on pre-v0.18 brain', async () => {// First call: bring the test DB to LATEST shape so we have something to mutate.await engine.initSchema();diff --git a/test/e2e/serve-http-consent.test.ts b/test/e2e/serve-http-consent.test.tsnew file mode 100644index 0000000000..7f8232d426--- /dev/null+++ b/test/e2e/serve-http-consent.test.ts@@ -0,0 +1,86 @@+/** Full production admin/login/consent route wiring on an isolated in-memory brain. */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { createServer } from 'node:net';+import { spawn, type ChildProcess } from 'node:child_process';+import { TEST_PKCE_CHALLENGE } from '../helpers/oauth.ts';++let child: ChildProcess;+let home: string;+let base: string;+const BOOTSTRAP = 'synthetic-consent-admin-test-token';+beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-consent-test-'));+ const probe = createServer();+ await new Promise<void>(resolve => probe.listen(0, '127.0.0.1', resolve));+ const address = probe.address();+ if (!address || typeof address === 'string') throw new Error('Expected TCP address');+ await new Promise<void>((resolve, reject) => probe.close(err => err ? reject(err) : resolve()));+ base = `http://127.0.0.1:${address.port}`;+ child = spawn(process.execPath, [join(import.meta.dir, '../fixtures/oauth-consent-server.ts')], {+ cwd: join(import.meta.dir, '../..'),+ env: { ...process.env, NODE_ENV: 'test', GBRAIN_HOME: home, DATABASE_URL: '', GBRAIN_DATABASE_URL: '',+ GBRAIN_TEST_HTTP_PORT: String(address.port), GBRAIN_ADMIN_BOOTSTRAP_TOKEN: BOOTSTRAP },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ let output = '';+ child.stderr?.on('data', chunk => { output += chunk.toString(); });+ child.stdout?.on('data', chunk => { output += chunk.toString(); });+ for (let attempt = 0; attempt < 150; attempt++) {+ if (child.exitCode !== null) throw new Error(`Consent server exited: ${output.slice(-2000)}`);+ try { if ((await fetch(`${base}/health`)).ok) return; } catch { /* starting */ }+ await Bun.sleep(100);+ }+ throw new Error(`Consent server did not start: ${output.slice(-2000)}`);+}, 30_000);+afterAll(async () => {+ if (child && child.exitCode === null) {+ const exited = new Promise<void>(resolve => child.once('exit', () => resolve()));+ child.kill('SIGTERM');+ await Promise.race([exited, Bun.sleep(5000)]);+ if (child.exitCode === null && child.signalCode === null) { child.kill('SIGKILL'); await exited; }+ }+ if (home) rmSync(home, { recursive: true, force: true });+});++test('login, magic-link recovery, consent authentication and single-use approval are wired in the real server', async () => {+ const registration = await fetch(`${base}/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({+ client_name: 'synthetic consent client', redirect_uris: [`${base}/callback`], grant_types: ['authorization_code', 'refresh_token'], scope: 'read write', token_endpoint_auth_method: 'none',+ }) });+ expect(registration.status).toBe(201);+ const client = await registration.json() as any;+ const query = new URLSearchParams({ client_id: client.client_id, response_type: 'code', redirect_uri: `${base}/callback`, code_challenge: TEST_PKCE_CHALLENGE, code_challenge_method: 'S256', scope: 'read write', state: 'synthetic-state' });+ const authorization = await fetch(`${base}/authorize?${query}`, { redirect: 'manual' });+ const pendingUrl = new URL(authorization.headers.get('location')!, base);+ expect(pendingUrl.pathname).toBe('/admin/');+ const id = pendingUrl.searchParams.get('oauth_request')!;+ expect((await fetch(pendingUrl)).status).toBe(200); // unauthenticated page shell+ expect((await fetch(`${base}/admin/api/oauth-requests/${id}`)).status).toBe(401);+ const login = await fetch(`${base}/admin/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: BOOTSTRAP }) });+ expect(login.status).toBe(200);+ const oldCookie = login.headers.get('set-cookie')!.split(';')[0];+ expect(login.headers.get('set-cookie')).toContain('SameSite=Strict');+ const oldDetails = await (await fetch(`${base}/admin/api/oauth-requests/${id}`, { headers: { Cookie: oldCookie } })).json() as any;+ const magic = await fetch(`${base}/admin/api/issue-magic-link`, { method: 'POST', headers: { Authorization: `Bearer ${BOOTSTRAP}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ oauth_request: id, return_url: 'https://untrusted.example' }) });+ expect(magic.status).toBe(200);+ const magicUrl = (await magic.json() as any).url.replace(`http://localhost:${new URL(base).port}`, base);+ const redemption = await fetch(magicUrl, { redirect: 'manual' });+ expect(redemption.status).toBe(302);+ expect(redemption.headers.get('location')).toBe(`/admin/?oauth_request=${id}#oauth-consent`);+ const newCookie = redemption.headers.get('set-cookie')!.split(';')[0];+ expect(newCookie).not.toBe(oldCookie);+ const endpoint = `${base}/admin/api/oauth-requests/${id}`;+ const headers = { Cookie: newCookie, 'Content-Type': 'application/json' };+ expect((await fetch(endpoint, { method: 'POST', headers, body: JSON.stringify({ decision: 'approve', csrf: oldDetails.csrf }) })).status).toBe(403);+ const details = await (await fetch(endpoint, { headers })).json() as any;+ expect(details.clientName).toBe('synthetic consent client');+ const approved = await fetch(endpoint, { method: 'POST', headers, body: JSON.stringify({ decision: 'approve', csrf: details.csrf }) });+ expect(approved.status).toBe(200);+ const redirect = new URL((await approved.json() as any).redirectUrl);+ expect(redirect.origin).toBe(base);+ expect(redirect.searchParams.get('state')).toBe('synthetic-state');+ expect(redirect.searchParams.get('code')).toStartWith('gbrain_code_');+ expect((await fetch(endpoint, { method: 'POST', headers, body: JSON.stringify({ decision: 'approve', csrf: details.csrf }) })).status).toBe(410);+}, 15_000);diff --git a/test/e2e/serve-http-oauth.test.ts b/test/e2e/serve-http-oauth.test.tsindex 87663b889d..7130e9e408 100644--- a/test/e2e/serve-http-oauth.test.ts+++ b/test/e2e/serve-http-oauth.test.ts@@ -257,6 +257,25 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {// =========================================================================// Fix 1: client_credentials tokens validate at /mcp+ for (const [label, resource, expectedStatus] of [+ ['matching', `${BASE}/mcp`, 200],+ ['foreign', 'https://different.example/resource', 401],+ ['legacy unbound', null, 200],+ ] as const) {+ test(`MCP enforces the ${label} persisted resource audience`, async () => {+ const { access_token } = await mintToken('read');+ const { default: postgres } = await import('postgres');+ const sql = postgres(process.env.GBRAIN_DATABASE_URL || process.env.DATABASE_URL!, { max: 1 });+ try {+ await sql`UPDATE oauth_tokens SET resource = ${resource}+ WHERE token_hash = ${createHash('sha256').update(access_token).digest('hex')}`;+ } finally { await sql.end(); }+ const response = await mcpCall(access_token, 'tools/list');+ expect(response.status).toBe(expectedStatus);+ if (expectedStatus === 401) expect((await response.json() as any).error).toBe('invalid_token');+ else await response.text();+ });+ }// =========================================================================test('mint token via client_credentials grant', async () => {@@ -608,7 +627,8 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {});expect(res.ok).toBe(false);const data = await res.json() as any;- expect(data.error).toBe('invalid_grant');+ expect(res.status).toBe(401);+ expect(data.error).toBe('invalid_client');});test('confidential client can revoke its token only with its valid secret', async () => {diff --git a/test/e2e/status-pglite.test.ts b/test/e2e/status-pglite.test.tsindex 139f0db4f8..970901f571 100644--- a/test/e2e/status-pglite.test.ts+++ b/test/e2e/status-pglite.test.ts@@ -48,8 +48,8 @@ async function seedAutopilotCycle(engine: PGLiteEngine, opts: {? { partial: false, status: 'ok', report: { totals: opts.totals } }: { partial: false, status: 'ok', report: {} };await engine.executeRaw(- `INSERT INTO minion_jobs (queue, name, data, status, started_at, finished_at, result)- VALUES ('default', $1, '{}'::jsonb, 'completed',+ `INSERT INTO minion_jobs (submission_authority, queue, name, data, status, started_at, finished_at, result)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'default', $1, '{}'::jsonb, 'completed',$2::timestamptz - INTERVAL '5 seconds', $2::timestamptz, $3::jsonb)`,[opts.name, opts.finishedAt, JSON.stringify(result)],);@@ -130,8 +130,8 @@ describe('gbrain status E2E (PGLite)', () => {// status renderer should IGNORE them (returns null), not silently surface// the wrong shape.await engine.executeRaw(- `INSERT INTO minion_jobs (queue, name, data, status, started_at, finished_at, result)- VALUES ('default', 'autopilot-cycle', '{}'::jsonb, 'completed',+ `INSERT INTO minion_jobs (submission_authority, queue, name, data, status, started_at, finished_at, result)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'default', 'autopilot-cycle', '{}'::jsonb, 'completed',NOW() - INTERVAL '5 seconds', NOW(),'{"totals":{"wrong_place":42}}'::jsonb)`,);@@ -173,8 +173,8 @@ describe('gbrain status E2E (PGLite)', () => {// Seed an OLD waiting job (created 10 days ago). The status query MUST// surface it — that's exactly the kind of stuck job operators want to see.await engine.executeRaw(- `INSERT INTO minion_jobs (queue, name, data, status, created_at)- VALUES ('default', 'stale-waiting', '{}'::jsonb, 'waiting',+ `INSERT INTO minion_jobs (submission_authority, queue, name, data, status, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'default', 'stale-waiting', '{}'::jsonb, 'waiting',NOW() - INTERVAL '10 days')`,);let jsonOut = '';diff --git a/test/e2e/subagent-crash-replay-multi-provider.test.ts b/test/e2e/subagent-crash-replay-multi-provider.test.tsindex ec54cc7d24..659922fd8d 100644--- a/test/e2e/subagent-crash-replay-multi-provider.test.ts+++ b/test/e2e/subagent-crash-replay-multi-provider.test.ts@@ -201,8 +201,8 @@ async function seedCrashedState(shape: 'v1' | 'v2',): Promise<{ jobId: number; toolUseId: string; gbrainId: string | null }> {const jobRows = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at)- VALUES ('subagent', 'active', $1::jsonb, 'default', 0, now())+ `INSERT INTO minion_jobs (submission_authority, name, status, data, queue, priority, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'active', $1::jsonb, 'default', 0, now())RETURNING id`,[JSON.stringify({ prompt })],);@@ -408,8 +408,8 @@ describe('SIGKILL crash-replay reconciliation across provider matrix (v0.38 LOAD// (which is the NEW assistant turn the resume will generate),// ordinal=0. priorTools must surface this as status='pending'.const jobRows = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at)- VALUES ('subagent', 'active', '{}'::jsonb, 'default', 0, now())+ `INSERT INTO minion_jobs (submission_authority, name, status, data, queue, priority, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'active', '{}'::jsonb, 'default', 0, now())RETURNING id`,);const jobId = jobRows[0].id;@@ -449,8 +449,8 @@ describe('SIGKILL crash-replay reconciliation across provider matrix (v0.38 LOADconst handler = buildHandler(tools);const jobRows = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at)- VALUES ('subagent', 'active', '{}'::jsonb, 'default', 0, now())+ `INSERT INTO minion_jobs (submission_authority, name, status, data, queue, priority, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'active', '{}'::jsonb, 'default', 0, now())RETURNING id`,);const jobId = jobRows[0].id;diff --git a/test/e2e/subagent-gateway-path.test.ts b/test/e2e/subagent-gateway-path.test.tsindex 777a0f4c1b..7a436aeb2a 100644--- a/test/e2e/subagent-gateway-path.test.ts+++ b/test/e2e/subagent-gateway-path.test.ts@@ -78,8 +78,8 @@ interface FakeJobOpts {async function makeFakeJob(opts: FakeJobOpts): Promise<{ jobId: number; ctx: MinionJobContext; tokenSink: any[] }> {// Insert a minion_jobs row so foreign keys validate (subagent_tool_executions.job_id FK).const rows = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at)- VALUES ('subagent', 'active', $1::jsonb, 'default', 0, now())+ `INSERT INTO minion_jobs (submission_authority, name, status, data, queue, priority, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'active', $1::jsonb, 'default', 0, now())RETURNING id`,[JSON.stringify({ prompt: opts.prompt, model: opts.model, allowed_tools: opts.allowed_tools, mode: opts.mode })],);diff --git a/test/e2e/subagent-gateway-resume-reconciliation.test.ts b/test/e2e/subagent-gateway-resume-reconciliation.test.tsindex cb38e30429..097db55fbc 100644--- a/test/e2e/subagent-gateway-resume-reconciliation.test.ts+++ b/test/e2e/subagent-gateway-resume-reconciliation.test.ts@@ -61,8 +61,8 @@ beforeEach(async () => {async function makeJob(prompt: string, model: string): Promise<{ jobId: number; ctx: MinionJobContext }> {const rows = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at)- VALUES ('subagent', 'active', $1::text::jsonb, 'default', 0, now()) RETURNING id`,+ `INSERT INTO minion_jobs (submission_authority, name, status, data, queue, priority, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'active', $1::text::jsonb, 'default', 0, now()) RETURNING id`,[JSON.stringify({ prompt, model })],);const jobId = rows[0].id;diff --git a/test/e2e/sync-sigkill-resume-postgres.test.ts b/test/e2e/sync-sigkill-resume-postgres.test.tsindex 973905006a..cf00e2a446 100644--- a/test/e2e/sync-sigkill-resume-postgres.test.ts+++ b/test/e2e/sync-sigkill-resume-postgres.test.ts@@ -9,7 +9,7 @@* leaves a durable partial checkpoint (0 < bankedFiles < total) and does* NOT advance the per-source `sources.last_commit` bookmark.* 2. SIGKILL is untrappable, so process-cleanup never runs and the- * per-source `gbrain_cycle_locks` row is STRANDED: holder pid dead, TTL+ * source and filesystem `gbrain_cycle_locks` rows are STRANDED: holder pid dead, TTL* still live, heartbeat recent. Lock-reclaim mechanics under test* (src/core/db-lock.ts:tryAcquireDbLock):* - a fresh strand is NOT stealable — the upsert's ON CONFLICT gate@@ -42,7 +42,8 @@*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';-import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from 'fs';+import { mkdtempSync, writeFileSync, rmSync, mkdirSync, realpathSync } from 'fs';+import { createHash } from 'node:crypto';import { join } from 'path';import { execSync } from 'child_process';import { tmpdir, hostname } from 'os';@@ -68,6 +69,7 @@ const TOTAL_PAGES = NEW_FILES + 1;let home: string;let repoDir: string;+let filesystemLockKey: string;let engine: PostgresEngine;let commitA = '';let commitB = '';@@ -155,6 +157,7 @@ async function bankedCount(): Promise<number> {}interface LockRow {+ id: string;holder_pid: number;holder_host: string;ttl_expired: boolean;@@ -162,16 +165,19 @@ interface LockRow {last_refreshed_at: unknown;}-async function lockRow(): Promise<LockRow | null> {- const rows = await engine.executeRaw<LockRow>(- `SELECT holder_pid::int AS holder_pid, holder_host,+function fixtureLockIds(): string[] {+ return [LOCK_KEY, filesystemLockKey].sort();+}++async function lockRows(): Promise<LockRow[]> {+ return engine.executeRaw<LockRow>(+ `SELECT id, holder_pid::int AS holder_pid, holder_host,(ttl_expires_at < NOW()) AS ttl_expired,(EXTRACT(EPOCH FROM (NOW() - acquired_at)) * 1000)::float8 AS age_ms,last_refreshed_at- FROM gbrain_cycle_locks WHERE id = $1`,- [LOCK_KEY],+ FROM gbrain_cycle_locks WHERE id = ANY($1::text[]) ORDER BY id`,+ [fixtureLockIds()],);- return rows[0] ?? null;}async function sourceLastCommit(): Promise<string | null> {@@ -190,6 +196,9 @@ describeE2E('E2E: real SIGKILL mid-sync on Postgres — checkpoint bank, strandehome = mkdtempSync(join(tmpdir(), 'gbrain-sigkill-home-'));repoDir = mkdtempSync(join(tmpdir(), 'gbrain-sigkill-repo-'));+ // The fixture is itself the Git worktree root, with no registered parent.+ // Pin both locks independently of the lock implementation's helpers.+ filesystemLockKey = `gbrain-fs:${createHash('sha256').update(JSON.stringify(realpathSync(repoDir))).digest('hex')}`;// Fixture repo, commit A: one seed file (establishes last_commit so the// killed run takes the INCREMENTAL checkpointed path, not first_sync).@@ -227,7 +236,9 @@ describeE2E('E2E: real SIGKILL mid-sync on Postgres — checkpoint bank, strandeconst cleanups: Array<[string, unknown[]]> = [[`DELETE FROM facts WHERE source_id = $1`, [SRC_ID]],[`DELETE FROM op_checkpoints WHERE op IN ('sync', 'sync-target') AND fingerprint = $1`, [ckptFingerprint || 'none']],- [`DELETE FROM gbrain_cycle_locks WHERE id = $1`, [LOCK_KEY]],+ [`DELETE FROM gbrain_cycle_locks+ WHERE id = ANY($1::text[]) AND holder_pid = $2 AND holder_host = $3`,+ [fixtureLockIds(), killedPid, hostname()]],[`DELETE FROM sources WHERE id = $1`, [SRC_ID]],];for (const [sql, params] of cleanups) {@@ -323,15 +334,17 @@ describeE2E('E2E: real SIGKILL mid-sync on Postgres — checkpoint bank, strande// (1) Bookmark frozen: last_commit did NOT advance.expect(await sourceLastCommit()).toBe(commitA);- // (2) The per-source lock row is STRANDED: held by the dead child's pid on+ // (2) Both source and filesystem locks are STRANDED: held by the dead child's pid on// this host, TTL still live (30-min default), heartbeat recorded — SIGKILL// bypassed process-cleanup's release.- const lock = await lockRow();- expect(lock).not.toBeNull();- expect(lock!.holder_pid).toBe(killedPid);- expect(lock!.holder_host).toBe(hostname());- expect(lock!.ttl_expired).toBe(false);- expect(lock!.last_refreshed_at).not.toBeNull();+ const locks = await lockRows();+ expect(locks.map(lock => lock.id)).toEqual(fixtureLockIds());+ for (const lock of locks) {+ expect(lock.holder_pid).toBe(killedPid);+ expect(lock.holder_host).toBe(hostname());+ expect(lock.ttl_expired).toBe(false);+ expect(lock.last_refreshed_at).not.toBeNull();+ }// The holder really is dead (proc.exited resolved above reaps the child,// so a signal-0 probe gets ESRCH, not a zombie's success).let probeErr: NodeJS.ErrnoException | null = null;@@ -343,39 +356,46 @@ describeE2E('E2E: real SIGKILL mid-sync on Postgres — checkpoint bank, strande// immediate retry is refused with the lock-busy error. Guard the premise// first so a pathologically slow runner fails loudly instead of flipping// the refusal into a reclaim.- expect(lock!.age_ms).toBeLessThan(40_000);+ for (const lock of locks) expect(lock.age_ms).toBeLessThan(40_000);const busy = await runCli(['sync', '--source', SRC_ID, '--no-embed', '--no-pull']);expect(busy.exitCode).toBe(1);expect(busy.stderr).toContain('Another sync is in progress');expect(busy.stderr).toContain(String(killedPid));// The refused run changed nothing.expect(await sourceLastCommit()).toBe(commitA);- expect((await lockRow())!.holder_pid).toBe(killedPid);+ const stillStranded = await lockRows();+ expect(stillStranded.map(lock => lock.id)).toEqual(fixtureLockIds());+ for (const lock of stillStranded) {+ expect(lock.holder_pid).toBe(killedPid);+ expect(lock.holder_host).toBe(hostname());+ }}, 120_000);test('second sync reclaims the aged-out stranded lock via TTL + steal grace and converges exactly-once', async () => {expect(bankedAfterKill).toBeGreaterThan(0); // depends on the kill test- // Simulate the dead holder aging out (a killed process never refreshes:+ // Simulate both dead-holder locks aging out (a killed process never refreshes:// its TTL lapses and last_refreshed_at drifts). Backdating the row is the// time-warp for the 30-min TTL; the steal grace is shrunk for real via the// documented env knob so the reclaim goes through tryAcquireDbLock's// production ON CONFLICT predicate:// ttl_expires_at < NOW() AND last_refreshed_at < NOW() - grace.- await engine.executeRaw(+ const aged = await engine.executeRaw<{ id: string }>(`UPDATE gbrain_cycle_locksSET ttl_expires_at = NOW() - INTERVAL '1 second',last_refreshed_at = NOW() - INTERVAL '10 minutes',acquired_at = acquired_at - INTERVAL '10 minutes'- WHERE id = $1`,- [LOCK_KEY],+ WHERE id = ANY($1::text[]) AND holder_pid = $2 AND holder_host = $3+ RETURNING id`,+ [fixtureLockIds(), killedPid, hostname()],);+ expect(aged.map(lock => lock.id).sort()).toEqual(fixtureLockIds());const r = await runCli(['sync', '--source', SRC_ID, '--no-embed', '--no-pull'],{ GBRAIN_LOCK_STEAL_GRACE_SECONDS: '60' },);- expect(r.exitCode).toBe(0);+ expect(r.exitCode, `stdout:\n${r.stdout}\nstderr:\n${r.stderr}`).toBe(0);// It RESUMED the banked checkpoint (did not restart): the resume banner// reports exactly the rows banked before the kill.const combined = r.stdout + r.stderr;@@ -408,7 +428,7 @@ describeE2E('E2E: real SIGKILL mid-sync on Postgres — checkpoint bank, strande);expect(Number(parents[0].n)).toBe(0);- // (3d) The reclaimed lock was released by withRefreshingLock's finally.- expect(await lockRow()).toBeNull();+ // (3d) Both reclaimed locks were released by withRefreshingLock's finally.+ expect(await lockRows()).toEqual([]);}, 120_000);});diff --git a/test/e2e/sync-status-pglite.test.ts b/test/e2e/sync-status-pglite.test.tsindex 0773ec4a51..c3afa06a2b 100644--- a/test/e2e/sync-status-pglite.test.ts+++ b/test/e2e/sync-status-pglite.test.ts@@ -201,14 +201,14 @@ describe('buildSyncStatusReport against real PGLite (IRON RULE regression for Bl// Seed embed-backfill minion jobs for source-a: 2 queued + 1 active +// 1 completed. source-b has none → idle.await engine.executeRaw(- `INSERT INTO minion_jobs (name, status, data) VALUES- ('embed-backfill', 'waiting', '{"sourceId":"source-a"}'::jsonb),- ('embed-backfill', 'waiting', '{"sourceId":"source-a"}'::jsonb),- ('embed-backfill', 'active', '{"sourceId":"source-a"}'::jsonb)`,+ `INSERT INTO minion_jobs (submission_authority, name, status, data) VALUES+ ('{"version":1,"kind":"application"}'::jsonb, 'embed-backfill', 'waiting', '{"sourceId":"source-a"}'::jsonb),+ ('{"version":1,"kind":"application"}'::jsonb, 'embed-backfill', 'waiting', '{"sourceId":"source-a"}'::jsonb),+ ('{"version":1,"kind":"application"}'::jsonb, 'embed-backfill', 'active', '{"sourceId":"source-a"}'::jsonb)`,);await engine.executeRaw(- `INSERT INTO minion_jobs (name, status, data, finished_at)- VALUES ('embed-backfill', 'completed', '{"sourceId":"source-a"}'::jsonb, now())`,+ `INSERT INTO minion_jobs (submission_authority, name, status, data, finished_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'embed-backfill', 'completed', '{"sourceId":"source-a"}'::jsonb, now())`,);const sources = await engine.executeRaw<{diff --git a/test/e2e/synthesize-bigint-job-id-postgres.test.ts b/test/e2e/synthesize-bigint-job-id-postgres.test.tsindex 3c64687bbc..b7584c134c 100644--- a/test/e2e/synthesize-bigint-job-id-postgres.test.ts+++ b/test/e2e/synthesize-bigint-job-id-postgres.test.ts@@ -35,8 +35,8 @@ describeE2E('synthesis receipt job-id correlation on Postgres', () => {const engine = getEngine();const conn = getConn();const [job] = await conn`- INSERT INTO minion_jobs (queue, name, data, status)- VALUES ('default', 'subagent', ${conn.json({})}, 'completed')+ INSERT INTO minion_jobs (submission_authority, queue, name, data, status)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'default', 'subagent', ${conn.json({})}, 'completed')RETURNING id`;const jobId = job.id as number;diff --git a/test/embed-backfill-submit.test.ts b/test/embed-backfill-submit.test.tsindex fefa6606f0..d894e5a1a6 100644--- a/test/embed-backfill-submit.test.ts+++ b/test/embed-backfill-submit.test.ts@@ -150,7 +150,7 @@ describe('submitEmbedBackfill — worker-surface gate', () => {);expect(response.isError).toBe(true);const envelope = JSON.parse(response.content[0]?.text ?? '{}') as Record<string, unknown>;- expect(envelope).toMatchObject({ error: 'invalid_params' });+ expect(envelope).toMatchObject({ error: 'permission_denied' });expect(envelope.message).not.toContain('gbrain embed --stale --source');});@@ -183,7 +183,7 @@ describe('submitEmbedBackfill — worker-surface gate', () => {dryRun: false,remote: true,} as never, { name: 'embed-backfill', data: { sourceId: 'default' } })).rejects.toThrow(- 'PGLite has no persistent worker',+ 'only sync, import, lint and lint-fix',);expect(fake.accesses).toEqual([]);@@ -196,17 +196,16 @@ describe('submitEmbedBackfill — worker-surface gate', () => {expect(response.isError).toBe(true);const envelope = JSON.parse(response.content[0]?.text ?? '{}') as Record<string, unknown>;expect(envelope).toMatchObject({- error: 'no_worker_surface',- suggestion: 'Run `gbrain embed --stale --source default` to drain embeddings inline.',+ error: 'permission_denied',});- expect(envelope.message).toContain('PGLite has no persistent worker');+ expect(envelope.message).toContain('only sync, import, lint and lint-fix');const rows = await engine.executeRaw<{ n: number }>(`SELECT COUNT(*)::int AS n FROM minion_jobs WHERE name = 'embed-backfill'`,);expect(Number(rows[0]?.n ?? 0)).toBe(0);});- test('submit_job dry-run reports the same no-worker capability refusal without access or a row', async () => {+ test('submit_job dry-run enforces the same remote job-kind refusal before access', async () => {const fake = failOnAccessPglite();const submitJob = operationsByName.submit_job;await expect(submitJob.handler({@@ -216,7 +215,7 @@ describe('submitEmbedBackfill — worker-surface gate', () => {dryRun: true,remote: true,} as never, { name: 'embed-backfill', data: { sourceId: 'default' } })).rejects.toMatchObject({- code: 'no_worker_surface',+ code: 'permission_denied',});expect(fake.accesses).toEqual([]);@@ -228,7 +227,7 @@ describe('submitEmbedBackfill — worker-surface gate', () => {);expect(response.isError).toBe(true);expect(JSON.parse(response.content[0]?.text ?? '{}')).toMatchObject({- error: 'no_worker_surface',+ error: 'permission_denied',});const rows = await engine.executeRaw<{ n: number }>(`SELECT COUNT(*)::int AS n FROM minion_jobs WHERE name = 'embed-backfill'`,@@ -278,7 +277,7 @@ describe('submitEmbedBackfill — cooldown gate', () => {// Seed an active job manuallyawait queue.add('embed-backfill', { sourceId: 'default' }, {});await engine.executeRaw(- `UPDATE minion_jobs SET status='active' WHERE name='embed-backfill'`,+ `UPDATE minion_jobs SET status='active', claim_generation = claim_generation + 1 WHERE name='embed-backfill'`,);const result = await submitWithWorker('default', { reason: 'unit' });@@ -428,7 +427,7 @@ describe('submitEmbedBackfill — source isolation', () => {const queue = new MinionQueue(workerBackedEngine);// Active job on 'default'await queue.add('embed-backfill', { sourceId: 'default' }, {});- await engine.executeRaw(`UPDATE minion_jobs SET status='active' WHERE name='embed-backfill'`);+ await engine.executeRaw(`UPDATE minion_jobs SET status='active', claim_generation = claim_generation + 1 WHERE name='embed-backfill'`);// Submit for 'other' — should NOT be blockedconst result = await submitWithWorker('other', { reason: 'unit' });diff --git a/test/embed.serial.test.ts b/test/embed.serial.test.tsindex 9a1c91fae3..23dc7a833e 100644--- a/test/embed.serial.test.ts+++ b/test/embed.serial.test.ts@@ -1,4 +1,5 @@import { describe, test, expect, mock, beforeEach, afterEach } from 'bun:test';+import * as realEmbedding from '../src/core/embedding.ts';import type { BrainEngine } from '../src/core/engine.ts';import type { DbLockHandle } from '../src/core/db-lock.ts';@@ -15,6 +16,9 @@ let lastEmbedBatchOpts: unknown = undefined;let embedBatchBehavior: ((texts: string[], opts?: unknown) => Promise<Float32Array[]>) | null = null;mock.module('../src/core/embedding.ts', () => ({+ // Import's withdrawal path also reaches query-side consumers. Keep the+ // module's complete export surface while overriding the transport tested here.+ ...realEmbedding,embedBatch: async (texts: string[], opts?: unknown) => {activeEmbedCalls++;totalEmbedCalls++;diff --git a/test/facts-mcp-allowlist.serial.test.ts b/test/facts-mcp-allowlist.serial.test.tsindex ed8b1b71b7..7469fdec26 100644--- a/test/facts-mcp-allowlist.serial.test.ts+++ b/test/facts-mcp-allowlist.serial.test.ts@@ -71,7 +71,7 @@ describe('forget_fact dispatch', () => {test('forget_fact succeeds on valid id, then becomes idempotent-as-error', async () => {const inserted = await engine.insertFact(- { fact: 'will be forgotten', kind: 'fact', source: 'test' },+ { fact: 'will be forgotten', kind: 'fact', source: 'test', visibility: 'world' },{ source_id: 'default' },);const r1 = await dispatchToolCall(engine, 'forget_fact', { id: inserted.id }, {diff --git a/test/fixtures/e2e-unmapped-baseline.txt b/test/fixtures/e2e-unmapped-baseline.txtindex b96f21dce9..276e496a3a 100644--- a/test/fixtures/e2e-unmapped-baseline.txt+++ b/test/fixtures/e2e-unmapped-baseline.txt@@ -126,8 +126,6 @@ test/e2e/source-routing.test.tstest/e2e/sources-remote-mcp.test.tstest/e2e/status-pglite.test.tstest/e2e/storage-tiering.test.ts-test/e2e/subagent-crash-replay-multi-provider.test.ts-test/e2e/subagent-gateway-path.test.tstest/e2e/subagent-gateway-resume-reconciliation.test.tstest/e2e/symbol-resolver-pglite.test.tstest/e2e/sync-cjk-git.test.tsdiff --git a/test/fixtures/guarded-http-localhost.crt b/test/fixtures/guarded-http-localhost.crtnew file mode 100644index 0000000000..7dde35c60f--- /dev/null+++ b/test/fixtures/guarded-http-localhost.crt@@ -0,0 +1,19 @@+-----BEGIN CERTIFICATE-----+MIIDDDCCAfSgAwIBAgIBATANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAlsb2Nh+bGhvc3QwHhcNMjUwMTAxMDAwMDAwWhcNMzUwMTAxMDAwMDAwWjAUMRIwEAYDVQQD+DAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCwOyJS+JnjEdMeio63Q5XEBg1a4A0YzZDj0gqtJUUd0mtP71Q6KSlRl5JRt4HeNIflGoBHv+8DUpKBYGrRPaIf38B5Idux+akQnccuMrmYh0BF5hdtWlKhgg8skL5kSBoAxI1IPv+PqJzVNPi9DFcpJ4KgiGfCSxBo+cD0uDfgnTgpyCuD3caJkH787T9igDs8cF+R0CY+MHzRkNE3rByOh1qS+kkj87xTDnB3CuwAsP2CgAjKLGlap0uuGBEqk1HaBQeBMBFJ+PDEtxrmw54T2X1p+gUgAOI4u+nqf47ARONdMy8LVm0wBidYr/Rj0DnfuoHMpqEkv+7TnSLk4TF106rxETAgMBAAGjaTBnMB0GA1UdDgQWBBR0ssBAiNpAmjlpv03jEbav+NjGbpzAfBgNVHSMEGDAWgBR0ssBAiNpAmjlpv03jEbavNjGbpzAPBgNVHRMBAf8E+BTADAQH/MBQGA1UdEQQNMAuCCWxvY2FsaG9zdDANBgkqhkiG9w0BAQsFAAOCAQEA+P1ri1iB05XA/sbz6ITQMGYdo+drBEcoCMn0EVupNWfCr8zWRXnD0Wd0dph1Ld6fz+jgyHD1kAhPCXhhcL8zIA9I/2iIRvqbxe8NyGb7rqgXMaXL9xCqWcWVYGZkJ5wbJ5+s8GR8ilhesp68HJ9ImOth9YN9D/9ANsLgnO4svmWfYAbIon+NP4woaL0ld9y25KN+dgbu+ne+k15hxY4ZL1IzFuj1XBLId7oE/wIcsIIiCmfADpSsVBuvAzpgtYI3MK+N+p8s3YvWhBONCzhnipQKqWQOXfR2GPLPTP0/AxFYPEogu7IvWnsB+XCC6aRKWSuuY+BWI5QZvybc5j7k1HsTmvIA==+-----END CERTIFICATE-----diff --git a/test/fixtures/guarded-http-localhost.key b/test/fixtures/guarded-http-localhost.keynew file mode 100644index 0000000000..632a082bbf--- /dev/null+++ b/test/fixtures/guarded-http-localhost.key@@ -0,0 +1,28 @@+-----BEGIN PRIVATE KEY-----+MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCwOyJSJnjEdMei+o63Q5XEBg1a4A0YzZDj0gqtJUUd0mtP71Q6KSlRl5JRt4HeNIflGoBHv8DUpKBYG+rRPaIf38B5Idux+akQnccuMrmYh0BF5hdtWlKhgg8skL5kSBoAxI1IPvPqJzVNPi+9DFcpJ4KgiGfCSxBo+cD0uDfgnTgpyCuD3caJkH787T9igDs8cF+R0CYMHzRkNE3+rByOh1qS+kkj87xTDnB3CuwAsP2CgAjKLGlap0uuGBEqk1HaBQeBMBFJPDEtxrmw+54T2X1p+gUgAOI4u+nqf47ARONdMy8LVm0wBidYr/Rj0DnfuoHMpqEkv7TnSLk4T+F106rxETAgMBAAECggEARpdRTp3Jd0wd4Xh1+fzGEOiWtnvdRV2qcMrcqLAtkrgo+HLKBsgRHHU974y1sRfSrYM5ikP1jlfpQJFl038YI8kjoDw+y/5uEWzEL7R2BapOL+aLgMqS2c36nQvXr9yvycnxm9RXqN4OvEOh89nJH2Glh49jba6uon8cCpQe6EOa4d+r3L6m+dPGkOsukxzDdJjtPIbE5nHy2lyg4CyCi1/cSMYVRGOFanp6x00C9M+ArtH+/WEEdXzteCzgbSBRAUiVTLwdYuuk92JPqm35Sr72lrsqyPovi12gQ2pWho1BckQt+IhqX3lwSjw9bBlhszTgK9b8y1v4QLpbkH1dxTMS75QKBgQDmaayJOTf8+SFbCJjX+CDdBZTlVD951Ve9BFXx5arNKQqjEujhNzpOs3kOJR91l4SAh7ERneFMv0q4rbFVo+PvzDCpGYh02w+AW4/F39FLpMXpeGnMr9WbVRbkRpNjg3/S+7hlLULdcSz6ZxgC7o+94ZvvLjPayQlRsLxb3ejp44XBwKBgQDDzST4bma4GzBUbYMJqTpy632lf22bwK5w+52Ar8xQhzWUb5DEYgRh+fr7DcfZLt7GV+BDDBhbvoG5m23S4q4MTgs9Exm1LjgKV+UhdZcitOJfsqyiEt9DdF5x4EVaD9tpooPSb4iC+E3WZbzQeh1ChQDDNgc3sHovbm+DgGFCiKGlQKBgFCIOs+zeggnIytoM9NkgbuPn5xFcaFdKcR7uAfP7V5VMhugYrF/+NEpFXSGMRqunJc31gGsRuTGL12hB8w/+g+W/ueev0s25wnZHbqpYJk0u+pMIFkK6+qg8OFUcYtkmLarWGW0jhxLxEa45cGQlACnLfaVDFx9pngxdTuGMw2w7dAoGBAJZ0+cX8wnl/EDKwjhniLAC3ERMVCGMCBG8oIEP9Uhti+kn4PJ6aztFWnIQDf9ikSmzQo+7QBfEorJlWwWICezK0J31rr7WoqfMd75uJVzxFEFoG2t6jb8nOhrAsbD4bRzdxuK+egKp6xHGatwJvV6dvuhbp7LqqdQhZmU6x/Ip6oPNAoGANSaN47Sdafq87JHlZQl2+GK4+pDId6mmLiNgK3qAsQCGf5ruSkOqclydE5zo21kDkxNlh1NH8e2sXcWNDUPux+iN/bjr/HOKjGKx7U7keytXddWhwbYfUFmJbS0PQkdJanykFfckbPGnXiVy5y+ksq+nA3DpTiaVqypvp+n1tUhp+g=+-----END PRIVATE KEY-----diff --git a/test/fixtures/oauth-consent-server.ts b/test/fixtures/oauth-consent-server.tsnew file mode 100644index 0000000000..7157a234e5--- /dev/null+++ b/test/fixtures/oauth-consent-server.ts@@ -0,0 +1,13 @@+/** Isolated HTTP server for consent integration tests; never opens a user's brain. */+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { runServeHttp } from '../../src/commands/serve-http.ts';++const engine = new PGLiteEngine();+await engine.connect({});+await engine.initSchema();+try {+ await runServeHttp(engine, {+ port: Number(process.env.GBRAIN_TEST_HTTP_PORT), tokenTtl: 3600,+ enableDcr: true, bind: '127.0.0.1',+ });+} finally { await engine.disconnect(); }diff --git a/test/frontmatter-inference.test.ts b/test/frontmatter-inference.test.tsindex 0e71c7b283..5773355847 100644--- a/test/frontmatter-inference.test.ts+++ b/test/frontmatter-inference.test.ts@@ -6,7 +6,7 @@*/import { describe, test, expect } from 'bun:test';-import matter from 'gray-matter';+import { dataFrontmatter as matter } from '../src/core/data-frontmatter.ts';import {compileExcludePatterns,DEFAULT_EXCLUDE_PATTERNS,diff --git a/test/frontmatter-security.test.ts b/test/frontmatter-security.test.tsnew file mode 100644index 0000000000..1c673284aa--- /dev/null+++ b/test/frontmatter-security.test.ts@@ -0,0 +1,33 @@+import { describe, expect, test } from 'bun:test';+import { parseMarkdown, serializeMarkdown } from '../src/core/markdown.ts';+import { mergeCaptureFrontmatter } from '../src/core/capture-content.ts';+import { importFromContent } from '../src/core/import-file.ts';+import type { BrainEngine } from '../src/core/engine.ts';++describe('data-only frontmatter boundary', () => {+ // The expression is inert: it creates an object and has no filesystem,+ // process, network, or other side effects, even against the old parser.+ const executable = '---javascript\n({title: "example", type: "note"})\n---\n# Body';++ test('executable selectors produce a validation error', () => {+ const parsed = parseMarkdown(executable, 'notes/example.md', { validate: true });+ expect(parsed.errors?.some(error => error.code === 'YAML_PARSE')).toBe(true);+ });++ test('capture rejects an executable selector before wrapping its body', () => {+ expect(() => mergeCaptureFrontmatter(executable, { type: 'note' })).toThrow(/frontmatter|language/i);+ });++ test('import rejects executable frontmatter before accessing the engine', async () => {+ const engine = new Proxy({}, { get() { throw new Error('unexpected engine access'); } }) as BrainEngine;+ const result = await importFromContent(engine, 'notes/example', executable, { noEmbed: true });+ expect(result.status).toBe('error');+ expect(result.error).toMatch(/frontmatter|language/i);+ });++ test('serialization never interprets a body beginning with frontmatter', () => {+ const body = '---\nbody_field: retained\n---\n# Body';+ const result = serializeMarkdown({}, body, '', { type: 'note', title: 'Example', tags: [] });+ expect(result).toContain('\n\n' + body + '\n');+ });+});diff --git a/test/gbrain-to-envelope.test.ts b/test/gbrain-to-envelope.test.tsindex e74d12c755..b4a6e127fd 100644--- a/test/gbrain-to-envelope.test.ts+++ b/test/gbrain-to-envelope.test.ts@@ -1993,7 +1993,7 @@ describe('gbrain-to-envelope exporter', () => {// corrupted with zero stderr. This drives gbrain's actual serializer// (gray-matter = js-yaml, the engine of serializeMarkdown) over a battery// of whitespace-hostile ids and requires every one back verbatim.- const matter = (await import('gray-matter')).default;+ const matter = (await import('../src/core/data-frontmatter.ts')).dataFrontmatter;const HOSTILE = ['a\n \nb', ' \na', '\n', '\n\n', 'a\n', 'a\n\n', '\na', 'a \n', 'x'.repeat(90), 'm-plain'];const ts = (i: number) => `2026-02-01T09:${String(i).padStart(2, '0')}:00.000Z`;const front = {diff --git a/test/get-agent-job.test.ts b/test/get-agent-job.test.tsindex 30d0441897..65b0350122 100644--- a/test/get-agent-job.test.ts+++ b/test/get-agent-job.test.ts@@ -72,8 +72,8 @@ async function seedJob(opts: {const data: Record<string, unknown> = { prompt: 'seeded' };if (opts.owner) data.__owner_client_id = opts.owner;const rows = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at, error_text, result)- VALUES ($1, $2, $3::text::jsonb, $4, $5, ${opts.createdAtSql ?? 'now()'}, $6, $7::text::jsonb)+ `INSERT INTO minion_jobs (submission_authority, name, status, data, queue, priority, created_at, error_text, result)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, $1, $2, $3::text::jsonb, $4, $5, ${opts.createdAtSql ?? 'now()'}, $6, $7::text::jsonb)RETURNING id`,[opts.name ?? 'subagent',diff --git a/test/get-job-stats-op.test.ts b/test/get-job-stats-op.test.tsindex dd0ea2bc37..0492faa9fe 100644--- a/test/get-job-stats-op.test.ts+++ b/test/get-job-stats-op.test.ts@@ -81,12 +81,12 @@ describe('get_job_stats — private dream-inline queues', () => {// ONLY the private-queue classification keeps wedged false here — if it// regressed, this fixture would trip the wedge derivation.await engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, created_at, updated_at)- VALUES ('subagent', '${PRIVATE_QUEUE}', 'waiting', now() - interval '2 hours', now() - interval '2 hours')`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, created_at, updated_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', '${PRIVATE_QUEUE}', 'waiting', now() - interval '2 hours', now() - interval '2 hours')`,);await engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, updated_at)- VALUES ('subagent', '${PRIVATE_QUEUE}', 'completed', now() - interval '90 minutes')`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, updated_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', '${PRIVATE_QUEUE}', 'completed', now() - interval '90 minutes')`,);await withEnv({ GBRAIN_WEDGED_QUEUE_WARN_MINUTES: undefined }, async () => {const res = await dispatchToolCall(engine, 'get_job_stats', { queue: PRIVATE_QUEUE }, { ...STDIO });diff --git a/test/google-source-reconcile.test.ts b/test/google-source-reconcile.test.tsindex 7a3304293d..50065cf2d7 100644--- a/test/google-source-reconcile.test.ts+++ b/test/google-source-reconcile.test.ts@@ -387,8 +387,8 @@ async function seedWaitingLoopsJobs(status: 'waiting' | 'delayed' | 'active' = 'waiting',): Promise<void> {await engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, data, idempotency_key, delay_until)- SELECT 'loops_extract', 'default', $4::text, jsonb_build_object('sourceId', $2::text), $3::text || '-' || i,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, idempotency_key, delay_until)+ SELECT '{"version":1,"kind":"application"}'::jsonb, 'loops_extract', 'default', $4::text, jsonb_build_object('sourceId', $2::text), $3::text || '-' || i,CASE WHEN $4::text = 'delayed' THEN now() + interval '10 minutes' ENDFROM generate_series(1, $1) AS i`,[n, sourceId, keyPrefix, status],diff --git a/test/guarded-http-tls.serial.test.ts b/test/guarded-http-tls.serial.test.tsnew file mode 100644index 0000000000..e32389496d--- /dev/null+++ b/test/guarded-http-tls.serial.test.ts@@ -0,0 +1,157 @@+/**+ * Real local TLS and proxy-trap tests. Public localhost-only test certificate+ * from oven-sh/bun bun-v1.3.11 test/regression/issue/27890 (MIT); its SAN contains+ * DNS:localhost only, so accidentally verifying the dialled IP cannot pass.+ */+import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { gzipSync, deflateSync, brotliCompressSync } from 'node:zlib';+import { createPinnedHttpFetch } from '../src/core/guarded-http.ts';+import { fetchWithSSRFGuard, type ResolvedTarget } from '../src/core/ssrf-validate.ts';++const certPath = join(import.meta.dir, 'fixtures/guarded-http-localhost.crt');+const tls = {+ cert: readFileSync(certPath, 'utf8'),+ key: readFileSync(join(import.meta.dir, 'fixtures/guarded-http-localhost.key'), 'utf8'),+};++function localTarget(url: URL): ResolvedTarget {+ const resolved = new URL(url);+ resolved.hostname = '127.0.0.1';+ return { resolvedUrl: resolved.href, resolvedIp: '127.0.0.1', originalHost: url.hostname, ipv6: false };+}++describe('pinned native HTTP transport', () => {+ test('original hostname cert and Host port survive IP pinning; wrong identity is rejected', async () => {+ const hosts: string[] = [];+ const server = Bun.serve({+ hostname: '127.0.0.1', port: 0, tls,+ fetch(req) { hosts.push(req.headers.get('host')!); return new Response('verified'); },+ });+ const nativeFetch = globalThis.fetch;+ const request = createPinnedHttpFetch(((url, options) => nativeFetch(url, {+ ...options, tls: { ...(options as any).tls, ca: tls.cert },+ })) as typeof fetch);+ try {+ const original = new URL(`https://localhost:${server.port}/hello`);+ const result = await fetchWithSSRFGuard(original.href, { maxBytes: 64 }, {+ resolve: async () => localTarget(original), fetch: request,+ });+ expect(result.body.toString()).toBe('verified');+ expect(hosts).toEqual([`localhost:${server.port}`]);++ const wrong = new URL(`https://wrong.example:${server.port}/hello`);+ await expect(fetchWithSSRFGuard(wrong.href, { maxBytes: 64 }, {+ resolve: async () => localTarget(wrong), fetch: request,+ })).rejects.toThrow();+ // An untrusted chain still fails when the DNS name matches.+ await expect(fetchWithSSRFGuard(original.href, { maxBytes: 64 }, {+ resolve: async () => localTarget(original),+ })).rejects.toThrow();+ expect(hosts).toHaveLength(1);+ } finally {+ await server.stop(true);+ }+ });++ test('ambient proxies fail closed in a fresh runtime, including NO_PROXY=*', async () => {+ let trapHits = 0;+ let directHits = 0;+ const trap = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch() { trapHits++; return new Response('proxy', { status: 502 }); } });+ const direct = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch() { directHits++; return new Response('direct'); } });+ const secure = Bun.serve({ hostname: '127.0.0.1', port: 0, tls, fetch() { directHits++; return new Response('secure'); } });+ const adapterPath = join(import.meta.dir, '../src/core/guarded-http.ts');+ const proxy = `http://127.0.0.1:${trap.port}`;+ // A child gives proxy env settings a chance to take effect at runtime startup.+ const script = `+ import { createPinnedHttpFetch } from ${JSON.stringify(adapterPath)};+ import { readFileSync } from 'node:fs';+ const proxyKeys = ['HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'];+ if (!proxyKeys.some(key => process.env[key] === ${JSON.stringify(proxy)})) {+ throw new Error('Proxy fixture did not reach subprocess');+ }+ const nativeFetch = globalThis.fetch;+ const request = createPinnedHttpFetch((url, opts) => nativeFetch(url, {+ ...opts, tls: { ...opts.tls, ca: readFileSync(${JSON.stringify(certPath)}, 'utf8') },+ }));+ for (const [scheme, port] of [['http', ${direct.port}], ['https', ${secure.port}]]) {+ const url = new URL(scheme + '://localhost:' + port + '/');+ const target = { resolvedUrl: scheme + '://127.0.0.1:' + port + '/', resolvedIp: '127.0.0.1', originalHost: 'localhost', ipv6: false };+ try {+ await request(target, url, { method: 'GET', headers: new Headers(), signal: AbortSignal.timeout(3000) });+ throw new Error('Unexpected connection');+ } catch (err) {+ if (err.code !== 'PROXY_NOT_SUPPORTED') throw err;+ console.log(err.code);+ }+ }+ `;+ // Windows environment names are case-insensitive: an empty lowercase alias+ // can overwrite the populated uppercase key (or vice versa) during spawn.+ // Remove every spelling before adding just the variant under test.+ const proxyEnv = Object.fromEntries(Object.entries(process.env).filter(([key]) =>+ !['http_proxy', 'https_proxy', 'all_proxy', 'no_proxy'].includes(key.toLowerCase())));+ try {+ for (const key of ['HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy']) {+ const proc = Bun.spawn([process.execPath, '--no-env-file', '--eval', script], {+ env: { ...proxyEnv, NO_PROXY: '*', [key]: proxy },+ stdout: 'pipe', stderr: 'pipe',+ });+ const [out, err, exit] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);+ expect({ exit, err }).toEqual({ exit: 0, err: '' });+ expect(out.trim().split('\n')).toEqual(['PROXY_NOT_SUPPORTED', 'PROXY_NOT_SUPPORTED']);+ }+ expect(directHits).toBe(0);+ expect(trapHits).toBe(0);+ } finally {+ await Promise.all([trap.stop(true), direct.stop(true), secure.stop(true)]);+ }+ });++ test.each(['overflow', 'header-only'])('%s closes a real response without consuming the full body', async mode => {+ let closed = false;+ const server = Bun.serve({+ hostname: '127.0.0.1', port: 0,+ fetch() {+ let timer: ReturnType<typeof setInterval>;+ return new Response(new ReadableStream({+ start(controller) { timer = setInterval(() => controller.enqueue(new Uint8Array(128)), 5); },+ cancel() { clearInterval(timer); closed = true; },+ }));+ },+ });+ try {+ const original = new URL(`http://localhost:${server.port}/`);+ const result = fetchWithSSRFGuard(original.href, { maxBytes: 8, headerOnly: mode === 'header-only' }, {+ resolve: async () => localTarget(original),+ });+ if (mode === 'overflow') await expect(result).rejects.toMatchObject({ code: 'BODY_TOO_LARGE' });+ else expect((await result).body.byteLength).toBe(0);+ for (let i = 0; i < 30 && !closed; i++) await Bun.sleep(5);+ expect(closed).toBe(true);+ } finally {+ await server.stop(true);+ }+ });++ test.each(['gzip', 'deflate', 'br'])('native %s responses are decoded exactly once and bounded', async encoding => {+ const payload = Buffer.from('bounded test payload');+ const compressed = encoding === 'gzip' ? gzipSync(payload)+ : encoding === 'deflate' ? deflateSync(payload) : brotliCompressSync(payload);+ const server = Bun.serve({+ hostname: '127.0.0.1', port: 0,+ fetch() { return new Response(new Uint8Array(compressed), { headers: { 'content-encoding': encoding } }); },+ });+ try {+ const original = new URL(`http://localhost:${server.port}/`);+ const deps = { resolve: async () => localTarget(original) };+ const response = await fetchWithSSRFGuard(original.href, { maxBytes: payload.length }, deps);+ expect(response.body).toEqual(payload);+ await expect(fetchWithSSRFGuard(original.href, { maxBytes: payload.length - 1 }, deps))+ .rejects.toMatchObject({ code: 'BODY_TOO_LARGE' });+ } finally {+ await server.stop(true);+ }+ });+});diff --git a/test/guarded-http.test.ts b/test/guarded-http.test.tsnew file mode 100644index 0000000000..6aa124482b--- /dev/null+++ b/test/guarded-http.test.ts@@ -0,0 +1,287 @@+import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { gzipSync, deflateSync, brotliCompressSync } from 'node:zlib';+import { assertSupportedBun } from '../src/core/runtime-version.ts';+import {+ __setDnsLookupForTests, fetchWithSSRFGuard, validateAndResolveUrl,+ type GuardedHttpDependencies, type GuardedHttpOptions,+} from '../src/core/ssrf-validate.ts';++beforeEach(() => {+ __setDnsLookupForTests((async () => [{ address: '8.8.8.8', family: 4 }]) as any);+});+afterEach(() => __setDnsLookupForTests(undefined));++const probe = { headerOnly: true };++test('unsupported runtime refuses guarded operations with upgrade guidance', () => {+ for (const version of ['', '1.3.10', '1.2.99', '1.3.11-canary']) {+ expect(() => assertSupportedBun(version)).toThrow('Run bun upgrade');+ }+ for (const version of ['1.3.11', '1.3.13', '1.4.0', '2.0.0']) {+ expect(() => assertSupportedBun(version)).not.toThrow();+ }+});++describe('guarded HTTP destination and redirect policy', () => {+ test('denial diagnostics exclude requested URLs and DNS exception content', async () => {+ for (const url of ['http://127.0.0.1/private-document?api_key=private-value', 'http://owner:private-value@']) {+ let error: unknown;+ try { await validateAndResolveUrl(url); } catch (caught) { error = caught; }+ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).not.toContain('private-');+ expect((error as Error).message.length).toBeLessThan(150);+ }+ __setDnsLookupForTests((async () => { throw new Error('private-document private-value'); }) as any);+ await expect(validateAndResolveUrl('https://private-document.example')).rejects.toMatchObject({+ code: 'DNS_RESOLUTION_FAILED', message: 'DNS resolution failed for the requested destination',+ });+ });+ test('pins the validated DNS answer and preserves the original URL', async () => {+ let lookups = 0;+ __setDnsLookupForTests((async () => {+ lookups++;+ return [{ address: lookups === 1 ? '8.8.8.8' : '127.0.0.1', family: 4 }];+ }) as any);+ const r = await fetchWithSSRFGuard('https://example.test:8443/path?q=1', probe, {+ fetch: async (target, url) => {+ expect(target.resolvedUrl).toBe('https://8.8.8.8:8443/path?q=1');+ expect(target.originalHost).toBe('example.test');+ expect(url.host).toBe('example.test:8443');+ return new Response('unused');+ },+ });+ expect(r.status).toBe(200);+ expect(r.body.length).toBe(0);+ expect(lookups).toBe(1);+ });++ test.each([+ { address: '::ffff:7f00:1', family: 6 },+ { address: '0:0:0:0:0:ffff:127.0.0.1', family: 6 },+ { address: '0:0:0:0:0:0:0:1', family: 6 },+ { address: 'fe90::1', family: 6 },+ { address: 'fd00::1', family: 6 },+ { address: '127.0.0.1', family: 6 },+ { address: '8.8.8.8', family: 99 },+ ])('rejects mixed DNS including nonpublic/corrupt answer %j', async answer => {+ __setDnsLookupForTests((async () => [{ address: '8.8.8.8', family: 4 }, answer]) as any);+ let calls = 0;+ await expect(fetchWithSSRFGuard('https://example.test', probe, {+ fetch: async () => { calls++; return new Response(); },+ })).rejects.toMatchObject({ code: 'DNS_RESOLVED_INTERNAL' });+ expect(calls).toBe(0);+ });++ test('public IPv6 DNS answer remains pinned and bracket encoded', async () => {+ __setDnsLookupForTests((async () => [{ address: '2606:4700:4700::1111', family: 6 }]) as any);+ const target = await validateAndResolveUrl('https://example.test:8443/a');+ expect(target.resolvedUrl).toBe('https://[2606:4700:4700::1111]:8443/a');+ });++ test('each redirect receives a fresh complete DNS check', async () => {+ let lookups = 0;+ __setDnsLookupForTests((async () => [{ address: ++lookups === 1 ? '8.8.8.8' : '10.0.0.1', family: 4 }]) as any);+ let requests = 0;+ await expect(fetchWithSSRFGuard('https://example.test/start', probe, {+ fetch: async () => {+ requests++;+ return new Response(null, { status: 302, headers: { location: '/next' } });+ },+ })).rejects.toMatchObject({ code: 'DNS_RESOLVED_INTERNAL' });+ expect(requests).toBe(1);+ });++ test('plain probes cross public origins with harmless headers', async () => {+ const urls: string[] = [];+ const r = await fetchWithSSRFGuard('https://one.test/start', { ...probe, headers: { Accept: 'text/html' } }, {+ fetch: async (_, url, init) => {+ urls.push(url.href);+ expect(init.headers.get('accept')).toBe('text/html');+ return urls.length === 1 ? new Response(null, { status: 302, headers: { location: 'https://two.test/final' } }) : new Response();+ },+ });+ expect(urls).toEqual(['https://one.test/start', 'https://two.test/final']);+ expect(r.url).toBe('https://two.test/final');+ });++ test.each([+ { headers: { Authorization: 'test-token' } },+ { headers: { 'X-Api-Key': 'test-token' } },+ { headers: { Accept: 'test-secret' }, sameOrigin: true },+ { method: 'POST', body: 'test-data' },+ { method: 'DELETE' },+ ] as GuardedHttpOptions[])('sensitive requests never cross origins: %j', async options => {+ let requests = 0;+ await expect(fetchWithSSRFGuard('https://one.test', { ...probe, ...options }, {+ fetch: async () => {+ requests++;+ return new Response(null, { status: 307, headers: { location: 'https://two.test' } });+ },+ })).rejects.toMatchObject({ code: 'SSRF_REDIRECT_DENIED' });+ expect(requests).toBe(1);+ });++ test('preserves recipe method/body/auth for a same-origin redirect', async () => {+ let requests = 0;+ await fetchWithSSRFGuard('https://one.test/start', {+ ...probe, method: 'PATCH', body: 'test-body', headers: { Authorization: 'test-only' },+ }, {+ fetch: async (_, url, init) => {+ expect(init.method).toBe('PATCH');+ expect(init.body).toBe('test-body');+ expect(init.headers.get('authorization')).toBe('test-only');+ return ++requests === 1 ? new Response(null, { status: 303, headers: { location: '/next' } }) : new Response();+ },+ });+ expect(requests).toBe(2);+ });++ test.each(['http://one.test', 'file:///tmp/unused', 'http://['])('refuses downgrade/invalid redirect %s', async location => {+ await expect(fetchWithSSRFGuard('https://one.test', probe, {+ fetch: async () => new Response(null, { status: 302, headers: { location } }),+ })).rejects.toMatchObject({ code: 'SSRF_REDIRECT_DENIED' });+ });++ test.each([3, 5])('enforces %i redirects and cancels every intermediate body', async limit => {+ let requests = 0;+ let cancelled = 0;+ await expect(fetchWithSSRFGuard('https://one.test', { ...probe, maxRedirects: limit }, {+ fetch: async () => {+ requests++;+ return new Response(new ReadableStream({ cancel: () => { cancelled++; } }), {+ status: 302, headers: { location: '/again' },+ });+ },+ })).rejects.toMatchObject({ code: 'SSRF_HOP_LIMIT' });+ expect(requests).toBe(limit + 1);+ expect(cancelled).toBe(requests);+ });++ test('HEAD fallback consumes no body and does not consume a redirect hop', async () => {+ const methods: string[] = [];+ let cancelled = 0;+ const r = await fetchWithSSRFGuard('https://one.test', {+ ...probe, method: 'HEAD', headFallback: true, maxRedirects: 0,+ }, {+ fetch: async (_, __, init) => {+ methods.push(init.method);+ return new Response(new ReadableStream({ cancel: () => { cancelled++; } }), { status: init.method === 'HEAD' ? 405 : 200 });+ },+ });+ expect(r.ok).toBe(true);+ expect(methods).toEqual(['HEAD', 'GET']);+ expect(cancelled).toBe(2);+ });+});++describe('one deadline and bounded decoded bodies', () => {+ test('timeout during DNS never starts a request, even after late resolution', async () => {+ let finish!: (target: Awaited<ReturnType<typeof validateAndResolveUrl>>) => void;+ let requests = 0;+ const pending = fetchWithSSRFGuard('https://one.test', { ...probe, timeoutMs: 20 }, {+ resolve: () => new Promise(resolve => { finish = resolve; }),+ fetch: async () => { requests++; return new Response(); },+ });+ await expect(pending).rejects.toMatchObject({ code: 'REQUEST_TIMEOUT' });+ finish({ resolvedUrl: 'https://8.8.8.8', resolvedIp: '8.8.8.8', originalHost: 'one.test', ipv6: false });+ await Promise.resolve();+ expect(requests).toBe(0);+ });++ test('external cancellation during DNS is immediate', async () => {+ const ac = new AbortController();+ const promise = fetchWithSSRFGuard('https://one.test', { ...probe, signal: ac.signal }, {+ resolve: () => new Promise(() => {}),+ });+ ac.abort();+ await expect(promise).rejects.toMatchObject({ code: 'REQUEST_ABORTED' });+ });++ test('headers do not end the deadline; stalled body is cancelled', async () => {+ let cancelled = false;+ await expect(fetchWithSSRFGuard('https://one.test', { maxBytes: 1024, timeoutMs: 20 }, {+ fetch: async () => new Response(new ReadableStream({+ start(controller) { controller.enqueue(new Uint8Array([1])); },+ cancel() { cancelled = true; },+ })),+ })).rejects.toMatchObject({ code: 'REQUEST_TIMEOUT' });+ expect(cancelled).toBe(true);+ });++ test('redirects and HEAD fallback share the original deadline', async () => {+ const methods: string[] = [];+ const deadlines: Array<() => void> = [];+ const handles: Array<ReturnType<typeof setTimeout>> = [];+ const realSetTimeout = globalThis.setTimeout;+ const timer = spyOn(globalThis, 'setTimeout').mockImplementation(((callback: () => void, delay: number) => {+ expect(delay).toBe(250);+ deadlines.push(callback);+ const handle = realSetTimeout(callback, 60000);+ handles.push(handle);+ return handle;+ }) as typeof setTimeout);+ const deps: GuardedHttpDependencies = { fetch: async (_, __, init) => {+ methods.push(init.method);+ if (methods.length === 1) return new Response(null, { status: 302, headers: { location: '/next' } });+ if (methods.length === 2) return new Response(null, { status: 405 });+ return new Promise<Response>((_, reject) => {+ init.signal.addEventListener('abort', () => reject(init.signal.reason), { once: true });+ queueMicrotask(() => deadlines.at(-1)!());+ });+ } };+ try {+ await expect(fetchWithSSRFGuard('https://one.test', {+ ...probe, method: 'HEAD', headFallback: true, timeoutMs: 250,+ }, deps)).rejects.toMatchObject({ code: 'REQUEST_TIMEOUT' });+ expect(methods).toEqual(['HEAD', 'HEAD', 'GET']);+ expect(deadlines).toHaveLength(1);+ } finally {+ timer.mockRestore();+ handles.forEach(handle => clearTimeout(handle));+ }+ });++ test.each(['identity', 'gzip', 'deflate', 'br'])('bounds decoded %s and supports ordinary data', async encoding => {+ const encode = (data: Buffer) => encoding === 'gzip' ? gzipSync(data)+ : encoding === 'deflate' ? deflateSync(data) : encoding === 'br' ? brotliCompressSync(data) : data;+ const makeResponse = (data: Buffer) => new Response(new Uint8Array(encode(data)), { headers: { 'content-encoding': encoding } });+ const r = await fetchWithSSRFGuard('https://one.test', { maxBytes: 8 }, { fetch: async () => makeResponse(Buffer.from('good')) });+ expect(r.body.toString()).toBe('good');+ await expect(fetchWithSSRFGuard('https://one.test', { maxBytes: 8 }, {+ fetch: async () => makeResponse(Buffer.alloc(65536)),+ })).rejects.toMatchObject({ code: 'BODY_TOO_LARGE' });+ });++ test('stream cap defeats missing and dishonest Content-Length', async () => {+ for (const length of [undefined, '1']) {+ let cancelled = false;+ await expect(fetchWithSSRFGuard('https://one.test', { maxBytes: 8 }, {+ fetch: async () => new Response(new ReadableStream({+ start(controller) { controller.enqueue(new Uint8Array(32)); },+ cancel() { cancelled = true; },+ }), { headers: length ? { 'content-length': length } : {} }),+ })).rejects.toMatchObject({ code: 'BODY_TOO_LARGE' });+ expect(cancelled).toBe(true);+ }+ });++ test('unsupported and stacked content encodings are rejected', async () => {+ for (const encoding of ['zstd', 'gzip, br']) {+ await expect(fetchWithSSRFGuard('https://one.test', { maxBytes: 8 }, {+ fetch: async () => new Response('unused', { headers: { 'content-encoding': encoding } }),+ })).rejects.toMatchObject({ code: 'UNSUPPORTED_ENCODING' });+ }+ });++ test('malformed compressed response fails without hanging', async () => {+ await expect(fetchWithSSRFGuard('https://one.test', { maxBytes: 8 }, {+ fetch: async () => new Response('invalid', { headers: { 'content-encoding': 'gzip' } }),+ })).rejects.toThrow();+ });++ test('a body limit is mandatory and invalid request options fail before DNS', async () => {+ await expect(fetchWithSSRFGuard('https://one.test')).rejects.toThrow('maxBytes');+ await expect(fetchWithSSRFGuard('https://one.test', { ...probe, timeoutMs: NaN })).rejects.toThrow();+ await expect(fetchWithSSRFGuard('https://one.test', { ...probe, method: 'GET', body: 'x' })).rejects.toThrow();+ });+});diff --git a/test/helpers/minion-authority-upgrade.ts b/test/helpers/minion-authority-upgrade.tsnew file mode 100644index 0000000000..5e1221529b--- /dev/null+++ b/test/helpers/minion-authority-upgrade.ts@@ -0,0 +1,48 @@+/** Destructive only within an already isolated test database. Rehearse the old queue shape. */+import { expect } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { LATEST_VERSION, MIGRATIONS, runMigrations } from '../../src/core/migrate.ts';+import { MinionQueue } from '../../src/core/minions/queue.ts';+import { authorizeLegacyJobs } from '../../src/core/minions/authorize-legacy.ts';+import { assertNoUnreviewedJobs } from '../../src/core/minions/submission-authority.ts';++export async function rehearseMinionAuthorityUpgrade(engine: BrainEngine): Promise<void> {+ const migration = MIGRATIONS.find(m => m.name === 'minion_submission_authority')!;+ // Releases through v0.49 already own these versions. The authority cutover+ // must still execute when upgrading that deployed ledger, not overwrite it.+ expect(MIGRATIONS.find(m => m.version === 147)?.name).toBe('oauth_client_capability_grants');+ expect(MIGRATIONS.find(m => m.version === 148)?.name).toBe('durable_fact_withdrawals');+ expect(migration.version).toBe(149);+ const originalVersion = await engine.getConfig('version');+ await engine.executeRaw('DELETE FROM minion_jobs');+ await engine.executeRaw('DROP TRIGGER minion_queue_protocol ON minion_jobs');+ await engine.executeRaw('ALTER TABLE minion_jobs DROP COLUMN submission_authority, DROP COLUMN claim_generation');+ await engine.setConfig('version', '148');+ const upgrade = () => runMigrations(engine);+ try {+ const [old] = await engine.executeRaw<{ id: number }>("INSERT INTO minion_jobs (name, status, data, attempts_made, attempts_started) VALUES ('fixture-upgrade', 'active', $1::jsonb, 2, 2) RETURNING id", [{ example: true }]);+ await expect(upgrade()).rejects.toThrow('Drain or cancel active');+ expect(await engine.getConfig('version')).toBe('148');+ await engine.executeRaw("UPDATE minion_jobs SET status = 'paused' WHERE id = $1", [old.id]);+ await upgrade();+ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));+ const queue = new MinionQueue(engine);+ const preserved = (await queue.getJob(old.id))!;+ expect(preserved.submission_authority).toBeNull();+ expect(preserved.status).toBe('paused');+ expect(preserved.attempts_made).toBe(2);+ expect(preserved.data).toEqual({ example: true });+ await expect(assertNoUnreviewedJobs(engine)).rejects.toThrow('legacy jobs');+ await expect(engine.executeRaw("INSERT INTO minion_jobs (name) VALUES ('old-producer')")).rejects.toThrow('protocol 1');+ const preview = await authorizeLegacyJobs(engine, [old.id]);+ await authorizeLegacyJobs(engine, [old.id], preview.snapshot_digest, true);+ await queue.resumeJob(old.id);+ await expect(engine.executeRaw("UPDATE minion_jobs SET status = 'active', lock_token = 'old' WHERE id = $1", [old.id])).rejects.toThrow('old workers');+ expect((await queue.claim('new', 30000, 'default', ['fixture-upgrade']))?.id).toBe(old.id);+ } finally {+ await engine.executeRaw('DELETE FROM minion_jobs');+ // Restore even after a failed assertion; sibling tests keep the current schema.+ await engine.transaction(async tx => { await tx.runMigration(migration.version, migration.sql); });+ await engine.setConfig('version', originalVersion ?? String(LATEST_VERSION));+ }+}diff --git a/test/helpers/oauth.ts b/test/helpers/oauth.tsnew file mode 100644index 0000000000..409d1eae0f--- /dev/null+++ b/test/helpers/oauth.ts@@ -0,0 +1,29 @@+import { createHash } from 'node:crypto';+import type { PGlite } from '@electric-sql/pglite';+import type { OAuthClientInformationFull } from '@modelcontextprotocol/sdk/shared/auth.js';+import type { AuthorizationParams } from '@modelcontextprotocol/sdk/server/auth/provider.js';+import type { Response } from 'express';+import type { GBrainOAuthProvider } from '../../src/core/oauth-provider.ts';+import type { OAuthTransaction } from '../../src/core/oauth-grants.ts';+import type { SqlQuery } from '../../src/core/sql-query.ts';++export const TEST_PKCE_VERIFIER = 'synthetic-verifier-for-oauth-regression-fixtures-0123456789';+export const TEST_PKCE_CHALLENGE = createHash('sha256').update(TEST_PKCE_VERIFIER).digest('base64url');+export function pgliteOAuthTransaction(db: PGlite): OAuthTransaction {+ return fn => db.transaction(async tx => {+ const sql: SqlQuery = async (strings, ...values) => {+ const query = strings.reduce((acc, str, i) => acc + str + (i < values.length ? `$${i + 1}` : ''), '');+ return (await tx.query<Record<string, unknown>>(query, values)).rows;+ };+ return fn(sql);+ });+}++/** Existing grant tests explicitly simulate the owner's decision after authorization. */+export async function authorizeAsOwner(provider: GBrainOAuthProvider, client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise<void> {+ let pendingUrl = '';+ await provider.authorize(client, params, { redirect: (url: string) => { pendingUrl = url; } } as Response);+ const id = new URL(pendingUrl, 'https://brain.example').searchParams.get('oauth_request');+ if (!id) throw new Error('Expected owner consent request');+ res.redirect(await provider.grants.decide(id, true));+}diff --git a/test/http-transport.test.ts b/test/http-transport.test.tsindex 1caa750477..4bbd2bd565 100644--- a/test/http-transport.test.ts+++ b/test/http-transport.test.ts@@ -67,7 +67,7 @@ interface FakeEngineConfig {* `permissions` JSONB column. Default permissions = {takes_holders: ['world']}* when unset, matching the migration v33 default.*/- validTokens?: Map<string, { id: string; name: string; permissions?: { takes_holders?: string[] } }>;+ validTokens?: Map<string, { id: string; name: string; scopes?: string[] | null; permissions?: { takes_holders?: string[] } }>;/** Tokens that are present but revoked (revoked_at IS NOT NULL — query returns empty). */revokedTokens?: Set<string>;/** If true, every SELECT throws (simulating DB outage). */@@ -93,7 +93,8 @@ function makeFakeEngine(cfg: FakeEngineConfig = {}): FakeEngine {// SELECT id, name, permissions FROM access_tokens WHERE token_hash = $1 AND revoked_at IS NULLif (norm.startsWith('select id, name from access_tokens') ||- norm.startsWith('select id, name, permissions from access_tokens')) {+ norm.startsWith('select id, name, permissions from access_tokens') ||+ norm.startsWith('select id, name, permissions, scopes from access_tokens')) {const tokenHash = values[0] as string;if (revokedTokens.has(tokenHash)) return [];const row = validTokens.get(tokenHash);@@ -189,6 +190,21 @@ function rpc(method: string, params?: unknown, id: number = 1) {return JSON.stringify({ jsonrpc: '2.0', id, method, ...(params !== undefined ? { params } : {}) });}+test('read-only legacy tokens hide and deny write operations while retaining read discovery', async () => {+ const token = 'fixture-read-only';+ const srv = await startTest({ validTokens: new Map([[hash(token), { id: 'readonly-id', name: 'fixture', scopes: ['read'] }]]) });+ try {+ const request = (method: string, params?: unknown) => fetch(`${srv.url}/mcp`, { method: 'POST',+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, body: rpc(method, params) });+ const list = await (await request('tools/list')).json() as { result: { tools: { name: string }[] } };+ expect(list.result.tools.some(t => t.name === 'get_page')).toBe(true);+ expect(list.result.tools.some(t => t.name === 'put_page')).toBe(false);+ const call = await (await request('tools/call', { name: 'put_page', arguments: { slug: 'example', content: 'fixture' } })).json() as { result: { isError: boolean; content: { text: string }[] } };+ expect(call.result.isError).toBe(true);+ expect(call.result.content[0].text).toContain('permission_denied');+ } finally { srv.stop(); }+});+// --------------------------------------------------------------------------// Auth path// --------------------------------------------------------------------------diff --git a/test/import-cancellation.serial.test.ts b/test/import-cancellation.serial.test.tsnew file mode 100644index 0000000000..8c82350cc5--- /dev/null+++ b/test/import-cancellation.serial.test.ts@@ -0,0 +1,161 @@+// Serial: child pool mocking and import/log spies are process-wide.+import { afterAll, beforeAll, expect, mock, spyOn, test } from 'bun:test';+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { execFileSync } from 'node:child_process';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import * as importFiles from '../src/core/import-file.ts';+import * as locks from '../src/core/db-lock.ts';+import { runImport, ImportAbortError } from '../src/commands/import.ts';+import { performSync } from '../src/commands/sync.ts';+import { withSourceFilesystemLock } from '../src/core/minions/source-filesystem.ts';+import { APPLICATION_AUTHORITY, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';+import { withEnv } from './helpers/with-env.ts';++let disconnects = 0;+mock.module('../src/core/postgres-engine.ts', () => ({+ PostgresEngine: class {+ kind = 'postgres';+ async connect(): Promise<void> {}+ async disconnect(): Promise<void> { disconnects++; }+ },+}));++const home = mkdtempSync(join(tmpdir(), 'gbrain-import-cancel-'));+const root = join(home, 'repo');+const checkpoint = join(home, '.gbrain', 'import-checkpoint.json');+let engine: PGLiteEngine;+const isolated = (fn: () => Promise<void>) => withEnv({+ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_MAX_CONNECTIONS: undefined,+}, fn);+beforeAll(async () => isolated(async () => {+ mkdirSync(root); mkdirSync(join(home, '.gbrain'));+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: 'postgresql://example.invalid/gbrain_test' }));+ for (let i = 0; i < 8; i++) writeFileSync(join(root, `page-${i}.md`), `---\ntype: note\ntitle: Page ${i}\n---\n\nA cancellation fixture body ${i}.\n`);+ execFileSync('git', ['init', '-q', root]);+ execFileSync('git', ['-C', root, 'add', '.']);+ execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', '-c', 'core.hooksPath=/dev/null', 'commit', '-qm', 'fixture']);+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [root]);+}), 60_000);+afterAll(async () => { await engine?.disconnect(); rmSync(home, { recursive: true, force: true }); });++async function reset(): Promise<void> {+ await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw("UPDATE sources SET last_commit = NULL WHERE id = 'default'");+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'sync.%'");+ rmSync(checkpoint, { force: true }); disconnects = 0;+}+function completedPaths(): string[] { return JSON.parse(readFileSync(checkpoint, 'utf8')).completedPaths; }++test('an admission database failure racing caller cancellation remains a failure', () => isolated(async () => {+ await reset();+ const controller = new AbortController();+ const failure = new Error('fixture admission connection failure');+ const original = engine.executeRaw.bind(engine);+ const querySpy = spyOn(engine, 'executeRaw').mockImplementation((sql, params) => {+ if (sql === "SELECT local_path FROM sources WHERE local_path IS NOT NULL AND local_path <> ''") {+ controller.abort();+ return Promise.reject(failure);+ }+ return original(sql, params);+ });+ try {+ await expect(performSync(engine, { repoPath: root, sourceId: 'default', noPull: true, noEmbed: true, signal: controller.signal })).rejects.toBe(failure);+ } finally { querySpy.mockRestore(); }+}));++for (const unexpectedFailure of [false, true]) {+ test(`parallel interruption drains every worker before pools/lock release (unexpected failure=${unexpectedFailure})`, () => isolated(async () => {+ await reset();+ const controller = new AbortController();+ const pending: Array<{ path: string; resolve: () => void; reject: (error: Error) => void }> = [];+ let ready!: () => void;+ const started = new Promise<void>(resolve => { ready = resolve; });+ const importSpy = spyOn(importFiles, 'importFile').mockImplementation(async (_engine, _path, path) => {+ await new Promise<void>((resolve, reject) => { pending.push({ path, resolve, reject }); if (pending.length === 3) ready(); });+ return { status: 'imported', slug: path.slice(0, -3), chunks: 1 };+ });+ // The actual outer PGLite lock encloses a parent facade whose import pools+ // are simulated. No database URL in this fixture can reach a real server.+ const parent = new Proxy(engine, { get(target, prop) {+ if (prop === 'kind') return 'postgres';+ const value = Reflect.get(target, prop); return typeof value === 'function' ? value.bind(target) : value;+ } }) as BrainEngine;+ let settled = false;+ const run = withSourceFilesystemLock(engine, root, () => runImport(parent, [root, '--no-embed', '--workers', '3'], {+ sourceId: 'default', signal: controller.signal,+ }), { signal: controller.signal }).then(value => { settled = true; return value; }, error => { settled = true; return error; });+ try {+ await started;+ controller.abort();+ const failure = new Error('fixture connection failure');+ if (unexpectedFailure) pending[0].reject(failure); else pending[0].resolve();+ await new Promise(resolve => setTimeout(resolve, 20));+ expect(settled).toBe(false);+ expect(disconnects).toBe(0);+ expect(await engine.executeRaw("SELECT id FROM gbrain_cycle_locks WHERE id LIKE 'gbrain-fs:%'")).toHaveLength(1);+ for (const item of pending.slice(1)) item.resolve();+ const result = await run;+ if (unexpectedFailure) expect(result).toBe(failure);+ else {+ expect(result).toBeInstanceOf(ImportAbortError);+ expect((result as ImportAbortError).partialResult?.imported).toBe(3);+ }+ expect(pending).toHaveLength(3); // Never dequeue another file after abort.+ expect(disconnects).toBe(3);+ expect(completedPaths().sort()).toEqual(pending.slice(unexpectedFailure ? 1 : 0).map(item => item.path).sort());+ expect(await engine.executeRaw("SELECT id FROM gbrain_cycle_locks WHERE id LIKE 'gbrain-fs:%'")).toHaveLength(0);+ } finally {+ for (const item of pending) item.resolve();+ await run; importSpy.mockRestore();+ }+ }), 30_000);+}++for (const mode of ['caller', 'job', 'log-ingest', 'lease', 'caller-and-lease'] as const) {+ test(`sync interruption preserves progress and bookmark (${mode})`, () => isolated(async () => {+ await reset();+ const controller = new AbortController();+ const originalImport = importFiles.importFile;+ const originalLog = engine.logIngest.bind(engine);+ const originalLock = locks.withRefreshingLock;+ let calls = 0;+ const importSpy = spyOn(importFiles, 'importFile').mockImplementation(async (...args) => {+ const result = await originalImport(...args); calls++;+ if (mode === 'lease' || mode === 'caller-and-lease') {+ if (mode === 'caller-and-lease') controller.abort();+ await new Promise(resolve => setTimeout(resolve, 80));+ } else if (mode !== 'log-ingest') controller.abort();+ return result;+ });+ const logSpy = spyOn(engine, 'logIngest').mockImplementation(async (...args) => {+ const result = await originalLog(...args);+ if (mode === 'log-ingest') controller.abort();+ return result;+ });+ const lockSpy = spyOn(locks, 'withRefreshingLock').mockImplementation((eng, key, fn, opts) =>+ originalLock(eng, key, fn, key.startsWith('gbrain-fs:') && mode.includes('lease') ? { ...opts, ttlMinutes: 0.0005 } : opts));+ const sync = () => performSync(engine, { repoPath: root, sourceId: 'default', noPull: true, noEmbed: true, noExtract: true, concurrency: 1, signal: controller.signal });+ try {+ if (mode === 'job') {+ await expect(withSubmissionAuthority(APPLICATION_AUTHORITY, sync, controller.signal)).rejects.toBeInstanceOf(ImportAbortError);+ } else if (mode.includes('lease')) {+ let followup = false;+ await expect(withSourceFilesystemLock(engine, root, async () => {+ await sync(); followup = true;+ }, { signal: controller.signal })).rejects.toBeInstanceOf(locks.LockStolenError);+ expect(followup).toBe(false);+ } else {+ const result = await sync();+ expect(result.status).toBe('partial');+ expect(result.filesImported).toBe(mode === 'log-ingest' ? 8 : 1);+ }+ expect(calls).toBe(mode === 'log-ingest' ? 8 : 1);+ expect(completedPaths()).toHaveLength(calls);+ expect((await engine.executeRaw<{ last_commit: string | null }>("SELECT last_commit FROM sources WHERE id = 'default'"))[0].last_commit).toBeNull();+ } finally { importSpy.mockRestore(); logSpy.mockRestore(); lockSpy.mockRestore(); }+ }), 30_000);+}diff --git a/test/import-configured-root-guard.serial.test.ts b/test/import-configured-root-guard.serial.test.tsindex 22deba273d..c9a6421dbc 100644--- a/test/import-configured-root-guard.serial.test.ts+++ b/test/import-configured-root-guard.serial.test.ts@@ -186,6 +186,8 @@ describe('runImport configured-root admission', () => {await expect(runImport(engine, [root, '--no-embed'], { sourceId: 'default' }),).rejects.toBeInstanceOf(ImportAbortError);+ const rows = await engine.executeRaw<{ n: number | string }>('SELECT COUNT(*) AS n FROM pages');+ expect(Number(rows[0].n)).toBe(0);} finally {query.mockRestore();}diff --git a/test/import-connection-budget.serial.test.ts b/test/import-connection-budget.serial.test.tsindex 9017963c57..ad413a219f 100644--- a/test/import-connection-budget.serial.test.ts+++ b/test/import-connection-budget.serial.test.ts@@ -15,7 +15,7 @@* top-level mock.module for the child-engine connections.*/import { afterAll, beforeAll, beforeEach, expect, mock, spyOn, test } from 'bun:test';-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';import type { BrainEngine } from '../src/core/engine.ts';@@ -40,6 +40,7 @@ let importDir: string;let previousGbrainHome: string | undefined;let previousMaxConnections: string | undefined;let previousPoolSize: string | undefined;+let restoreFilesystemLock: (() => void) | undefined;beforeAll(async () => {root = mkdtempSync(join(tmpdir(), 'gbrain-import-budget-'));@@ -56,10 +57,17 @@ beforeAll(async () => {process.env.GBRAIN_HOME = root;process.env.GBRAIN_MAX_CONNECTIONS = '10';delete process.env.GBRAIN_POOL_SIZE;+ // These fake engines model pool allocation, not lock-table SQL. Imports+ // here run inside an already-held fixture-root lock, as nested sync imports do.+ const filesystem = await import('../src/core/minions/source-filesystem.ts');+ const heldRoot = realpathSync(importDir);+ const lockSpy = spyOn(filesystem, 'hasSourceFilesystemLock').mockImplementation(path => path === heldRoot);+ restoreFilesystemLock = () => lockSpy.mockRestore();({ runImport } = await import('../src/commands/import.ts'));});afterAll(() => {+ restoreFilesystemLock?.();if (previousGbrainHome === undefined) delete process.env.GBRAIN_HOME;else process.env.GBRAIN_HOME = previousGbrainHome;if (previousMaxConnections === undefined) delete process.env.GBRAIN_MAX_CONNECTIONS;diff --git a/test/import-json-stdout.serial.test.ts b/test/import-json-stdout.serial.test.tsindex 87cf905aa2..a46753528d 100644--- a/test/import-json-stdout.serial.test.ts+++ b/test/import-json-stdout.serial.test.ts@@ -127,37 +127,47 @@ describe('import --json stdout is parseable JSON (#3637) and lists per-file fail'---\ntitle: a: b\ntags: [\n---\n\n# broken\n',);const mixed = await runCli(['import', mixedNotes, '--no-embed', '--json'], env, 120_000);- if (mixed.exitCode !== 0) {+ if (mixed.exitCode !== 1) {console.error('--- import mixed stdout ---\n' + mixed.stdout);console.error('--- import mixed stderr ---\n' + mixed.stderr);}- expect(mixed.exitCode).toBe(0);+ expect(mixed.exitCode).toBe(1);const mixedJson = JSON.parse(mixed.stdout);+ expect(mixedJson.status).toBe('partial');expect(mixedJson.imported).toBe(1);expect(mixedJson.skipped).toBe(1);- expect(mixedJson.errors).toBe(0);+ expect(mixedJson.errors).toBe(1);expect(mixedJson.unchanged).toBe(0);expect(mixedJson.malformed_skipped).toBe(0);expect(mixedJson.failures).toHaveLength(1);expect(mixedJson.failures[0].path).toBe('broken.md');expect(mixedJson.failures[0].error).toContain('Invalid YAML frontmatter');- // Re-import the same dir: the good note is now a content-hash no-op and+ // A failed import retains its checkpoint: a normal retry only processes+ // the failed document and reports its error again.+ const resumed = await runCli(['import', mixedNotes, '--no-embed', '--json'], env, 120_000);+ expect(resumed.exitCode).toBe(1);+ expect(JSON.parse(resumed.stdout)).toMatchObject({+ status: 'partial', total_files: 2, imported: 0, skipped: 1, errors: 1, unchanged: 0,+ });++ // A fresh re-import scans both files: the good note is a content-hash no-op and// must land in `unchanged` (not `imported`, not `failures`), while the// broken note fails again and stays a named failure. Pins the// `unchanged = skipped - failures - malformed_skipped` derivation and// that a repeat run still lists the failing file by path.- const again = await runCli(['import', mixedNotes, '--no-embed', '--json'], env, 120_000);- if (again.exitCode !== 0) {+ const again = await runCli(['import', mixedNotes, '--no-embed', '--fresh', '--json'], env, 120_000);+ if (again.exitCode !== 1) {console.error('--- import mixed (re-run) stdout ---\n' + again.stdout);console.error('--- import mixed (re-run) stderr ---\n' + again.stderr);}- expect(again.exitCode).toBe(0);+ expect(again.exitCode).toBe(1);const againJson = JSON.parse(again.stdout);+ expect(againJson.status).toBe('partial');expect(againJson.total_files).toBe(2);expect(againJson.imported).toBe(0);expect(againJson.skipped).toBe(2);- expect(againJson.errors).toBe(0);+ expect(againJson.errors).toBe(1);expect(againJson.unchanged).toBe(1);expect(againJson.malformed_skipped).toBe(0);expect(againJson.failures.map((f: { path: string }) => f.path)).toEqual(['broken.md']);diff --git a/test/ingestion/markdown-greenfield.test.ts b/test/ingestion/markdown-greenfield.test.tsindex 5c26a5a126..20f232d167 100644--- a/test/ingestion/markdown-greenfield.test.ts+++ b/test/ingestion/markdown-greenfield.test.ts@@ -194,19 +194,28 @@ describe('v0.41 T7: validation failure → JSONL audit', () => {expect(Object.keys(fs.audit).length).toBe(0);});- test('continues processing after a failed file', async () => {- // First file good, second file good — no failures triggered by the- // happy path. Failure-injection test would require mocking matter()- // to throw; for v0.41 minimal, we assert the stats tracker exposes- // the counters.+ test('rejected frontmatter is audited as invalid and later valid files still import', async () => {const fs = makeFakeFs({- [`${REPO}/atoms/2026-05-24/a.md`]: '---\ntype: atom\n---\na',- [`${REPO}/atoms/2026-05-24/b.md`]: '---\ntype: atom\n---\nb',+ // An inert object expression reproduces old executable-engine acceptance+ // without any process, filesystem or network side effects.+ [`${REPO}/atoms/2026-05-24/a.md`]: '---javascript\n({type: "atom", title: "private-content"})\n---\nbody',+ [`${REPO}/atoms/2026-05-24/b.md`]: '---\ntype: atom\ntitle: [private-content\n---\nbody',+ [`${REPO}/atoms/2026-05-24/c.md`]: '---\ntype: atom\n---\nvalid body',});const src = new MarkdownGreenfieldSource({ repoPath: REPO, ...fsOpts(fs) });const ctx = makeCtx();await src.start(ctx);- expect(src.stats.emitted).toBe(2);+ expect(src.stats).toEqual({ emitted: 1, skipped_invalid: 2, skipped_no_type: 0, total_walked: 3 });+ expect(ctx.emitted).toHaveLength(1);+ expect(ctx.emitted[0]!.source_uri).toEndWith('/c.md');+ expect(ctx.warnings).toHaveLength(2);+ expect(ctx.warnings.join('\n')).not.toContain('private-content');+ const failures = Object.values(fs.audit).flatMap(lines => lines.trim().split('\n').map(line => JSON.parse(line)));+ expect(failures.map(row => row.path)).toEqual([`${REPO}/atoms/2026-05-24/a.md`, `${REPO}/atoms/2026-05-24/b.md`]);+ expect(failures[0].error).toContain('Unsupported frontmatter language');+ expect(failures[1].error).toContain('Malformed YAML frontmatter');+ expect(JSON.stringify(failures)).not.toContain('private-content');+ expect(await src.healthCheck()).toMatchObject({ status: 'warn', message: '2/3 files failed validation; check audit log' });});test('audit JSONL path follows ISO-week-rotation pattern', async () => {diff --git a/test/integrations.test.ts b/test/integrations.test.tsindex 9b806889ff..dd942af673 100644--- a/test/integrations.test.ts+++ b/test/integrations.test.ts@@ -14,6 +14,7 @@ import {isPrivateIpv4,isInternalUrl,} from '../src/commands/integrations.ts';+import { __setDnsLookupForTests } from '../src/core/ssrf-validate.ts';const RECIPES_DIR = resolve(import.meta.dir, '..', 'recipes');@@ -561,6 +562,101 @@ describe('executeHealthCheck', () => {});});+describe('HTTP health checks use the guarded transport', () => {+ const originalFetch = globalThis.fetch;+ beforeEach(() => {+ __setDnsLookupForTests((async () => [{ address: '8.8.8.8', family: 4 }]) as any);+ });+ afterEach(() => {+ globalThis.fetch = originalFetch;+ __setDnsLookupForTests(undefined);+ });++ test('preserves configured method, string body and auth on a same-origin redirect', async () => {+ const requests: Array<{ url: string; method?: string; body: unknown; auth: string | null }> = [];+ let cancelled = 0;+ globalThis.fetch = (async (url: string, init?: RequestInit) => {+ requests.push({ url, method: init?.method, body: init?.body, auth: new Headers(init?.headers).get('authorization') });+ return new Response(new ReadableStream({ cancel() { cancelled++; } }), requests.length === 1+ ? { status: 303, headers: { location: '/final' } } : { status: 200 });+ }) as unknown as typeof fetch;+ const result = await executeHealthCheck({+ type: 'http', url: 'https://api.example.test/start', method: 'POST', body: '{"probe":true}',+ auth: 'bearer', auth_token: 'synthetic-test-value',+ }, 'test-id', true);+ expect(result.status).toBe('ok');+ expect(requests).toEqual([+ { url: 'https://8.8.8.8/start', method: 'POST', body: '{"probe":true}', auth: 'Bearer synthetic-test-value' },+ { url: 'https://8.8.8.8/final', method: 'POST', body: '{"probe":true}', auth: 'Bearer synthetic-test-value' },+ ]);+ expect(cancelled).toBe(2);+ });++ test('even a configured Accept header prevents cross-origin forwarding', async () => {+ let requests = 0;+ globalThis.fetch = (async () => {+ requests++;+ return new Response(null, { status: 302, headers: { location: 'https://other.example.test/final' } });+ }) as unknown as typeof fetch;+ const result = await executeHealthCheck({+ type: 'http', url: 'https://api.example.test/start', headers: { Accept: 'synthetic-test-value' },+ }, 'test-id', true);+ expect(result.status).toBe('blocked');+ expect(result.output).toContain('SSRF_REDIRECT_DENIED');+ expect(result.output).not.toContain('synthetic-test-value');+ expect(requests).toBe(1);+ });++ test('plain probes cross public origins and never consume the response body', async () => {+ let requests = 0;+ let cancelled = 0;+ globalThis.fetch = (async () => {+ requests++;+ return new Response(new ReadableStream({ cancel() { cancelled++; } }), requests === 1+ ? { status: 302, headers: { location: 'https://other.example.test/final' } } : { status: 200 });+ }) as unknown as typeof fetch;+ const result = await executeHealthCheck({ type: 'http', url: 'https://api.example.test/start' }, 'test-id', true);+ expect(result.status).toBe('ok');+ expect(requests).toBe(2);+ expect(cancelled).toBe(2);+ });++ test('unlabelled HTTP checks never serialize configured credentials into results', async () => {+ globalThis.fetch = (async () => new Response(null, { status: 200 })) as unknown as typeof fetch;+ const result = await executeHealthCheck({+ type: 'http', url: 'https://api.example.test/private-document?signature=private-value',+ auth: 'bearer', auth_token: 'private-token', method: 'POST', body: 'private-body',+ }, 'test-id', true);+ expect(result.status).toBe('ok');+ expect(result.check).toBe('HTTP');+ expect(JSON.stringify(result)).not.toContain('private-');+ });++ test('any_of results do not serialize nested HTTP credentials', async () => {+ globalThis.fetch = (async () => new Response(null, { status: 200 })) as unknown as typeof fetch;+ const result = await executeHealthCheck({ type: 'any_of', checks: [{+ type: 'http', url: 'https://api.example.test/check', auth: 'bearer', auth_token: 'private-token',+ }] }, 'test-id', true);+ expect(result.status).toBe('ok');+ expect(JSON.stringify(result)).not.toContain('private-');+ });++ test('HTTP denials and transport errors omit configured URLs and exception contents', async () => {+ for (const [url, embedded] of [+ ['https://api.example.test/private-document?signature=private-value', false],+ ['http://127.0.0.1/private-document?signature=private-value', true],+ ] as const) {+ const result = await executeHealthCheck({ type: 'http', url }, 'test-id', embedded);+ expect(result.status).toBe('blocked');+ expect(JSON.stringify(result)).not.toContain('private-');+ }+ globalThis.fetch = (async () => { throw new Error('TLS error private-document private-value'); }) as unknown as typeof fetch;+ const failed = await executeHealthCheck({ type: 'http', url: 'https://api.example.test/check' }, 'test-id', true);+ expect(failed.status).toBe('fail');+ expect(failed.output).not.toContain('private-');+ });+});+// --- SSRF helper tests (B3/B4/Fix 4) ---describe('parseOctet', () => {diff --git a/test/jobs-import-errors.serial.test.ts b/test/jobs-import-errors.serial.test.tsnew file mode 100644index 0000000000..75e9cc6438--- /dev/null+++ b/test/jobs-import-errors.serial.test.ts@@ -0,0 +1,64 @@+// Serial: the real import command reads a temporary GBRAIN_HOME per test.+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionWorker } from '../src/core/minions/worker.ts';+import type { MinionJobContext } from '../src/core/minions/types.ts';+import { registerBuiltinHandlers } from '../src/commands/jobs.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-job-import-errors-'));+const root = join(home, 'source');+let engine: PGLiteEngine;+let handler: (job: MinionJobContext) => Promise<unknown>;+const isolated = (fn: () => Promise<void>) => withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined }, fn);++beforeAll(async () => isolated(async () => {+ mkdirSync(root);+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [root]);+ const worker = new MinionWorker(engine, { concurrency: 1 });+ await registerBuiltinHandlers(worker, engine, { quiet: true });+ const registered = (worker as unknown as { handlers: Map<string, typeof handler> }).handlers.get('import');+ if (!registered) throw new Error('import handler not registered');+ handler = registered;+}), 60_000);++afterAll(async () => {+ await engine?.disconnect();+ rmSync(home, { recursive: true, force: true });+});++test('queued import rejects malformed frontmatter, preserves progress, and succeeds after repair', () => isolated(async () => {+ writeFileSync(join(root, 'valid.md'), '---\ntype: note\ntitle: Valid fixture\n---\n\nA valid fixture body.\n');+ writeFileSync(join(root, 'rejected.md'), '---\ntitle: [\n---\n\nA rejected fixture body.\n');+ const job: MinionJobContext = {+ id: 1,+ name: 'import',+ data: { dir: root, sourceId: 'default', noEmbed: true },+ attempts_made: 0,+ signal: new AbortController().signal,+ deadlineAtMs: null,+ shutdownSignal: new AbortController().signal,+ updateProgress: async () => {},+ updateTokens: async () => {},+ log: async () => {},+ isActive: async () => true,+ readInbox: async () => [],+ };++ await expect(handler(job)).rejects.toThrow('Import failed for 1 file(s); fix rejected documents and retry the job.');+ expect(await engine.getPage('valid', { sourceId: 'default' })).not.toBeNull();+ expect(await engine.getPage('rejected', { sourceId: 'default' })).toBeNull();+ const checkpoint = JSON.parse(readFileSync(join(home, '.gbrain', 'import-checkpoint.json'), 'utf8'));+ expect(checkpoint.completedPaths).toContain('valid.md');+ expect(checkpoint.completedPaths).not.toContain('rejected.md');++ writeFileSync(join(root, 'rejected.md'), '---\ntype: note\ntitle: Repaired fixture\n---\n\nA repaired fixture body.\n');+ await expect(handler(job)).resolves.toEqual({ imported: true });+ expect(await engine.getPage('rejected', { sourceId: 'default' })).not.toBeNull();+}));diff --git a/test/jobs-lifecycle-ops.test.ts b/test/jobs-lifecycle-ops.test.tsindex 38b8aaccf3..eca0e06db8 100644--- a/test/jobs-lifecycle-ops.test.ts+++ b/test/jobs-lifecycle-ops.test.ts@@ -89,7 +89,7 @@ function ctxOf(overrides: Partial<OperationContext> = {}): OperationContext {}const dryCtx = () => ctxOf({ dryRun: true });-/** Direct SQL seed (columns beyond these fall back to schema defaults). */+/** Direct SQL fixture of reviewed application work (never unknown legacy provenance). */async function seedJob(opts: {status: string;name?: string;@@ -109,12 +109,13 @@ async function seedJob(opts: {(name, queue, status, data, priority, max_attempts,lock_token, lock_until, error_text,attempts_made, attempts_started, stalled_counter,- started_at, finished_at)+ started_at, finished_at, submission_authority)VALUES ($1, 'default', $2, $3::jsonb, $4, $5,$6, CASE WHEN $6::text IS NULL THEN NULL ELSE now() + interval '5 minutes' END,$7, $8, $9, $10,CASE WHEN $11::boolean THEN now() ELSE NULL END,- CASE WHEN $11::boolean THEN now() ELSE NULL END)+ CASE WHEN $11::boolean THEN now() ELSE NULL END,+ '{"version":1,"kind":"application"}'::jsonb)RETURNING id`,[opts.name ?? 'embed',diff --git a/test/jobs-list-get-json.serial.test.ts b/test/jobs-list-get-json.serial.test.tsindex 6c8da31e80..7b715f62e8 100644--- a/test/jobs-list-get-json.serial.test.ts+++ b/test/jobs-list-get-json.serial.test.ts@@ -45,8 +45,8 @@ beforeEach(async () => {async function seedJob(name: string): Promise<number> {const rows = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, queue, status, data, started_at, finished_at)- VALUES ($1, 'default', 'completed', '{}'::jsonb,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, started_at, finished_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, $1, 'default', 'completed', '{}'::jsonb,now() - interval '10 minutes', now() - interval '5 minutes')RETURNING id`,[name],@@ -92,7 +92,7 @@ describe('jobs list/get --json (#3685)', () => {await seedJob('sync');await seedJob('sync');await engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, data) VALUES ('sync', 'default', 'waiting', '{}'::jsonb)`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data) VALUES ('{"version":1,"kind":"application"}'::jsonb, 'sync', 'default', 'waiting', '{}'::jsonb)`,[],);const out = await captureJobs(['list', '--json', '--status', 'completed', '--limit', '1']);diff --git a/test/jobs-ops-token-redaction.test.ts b/test/jobs-ops-token-redaction.test.tsindex 5fd39ec511..ec835e5cd8 100644--- a/test/jobs-ops-token-redaction.test.ts+++ b/test/jobs-ops-token-redaction.test.ts@@ -49,8 +49,8 @@ function parsed(result: { content: Array<{ text: string }> }) {/** Direct SQL seed: a waiting private-queue job carrying the raw token. */async function seedPrivateJob(queue: string): Promise<number> {const rows = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, queue, status, data, private_queue_owner_token, private_queue_lease_until)- VALUES ('subagent', $1, 'waiting', '{}'::jsonb, $2, now() + interval '10 minutes')+ `INSERT INTO minion_jobs (name, queue, status, data, private_queue_owner_token, private_queue_lease_until, submission_authority)+ VALUES ('subagent', $1, 'waiting', '{}'::jsonb, $2, now() + interval '10 minutes', '{"version":1,"kind":"application"}'::jsonb)RETURNING id`,[queue, RAW_TOKEN],);@@ -59,8 +59,8 @@ async function seedPrivateJob(queue: string): Promise<number> {async function seedPlainJob(): Promise<number> {const rows = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, queue, status, data)- VALUES ('embed', 'default', 'waiting', '{}'::jsonb)+ `INSERT INTO minion_jobs (name, queue, status, data, submission_authority)+ VALUES ('embed', 'default', 'waiting', '{}'::jsonb, '{"version":1,"kind":"application"}'::jsonb)RETURNING id`,);return Number(rows[0].id);@@ -140,7 +140,7 @@ describe('submit_job — owner-token redaction', () => {});it('null passthrough: a fresh tokenless submission reports null, not the string [redacted]', async () => {- const res = await dispatchToolCall(engine, 'submit_job', { name: 'embed' }, { ...STDIO });+ const res = await dispatchToolCall(engine, 'submit_job', { name: 'embed' }, { ...STDIO, remote: false });expect(res.isError ?? false).toBe(false);const body = parsed(res);expect(body.id).toBeGreaterThan(0);@@ -152,8 +152,8 @@ describe('submit_job — owner-token redaction', () => {/** A2 (test-gap wave 1): status-variant seeder for the cancel/retry pair. */async function seedPrivateJobWithStatus(status: string): Promise<number> {const rows = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, queue, status, data, private_queue_owner_token, private_queue_lease_until)- VALUES ('subagent', 'dream-inline-1700000000000-cafe0002', $1, '{}'::jsonb, $2, now() + interval '10 minutes')+ `INSERT INTO minion_jobs (name, queue, status, data, private_queue_owner_token, private_queue_lease_until, submission_authority)+ VALUES ('subagent', 'dream-inline-1700000000000-cafe0002', $1, '{}'::jsonb, $2, now() + interval '10 minutes', '{"version":1,"kind":"application"}'::jsonb)RETURNING id`,[status, RAW_TOKEN],);@@ -171,7 +171,7 @@ describe('cancel_job / retry_job — owner-token redaction (A2)', () => {it('retry_job redacts a present token across the whole envelope', async () => {const id = await seedPrivateJobWithStatus('failed');- const res = await dispatchToolCall(engine, 'retry_job', { id }, { ...STDIO });+ const res = await dispatchToolCall(engine, 'retry_job', { id }, { ...STDIO, remote: false });expect(res.isError ?? false).toBe(false);expect(parsed(res).private_queue_owner_token).toBe('[redacted]');expect(res.content[0].text).not.toContain(RAW_TOKEN);@@ -182,9 +182,9 @@ describe('cancel_job / retry_job — owner-token redaction (A2)', () => {const cancelRes = await dispatchToolCall(engine, 'cancel_job', { id: waiting }, { ...STDIO });expect(parsed(cancelRes).private_queue_owner_token).toBeNull();const failedRows = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, queue, status, data) VALUES ('embed', 'default', 'failed', '{}'::jsonb) RETURNING id`,+ `INSERT INTO minion_jobs (name, queue, status, data, submission_authority) VALUES ('embed', 'default', 'failed', '{}'::jsonb, '{"version":1,"kind":"application"}'::jsonb) RETURNING id`,);- const retryRes = await dispatchToolCall(engine, 'retry_job', { id: Number(failedRows[0].id) }, { ...STDIO });+ const retryRes = await dispatchToolCall(engine, 'retry_job', { id: Number(failedRows[0].id) }, { ...STDIO, remote: false });expect(parsed(retryRes).private_queue_owner_token).toBeNull();});});diff --git a/test/jobs-sidechannel-fence.test.ts b/test/jobs-sidechannel-fence.test.tsindex 79456d6d7a..4100485c31 100644--- a/test/jobs-sidechannel-fence.test.ts+++ b/test/jobs-sidechannel-fence.test.ts@@ -63,8 +63,8 @@ const AUTHED = {/** Direct SQL seed (same shape as test/jobs-ops-token-redaction.test.ts). */async function seedJob(status = 'waiting'): Promise<number> {const rows = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, queue, status, data)- VALUES ('embed', 'default', $1, '{}'::jsonb)+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'embed', 'default', $1, '{}'::jsonb)RETURNING id`,[status],);@@ -147,8 +147,8 @@ describe('send_job_message — local caller behavior preserved', () => {it('local caller with an explicit sender param passes it through (parent job id)', async () => {const parentId = await seedJob();const childRows = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, queue, status, data, parent_job_id)- VALUES ('research', 'default', 'waiting', '{}'::jsonb, $1)+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, parent_job_id)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'research', 'default', 'waiting', '{}'::jsonb, $1)RETURNING id`,[parentId],);diff --git a/test/jobs-stats-backpressure.serial.test.ts b/test/jobs-stats-backpressure.serial.test.tsindex 5327124311..6978c1e08c 100644--- a/test/jobs-stats-backpressure.serial.test.ts+++ b/test/jobs-stats-backpressure.serial.test.ts@@ -59,7 +59,7 @@ describe('jobs stats — Backpressure line + suppression hint wiring', () => {// shape that used to be invisible to the waiting>0 wedge detectors.const job = await queue.add('autopilot-cycle', {});await engine.executeRaw(- `UPDATE minion_jobs SET status = 'active', lock_token = 'live-worker',+ `UPDATE minion_jobs SET status = 'active', claim_generation = claim_generation + 1, lock_token = 'live-worker',lock_until = now() + interval '5 minutes',started_at = now() - interval '30 minutes'WHERE id = $1`,diff --git a/test/jobs-stats-divergence.serial.test.ts b/test/jobs-stats-divergence.serial.test.tsindex b3ec8e236f..a692bc0131 100644--- a/test/jobs-stats-divergence.serial.test.ts+++ b/test/jobs-stats-divergence.serial.test.ts@@ -40,21 +40,21 @@ beforeEach(async () => {async function seedJobs(opts: { waiting: number; completed: number; ttlCancelled?: number }): Promise<void> {for (let i = 0; i < opts.waiting; i++) {await engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, data) VALUES ('subagent', 'default', 'waiting', '{}'::jsonb)`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data) VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'default', 'waiting', '{}'::jsonb)`,[],);}for (let i = 0; i < opts.completed; i++) {await engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, data, started_at, finished_at)- VALUES ('subagent', 'default', 'completed', '{}'::jsonb, now() - interval '10 minutes', now() - interval '5 minutes')`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, started_at, finished_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'default', 'completed', '{}'::jsonb, now() - interval '10 minutes', now() - interval '5 minutes')`,[],);}for (let i = 0; i < (opts.ttlCancelled ?? 0); i++) {await engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, data, error_text, finished_at)- VALUES ('subagent', 'default', 'cancelled', '{}'::jsonb,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, error_text, finished_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'default', 'cancelled', '{}'::jsonb,'waiting_ttl_expired: waited > 48h in queue', now() - interval '1 hour')`,[],);diff --git a/test/jobs-stats-private-queue.serial.test.ts b/test/jobs-stats-private-queue.serial.test.tsindex 3af894fa81..e47dd4f546 100644--- a/test/jobs-stats-private-queue.serial.test.ts+++ b/test/jobs-stats-private-queue.serial.test.ts@@ -51,15 +51,15 @@ describe('jobs stats — ABANDONED PRIVATE QUEUE classifier gating', () => {test('orphan (terminal owner, aged, expired lease) screams ABANDONED with the auto-recovery remediation', async () => {const q = 'dream-inline-1700000000000-dead0001';await engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, data, created_at)- VALUES ('dream-cycle', 'default', 'completed', '{}'::jsonb, now() - interval '3 hours')`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'dream-cycle', 'default', 'completed', '{}'::jsonb, now() - interval '3 hours')`,[],);const owner = await engine.executeRaw<{ id: number }>(`SELECT max(id)::int AS id FROM minion_jobs`, []);await engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, data, created_at, updated_at,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, created_at, updated_at,private_queue_owner_job_id, private_queue_owner_token, private_queue_lease_until)- SELECT 'subagent', $1, 'waiting', '{}'::jsonb, now() - interval '2 hours', now() - interval '2 hours',+ SELECT '{"version":1,"kind":"application"}'::jsonb, 'subagent', $1, 'waiting', '{}'::jsonb, now() - interval '2 hours', now() - interval '2 hours',$2, 'tok', now() - interval '1 hour'FROM generate_series(1, 2)`,[q, owner[0].id],@@ -73,8 +73,8 @@ describe('jobs stats — ABANDONED PRIVATE QUEUE classifier gating', () => {test('legacy unowned (no owner metadata, aged) screams ABANDONED with the retriage remediation', async () => {const q = 'dream-inline-1700000000000-dead0002';await engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, data, created_at, updated_at)- VALUES ('subagent', $1, 'waiting', '{}'::jsonb, now() - interval '2 hours', now() - interval '2 hours')`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, created_at, updated_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', $1, 'waiting', '{}'::jsonb, now() - interval '2 hours', now() - interval '2 hours')`,[q],);const out = await captureStats(['stats', '--queue', q]);@@ -88,8 +88,8 @@ describe('jobs stats — ABANDONED PRIVATE QUEUE classifier gating', () => {// Aged enough to be a candidate, but the future lease classifies live —// a healthy mid-drain queue must not scream.await engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, data, created_at, updated_at, private_queue_lease_until)- VALUES ('subagent', $1, 'waiting', '{}'::jsonb, now() - interval '2 hours', now() - interval '2 hours',+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, created_at, updated_at, private_queue_lease_until)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', $1, 'waiting', '{}'::jsonb, now() - interval '2 hours', now() - interval '2 hours',now() + interval '30 minutes')`,[q],);diff --git a/test/jobs-submit-identity-stamp.test.ts b/test/jobs-submit-identity-stamp.test.tsindex 0f1ff3555b..794832c75c 100644--- a/test/jobs-submit-identity-stamp.test.ts+++ b/test/jobs-submit-identity-stamp.test.ts@@ -1,24 +1,5 @@-/**- * submit_job `data.client_id` identity stamp (pre-landing review fix).- *- * `data.client_id` is a spend-attribution identity: minion handlers settle- * their LLM/embedding spend against it via getJobClientId →- * recordMinionJobSpend (src/core/minion-spend.ts), charging the named OAuth- * client's mcp_spend_log / daily cap. Pre-fix, submit_job passed the- * caller-supplied `data` payload through to queue.add unmodified, so a- * remote caller could stamp ANOTHER client's id (billing/cap spoof) or- * invent one. Mirroring send_job_message's derived-identity fence:- *- * - remote caller (ctx.remote !== false) WITH an authenticated clientId →- * data.client_id is OVERWRITTEN with ctx.auth.clientId (the same- * identity source run_onboard/A23 uses for spend attribution).- * - remote caller WITHOUT an authenticated identity (e.g. stdio pipe) →- * the key is DELETED (a job with no client_id records spend with- * clientId=null; it never counts against a specific client's cap).- * - trusted local caller (ctx.remote === false) keeps today's behavior:- * the caller-supplied value passes through (the CLI/autopilot path is- * the trusted surface that legitimately sets it, e.g. run_onboard).- */+/** Generic remote jobs reject spend identities in data; authority comes only+ * from the verifier. Trusted local application submitters retain attribution. */import { describe, it, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { operationsByName, type OperationContext } from '../src/core/operations.ts';@@ -53,6 +34,8 @@ const AUTHED = {token: 'test-token',clientId: 'client-abcdef0123456789',scopes: ['admin'],+ sourceId: 'default',+ principal: { kind: 'oauth_client', id: 'client-abcdef0123456789' },} as OperationContext['auth'];async function storedData(jobId: number): Promise<Record<string, unknown>> {@@ -65,25 +48,16 @@ async function storedData(jobId: number): Promise<Record<string, unknown>> {}describe('submit_job — data.client_id derived-identity stamp', () => {- it('remote + authenticated: caller-supplied client_id is OVERWRITTEN with the authenticated id', async () => {- const res = (await submit_job.handler(- ctxOf({ auth: AUTHED }),- { name: 'lint', data: { client_id: 'victim-client', nonce: 'stamp-1' } },- )) as { id: number };- const data = await storedData(res.id);- expect(data.client_id).toBe('client-abcdef0123456789');- expect(data.client_id).not.toBe('victim-client');- expect(data.nonce).toBe('stamp-1'); // rest of the payload untouched+ it('remote authenticated caller cannot supply a spend identity in data', async () => {+ await expect(submit_job.handler(ctxOf({ auth: AUTHED }), {+ name: 'lint', data: { client_id: 'victim-client' },+ })).rejects.toThrow('unsupported remote job parameter');+ expect(await engine.executeRaw('SELECT id FROM minion_jobs')).toHaveLength(0);});- it('remote + NO authenticated identity: the key is stripped, never persisted', async () => {- const res = (await submit_job.handler(- ctxOf(),- { name: 'lint', data: { client_id: 'victim-client', nonce: 'stamp-2' } },- )) as { id: number };- const data = await storedData(res.id);- expect(data.client_id).toBeUndefined();- expect(data.nonce).toBe('stamp-2');+ it('remote caller without a durable identity cannot submit generic work', async () => {+ await expect(submit_job.handler(ctxOf(), { name: 'lint', data: {} })).rejects.toThrow('persistent principal');+ expect(await engine.executeRaw('SELECT id FROM minion_jobs')).toHaveLength(0);});it('local caller (ctx.remote === false) preserves the caller-supplied value', async () => {diff --git a/test/lint-shared-engine.test.ts b/test/lint-shared-engine.test.tsindex a50ddbc96c..e311f183a5 100644--- a/test/lint-shared-engine.test.ts+++ b/test/lint-shared-engine.test.ts@@ -34,6 +34,16 @@ describe('runLintCore engine reuse (issue #1678)', () => {const state = { disconnects: 0, connects: 0, getConfigCalls: 0 };const engine = {kind: 'postgres' as const,+ // Model the shared engine's source-root lookup and lock bookkeeping;+ // neither operation opens another pool or changes the reuse counters.+ executeRaw: async () => [],+ sql: async (parts: TemplateStringsArray, ...params: unknown[]) => {+ const statement = parts.join('?');+ if (statement.includes('INSERT INTO gbrain_cycle_locks')) return [{ id: params[0], fence: 'test-fence' }];+ if (statement.includes('DELETE FROM gbrain_cycle_locks')) return [];+ throw new Error('Unexpected SQL in lint shared-engine fixture');+ },+ executeRawDirect: async () => [{ id: 'test-lock' }],getConfig: async () => { state.getConfigCalls++; return null; },connect: async () => { state.connects++; },disconnect: async () => { state.disconnects++; },diff --git a/test/list-pages-source-scope.test.ts b/test/list-pages-source-scope.test.tsindex 2212cd18d7..998b04439d 100644--- a/test/list-pages-source-scope.test.ts+++ b/test/list-pages-source-scope.test.ts@@ -40,8 +40,11 @@ function makeCtx(overrides: Partial<OperationContext> = {}): {}describe('list_pages — explicit source_id param (#4400)', () => {- test('an explicit source_id scopes the engine call to that source', async () => {- const { ctx, calls } = makeCtx({ sourceId: 'default' });+ test('an explicitly granted source_id scopes the engine call to that source', async () => {+ const { ctx, calls } = makeCtx({+ sourceId: 'default',+ auth: { token: 't', clientId: 'c', scopes: ['read'], allowedSources: ['default', 'hermes-coding-agent'] },+ });await list_pages.handler(ctx, { source_id: 'hermes-coding-agent' });expect(calls[0]).toMatchObject({ sourceId: 'hermes-coding-agent' });});@@ -74,6 +77,15 @@ describe('list_pages — explicit source_id param (#4400)', () => {);});+ test.each(['scalar', 'absent'] as const)('a remote caller with a %s grant cannot explicitly select a foreign source', async grant => {+ const { ctx, calls } = makeCtx({+ sourceId: grant === 'scalar' ? 'default' : undefined,+ auth: grant === 'scalar' ? { token: 't', clientId: 'c', scopes: ['read'], sourceId: 'default' } : undefined,+ });+ await expect(list_pages.handler(ctx, { source_id: 'hermes-coding-agent' })).rejects.toMatchObject({ code: 'permission_denied' });+ expect(calls).toHaveLength(0);+ });+test('no source_id param still falls back to federatedSearchScope(ctx) (back-compat)', async () => {const { ctx, calls } = makeCtx({remote: false,diff --git a/test/mcp-eval-capture.test.ts b/test/mcp-eval-capture.test.tsindex 34387ca16c..90c5d564c5 100644--- a/test/mcp-eval-capture.test.ts+++ b/test/mcp-eval-capture.test.ts@@ -156,9 +156,10 @@ describe('op-layer capture — query', () => {expect(rows).toHaveLength(0);});- test('explicit source_id overrides ctx.sourceId for query retrieval', async () => {+ test('explicitly granted source_id overrides ctx.sourceId for query retrieval', async () => {const ctx = makeCtx({sourceId: 'default',+ auth: { token: 't', clientId: 'c', scopes: ['read'], allowedSources: ['default', 'testsrc'] },config: makeConfig({ capture: false }),});diff --git a/test/migrate.test.ts b/test/migrate.test.tsindex b5b925ca0a..68d2badfe0 100644--- a/test/migrate.test.ts+++ b/test/migrate.test.ts@@ -802,7 +802,7 @@ describe('migrate — runner behavioral (v14 handler + v15 backfill)', () => {test('v15 backfilled any max_stalled=1 rows (smoke: schema default is 5)', async () => {await (engine as any).db.exec(- `INSERT INTO minion_jobs (name, queue, status, max_stalled) VALUES ('test', 'default', 'waiting', 1)`+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, max_stalled) VALUES ('{"version":1,"kind":"application"}'::jsonb, 'test', 'default', 'waiting', 1)`);await (engine as any).db.exec(`UPDATE minion_jobs SET max_stalled = 5diff --git a/test/migrations-v128.test.ts b/test/migrations-v128.test.tsindex 92e8142e9e..ee819e74f3 100644--- a/test/migrations-v128.test.ts+++ b/test/migrations-v128.test.ts@@ -15,8 +15,10 @@* cycles per (name, queue, source scope). Manual submissions (no ticker* idempotency-key prefix) and parented rows are never touched; distinct* sources each keep their newest row; cancelled rows carry error_text.- * 4. Ledger round-trip: rewind to 127 → runMigrations applies v128; re-run- * is 0 applied. AND (Codex C9) SQL-level idempotency: re-executing the+ * 4. Ledger round-trip on a waiting fixture: rewind to 127 → runMigrations+ * applies v128; re-run is 0 applied. The active-row matrix runs v128 SQL+ * directly because later authority cutovers require active jobs drained.+ * AND (Codex C9) SQL-level idempotency: re-executing the* v128 SQL directly changes zero rows — the ledger check alone only* proves version bookkeeping.* 5. Empty table → 0-row no-op.@@ -117,7 +119,7 @@ describe('migration v128 — backfill + cleanup semantics (PGLite)', () => {idempotency_key: 'autopilot-cycle:src-active:slot-0',});await forceRow(legacyActive.id,- `timeout_ms = NULL, timeout_at = NULL, status = 'active',+ `timeout_ms = NULL, timeout_at = NULL, status = 'active', claim_generation = claim_generation + 1,lock_token = 'legacy-worker', lock_until = now() + interval '30 seconds',started_at = now() - interval '10 minutes'`);// Terminal row: NULL budget stays NULL (completed is not rescued).@@ -179,11 +181,9 @@ describe('migration v128 — backfill + cleanup semantics (PGLite)', () => {await forceRow(parented.id,`created_at = now() - interval '6 hours', parent_job_id = $1`, [dupNew.id]);- // --- Apply v128 via the real migration runner (ledger rewind). ---- await engine.setConfig('version', '127');- const res = await runMigrations(engine);- expect(res.applied).toBeGreaterThanOrEqual(1);- expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));+ // Keep the active-row contract local to v128; the v149 authority+ // cutover independently requires active jobs to have drained.+ await execV128Directly();const rows = await engine.executeRaw<{id: number; status: string; timeout_ms: string | null;@@ -214,10 +214,6 @@ describe('migration v128 — backfill + cleanup semantics (PGLite)', () => {expect(byId.get(parented.id)!.status).toBe('waiting'); // parented never touchedexpect(byId.get(camelMimic.id)!.status).toBe('waiting'); // camelCase sourceId never swept- // Ledger idempotency: re-run applies nothing.- const rerun = await runMigrations(engine);- expect(rerun.applied).toBe(0);-// SQL-level idempotency (Codex C9): re-execute the v128 SQL directly and// prove zero rows change — version bookkeeping alone can't show this.const before = await snapshot();@@ -229,6 +225,18 @@ describe('migration v128 — backfill + cleanup semantics (PGLite)', () => {expect(V128_STATEMENTS.length).toBe(2);}, 30_000);+ test('migration runner backfills a waiting fixture and records an idempotent ledger', async () => {+ const waiting = await queue.add('subagent', {}, undefined, { allowProtectedSubmit: true });+ await forceRow(waiting.id, `timeout_ms = NULL, timeout_at = NULL`);+ await engine.setConfig('version', '127');++ const res = await runMigrations(engine);+ expect(res.applied).toBeGreaterThanOrEqual(1);+ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));+ expect((await queue.getJob(waiting.id))?.timeout_ms).toBe(1_800_000);+ expect((await runMigrations(engine)).applied).toBe(0);+ });+test('empty table: v128 SQL is a 0-row no-op', async () => {const before = await snapshot();expect(before).toEqual([]);diff --git a/test/minions-admission.test.ts b/test/minions-admission.test.tsindex aa1ca5fe38..4be6449583 100644--- a/test/minions-admission.test.ts+++ b/test/minions-admission.test.ts@@ -106,7 +106,7 @@ describe('param-coalescing (subagent default-on)', () => {test('a RUNNING identical job does not suppress a re-run (waiting-only)', async () => {const first = await queue.add('subagent', { prompt: 'rerun me' }, {}, SUB);await engine.executeRaw(- `UPDATE minion_jobs SET status = 'active', lock_until = now() + interval '5 minutes' WHERE id = $1`,+ `UPDATE minion_jobs SET status = 'active', claim_generation = claim_generation + 1, lock_until = now() + interval '5 minutes' WHERE id = $1`,[first.id],);const second = await queue.add('subagent', { prompt: 'rerun me' }, {}, SUB);@@ -230,7 +230,7 @@ describe('waiting-TTL sweep (handleWaitingTTL via cancelJobs)', () => {test('active and delayed rows are never TTL-cancelled', async () => {const active = await queue.add('subagent', { prompt: 'running' }, {}, SUB);await engine.executeRaw(- `UPDATE minion_jobs SET status = 'active', lock_until = now() + interval '5 minutes',+ `UPDATE minion_jobs SET status = 'active', claim_generation = claim_generation + 1, lock_until = now() + interval '5 minutes',created_at = now() - interval '100 hours' WHERE id = $1`,[active.id],);@@ -370,7 +370,7 @@ describe('cancelJobs reason + rootStatuses (direct)', () => {const w = await queue.add('subagent', { prompt: 'still waiting' }, {}, SUB);const act = await queue.add('subagent', { prompt: 'claimed meanwhile' }, {}, SUB);await engine.executeRaw(- `UPDATE minion_jobs SET status = 'active', lock_until = now() + interval '5 minutes' WHERE id = $1`,+ `UPDATE minion_jobs SET status = 'active', claim_generation = claim_generation + 1, lock_until = now() + interval '5 minutes' WHERE id = $1`,[act.id],);const swept = await queue.cancelJobs([w.id, act.id], { reason: 'sweep', rootStatuses: ['waiting'] });diff --git a/test/minions-cold-import.test.ts b/test/minions-cold-import.test.tsnew file mode 100644index 0000000000..5283e6902f--- /dev/null+++ b/test/minions-cold-import.test.ts@@ -0,0 +1,35 @@+import { expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { keylessBrainEnv } from './helpers/provider-env.ts';++const moduleUrl = (name: string) => new URL(`../src/core/minions/${name}`, import.meta.url).href;++for (const entry of ['types.ts', 'handlers/subagent.ts', 'worker.ts']) {+ test(`cold ${entry} import preserves unrecoverable error identity`, () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-minion-import-'));+ try {+ // A fresh process is essential: a warm test module registry hides cycles.+ const script = `+ await import(${JSON.stringify(moduleUrl(entry))});+ const { UnrecoverableError } = await import(${JSON.stringify(moduleUrl('types.ts'))});+ const { DelegationDeniedError } = await import(${JSON.stringify(moduleUrl('delegated-policy.ts'))});+ const { encodeHandlerError, reconstructHandlerError } = await import(${JSON.stringify(moduleUrl('job-isolation.ts'))});+ const denied = new DelegationDeniedError(['fixture_denial']);+ const encoded = encodeHandlerError(denied);+ console.log(JSON.stringify({+ unrecoverable: denied instanceof UnrecoverableError,+ errorKind: encoded.errorKind,+ reconstructed: reconstructHandlerError(encoded) instanceof UnrecoverableError,+ }));+ `;+ const child = Bun.spawnSync([process.execPath, '--no-env-file', '-e', script], {+ cwd: home, env: keylessBrainEnv(process.env, home, { DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }),+ stdout: 'pipe', stderr: 'pipe', timeout: 20_000,+ });+ expect(child.exitCode, child.stderr.toString()).toBe(0);+ expect(JSON.parse(child.stdout.toString())).toEqual({ unrecoverable: true, errorKind: 'unrecoverable', reconstructed: true });+ } finally { rmSync(home, { recursive: true, force: true }); }+ });+}diff --git a/test/minions-submission-authority.test.ts b/test/minions-submission-authority.test.tsnew file mode 100644index 0000000000..cea08d6707--- /dev/null+++ b/test/minions-submission-authority.test.ts@@ -0,0 +1,416 @@+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { execFileSync } from 'node:child_process';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import { MinionWorker } from '../src/core/minions/worker.ts';+import { runChildJobEntry } from '../src/core/minions/run-child.ts';+import { buildJobContext } from '../src/core/minions/job-context.ts';+import { jobsOperations } from '../src/core/ops/jobs.ts';+import { authorizeLegacyJobs } from '../src/core/minions/authorize-legacy.ts';+import { readSourceFileSync, writeSourceFileSync, withSourceFilesystemLock } from '../src/core/minions/source-filesystem.ts';+import { APPLICATION_AUTHORITY, assertNoUnreviewedJobs, assertRemoteJobControl, authorizeJobExecution, prepareRemoteJob, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { withEnv } from './helpers/with-env.ts';++const sandbox = mkdtempSync(join(tmpdir(), 'gbrain-job-authority-'));+const root = join(sandbox, 'repo');+const brainHome = join(sandbox, 'home');+const legacyId = '11111111-1111-4111-8111-111111111111';+let engine: PGLiteEngine;+let queue: MinionQueue;+function isolated<T>(fn: () => T | Promise<T>): Promise<T> {+ return withEnv({ GBRAIN_HOME: brainHome, DATABASE_URL: undefined }, fn);+}+function ctx(): OperationContext {+ return {+ engine, config: {} as OperationContext['config'], dryRun: false, remote: true, sourceId: 'default',+ logger: { info() {}, warn() {}, error() {} },+ auth: { token: 'test-only', clientId: 'client-a', principal: { kind: 'oauth_client', id: 'client-a' }, scopes: ['admin'], sourceId: 'default' },+ };+}+async function submit(name = 'lint', data?: unknown) {+ const accepted = await prepareRemoteJob(ctx(), name, data);+ return queue.add(name, accepted.data, {}, { submissionAuthority: accepted.authority });+}++beforeAll(async () => isolated(async () => {+ mkdirSync(root); mkdirSync(brainHome);+ execFileSync('git', ['init', '-q', root]);+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ queue = new MinionQueue(engine);+}), 60_000);+afterAll(async () => { await engine?.disconnect(); rmSync(sandbox, { recursive: true, force: true }); }, 60_000);+beforeEach(async () => isolated(async () => {+ await engine.executeRaw('DELETE FROM minion_jobs');+ await engine.executeRaw('DELETE FROM oauth_clients');+ await engine.executeRaw('DELETE FROM access_tokens');+ await engine.executeRaw("UPDATE sources SET config = '{}'::jsonb, archived = false, local_path = $1 WHERE id = 'default'", [root]);+ await engine.executeRaw("INSERT INTO oauth_clients (client_id, client_secret_hash, client_name, scope, source_id) VALUES ('client-a', 'test-only', 'example-client', 'admin', 'default')");+}));++describe('generic remote job authority', () => {+ test('controlled migration drains active work, preserves legacy rows and excludes old binaries', () => isolated(async () => {+ const { rehearseMinionAuthorityUpgrade } = await import('./helpers/minion-authority-upgrade.ts');+ await rehearseMinionAuthorityUpgrade(engine);+ }));+ test('exactly four jobs normalize source, paths and no paid descendants', () => isolated(async () => {+ const sync = await prepareRemoteJob(ctx(), 'sync', {});+ expect(sync.data).toEqual({ repoPath: root, sourceId: 'default', noPull: false, noEmbed: true, noExtract: true, auto_embed_backfill: false });+ expect((await prepareRemoteJob(ctx(), 'sync', { noPull: true })).data.noPull).toBe(true);+ expect((await prepareRemoteJob(ctx(), 'import', {})).data).toEqual({ dir: root, sourceId: 'default', noEmbed: true });+ for (const name of ['lint', 'lint-fix']) expect((await prepareRemoteJob(ctx(), name, {})).data).toEqual({ dir: root, sourceId: 'default' });+ for (const name of ['embed', 'shell', 'extract', 'subagent', 'sync-retry-failed']) await expect(prepareRemoteJob(ctx(), name, {})).rejects.toThrow('only sync');+ for (const [name, data] of [['sync', { noExtract: false }], ['sync', { github_item: {} }], ['sync', { sourceId: 'other' }], ['sync', { pull: true, noPull: false }], ['import', { dir: '/tmp' }], ['lint-fix', { fix: false }]] as const) {+ await expect(prepareRemoteJob(ctx(), name, data)).rejects.toThrow();+ }+ }));++ test('connector/unknown kind, stdio, missing source and revoked admission fail closed', () => isolated(async () => {+ for (const kind of ['google', 'github', 'future-kind']) {+ await engine.executeRaw('UPDATE sources SET config = $1::jsonb WHERE id = $2', [{ kind }, 'default']);+ await expect(prepareRemoteJob(ctx(), 'sync', {})).rejects.toThrow('filesystem source');+ }+ const stdio = { ...ctx(), auth: undefined, transport: 'stdio' as const };+ await expect(prepareRemoteJob(stdio, 'lint', {})).rejects.toThrow('persistent principal');+ await engine.executeRaw("UPDATE sources SET config = '{}'::jsonb, local_path = NULL WHERE id = 'default'");+ await expect(prepareRemoteJob(ctx(), 'lint', {})).rejects.toThrow('registered filesystem root');+ }));++ test('nested source defaults no-pull and rejects explicit whole-worktree mutation', () => isolated(async () => {+ const nested = join(root, 'nested'); mkdirSync(nested, { recursive: true });+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [nested]);+ expect((await prepareRemoteJob(ctx(), 'sync', {})).data.noPull).toBe(true);+ await expect(prepareRemoteJob(ctx(), 'sync', { pull: true })).rejects.toThrow('nested');+ }));++ test('original payload and current client/source policy must both authorize execution', () => isolated(async () => {+ const job = await submit();+ expect((await authorizeJobExecution(engine, job)).kind).toBe('remote_generic');+ // Accepted OAuth work is client-bound, not tied to a short-lived credential row.+ await engine.executeRaw('DELETE FROM oauth_tokens');+ await authorizeJobExecution(engine, job);+ await expect(authorizeJobExecution(engine, { ...job, data: { ...job.data, dir: sandbox } })).rejects.toThrow('differs');+ await engine.executeRaw("UPDATE oauth_clients SET scope = 'read' WHERE client_id = 'client-a'");+ await expect(authorizeJobExecution(engine, job)).rejects.toThrow('current principal');+ await engine.executeRaw("UPDATE oauth_clients SET scope = 'admin', bound_slug_prefixes = ARRAY['wiki/*'] WHERE client_id = 'client-a'");+ await expect(authorizeJobExecution(engine, job)).rejects.toThrow('slug-bound');+ await engine.executeRaw("UPDATE oauth_clients SET bound_slug_prefixes = NULL, deleted_at = now() WHERE client_id = 'client-a'");+ await expect(authorizeJobExecution(engine, job)).rejects.toThrow('revoked');+ }));++ test('current operation profiles and the submitted ceiling both authorize generic jobs', () => isolated(async () => {+ const narrowed = ctx(); narrowed.auth!.allowedOperations = ['get_page'];+ await expect(prepareRemoteJob(narrowed, 'lint', {})).rejects.toThrow('operation grants');+ const allowed = ctx(); allowed.auth!.allowedOperations = ['submit_job'];+ const accepted = await prepareRemoteJob(allowed, 'lint', {});+ const job = await queue.add('lint', accepted.data, {}, { submissionAuthority: accepted.authority });+ expect(job.submission_authority?.kind === 'remote_generic' && job.submission_authority.grant.allowedOperations).toEqual(['submit_job']);+ await engine.executeRaw("UPDATE oauth_clients SET allowed_operations=ARRAY['get_page'] WHERE client_id='client-a'");+ await expect(authorizeJobExecution(engine, job)).rejects.toThrow('operation grants');+ await expect(prepareRemoteJob(ctx(), 'lint', {})).rejects.toThrow('operation grants');+ }));++ test('legacy principal is UUID: names cannot transfer authority and revocation blocks retry', () => isolated(async () => {+ await engine.executeRaw('INSERT INTO access_tokens (id, name, token_hash, permissions, scopes) VALUES ($1, $2, $3, $4::jsonb, ARRAY[\'admin\'])', [legacyId, 'same-name', 'test-hash-a', { source_id: 'default' }]);+ const legacy = ctx(); legacy.auth = { ...legacy.auth!, principal: { kind: 'legacy_token', id: legacyId }, clientId: 'same-name' };+ const accepted = await prepareRemoteJob(legacy, 'lint', {});+ const job = await queue.add('lint', accepted.data, {}, { submissionAuthority: accepted.authority });+ await engine.executeRaw("UPDATE minion_jobs SET status = 'failed' WHERE id = $1", [job.id]);+ await engine.executeRaw('UPDATE access_tokens SET revoked_at = now() WHERE id = $1', [legacyId]);+ await engine.executeRaw("INSERT INTO access_tokens (name, token_hash, scopes) VALUES ('same-name', 'test-hash-b', ARRAY['admin'])");+ await expect(queue.retryJob(job.id)).rejects.toThrow('revoked');+ }));++ test('retry/resume/replay retain authority; remote overrides and other principals cannot restart', () => isolated(async () => {+ const job = await submit();+ await engine.executeRaw("UPDATE minion_jobs SET status = 'failed' WHERE id = $1", [job.id]);+ const retry = await queue.retryJob(job.id); expect(retry?.submission_authority).toEqual(job.submission_authority);+ await queue.pauseJob(job.id);+ expect((await queue.resumeJob(job.id))?.submission_authority).toEqual(job.submission_authority);+ await engine.executeRaw("UPDATE minion_jobs SET status = 'completed' WHERE id = $1", [job.id]);+ const replay = await queue.replayJob(job.id); expect(replay?.submission_authority).toEqual(job.submission_authority);+ await expect(queue.replayJob(job.id, { dir: sandbox })).rejects.toThrow('cannot override');+ const foreign = ctx(); foreign.auth = { ...foreign.auth!, principal: { kind: 'oauth_client', id: 'client-b' } };+ await expect(assertRemoteJobControl(foreign, job)).rejects.toThrow('submitting principal');+ await expect(assertRemoteJobControl(ctx(), await queue.add('lint', {}))).rejects.toThrow('submitting principal');+ }));++ test('idempotency and backpressure never return an application job to remote authority', () => isolated(async () => {+ const accepted = await prepareRemoteJob(ctx(), 'lint', {});+ await queue.add('lint', accepted.data, { idempotency_key: 'same-key' });+ await expect(queue.add('lint', accepted.data, { idempotency_key: 'same-key' }, { submissionAuthority: accepted.authority })).rejects.toThrow('coalescing across');+ await expect(queue.add('lint', accepted.data, { maxPending: 1 }, { submissionAuthority: accepted.authority })).rejects.toThrow('coalescing across');+ await expect(queue.add('lint', accepted.data, { maxWaiting: 1 }, { submissionAuthority: accepted.authority })).rejects.toThrow('coalescing across');+ }));++ test('remote descendants fail even without parent id; internal maintenance remains available', () => isolated(async () => {+ const accepted = await prepareRemoteJob(ctx(), 'lint', {});+ await expect(withSubmissionAuthority(accepted.authority, () => queue.add('embed', {}))).rejects.toThrow('descendant');+ const parent = await queue.add('lint', accepted.data, {}, { submissionAuthority: accepted.authority });+ await expect(queue.add('embed', {}, { parent_job_id: parent.id })).rejects.toThrow('descendant');+ expect((await withSubmissionAuthority(APPLICATION_AUTHORITY, () => queue.add('maintenance', {}))).submission_authority?.kind).toBe('application');+ }));++ test('operation admission ignores forged authority and never returns private authority metadata', () => isolated(async () => {+ const operation = jobsOperations.find(op => op.name === 'submit_job')!;+ await expect(operation.handler(ctx(), { name: 'lint', data: { submission_authority: APPLICATION_AUTHORITY } })).rejects.toThrow('unsupported');+ const result = await operation.handler(ctx(), { name: 'lint', data: {} }) as Record<string, unknown>;+ expect(result.submission_authority).toBeUndefined();+ expect((await queue.getJob(result.id as number))?.submission_authority?.kind).toBe('remote_generic');+ const get = jobsOperations.find(op => op.name === 'get_job')!;+ expect((await get.handler(ctx(), { id: result.id }) as Record<string, unknown>).submission_authority).toBeUndefined();+ const local = await queue.add('maintenance', {});+ await engine.executeRaw("UPDATE minion_jobs SET status = 'failed' WHERE id = $1", [local.id]);+ await expect(jobsOperations.find(op => op.name === 'retry_job')!.handler(ctx(), { id: local.id })).rejects.toThrow('submitting principal');+ }));++ test('legacy preview is inert, CAS detects changes, exact IDs retain scheduling and dependencies', () => isolated(async () => {+ const parent = await queue.add('maintenance', {});+ const child = await queue.add('lint', { dir: root }, { parent_job_id: parent.id, delay: 5000 });+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = NULL WHERE id = ANY($1::int[])', [[parent.id, child.id]]);+ await expect(assertNoUnreviewedJobs(engine)).rejects.toThrow('legacy jobs');+ const preview = await authorizeLegacyJobs(engine, [parent.id]);+ expect(preview.applied).toBe(false);+ expect((await queue.getJob(parent.id))?.submission_authority).toBeNull();+ await engine.executeRaw('UPDATE minion_jobs SET priority = priority + 1 WHERE id = $1', [parent.id]);+ await expect(authorizeLegacyJobs(engine, [parent.id], preview.snapshot_digest, true)).rejects.toThrow('snapshot changed');+ const reviewed = await authorizeLegacyJobs(engine, [parent.id]);+ await authorizeLegacyJobs(engine, [parent.id], reviewed.snapshot_digest, true);+ expect((await queue.getJob(child.id))?.submission_authority).toBeNull();+ await expect(assertNoUnreviewedJobs(engine)).rejects.toThrow('legacy jobs');+ const childPreview = await authorizeLegacyJobs(engine, [child.id]);+ await authorizeLegacyJobs(engine, [child.id], childPreview.snapshot_digest, true);+ const restored = await queue.getJob(child.id);+ expect(restored?.parent_job_id).toBe(parent.id);+ expect(restored?.delay_until).toEqual(child.delay_until);+ expect(restored?.status).toBe('delayed');+ await assertNoUnreviewedJobs(engine);+ }));++ test('inline and isolated worker entry points revalidate revoked authority before handlers', () => isolated(async () => {+ let calls = 0;+ const job = await submit();+ await engine.executeRaw("UPDATE oauth_clients SET deleted_at = now() WHERE client_id = 'client-a'");+ const worker = new MinionWorker(engine, { pollInterval: 10, healthCheckInterval: 0, stalledInterval: 60000 });+ worker.register('lint', async () => { calls++; });+ const running = worker.start();+ for (let i = 0; i < 100; i++) {+ if ((await queue.getJob(job.id))?.attempts_made) break;+ await new Promise(resolve => setTimeout(resolve, 10));+ }+ await worker.stop(); await running;+ expect(calls).toBe(0);+ await engine.executeRaw("UPDATE minion_jobs SET status = 'active', claim_generation = claim_generation + 1, lock_token = 'child-test' WHERE id = $1", [job.id]);+ const resultPath = join(sandbox, 'child-outcome.json');+ await runChildJobEntry(engine, { jobId: job.id, lockToken: 'child-test', resultPath, parentPid: 0 }, { resolveHandler: () => async () => { calls++; } });+ expect(calls).toBe(0);+ expect(readFileSync(resultPath, 'utf8')).toContain('revoked');+ }));++ test('delegated jobs retain owner, source, tool and slug ceilings through queue execution', () => isolated(async () => {+ await engine.executeRaw("UPDATE oauth_clients SET scope = 'read agent', bound_tools = ARRAY['search','get_page'], bound_slug_prefixes = ARRAY['direct-only/'], delegated_namespace = 'prefixes', delegated_slug_prefixes = ARRAY['wiki/'], bound_source_id = 'default', federated_read = ARRAY['default'], bound_max_concurrent = 3 WHERE client_id = 'client-a'");+ const caller = ctx(); caller.auth!.scopes = ['read', 'agent'];+ const submitAgent = jobsOperations.find(op => op.name === 'submit_agent')!;+ const result = await submitAgent.handler(caller, { prompt: 'Fixture task', allowed_tools: ['search'], allowed_slug_prefixes: ['wiki/example/'] }) as { id: number };+ const job = (await queue.getJob(result.id))!;+ expect(job.submission_authority?.kind).toBe('remote_agent');+ await authorizeJobExecution(engine, job);+ await expect(withSubmissionAuthority(job.submission_authority!, () => queue.add('maintenance', {}))).rejects.toThrow('descendant');+ await expect(authorizeJobExecution(engine, { ...job, data: { ...job.data, allowed_tools: ['put_page'] } })).rejects.toThrow('differs');+ await engine.executeRaw("UPDATE oauth_clients SET bound_tools = ARRAY['get_page'] WHERE client_id = 'client-a'");+ await expect(authorizeJobExecution(engine, job)).rejects.toThrow('submitted_grant_no_longer_usable');+ await engine.executeRaw("UPDATE oauth_clients SET bound_tools = ARRAY['search','get_page'], delegated_slug_prefixes = ARRAY['other/'] WHERE client_id = 'client-a'");+ await expect(authorizeJobExecution(engine, job)).rejects.toThrow('submitted_grant_no_longer_usable');+ await engine.executeRaw("UPDATE oauth_clients SET delegated_slug_prefixes = ARRAY['wiki/'], scope = 'read' WHERE client_id = 'client-a'");+ await expect(authorizeJobExecution(engine, job)).rejects.toThrow('agent_scope_missing');+ await engine.executeRaw("UPDATE oauth_clients SET scope = 'read agent', deleted_at = now() WHERE client_id = 'client-a'");+ await expect(authorizeJobExecution(engine, job)).rejects.toThrow('revoked');+ expect((await queue.getJob(job.id))?.data.allowed_tools).toEqual(['search']);+ }));++ test('narrowing a job namespace to its concrete job preserves execution and retry only for that job', () => isolated(async () => {+ await engine.executeRaw("UPDATE oauth_clients SET scope = 'read agent', bound_tools = ARRAY['search'], delegated_namespace = 'job', delegated_slug_prefixes = NULL, bound_source_id = 'default', federated_read = ARRAY['default'], bound_max_concurrent = 3 WHERE client_id = 'client-a'");+ const caller = ctx(); caller.auth!.scopes = ['read', 'agent'];+ const submitAgent = jobsOperations.find(op => op.name === 'submit_agent')!;+ const first = await submitAgent.handler(caller, { prompt: 'First fixture task' }) as { id: number };+ const second = await submitAgent.handler(caller, { prompt: 'Second fixture task' }) as { id: number };+ const job = (await queue.getJob(first.id))!;+ const other = (await queue.getJob(second.id))!;+ await engine.executeRaw("UPDATE oauth_clients SET delegated_namespace = 'prefixes', delegated_slug_prefixes = ARRAY[$1] WHERE client_id = 'client-a'", [`wiki/agents/${job.id}/*`]);++ await expect(authorizeJobExecution(engine, job)).resolves.toEqual(job.submission_authority!);+ await expect(authorizeJobExecution(engine, other)).rejects.toThrow('submitted_grant_no_longer_usable');+ await engine.executeRaw("UPDATE minion_jobs SET status = 'failed' WHERE id = $1", [job.id]);+ // Replay creates a different job, so the existing job's path grant is insufficient.+ await expect(queue.replayJob(job.id)).rejects.toThrow('submitted_grant_no_longer_usable');+ const retried = await queue.retryJob(job.id);+ expect(retried?.status).toBe('waiting');+ expect(retried?.data).toEqual(job.data);+ expect(retried?.submission_authority).toEqual(job.submission_authority);+ }));++ test('future or malformed non-NULL authority is never authorized as legacy work', () => isolated(async () => {+ const job = await queue.add('maintenance', {});+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = NULL WHERE id = $1', [job.id]);+ const preview = await authorizeLegacyJobs(engine, [job.id]);+ for (const value of [{ version: 2, kind: 'application' }, { version: 1, kind: 'remote_generic' }, null]) {+ if (value === null) {+ // JSON null is not SQL NULL, even though both drivers decode it to null.+ await engine.executeRaw("UPDATE minion_jobs SET submission_authority = 'null'::jsonb WHERE id = $1", [job.id]);+ } else {+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = $1::jsonb WHERE id = $2', [value, job.id]);+ }+ const [before] = await engine.executeRaw<{ authority: string }>('SELECT submission_authority::text AS authority FROM minion_jobs WHERE id = $1', [job.id]);+ await expect(assertNoUnreviewedJobs(engine)).rejects.toThrow('unsupported authority');+ await expect(authorizeLegacyJobs(engine, [job.id])).rejects.toThrow('SQL NULL');+ await expect(authorizeLegacyJobs(engine, [job.id], preview.snapshot_digest, true)).rejects.toThrow('SQL NULL');+ const [after] = await engine.executeRaw<{ authority: string }>('SELECT submission_authority::text AS authority FROM minion_jobs WHERE id = $1', [job.id]);+ expect(after.authority).toBe(before.authority);+ }+ }));++ test('NULL-authority local review covers the whole recursive graph', () => isolated(async () => {+ const parent = await queue.add('maintenance', {});+ const child = await queue.add('maintenance-child', {}, { parent_job_id: parent.id });+ const grandchild = await queue.add('maintenance-grandchild', { revision: 1 }, { parent_job_id: child.id });+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = NULL WHERE id = $1', [parent.id]);+ await expect(assertNoUnreviewedJobs(engine)).rejects.toThrow('unsupported authority');+ await expect(queue.handleWaitingTTL()).rejects.toThrow('unsupported authority');+ const preview = await authorizeLegacyJobs(engine, [parent.id]);+ expect(preview.dependencies.map(row => row.id)).toContain(grandchild.id);+ await engine.executeRaw('UPDATE minion_jobs SET data = $1::jsonb WHERE id = $2', [{ revision: 2 }, grandchild.id]);+ await expect(authorizeLegacyJobs(engine, [parent.id], preview.snapshot_digest, true)).rejects.toThrow('snapshot changed');+ const next = await authorizeLegacyJobs(engine, [parent.id]);+ await authorizeLegacyJobs(engine, [parent.id], next.snapshot_digest, true);+ await assertNoUnreviewedJobs(engine);+ expect((await queue.getJob(grandchild.id))?.data).toEqual({ revision: 2 });+ }));++ test('upgraded database rejects old producers and every old-style claim', () => isolated(async () => {+ await expect(engine.executeRaw("INSERT INTO minion_jobs (name) VALUES ('old-worker')")).rejects.toThrow('protocol 1');+ const job = await queue.add('maintenance', {});+ const oldClaim = () => engine.executeRaw("UPDATE minion_jobs SET status = 'active', lock_token = 'old' WHERE id = $1", [job.id]);+ await expect(oldClaim()).rejects.toThrow('old workers');+ expect((await queue.claim('new-first', 30000, 'default', ['maintenance']))?.id).toBe(job.id);+ await engine.executeRaw("UPDATE minion_jobs SET status = 'waiting', lock_token = NULL WHERE id = $1", [job.id]);+ await expect(oldClaim()).rejects.toThrow('old workers');+ expect((await queue.claim('new-second', 30000, 'default', ['maintenance']))?.id).toBe(job.id);+ }));++ test('abort after lock acquisition prevents the next source read and write', () => isolated(async () => {+ const accepted = await prepareRemoteJob(ctx(), 'lint-fix', {});+ const controller = new AbortController();+ const page = join(root, 'cancelled.md'); writeFileSync(page, 'before');+ await expect(withSubmissionAuthority(accepted.authority, () => withSourceFilesystemLock(engine, root, async () => {+ expect(readSourceFileSync(page, 'utf8')).toBe('before');+ controller.abort(new Error('fixture cancelled'));+ expect(() => readSourceFileSync(page)).toThrow('fixture cancelled');+ writeSourceFileSync(page, 'after');+ }), controller.signal)).rejects.toThrow('fixture cancelled');+ expect(readFileSync(page, 'utf8')).toBe('before');+ }));++ test('an unrenewed cooperative filesystem lease aborts before the next write', () => isolated(async () => {+ const { withRefreshingLock } = await import('../src/core/db-lock.ts');+ const accepted = await prepareRemoteJob(ctx(), 'lint-fix', {});+ const controller = new AbortController();+ const page = join(root, 'lease-lost.md'); writeFileSync(page, 'before');+ let failure: unknown;+ try {+ await withRefreshingLock(engine, 'fixture-short-filesystem-lease', async () => {+ await new Promise(resolve => setTimeout(resolve, 80));+ expect(controller.signal.aborted).toBe(true);+ return withSubmissionAuthority(accepted.authority, () => writeSourceFileSync(page, 'after'), controller.signal);+ }, { ttlMinutes: 0.0005, onLockLost: reason => controller.abort(reason) });+ } catch (error) { failure = error; }+ expect(failure).toBeInstanceOf(Error);+ expect(String(failure)).toMatch(/stolen|lock lease lost/);+ expect(readFileSync(page, 'utf8')).toBe('before');+ }));++ test('real import/lint/sync handlers retain the scalar source and enqueue no descendants', () => isolated(async () => {+ const source = 'job-source';+ await engine.executeRaw('INSERT INTO sources (id, name, local_path) VALUES ($1, $1, $2)', [source, root]);+ await engine.executeRaw("UPDATE oauth_clients SET source_id = $1 WHERE client_id = 'client-a'", [source]);+ const scoped = ctx(); scoped.sourceId = source; scoped.auth = { ...scoped.auth!, sourceId: source };+ const page = join(root, 'example.md');+ writeFileSync(page, '---\ntype: note\ntitle: Example\n---\n\n# Example\n\nA deterministic fixture for source-scoped background import.\n');+ execFileSync('git', ['-C', root, 'add', '--', 'example.md']);+ execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', '-c', 'core.hooksPath=/dev/null', 'commit', '-q', '-m', 'test fixture', '--', 'example.md']);+ const { registerBuiltinHandlers } = await import('../src/commands/jobs.ts');+ const worker = new MinionWorker(engine);+ await registerBuiltinHandlers(worker, engine, { quiet: true });+ for (const name of ['import', 'lint', 'lint-fix', 'sync']) {+ const accepted = await prepareRemoteJob(scoped, name, name === 'sync' ? { noPull: true } : {});+ const job = await queue.add(name, accepted.data, {}, { submissionAuthority: accepted.authority });+ const token = `fixture-${name}`;+ const claimed = await queue.claim(token, 30000, 'default', [name]);+ expect(claimed?.id).toBe(job.id);+ const authority = await authorizeJobExecution(engine, claimed!);+ const context = buildJobContext(engine, queue, claimed!, token, new AbortController().signal, new AbortController().signal);+ await withSubmissionAuthority(authority, () => worker.getHandler(name)!(context));+ await queue.completeJob(job.id, token);+ }+ expect(await engine.getPage('example', { sourceId: source })).not.toBeNull();+ expect(await engine.getPage('example', { sourceId: 'default' })).toBeNull();+ const names = (await queue.getJobs()).map(job => job.name).sort();+ expect(names).toEqual(['import', 'lint', 'lint-fix', 'sync']);+ await engine.executeRaw("UPDATE oauth_clients SET source_id = 'default' WHERE client_id = 'client-a'");+ await engine.executeRaw('DELETE FROM sources WHERE id = $1', [source]);+ }));++ test('source reads/writes reject escaping and in-root symlinks and use the retained descriptor', () => isolated(async () => {+ const accepted = await prepareRemoteJob(ctx(), 'lint-fix', {});+ const page = join(root, 'page.md'), outside = join(sandbox, 'outside.md'), link = join(root, 'link.md');+ writeFileSync(page, 'before'); writeFileSync(outside, 'private fixture');+ symlinkSync(outside, link);+ try {+ withSubmissionAuthority(accepted.authority, () => {+ expect(readSourceFileSync(page, 'utf8')).toBe('before');+ writeSourceFileSync(page, 'after');+ expect(readSourceFileSync(page, 'utf8')).toBe('after');+ expect(() => readSourceFileSync(outside)).toThrow('escapes');+ expect(() => readSourceFileSync(link)).toThrow('symlink');+ expect(() => writeSourceFileSync(link, 'changed')).toThrow('symlink');+ });+ expect(readFileSync(outside, 'utf8')).toBe('private fixture');+ } finally { rmSync(link); }+ // Reentrant sync -> full import shares the canonical root lock.+ await withSourceFilesystemLock(engine, root, () => withSourceFilesystemLock(engine, root, async () => undefined));+ let release!: () => void, entered!: () => void;+ const started = new Promise<void>(resolve => { entered = resolve; });+ const hold = new Promise<void>(resolve => { release = resolve; });+ const first = withSourceFilesystemLock(engine, root, async () => { entered(); await hold; });+ await started;+ try {+ await expect(withSourceFilesystemLock(engine, join(root, 'nested'), async () => undefined, { waitMs: 0 })).rejects.toThrow('held');+ } finally { release(); await first; }+ }));++ test('overlapping registered non-Git roots and nested Git roots share one writer lock', () => isolated(async () => {+ const parent = join(sandbox, 'overlap'); const child = join(parent, 'nested');+ mkdirSync(child, { recursive: true });+ await engine.executeRaw('INSERT INTO sources (id, name, local_path) VALUES ($1, $1, $2), ($3, $3, $4)', ['overlap-parent', parent, 'overlap-child', child]);+ try {+ for (const gitNested of [false, true]) {+ if (gitNested) execFileSync('git', ['init', '-q', child]);+ let release!: () => void, entered!: () => void;+ const started = new Promise<void>(resolve => { entered = resolve; });+ const held = new Promise<void>(resolve => { release = resolve; });+ const childWriter = withSourceFilesystemLock(engine, child, async () => { entered(); await held; });+ await started;+ try {+ await expect(withSourceFilesystemLock(engine, parent, async () => undefined, { waitMs: 0 })).rejects.toThrow('held');+ } finally { release(); await childWriter; }+ await withSourceFilesystemLock(engine, parent, () => withSourceFilesystemLock(engine, child, async () => undefined));+ }+ } finally {+ await engine.executeRaw("DELETE FROM sources WHERE id IN ('overlap-parent', 'overlap-child')");+ }+ }));+});diff --git a/test/minions.test.ts b/test/minions.test.tsindex 0a8c8d618d..407f1e8700 100644--- a/test/minions.test.ts+++ b/test/minions.test.ts@@ -1015,8 +1015,8 @@ describe('MinionQueue: Inbox', () => {const parent = await queue.add('orchestrate', {});// Create child directly with waiting status so it's claimableconst childRows = await engine.executeRaw<Record<string, unknown>>(- `INSERT INTO minion_jobs (name, queue, status, data, parent_job_id)- VALUES ('research', 'default', 'waiting', '{}', $1) RETURNING *`,+ `INSERT INTO minion_jobs (name, queue, status, data, parent_job_id, submission_authority)+ VALUES ('research', 'default', 'waiting', '{}', $1, '{"version":1,"kind":"application"}'::jsonb) RETURNING *`,[parent.id]);const childId = childRows[0].id as number;@@ -1783,7 +1783,7 @@ describe('MinionQueue: Idempotency', () => {idempotency_key: 'dream:synth:test:active',});await engine.executeRaw(- `UPDATE minion_jobs SET status = 'active' WHERE id = $1`,+ `UPDATE minion_jobs SET status = 'active', claim_generation = claim_generation + 1 WHERE id = $1`,[j1.id]);const j2 = await queue.add('sync', {}, {@@ -2067,7 +2067,7 @@ describe('MinionQueue: v0.19.1 handleWallClockTimeouts (Layer 3 kill shot)', ()const job = await queue.add('noop', {}, { timeout_ms: 100 });await engine.executeRaw(`UPDATE minion_jobs- SET status='active',+ SET status='active', claim_generation = claim_generation + 1,lock_token='wc-test',lock_until=now() - interval '1 second',started_at=now() - interval '1 second',@@ -2089,7 +2089,7 @@ describe('MinionQueue: v0.19.1 handleWallClockTimeouts (Layer 3 kill shot)', ()// Force timeout_ms / timeout_at NULL on-disk (columns might or might not be set by add).await engine.executeRaw(`UPDATE minion_jobs- SET status='active',+ SET status='active', claim_generation = claim_generation + 1,timeout_ms=NULL,timeout_at=NULL,lock_token='wc-null',@@ -2111,7 +2111,7 @@ describe('MinionQueue: v0.19.1 handleWallClockTimeouts (Layer 3 kill shot)', ()const job = await queue.add('noop', {}, { timeout_ms: 100_000 });await engine.executeRaw(`UPDATE minion_jobs- SET status='active',+ SET status='active', claim_generation = claim_generation + 1,lock_token='wc-inside',lock_until=now() + interval '30 seconds',started_at=now() - interval '10 seconds',@@ -2235,7 +2235,7 @@ describe('MinionQueue: v0.19.1 maxWaiting — cap correctness + race (D2/H2)', (describe('MinionQueue: maxPending — single-flight (waiting + live-lock active)', () => {async function forceActive(id: number, lockUntilSql: string): Promise<void> {await engine.executeRaw(- `UPDATE minion_jobs SET status = 'active', lock_token = 'tok-mp',+ `UPDATE minion_jobs SET status = 'active', claim_generation = claim_generation + 1, lock_token = 'tok-mp',lock_until = ${lockUntilSql}, started_at = now() - interval '5 minutes'WHERE id = $1`,[id],@@ -2459,7 +2459,7 @@ describe('MinionQueue: v0.19.1 wall-clock + handleTimeouts non-interference (T1)const job = await queue.add('noop', {}, { timeout_ms: 100_000 });await engine.executeRaw(`UPDATE minion_jobs- SET status='active',+ SET status='active', claim_generation = claim_generation + 1,lock_token='t1',lock_until=now() + interval '30 seconds',started_at=now() - interval '2 seconds',diff --git a/test/minions/delegated-execution.serial.test.ts b/test/minions/delegated-execution.serial.test.tsindex 58c3b2aceb..f6f9a94158 100644--- a/test/minions/delegated-execution.serial.test.ts+++ b/test/minions/delegated-execution.serial.test.ts@@ -3,6 +3,7 @@ import { mkdtempSync, rmSync } from 'node:fs';import { join } from 'node:path';import { tmpdir } from 'node:os';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { LATEST_VERSION } from '../../src/core/migrate.ts';import { MinionQueue } from '../../src/core/minions/queue.ts';import { resetPgliteState } from '../helpers/reset-pglite.ts';import { withEnv } from '../helpers/with-env.ts';@@ -28,7 +29,7 @@ beforeAll(async () => {engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();auditDir = mkdtempSync(join(tmpdir(), 'gbrain-delegated-execution-'));});-beforeEach(async () => { await resetPgliteState(engine); await engine.setConfig('version', '147'); });+beforeEach(async () => { await resetPgliteState(engine); await engine.setConfig('version', String(LATEST_VERSION)); });afterEach(() => { __setChatTransportForTests(null); });afterAll(async () => { await engine.disconnect(); rmSync(auditDir, { recursive: true, force: true }); });diff --git a/test/minions/dream-quota-degradation.test.ts b/test/minions/dream-quota-degradation.test.tsindex cc7a54380c..bb18348897 100644--- a/test/minions/dream-quota-degradation.test.ts+++ b/test/minions/dream-quota-degradation.test.ts@@ -96,8 +96,8 @@ const FILLER_QUEUE = 'quota-filler-fixture';*/async function seedWaitingSubagentFiller(): Promise<void> {await engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, data)- VALUES ('subagent', $1, 'waiting', '{"prompt": "quota filler"}'::jsonb)`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', $1, 'waiting', '{"prompt": "quota filler"}'::jsonb)`,[FILLER_QUEUE],);}diff --git a/test/mode-switch-ux.test.ts b/test/mode-switch-ux.test.tsindex cd85208a58..d3d96931bd 100644--- a/test/mode-switch-ux.test.ts+++ b/test/mode-switch-ux.test.ts@@ -102,8 +102,8 @@ describe('probeWorkerAvailable (DI for active/stale/never_seen)', () => {test('active when minion_jobs activity is fresh (<2 min)', async () => {// Seed a recently-started job.await engine.executeRaw(- `INSERT INTO minion_jobs (queue, name, data, status, started_at)- VALUES ('default', 'test-job', '{}'::jsonb, 'active', now())`,+ `INSERT INTO minion_jobs (submission_authority, queue, name, data, status, started_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'default', 'test-job', '{}'::jsonb, 'active', now())`,);const result = await probeWorkerAvailable(engine);expect(result.status).toBe('active');@@ -113,8 +113,8 @@ describe('probeWorkerAvailable (DI for active/stale/never_seen)', () => {test('stale when activity is older than 2 min but within 10-min window', async () => {// Seed a 5-minute-old started_at (within 10-min query window, > 2-min stale).await engine.executeRaw(- `INSERT INTO minion_jobs (queue, name, data, status, started_at)- VALUES ('default', 'test-stale-job', '{}'::jsonb, 'completed',+ `INSERT INTO minion_jobs (submission_authority, queue, name, data, status, started_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'default', 'test-stale-job', '{}'::jsonb, 'completed',now() - INTERVAL '5 minutes')`,);const result = await probeWorkerAvailable(engine);diff --git a/test/oauth-authorize-scope-default.test.ts b/test/oauth-authorize-scope-default.test.tsindex 4dc2c3d81e..612dc66f8c 100644--- a/test/oauth-authorize-scope-default.test.ts+++ b/test/oauth-authorize-scope-default.test.ts@@ -1,3 +1,4 @@+import { authorizeAsOwner, pgliteOAuthTransaction, TEST_PKCE_VERIFIER, TEST_PKCE_CHALLENGE } from './helpers/oauth.ts';/*** Authorize-grant scope default (RFC 6749 §3.3).*@@ -23,7 +24,7 @@ beforeAll(async () => {await engine.connect({});await engine.initSchema();sql = sqlQueryForEngine(engine);- provider = new GBrainOAuthProvider({ sql });+ provider = new GBrainOAuthProvider({ transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))), sql });});afterAll(async () => {@@ -49,11 +50,11 @@ async function authorizeAndReadScopes();const client = await provider.clientsStore.getClient(reg.clientId);expect(client).toBeTruthy();- await provider.authorize(+ await authorizeAsOwner(provider,client!,{scopes: requested,- codeChallenge: 'test-challenge',+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'https://example.test/cb',state: 'xyz',} as any,diff --git a/test/oauth-confidential-client.test.ts b/test/oauth-confidential-client.test.tsindex 145cc3593f..376b093f9f 100644--- a/test/oauth-confidential-client.test.ts+++ b/test/oauth-confidential-client.test.ts@@ -1,3 +1,4 @@+import { authorizeAsOwner, pgliteOAuthTransaction, TEST_PKCE_VERIFIER, TEST_PKCE_CHALLENGE } from './helpers/oauth.ts';/*** v0.37.7.0 #1166 — OAuth confidential clients regression test.*@@ -27,7 +28,7 @@ beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();- provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine) });+ provider = new GBrainOAuthProvider({ transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))), sql: sqlQueryForEngine(engine) });});afterAll(async () => {diff --git a/test/oauth-consent-security.test.ts b/test/oauth-consent-security.test.tsnew file mode 100644index 0000000000..6c1424a5c0--- /dev/null+++ b/test/oauth-consent-security.test.ts@@ -0,0 +1,243 @@+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGlite } from '@electric-sql/pglite';+import { vector } from '@electric-sql/pglite/vector';+import { pg_trgm } from '@electric-sql/pglite/contrib/pg_trgm';+import express from 'express';+import cookieParser from 'cookie-parser';+import { mcpAuthRouter } from '@modelcontextprotocol/sdk/server/auth/router.js';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { OAuthGrants } from '../src/core/oauth-grants.ts';+import type { SqlQuery } from '../src/core/sql-query.ts';+import { PGLITE_SCHEMA_SQL } from '../src/core/pglite-schema.ts';+import { mountConfidentialOAuth, mountOAuthConsent } from '../src/commands/serve-http-oauth.ts';+import { hashToken } from '../src/core/utils.ts';+import { pgliteOAuthTransaction, TEST_PKCE_CHALLENGE, TEST_PKCE_VERIFIER } from './helpers/oauth.ts';++let db: PGlite;+let sql: SqlQuery;+let provider: GBrainOAuthProvider;+let server: ReturnType<ReturnType<typeof express>['listen']>;+let base: string;+const REDIRECT = 'https://client.example/callback';+const RESOURCE = 'https://brain.example/mcp';+const OWNER = 'gbrain_admin=synthetic-owner-session';+const OTHER_SESSION = 'gbrain_admin=synthetic-new-owner-session';++beforeAll(async () => {+ db = new PGlite({ extensions: { vector, pg_trgm } });+ await db.exec(PGLITE_SCHEMA_SQL);+ sql = async (strings, ...values) => (await db.query<Record<string, unknown>>(+ strings.reduce((query, fragment, i) => query + fragment + (i < values.length ? `$${i + 1}` : ''), ''), values)).rows;+ provider = new GBrainOAuthProvider({ sql, transaction: pgliteOAuthTransaction(db) });+ const app = express();+ app.use(cookieParser());+ const pass: express.RequestHandler = (_req, _res, next) => next();+ const requireAdmin: express.RequestHandler = (req, res, next) => {+ if (!['synthetic-owner-session', 'synthetic-new-owner-session'].includes(req.cookies?.gbrain_admin)) { res.status(401).json({ error: 'unauthorized' }); return; }+ next();+ };+ mountConfidentialOAuth(app, provider, pass);+ mountOAuthConsent(app, provider, requireAdmin, pass);+ app.use(mcpAuthRouter({ provider, issuerUrl: new URL('http://localhost:3131'), scopesSupported: ['read', 'write', 'admin'] }));+ server = app.listen(0, '127.0.0.1');+ await new Promise<void>(resolve => server.once('listening', resolve));+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('Expected TCP listener');+ base = `http://127.0.0.1:${address.port}`;+}, 30_000);++afterAll(async () => {+ if (server) { server.closeAllConnections(); await new Promise<void>((resolve, reject) => server.close(error => error && (error as NodeJS.ErrnoException).code !== 'ERR_SERVER_NOT_RUNNING' ? reject(error) : resolve())); }+ if (db) await db.close();+});++async function register(method: 'none' | 'client_secret_post' | 'client_secret_basic' = 'none', scope = 'read write') {+ return provider.registerClientManual('synthetic-client', ['authorization_code', 'refresh_token', 'client_credentials'], scope, [REDIRECT], 'default', undefined, method);+}+async function begin(clientId: string, scopes = 'read', state = 'original-state') {+ const query = new URLSearchParams({ client_id: clientId, response_type: 'code', redirect_uri: REDIRECT,+ code_challenge: TEST_PKCE_CHALLENGE, code_challenge_method: 'S256', scope: scopes, state, resource: RESOURCE });+ const response = await fetch(`${base}/authorize?${query}`, { redirect: 'manual' });+ expect(response.status).toBe(302);+ const location = new URL(response.headers.get('location')!, base);+ expect(location.pathname).toBe('/admin/');+ expect(location.searchParams.has('code')).toBe(false);+ return location.searchParams.get('oauth_request')!;+}+async function details(id: string, cookie = OWNER): Promise<any> {+ const response = await fetch(`${base}/admin/api/oauth-requests/${id}`, { headers: { Cookie: cookie } });+ expect(response.status).toBe(200);+ return response.json();+}+async function decide(id: string, csrf: string, decision = 'approve', cookie = OWNER, extra: Record<string, unknown> = {}) {+ return fetch(`${base}/admin/api/oauth-requests/${id}`, { method: 'POST', headers: { Cookie: cookie, 'Content-Type': 'application/json' }, body: JSON.stringify({ csrf, decision, ...extra }) });+}+async function approve(clientId: string) {+ const id = await begin(clientId);+ const request = await details(id);+ const response = await decide(id, request.csrf);+ expect(response.status).toBe(200);+ return new URL((await response.json() as any).redirectUrl).searchParams.get('code')!;+}+async function token(clientId: string, code: string, verifier?: string, secret?: string, basic = false, resource?: string) {+ const body = new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: REDIRECT });+ const headers: Record<string, string> = {};+ if (basic) headers.Authorization = `Basic ${Buffer.from(`${clientId}:${secret}`).toString('base64')}`;+ else { body.set('client_id', clientId); if (secret) body.set('client_secret', secret); }+ if (verifier !== undefined) body.set('code_verifier', verifier);+ if (resource !== undefined) body.set('resource', resource);+ return fetch(`${base}/token`, { method: 'POST', headers, body });+}++describe('owner-approved HTTP authorization', () => {+ test('anonymous authorization creates no code, and consent requires owner authentication and session-bound CSRF', async () => {+ const { clientId } = await register('none', 'admin');+ const id = await begin(clientId, 'admin');+ expect(await sql`SELECT * FROM oauth_codes WHERE client_id = ${clientId}`).toHaveLength(0);+ expect((await fetch(`${base}/admin/api/oauth-requests/${id}`)).status).toBe(401);+ const request = await details(id);+ expect(request).toMatchObject({ clientId, redirectUri: REDIRECT, scopes: ['admin'], sourceId: 'default', resource: RESOURCE });+ expect((await decide(id, '0'.repeat(64))).status).toBe(403);+ expect((await decide(id, request.csrf, 'approve', OTHER_SESSION)).status).toBe(403);+ expect((await decide(id, request.csrf, 'approve', OWNER, { scopes: ['write'] })).status).toBe(403);+ expect(await sql`SELECT * FROM oauth_codes WHERE client_id = ${clientId}`).toHaveLength(0);+ const renewed = await details(id, OTHER_SESSION);+ const response = await decide(id, renewed.csrf, 'approve', OTHER_SESSION);+ expect(response.status).toBe(200);+ const redirect = new URL((await response.json() as any).redirectUrl);+ expect(redirect.searchParams.get('state')).toBe('original-state');+ expect(redirect.searchParams.get('code')).toStartWith('gbrain_code_');+ expect((await decide(id, renewed.csrf, 'approve', OTHER_SESSION)).status).toBe(410);+ expect(await sql`SELECT * FROM oauth_codes WHERE client_id = ${clientId}`).toHaveLength(1);+ });++ test('denial returns access_denied with original state and never creates a code', async () => {+ const { clientId } = await register();+ const id = await begin(clientId);+ const request = await details(id);+ const response = await decide(id, request.csrf, 'deny');+ const redirect = new URL((await response.json() as any).redirectUrl);+ expect(redirect.searchParams.get('error')).toBe('access_denied');+ expect(redirect.searchParams.get('state')).toBe('original-state');+ expect(await sql`SELECT * FROM oauth_codes WHERE client_id = ${clientId}`).toHaveLength(0);+ });++ test('policy changes and concurrent approvals cannot issue unseen or duplicate grants', async () => {+ const { clientId } = await register();+ const id = await begin(clientId);+ const request = await details(id);+ await sql`UPDATE oauth_clients SET scope = 'admin' WHERE client_id = ${clientId}`;+ expect((await decide(id, request.csrf)).status).toBe(409);+ expect(await sql`SELECT * FROM oauth_codes WHERE client_id = ${clientId}`).toHaveLength(0);+ const nextId = await begin(clientId);+ const next = await details(nextId);+ const responses = await Promise.all([decide(nextId, next.csrf), decide(nextId, next.csrf)]);+ expect(responses.map(response => response.status).sort()).toEqual([200, 410]);+ expect(await sql`SELECT * FROM oauth_codes WHERE client_id = ${clientId}`).toHaveLength(1);+ });++ for (const method of ['none', 'client_secret_post', 'client_secret_basic'] as const) {+ test(`${method}: real token endpoint requires PKCE and preserves resource through redemption and refresh`, async () => {+ const { clientId, clientSecret } = await register(method);+ const code = await approve(clientId);+ const isBasic = method === 'client_secret_basic';+ for (const verifier of [undefined, 'wrong-verifier-that-is-long-enough-to-pass-syntax']) {+ const response = await token(clientId, code, verifier, clientSecret, isBasic);+ expect(response.status).toBe(400);+ expect((await response.json() as any).error).toBe(method === 'none' && verifier === undefined ? 'invalid_request' : 'invalid_grant');+ }+ const widened = await token(clientId, code, TEST_PKCE_VERIFIER, clientSecret, isBasic, 'https://other.example/mcp');+ expect(widened.status).toBe(400);+ const response = await token(clientId, code, TEST_PKCE_VERIFIER, clientSecret, isBasic);+ expect(response.status).toBe(200);+ const tokens = await response.json() as any;+ const verified = await provider.verifyAccessToken(tokens.access_token) as any;+ expect(verified.resource.toString()).toBe(RESOURCE);+ expect(verified.principal).toEqual({ kind: 'oauth_client', id: clientId });+ const body = new URLSearchParams({ grant_type: 'refresh_token', refresh_token: tokens.refresh_token });+ const headers: Record<string, string> = {};+ if (isBasic) headers.Authorization = `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`;+ else { body.set('client_id', clientId); if (clientSecret) body.set('client_secret', clientSecret); }+ const refreshed = await fetch(`${base}/token`, { method: 'POST', headers, body });+ expect(refreshed.status).toBe(200);+ const rotated = await refreshed.json() as any;+ expect((await provider.verifyAccessToken(rotated.access_token)).resource?.toString()).toBe(RESOURCE);+ expect((await fetch(`${base}/token`, { method: 'POST', headers, body })).status).toBe(400);+ });+ }++ test('client revocation invalidates outstanding codes, access and refresh tokens, and client lookup', async () => {+ const { clientId } = await register();+ const code = await approve(clientId);+ const response = await token(clientId, code, TEST_PKCE_VERIFIER);+ const tokens = await response.json() as any;+ const client = (await provider.clientsStore.getClient(clientId))!;+ const unredeemed = await approve(clientId);+ await provider.revokeClient(clientId);+ expect(await provider.clientsStore.getClient(clientId)).toBeUndefined();+ await expect(provider.verifyAccessToken(tokens.access_token)).rejects.toThrow();+ await expect(provider.exchangeAuthorizationCode(client, unredeemed, TEST_PKCE_VERIFIER, REDIRECT)).rejects.toThrow();+ await expect(provider.exchangeRefreshToken(client, tokens.refresh_token)).rejects.toThrow();+ expect(await sql`SELECT * FROM oauth_codes WHERE client_id = ${clientId}`).toHaveLength(0);+ expect(await sql`SELECT * FROM oauth_tokens WHERE client_id = ${clientId}`).toHaveLength(0);+ });++ test('failed token-pair creation rolls back code consumption and preserves pre-upgrade grants', async () => {+ const { clientId } = await register();+ const client = (await provider.clientsStore.getClient(clientId))!;+ const legacyCode = 'synthetic-pre-upgrade-code';+ await sql`INSERT INTO oauth_codes (code_hash, client_id, scopes, code_challenge, code_challenge_method, redirect_uri, expires_at)+ VALUES (${hashToken(legacyCode)}, ${clientId}, ${'{read}'}, ${TEST_PKCE_CHALLENGE}, ${'S256'}, ${REDIRECT}, ${Math.floor(Date.now() / 1000) + 600})`;+ const transaction = pgliteOAuthTransaction(db);+ const failing = new GBrainOAuthProvider({ sql, transaction: fn => transaction(tx => fn(async (strings, ...values) => {+ if (strings.join('').includes('INSERT INTO oauth_tokens') && values.includes('refresh')) throw new Error('synthetic storage failure');+ return tx(strings, ...values);+ })) });+ await expect(failing.exchangeAuthorizationCode(client, legacyCode, TEST_PKCE_VERIFIER, REDIRECT)).rejects.toThrow('synthetic storage failure');+ expect(await sql`SELECT * FROM oauth_codes WHERE code_hash = ${hashToken(legacyCode)}`).toHaveLength(1);+ expect(await sql`SELECT * FROM oauth_tokens WHERE client_id = ${clientId}`).toHaveLength(0);+ const tokens = await provider.exchangeAuthorizationCode(client, legacyCode, TEST_PKCE_VERIFIER, REDIRECT);+ const restarted = new GBrainOAuthProvider({ sql, transaction });+ expect((await restarted.verifyAccessToken(tokens.access_token)).clientId).toBe(clientId);+ await expect(restarted.exchangeRefreshToken(client, tokens.refresh_token!)).resolves.toHaveProperty('access_token');+ });++ test('uncertain approval completion is terminal and cannot issue a second code', async () => {+ const { clientId } = await register();+ const transaction = pgliteOAuthTransaction(db);+ const uncertain = new GBrainOAuthProvider({ sql, transaction: async fn => {+ await transaction(fn);+ throw new Error('synthetic connection loss after commit');+ } });+ const id = await uncertain.grants.begin(clientId, { codeChallenge: TEST_PKCE_CHALLENGE, redirectUri: REDIRECT });+ await expect(uncertain.grants.decide(id, true)).rejects.toThrow('synthetic connection loss');+ await expect(uncertain.grants.decide(id, true)).rejects.toThrow('completed');+ expect(await sql`SELECT * FROM oauth_codes WHERE client_id = ${clientId}`).toHaveLength(1);+ });++ test('an existing access token cannot retain a permission removed from current client policy', async () => {+ const { clientId, clientSecret } = await register('client_secret_post', 'read write');+ const tokens = await provider.exchangeClientCredentials(clientId, clientSecret!, 'write');+ expect((await provider.verifyAccessToken(tokens.access_token)).scopes).toEqual(['write']);+ await sql`UPDATE oauth_clients SET scope = 'read' WHERE client_id = ${clientId}`;+ // Preserve the read capability implied by the original write grant,+ // while dropping the write capability removed by the owner.+ expect((await provider.verifyAccessToken(tokens.access_token)).scopes).toEqual(['read']);+ });+});++test('pending authorization expires, restart forgets it, and capacity is bounded without evicting live requests', async () => {+ const row = { client_id: 'synthetic', client_name: 'synthetic', scope: 'read', grant_types: ['authorization_code'], redirect_uris: [REDIRECT] };+ let now = 0;+ const options = { sql: (async () => [row]) as SqlQuery, tokenTtl: 60, refreshTtl: 3600, now: () => now };+ const grants = new OAuthGrants(options);+ const params = { codeChallenge: TEST_PKCE_CHALLENGE, redirectUri: REDIRECT };+ const first = await grants.begin('synthetic', params);+ for (let i = 1; i < 1000; i++) await grants.begin('synthetic', params);+ await expect(grants.begin('synthetic', params)).rejects.toThrow('Too many pending');+ expect(grants.details(first).clientId).toBe('synthetic');+ expect(() => new OAuthGrants(options).details(first)).toThrow('server restarted');+ now = 600_001;+ expect(() => grants.details(first)).toThrow('expired');+ await expect(grants.begin('synthetic', params)).resolves.toBeString();+});diff --git a/test/oauth-dcr-ttl.test.ts b/test/oauth-dcr-ttl.test.tsindex 0d88b646ff..185e69ec65 100644--- a/test/oauth-dcr-ttl.test.ts+++ b/test/oauth-dcr-ttl.test.ts@@ -1,3 +1,4 @@+import { authorizeAsOwner, pgliteOAuthTransaction, TEST_PKCE_VERIFIER, TEST_PKCE_CHALLENGE } from './helpers/oauth.ts';/*** #2179 — DCR `token_ttl_seconds`: clamp boundaries, persistence, response* echo, and per-client TTL enforcement across grant paths.@@ -18,7 +19,6 @@ import {DEFAULT_DCR_TTL_MIN_SECONDS,} from '../src/core/oauth-provider.ts';import { PGLITE_SCHEMA_SQL } from '../src/core/pglite-schema.ts';-import { createHash } from 'node:crypto';let db: PGlite;let sql: (strings: TemplateStringsArray, ...values: unknown[]) => Promise<any>;@@ -92,7 +92,7 @@ describe('clampDcrTokenTtl', () => {function makeProvider(bounds?: { min?: number; max?: number }) {return new GBrainOAuthProvider({- sql,+ transaction: pgliteOAuthTransaction(db), sql,tokenTtl: 60,allowClientCredentialsDcr: true,dcrTtlMinSeconds: bounds?.min,@@ -177,7 +177,7 @@ describe('DCR registration with token_ttl_seconds (#2179)', () => {// --enable-dcr server from handing anonymous registrants 7-day tokens.test('unset max cannot exceed the server --token-ttl (fail-closed)', async () => {const provider = new GBrainOAuthProvider({- sql,+ transaction: pgliteOAuthTransaction(db), sql,tokenTtl: 3600,allowClientCredentialsDcr: true,});@@ -190,7 +190,7 @@ describe('DCR registration with token_ttl_seconds (#2179)', () => {test('explicitly configured max above --token-ttl is honored (admin opt-in)', async () => {const provider = new GBrainOAuthProvider({- sql,+ transaction: pgliteOAuthTransaction(db), sql,tokenTtl: 3600,allowClientCredentialsDcr: true,dcrTtlMaxSeconds: 86_400,@@ -217,17 +217,16 @@ describe('per-client token_ttl across grant paths (#2179)', () => {const client = (await provider.clientsStore.getClient(clientId))!;let redirectUrl = '';- const verifier = 'ttl-pkce-verifier-example-'.repeat(3);const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(client, {- codeChallenge: createHash('sha256').update(verifier).digest('base64url'),+ await authorizeAsOwner(provider, client, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['read'],state: 'ttl-state',}, mockRes);const code = new URL(redirectUrl).searchParams.get('code')!;- const tokens = await provider.exchangeAuthorizationCode(client, code, verifier);+ const tokens = await provider.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER, client.redirect_uris![0]);expect(tokens.expires_in).toBe(222);// Refresh issuance honors it too.diff --git a/test/oauth-owner-consent.test.ts b/test/oauth-owner-consent.test.tsindex c4fbaf5ab5..f8204262e0 100644--- a/test/oauth-owner-consent.test.ts+++ b/test/oauth-owner-consent.test.ts@@ -1,67 +1,67 @@import { afterAll, beforeAll, expect, test } from 'bun:test';-import express from 'express';-import cookieParser from 'cookie-parser';-import type { AddressInfo } from 'node:net';-import type { Server } from 'node:http';-import { mountOAuthOwnerConsent } from '../src/commands/serve-http-consent.ts';-import type { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { resolveGrantProfile, rescopeClientGrant } from '../src/core/grants/service.ts';+import { TEST_PKCE_CHALLENGE } from './helpers/oauth.ts';-let server: Server;-let base: string;-let issued = 0;-const query = new URLSearchParams({ client_id: 'gbrain_cl_example', redirect_uri: 'https://client.example.com/callback', response_type: 'code', state: 'fixture-state', scope: 'read write', code_challenge: 'fixture-challenge', code_challenge_method: 'S256' });-const cookie = 'gbrain_admin=owner-session';+let engine: PGLiteEngine;+let provider: GBrainOAuthProvider;beforeAll(async () => {- const app = express(); app.use(cookieParser());- const provider = { clientsStore: { getClient: async (id: string) => id === 'gbrain_cl_example' ? { client_name: '<script>untrusted</script>', redirect_uris: ['https://client.example.com/callback'], scope: 'read write' } : undefined } } as unknown as GBrainOAuthProvider;- // publicOrigin is known only after the ephemeral listener binds.- server = app.listen(0, '127.0.0.1');- await new Promise<void>(resolve => server.once('listening', resolve));- base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;- mountOAuthOwnerConsent(app, { provider, publicOrigin: base, sessionValid: sid => sid === 'owner-session' });- app.get('/authorize', (req, res) => { issued++; res.json({ approved: res.locals.gbrainOwnerApproved, query: req.query }); });-});-afterAll(async () => { server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())); });-async function getConsent() {- const r = await fetch(`${base}/authorize?${query}`, { headers: { Cookie: cookie }, redirect: 'manual' });- const body = await r.text();- return { r, body, nonce: body.match(/name="nonce" value="([a-f0-9]+)"/)?.[1] ?? '' };-}-async function decide(nonce: string, decision: string, sid = cookie, origin = base) {- return fetch(`${base}/authorize/consent`, { method: 'POST', redirect: 'manual', headers: { Cookie: sid, Origin: origin, 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ nonce, decision }) });+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ provider = new GBrainOAuthProvider({+ sql: sqlQueryForEngine(engine),+ transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))),+ });+}, 60_000);+afterAll(async () => { await engine?.disconnect(); }, 15_000);++async function pending() {+ const grant = resolveGrantProfile({ profile: 'delegating-agent', sourceId: 'default', boundTools: ['search'] });+ const client = await provider.registerClientManual('consent-profile-example', ['authorization_code'], grant.scopes!.join(' '),+ ['https://client.example.com/callback'], 'default', undefined, 'none', undefined, grant);+ const id = await provider.grants.begin(client.clientId, {+ codeChallenge: TEST_PKCE_CHALLENGE, redirectUri: 'https://client.example.com/callback', scopes: grant.scopes,+ });+ return { id, clientId: client.clientId };}-test('anonymous authorization cannot mint a code and shows owner sign-in', async () => {- const before = issued;- const r = await fetch(`${base}/authorize?${query}`, { redirect: 'manual' });- expect(r.status).toBe(401); expect(await r.text()).toContain('Sign in to approve'); expect(issued).toBe(before);-});-test('owner reviews escaped client identity before a single-use approval', async () => {- const { r, body, nonce } = await getConsent();- expect(r.status).toBe(200); expect(nonce).not.toBe('');- expect(body).toContain('<script>untrusted</script>');- expect(body).not.toContain('<script>untrusted</script>');- const decision = await decide(nonce, 'approve'); expect(decision.status).toBe(303);- const location = decision.headers.get('location')!;- const approved = await fetch(`${base}${location}`, { headers: { Cookie: cookie }, redirect: 'manual' });- expect(approved.status).toBe(200);- const value = await approved.json() as any;- expect(value.approved).toBe(true); expect(value.query._gbrain_approval).toBeUndefined();- expect(value.query.code_challenge).toBe('fixture-challenge');- expect((await fetch(`${base}${location}`, { headers: { Cookie: cookie }, redirect: 'manual' })).status).toBe(403);-});-test('approval is bound to the session, origin, and complete authorization request', async () => {- const { nonce } = await getConsent();- expect((await decide(nonce, 'approve', 'gbrain_admin=other-session')).status).toBe(403);- expect((await decide(nonce, 'approve', cookie, 'https://other.example.com')).status).toBe(403);- const d = await decide(nonce, 'approve');- const modified = new URL(`${base}${d.headers.get('location')}`); modified.searchParams.set('scope', 'admin');- expect((await fetch(modified, { headers: { Cookie: cookie }, redirect: 'manual' })).status).toBe(403);++test('owner review includes operation and delegation ceilings without creating a code', async () => {+ const { id, clientId } = await pending();+ const details = provider.grants.details(id);+ expect(details.allowedOperations).toContain('submit_agent');+ expect(details.delegatedTools).toEqual(['search']);+ expect(details.delegatedNamespace).toBe('job');+ expect(details.sourceId).toBe('default');+ expect(await engine.executeRaw('SELECT code_hash FROM oauth_codes WHERE client_id = $1', [clientId])).toHaveLength(0);+ // A UI consumer cannot mutate the stored review snapshot through a returned array.+ details.allowedOperations!.push('shell');+ details.delegatedTools!.push('file_list');+ expect(provider.grants.details(id).allowedOperations).not.toContain('shell');+ expect(provider.grants.details(id).delegatedTools).toEqual(['search']);});-test('denial returns only to a registered redirect with state; unregistered redirects are refused', async () => {- const { nonce } = await getConsent();- const r = await decide(nonce, 'deny'); const target = new URL(r.headers.get('location')!);- expect(target.origin).toBe('https://client.example.com'); expect(target.searchParams.get('error')).toBe('access_denied');- expect(target.searchParams.get('state')).toBe('fixture-state');- const bad = new URLSearchParams(query); bad.set('redirect_uri', 'https://other.example.com/callback');- expect((await fetch(`${base}/authorize?${bad}`, { headers: { Cookie: cookie }, redirect: 'manual' })).status).toBe(400);++for (const patch of [+ { allowedOperations: ['search'] },+ { boundTools: ['get_page'] },+ { delegatedNamespace: 'prefixes' as const, delegatedSlugPrefixes: ['reviewed-example/'] },+]) {+ test(`changing ${Object.keys(patch).join(', ')} requires a new review and never issues a code`, async () => {+ const { id, clientId } = await pending();+ await rescopeClientGrant(engine, clientId, patch, { actor: 'test' });+ await expect(provider.grants.decide(id, true)).rejects.toThrow('Client permissions changed');+ await expect(provider.grants.decide(id, true)).rejects.toThrow('Restart the connection');+ expect(await engine.executeRaw('SELECT code_hash FROM oauth_codes WHERE client_id = $1', [clientId])).toHaveLength(0);+ });+}++test('unchanged profile grants still require one owner decision', async () => {+ const { id, clientId } = await pending();+ const redirect = new URL(await provider.grants.decide(id, true));+ expect(redirect.origin).toBe('https://client.example.com');+ expect(redirect.searchParams.get('code')).toStartWith('gbrain_code_');+ await expect(provider.grants.decide(id, true)).rejects.toThrow('Restart the connection');+ expect(await engine.executeRaw('SELECT code_hash FROM oauth_codes WHERE client_id = $1', [clientId])).toHaveLength(1);});diff --git a/test/oauth-refresh-invalid-grant.test.ts b/test/oauth-refresh-invalid-grant.test.tsindex 0573ad610a..411e11b6fa 100644--- a/test/oauth-refresh-invalid-grant.test.ts+++ b/test/oauth-refresh-invalid-grant.test.ts@@ -1,3 +1,4 @@+import { authorizeAsOwner, pgliteOAuthTransaction, TEST_PKCE_VERIFIER, TEST_PKCE_CHALLENGE } from './helpers/oauth.ts';// #4532 — exchangeRefreshToken failures must be InvalidGrantError, not bare// Error.//@@ -14,8 +15,6 @@ import { vector } from '@electric-sql/pglite/vector';import { pg_trgm } from '@electric-sql/pglite/contrib/pg_trgm';import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';import { hashToken } from '../src/core/utils.ts';-const PKCE_VERIFIER = 'oauth-refresh-verifier-example-'.repeat(3);-const PKCE_CHALLENGE = Buffer.from(hashToken(PKCE_VERIFIER), 'hex').toString('base64url');import { PGLITE_SCHEMA_SQL } from '../src/core/pglite-schema.ts';import { InvalidGrantError, ServerError, OAuthError } from '@modelcontextprotocol/sdk/server/auth/errors.js';@@ -31,7 +30,7 @@ beforeAll(async () => {const result = await db.query(query, values as any[]);return result.rows;};- provider = new GBrainOAuthProvider({ sql, tokenTtl: 60, refreshTtl: 300 });+ provider = new GBrainOAuthProvider({ transaction: pgliteOAuthTransaction(db), sql, tokenTtl: 60, refreshTtl: 300 });}, 120_000);afterAll(async () => {@@ -46,13 +45,13 @@ async function mintTokens() {const client = (await provider.clientsStore.getClient(clientId))!;let redirectUrl = '';const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(client, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, client, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['read', 'write'],}, mockRes);const code = new URL(redirectUrl).searchParams.get('code')!;- const tokens = await provider.exchangeAuthorizationCode(client, code, PKCE_VERIFIER);+ const tokens = await provider.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER, client.redirect_uris![0]);return { client, tokens };}diff --git a/test/oauth-surface-ladder.test.ts b/test/oauth-surface-ladder.test.tsindex 48171b5ef5..4b6e20cdea 100644--- a/test/oauth-surface-ladder.test.ts+++ b/test/oauth-surface-ladder.test.ts@@ -1,3 +1,4 @@+import { authorizeAsOwner, pgliteOAuthTransaction, TEST_PKCE_VERIFIER, TEST_PKCE_CHALLENGE } from './helpers/oauth.ts';/*** WP4 (amendments 17-19, ENG-9) — oauth_clients.surface threading + the* verifyAccessToken degrade ladder's NEW top rung + rescopeClient's surface@@ -28,7 +29,7 @@ beforeAll(async () => {const result = await db.query(query, values as any[]);return result.rows;};- provider = new GBrainOAuthProvider({ sql, tokenTtl: 60, refreshTtl: 300 });+ provider = new GBrainOAuthProvider({ transaction: pgliteOAuthTransaction(db), sql, tokenTtl: 60, refreshTtl: 300 });}, 30_000);afterAll(async () => {diff --git a/test/oauth.test.ts b/test/oauth.test.tsindex 3874870198..c3eef145f5 100644--- a/test/oauth.test.ts+++ b/test/oauth.test.ts@@ -1,3 +1,4 @@+import { authorizeAsOwner, pgliteOAuthTransaction, TEST_PKCE_VERIFIER, TEST_PKCE_CHALLENGE } from './helpers/oauth.ts';import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGlite } from '@electric-sql/pglite';import { vector } from '@electric-sql/pglite/vector';@@ -14,9 +15,6 @@ import { PGLITE_SCHEMA_SQL } from '../src/core/pglite-schema.ts';import { InvalidTokenError, InvalidClientMetadataError } from '@modelcontextprotocol/sdk/server/auth/errors.js';import type { AuthInfo as CoreAuthInfo } from '../src/core/operations.ts';-const PKCE_VERIFIER = 'oauth-test-verifier-example-'.repeat(3);-const PKCE_CHALLENGE = Buffer.from(hashToken(PKCE_VERIFIER), 'hex').toString('base64url');-// ---------------------------------------------------------------------------// Test setup: in-memory PGLite with OAuth tables// ---------------------------------------------------------------------------@@ -36,7 +34,7 @@ beforeAll(async () => {return result.rows;};- provider = new GBrainOAuthProvider({ sql, tokenTtl: 60, refreshTtl: 300 });+ provider = new GBrainOAuthProvider({ transaction: pgliteOAuthTransaction(db), sql, tokenTtl: 60, refreshTtl: 300 });}, 30_000); // PGLITE_SCHEMA_SQL execution under full-suite load can exceed default 5safterAll(async () => {@@ -185,7 +183,7 @@ describe('rescopeClient', () => {// source_id='default', federated_read=['default']. client_credentials// over DCR needs the explicit --enable-dcr-insecure opt-in, so build a// provider with that flag just for this registration.- const dcrProvider = new GBrainOAuthProvider({ sql, tokenTtl: 60, allowClientCredentialsDcr: true });+ const dcrProvider = new GBrainOAuthProvider({ transaction: pgliteOAuthTransaction(db), sql, tokenTtl: 60, allowClientCredentialsDcr: true });const dcr = await dcrProvider.clientsStore.registerClient!({client_name: 'dcr-stuck-client',redirect_uris: [],@@ -687,8 +685,8 @@ describe('authorization code flow', () => {redirect: (url: string) => { redirectUrl = url; },} as any;- await provider.authorize(client, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, client, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['read', 'write'],state: 'test-state',@@ -702,7 +700,7 @@ describe('authorization code flow', () => {const code = url.searchParams.get('code')!;// Exchange code for tokens- const tokens = await provider.exchangeAuthorizationCode(client, code, PKCE_VERIFIER);+ const tokens = await provider.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER, client.redirect_uris![0]);expect(tokens.access_token).toStartWith('gbrain_at_');expect(tokens.refresh_token).toBeDefined(); // Auth code flow includes refresh});@@ -717,8 +715,8 @@ describe('authorization code flow', () => {let redirectUrl = '';const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(client, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, client, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['read'],}, mockRes);@@ -726,10 +724,10 @@ describe('authorization code flow', () => {const code = new URL(redirectUrl).searchParams.get('code')!;// First exchange works- await provider.exchangeAuthorizationCode(client, code, PKCE_VERIFIER);+ await provider.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER, client.redirect_uris![0]);// Second exchange fails (code consumed)- await expect(provider.exchangeAuthorizationCode(client, code, PKCE_VERIFIER)).rejects.toThrow();+ await expect(provider.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER, client.redirect_uris![0])).rejects.toThrow();});test('expired code is rejected', async () => {@@ -746,7 +744,7 @@ describe('authorization code flow', () => {`;const client = (await provider.clientsStore.getClient(firstClient.client_id as string))!;- await expect(provider.exchangeAuthorizationCode(client, expiredCode, PKCE_VERIFIER)).rejects.toThrow();+ await expect(provider.exchangeAuthorizationCode(client, expiredCode, TEST_PKCE_VERIFIER, client.redirect_uris![0])).rejects.toThrow();});// F-AUTHZ regression. The MCP SDK's authorize handler splits `?scope=...`@@ -767,14 +765,14 @@ describe('authorization code flow', () => {const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;// Read-only client requests admin via the SDK's parsed scopes array.- await provider.authorize(client, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, client, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['read', 'write', 'admin'],}, mockRes);const code = new URL(redirectUrl).searchParams.get('code')!;- const tokens = await provider.exchangeAuthorizationCode(client, code, PKCE_VERIFIER);+ const tokens = await provider.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER, client.redirect_uris![0]);// The token's stored scopes must equal the clamped subset.const auth = await provider.verifyAccessToken(tokens.access_token);@@ -793,14 +791,14 @@ describe('authorization code flow', () => {let redirectUrl = '';const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(client, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, client, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['read'],}, mockRes);const code = new URL(redirectUrl).searchParams.get('code')!;- const tokens = await provider.exchangeAuthorizationCode(client, code, PKCE_VERIFIER);+ const tokens = await provider.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER, client.redirect_uris![0]);const auth = await provider.verifyAccessToken(tokens.access_token);expect(auth.scopes).toEqual(['read']);});@@ -819,8 +817,8 @@ describe('authorization code flow', () => {let redirectUrl = '';const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(client, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, client, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['read'],}, mockRes);@@ -828,7 +826,7 @@ describe('authorization code flow', () => {const N = 10;const results = await Promise.allSettled(- Array.from({ length: N }, () => provider.exchangeAuthorizationCode(client, code, PKCE_VERIFIER)),+ Array.from({ length: N }, () => provider.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER, client.redirect_uris![0])),);const successes = results.filter(r => r.status === 'fulfilled');const failures = results.filter(r => r.status === 'rejected');@@ -852,14 +850,14 @@ describe('refresh token', () => {let redirectUrl = '';const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(client, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, client, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['read', 'write'],}, mockRes);const code = new URL(redirectUrl).searchParams.get('code')!;- const tokens = await provider.exchangeAuthorizationCode(client, code, PKCE_VERIFIER);+ const tokens = await provider.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER, client.redirect_uris![0]);// Refreshconst newTokens = await provider.exchangeRefreshToken(client, tokens.refresh_token!, ['read']);@@ -883,13 +881,13 @@ describe('refresh token', () => {let redirectUrl = '';const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(client, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, client, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['read'],}, mockRes);const code = new URL(redirectUrl).searchParams.get('code')!;- const tokens = await provider.exchangeAuthorizationCode(client, code, PKCE_VERIFIER);+ const tokens = await provider.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER, client.redirect_uris![0]);const N = 10;const results = await Promise.allSettled(@@ -1137,20 +1135,20 @@ describe('F1/F4 cross-client isolation', () => {let redirectUrl = '';const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(owner, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, owner, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['read'],}, mockRes);const code = new URL(redirectUrl).searchParams.get('code')!;// Attacker holding the same code MUST be rejected.- await expect(provider.exchangeAuthorizationCode(attacker, code, PKCE_VERIFIER)).rejects.toThrow();+ await expect(provider.exchangeAuthorizationCode(attacker, code, TEST_PKCE_VERIFIER, attacker.redirect_uris![0])).rejects.toThrow();// The atomic predicate's payoff: the legitimate owner can STILL redeem// the code afterward. Without it, the attacker would have burned the// row in the DELETE and the owner's redemption would 404.- const tokens = await provider.exchangeAuthorizationCode(owner, code, PKCE_VERIFIER);+ const tokens = await provider.exchangeAuthorizationCode(owner, code, TEST_PKCE_VERIFIER, owner.redirect_uris![0]);expect(tokens.access_token).toStartWith('gbrain_at_');});@@ -1168,15 +1166,15 @@ describe('F1/F4 cross-client isolation', () => {let redirectUrl = '';const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(owner, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, owner, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['read'],}, mockRes);const code = new URL(redirectUrl).searchParams.get('code')!;await expect(provider.challengeForAuthorizationCode!(attacker, code)).rejects.toThrow();- await expect(provider.challengeForAuthorizationCode!(owner, code)).resolves.toBe(PKCE_CHALLENGE);+ await expect(provider.challengeForAuthorizationCode!(owner, code)).resolves.toBe(TEST_PKCE_CHALLENGE);});test('wrong client cannot revoke another client token', async () => {@@ -1216,13 +1214,13 @@ describe('F2/F3 refresh hardening', () => {let redirectUrl = '';const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(owner, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, owner, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['read'],}, mockRes);const code = new URL(redirectUrl).searchParams.get('code')!;- const tokens = await provider.exchangeAuthorizationCode(owner, code, PKCE_VERIFIER);+ const tokens = await provider.exchangeAuthorizationCode(owner, code, TEST_PKCE_VERIFIER, owner.redirect_uris![0]);// Attacker rejected.await expect(provider.exchangeRefreshToken(attacker, tokens.refresh_token!)).rejects.toThrow();@@ -1249,13 +1247,13 @@ describe('F2/F3 refresh hardening', () => {let redirectUrl = '';const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(client, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, client, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['read'],}, mockRes);const code = new URL(redirectUrl).searchParams.get('code')!;- const tokens = await provider.exchangeAuthorizationCode(client, code, PKCE_VERIFIER);+ const tokens = await provider.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER, client.redirect_uris![0]);// Attempt to escalate to write — must reject.await expect(@@ -1276,13 +1274,13 @@ describe('F2/F3 refresh hardening', () => {let redirectUrl = '';const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(client, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, client, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['admin'],}, mockRes);const code = new URL(redirectUrl).searchParams.get('code')!;- const tokens = await provider.exchangeAuthorizationCode(client, code, PKCE_VERIFIER);+ const tokens = await provider.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER, client.redirect_uris![0]);// Refresh requesting only sources_admin — admin implies it, so this// must succeed and the new token must carry only the requested subset.@@ -1314,13 +1312,13 @@ describe('F2/F3 refresh hardening', () => {let redirectUrl = '';const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(client, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, client, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['admin'],}, mockRes);const code = new URL(redirectUrl).searchParams.get('code')!;- const tokens = await provider.exchangeAuthorizationCode(client, code, PKCE_VERIFIER);+ const tokens = await provider.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER, client.redirect_uris![0]);const rotated = await provider.exchangeRefreshToken(client, tokens.refresh_token!, ['users_admin'],@@ -1338,13 +1336,13 @@ describe('F2/F3 refresh hardening', () => {let redirectUrl = '';const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(client, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, client, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['write'],}, mockRes);const code = new URL(redirectUrl).searchParams.get('code')!;- const tokens = await provider.exchangeAuthorizationCode(client, code, PKCE_VERIFIER);+ const tokens = await provider.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER, client.redirect_uris![0]);await expect(provider.exchangeRefreshToken(client, tokens.refresh_token!, ['sources_admin']),@@ -1419,23 +1417,8 @@ describe('F5 verifyAccessToken / client_credentials column probes', () => {// the client as not-revoked. Without the predicate this throw used to// disappear into the void.const sqlFailure = Object.assign(new Error('database session failed'), { code: '57P01' });- const fakeSql = async (strings: TemplateStringsArray): Promise<Record<string, unknown>[]> => {- const query = strings.join('$');- if (query.includes('SELECT client_id, client_secret_hash')) {- return [{- client_id: 'gbrain_cl_fake',- client_secret_hash: hashToken('secret'),- client_name: 'fake',- redirect_uris: [],- grant_types: ['client_credentials'],- scope: 'read',- client_id_issued_at: 1,- }];- }- if (query.includes('SELECT deleted_at')) throw sqlFailure;- return [];- };- const failingProvider = new GBrainOAuthProvider({ sql: fakeSql as any });+ const fakeSql = async (): Promise<Record<string, unknown>[]> => { throw sqlFailure; };+ const failingProvider = new GBrainOAuthProvider({ sql: fakeSql, transaction: fn => fn(fakeSql) });await expect(failingProvider.exchangeClientCredentials('gbrain_cl_fake', 'secret', 'read'),@@ -1480,15 +1463,15 @@ describe('F7c redirect_uri binding on auth code exchange', () => {let redirectUrl = '';const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(client, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, client, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['read'],}, mockRes);const code = new URL(redirectUrl).searchParams.get('code')!;const tokens = await provider.exchangeAuthorizationCode(- client, code, PKCE_VERIFIER, 'http://localhost:3000/callback',+ client, code, TEST_PKCE_VERIFIER, 'http://localhost:3000/callback',);expect(tokens.access_token).toStartWith('gbrain_at_');});@@ -1502,8 +1485,8 @@ describe('F7c redirect_uri binding on auth code exchange', () => {let redirectUrl = '';const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(client, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, client, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['read'],}, mockRes);@@ -1513,7 +1496,7 @@ describe('F7c redirect_uri binding on auth code exchange', () => {// an attacker-controlled callback URL) MUST be rejected. RFC 6749 §4.1.3.await expect(provider.exchangeAuthorizationCode(- client, code, PKCE_VERIFIER, 'https://attacker.example/cb',+ client, code, TEST_PKCE_VERIFIER, 'https://attacker.example/cb',),).rejects.toThrow();});@@ -1533,23 +1516,20 @@ describe('F7c redirect_uri binding on auth code exchange', () => {let redirectUrl = '';const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(client, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, client, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['read'],}, mockRes);const code = new URL(redirectUrl).searchParams.get('code')!;await expect(- provider.exchangeAuthorizationCode(client, code, PKCE_VERIFIER, ''),+ provider.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER, ''),).rejects.toThrow();});- test('omitted redirect_uri (back-compat) still succeeds', async () => {- // Existing callers that don't pass redirectUri keep working — the- // predicate only fires when redirectUri is provided. This protects- // against breaking SDK consumers that haven't adopted the parameter- // yet, while still hardening the path for those that have.+ test('omitted redirect_uri cannot bypass code binding', async () => {+ // The exact redirect selected at authorization remains required at redemption.const { clientId } = await provider.registerClientManual('redir-omitted-test', ['authorization_code'], 'read',['http://localhost:3000/callback'],@@ -1558,15 +1538,14 @@ describe('F7c redirect_uri binding on auth code exchange', () => {let redirectUrl = '';const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(client, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, client, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['read'],}, mockRes);const code = new URL(redirectUrl).searchParams.get('code')!;- const tokens = await provider.exchangeAuthorizationCode(client, code, PKCE_VERIFIER);- expect(tokens.access_token).toStartWith('gbrain_at_');+ await expect(provider.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER)).rejects.toThrow('Redirect URI');});});@@ -1576,7 +1555,7 @@ describe('F7c redirect_uri binding on auth code exchange', () => {describe('F12 dcrDisabled constructor option', () => {test('clientsStore omits registerClient when dcrDisabled=true', () => {- const dcrOff = new GBrainOAuthProvider({ sql, dcrDisabled: true });+ const dcrOff = new GBrainOAuthProvider({ transaction: pgliteOAuthTransaction(db), sql, dcrDisabled: true });const store = dcrOff.clientsStore;expect(typeof store.getClient).toBe('function');// SDK's mcpAuthRouter checks for registerClient before wiring up the@@ -1585,14 +1564,14 @@ describe('F12 dcrDisabled constructor option', () => {});test('clientsStore exposes registerClient when dcrDisabled is false/unset', () => {- const dcrOn = new GBrainOAuthProvider({ sql });+ const dcrOn = new GBrainOAuthProvider({ transaction: pgliteOAuthTransaction(db), sql });expect(typeof dcrOn.clientsStore.registerClient).toBe('function');});test('registerClientManual still works on dcrDisabled providers (CLI path)', async () => {// The CLI code path uses registerClientManual, which is independent of// the DCR /register endpoint. dcrDisabled must NOT break it.- const dcrOff = new GBrainOAuthProvider({ sql, dcrDisabled: true });+ const dcrOff = new GBrainOAuthProvider({ transaction: pgliteOAuthTransaction(db), sql, dcrDisabled: true });const result = await dcrOff.registerClientManual('dcr-disabled-cli-test', ['client_credentials'], 'read',);@@ -1687,8 +1666,8 @@ describe('PKCE DCR public-client gate (#909)', () => {let redirectUrl = '';const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;- await provider.authorize(client, {- codeChallenge: PKCE_CHALLENGE,+ await authorizeAsOwner(provider, client, {+ codeChallenge: TEST_PKCE_CHALLENGE,redirectUri: 'http://localhost:3000/callback',scopes: ['read'],}, mockRes);@@ -1696,7 +1675,7 @@ describe('PKCE DCR public-client gate (#909)', () => {expect(code).toMatch(/^gbrain_code_/);// Exchange the code — public client; no secret on the wire.- const tokens = await provider.exchangeAuthorizationCode(client, code, PKCE_VERIFIER);+ const tokens = await provider.exchangeAuthorizationCode(client, code, TEST_PKCE_VERIFIER, client.redirect_uris![0]);expect(tokens.access_token).toStartWith('gbrain_at_');// SDK normalizes token_type per RFC 6750 §6.1.1 (case-insensitive);// implementations may emit "bearer" lowercase.@@ -1911,7 +1890,7 @@ describe('#1353 DCR default-grant hardening', () => {});test('--enable-dcr-insecure (allowClientCredentialsDcr) permits client_credentials', async () => {- const insecure = new GBrainOAuthProvider({ sql, allowClientCredentialsDcr: true });+ const insecure = new GBrainOAuthProvider({ transaction: pgliteOAuthTransaction(db), sql, allowClientCredentialsDcr: true });const reg = await insecure.clientsStore.registerClient!({client_name: 'cc-allowed-test',grant_types: ['client_credentials'],diff --git a/test/operations-trust-boundary.test.ts b/test/operations-trust-boundary.test.tsindex c0b6ebf7ec..11a7b3bf87 100644--- a/test/operations-trust-boundary.test.ts+++ b/test/operations-trust-boundary.test.ts@@ -304,19 +304,12 @@ describe('handler invocation — historically-broken trust-boundary classes', ()expect(submitJob).toBeDefined();const ctx = makeContext({ remote: true });- let threw = false;- let message = '';- try {- await submitJob!.handler(ctx, { name: 'shell', data: { cmd: 'echo hi' } });- } catch (e) {- threw = true;- message = e instanceof Error ? e.message : String(e);- }- expect(threw, 'submit_job(shell) with remote=true MUST reject').toBe(true);- // Should mention the protected status — "permission_denied" is the- // canonical OperationError code, plus the user-facing string names- // the rejected name.- expect(message.toLowerCase()).toContain('shell');+ await expect(submitJob!.handler(ctx, { name: 'shell', data: { cmd: 'echo hi' } })).rejects.toMatchObject({+ code: 'permission_denied',+ // Bounded diagnostics identify the supported alternatives, without+ // echoing caller-controlled job names or payloads.+ message: expect.stringContaining('only sync, import, lint and lint-fix'),+ });});test('submit_job allows shell when ctx.remote=false (local CLI is trusted)', async () => {diff --git a/test/plugin-loader.test.ts b/test/plugin-loader.test.tsindex 3ab97a513d..e119194767 100644--- a/test/plugin-loader.test.ts+++ b/test/plugin-loader.test.ts@@ -103,6 +103,22 @@ describe('loadSinglePlugin', () => {expect(res.subagents[0]!.body.trim()).toBe('You are a meeting ingester.');});+ test('rejects executable selectors and malformed metadata without returning a partial plugin', () => {+ for (const [name, content, reason] of [+ ['selector', '---javascript\n({name: "private-content"})\n---\nbody', 'Unsupported frontmatter language'],+ ['malformed', '---\nname: [private-content\n---\nbody', 'Malformed YAML frontmatter'],+ ]) {+ const dir = writePlugin(name, { subagents: { 'a-good.md': '---\nname: valid\n---\nbody', 'b-rejected.md': content } });+ const result = loadSinglePlugin(dir);+ expect('error' in result).toBe(true);+ expect('subagents' in result).toBe(false);+ if ('error' in result) {+ expect(result.error).toContain(reason);+ expect(result.error).not.toContain('private-content');+ }+ }+ });+test('missing manifest returns error', () => {const dir = writePlugin('empty', { omit_manifest: true });const res = loadSinglePlugin(dir);diff --git a/test/queue-getstats-wedge.test.ts b/test/queue-getstats-wedge.test.tsindex 813f6f651f..a7e6bd32f1 100644--- a/test/queue-getstats-wedge.test.ts+++ b/test/queue-getstats-wedge.test.ts@@ -34,8 +34,8 @@ async function seed(extra: { lockUntilSql?: string; updatedAtSql?: string } = {},): Promise<void> {await engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, lock_until, updated_at)- VALUES ($1, $2, $3, ${extra.lockUntilSql ?? 'NULL'}, ${extra.updatedAtSql ?? 'now()'})`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, lock_until, updated_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, $1, $2, $3, ${extra.lockUntilSql ?? 'NULL'}, ${extra.updatedAtSql ?? 'now()'})`,[name, q, status],);}diff --git a/test/queue-lock-retry.test.ts b/test/queue-lock-retry.test.tsindex 14bc9c0829..a50ae7e682 100644--- a/test/queue-lock-retry.test.ts+++ b/test/queue-lock-retry.test.ts@@ -22,6 +22,11 @@ function connEndedError(): Error & { code: string } {return e;}+function isAuthorityInventory(sql: string): boolean {+ return sql.includes('SELECT id, submission_authority FROM minion_jobs') &&+ sql.includes('submission_authority IS DISTINCT FROM');+}+const AUDIT_DIR = join(tmpdir(), `gbrain-queue-lock-retry-${process.pid}-${Date.now()}`);// Fast retry + isolated audit dir so the test doesn't sleep ~1s or pollute ~/.gbrain.const FAST_ENV = {@@ -37,7 +42,12 @@ describe('MinionQueue lock-path recovery (issue #1678)', () => {let reconnects = 0;const engine = {kind: 'postgres',- executeRaw: async () => {+ executeRaw: async (sql: string) => {+ if (isAuthorityInventory(sql)) return [];+ if (!sql.startsWith('UPDATE minion_jobs SET') ||+ !sql.includes("WHERE status = 'delayed' AND delay_until <= now()")) {+ throw new Error('Unexpected SQL in promotion retry fixture');+ }calls++;if (calls === 1) throw connEndedError();return [];@@ -59,10 +69,19 @@ describe('MinionQueue lock-path recovery (issue #1678)', () => {const engine = {kind: 'postgres',// claim() routes through executeRawDirect (direct session pool) as of- // the lock-hot-path fix; executeRaw is kept as a throwing guard to- // prove claim never falls back to it.- executeRawDirect: async () => { calls++; throw connEndedError(); },- executeRaw: async () => { throw new Error('claim must not use executeRaw'); },+ // the lock-hot-path fix. Only the read-only authority inventory may+ // use executeRaw; the claim mutation must stay on the direct pool.+ executeRawDirect: async (sql: string) => {+ if (!sql.includes("status = 'active'") || !sql.includes('FOR UPDATE SKIP LOCKED')) {+ throw new Error('Unexpected SQL in claim retry fixture');+ }+ calls++;+ throw connEndedError();+ },+ executeRaw: async (sql: string) => {+ if (isAuthorityInventory(sql)) return [];+ throw new Error('claim mutation must not use executeRaw');+ },reconnect: async () => {},} as unknown as ConstructorParameters<typeof MinionQueue>[0];@@ -71,4 +90,24 @@ describe('MinionQueue lock-path recovery (issue #1678)', () => {expect(calls).toBe(1); // exactly one attempt — no inline retry});});++ it('an unavailable authority inventory prevents both claim and promotion mutations', async () => {+ await withEnv(FAST_ENV, async () => {+ let mutations = 0;+ const engine = {+ kind: 'postgres',+ executeRaw: async (sql: string) => {+ if (isAuthorityInventory(sql)) throw connEndedError();+ mutations++;+ return [];+ },+ executeRawDirect: async () => { mutations++; return []; },+ reconnect: async () => {},+ } as unknown as ConstructorParameters<typeof MinionQueue>[0];+ const q = new MinionQueue(engine);+ await expect(q.promoteDelayed()).rejects.toThrow('CONNECTION_ENDED');+ await expect(q.claim('tok', 1000, 'default', ['sync'])).rejects.toThrow('CONNECTION_ENDED');+ expect(mutations).toBe(0);+ });+ });});diff --git a/test/resolvers.test.ts b/test/resolvers.test.tsindex de9482c3cb..a577270cd5 100644--- a/test/resolvers.test.ts+++ b/test/resolvers.test.ts@@ -19,6 +19,7 @@ import type {ResolverResult,} from '../src/core/resolvers/index.ts';import { urlReachableResolver, checkDnsRebinding } from '../src/core/resolvers/builtin/url-reachable.ts';+import { __setDnsLookupForTests } from '../src/core/ssrf-validate.ts';import { xHandleToTweetResolver, computeBackoffMs } from '../src/core/resolvers/builtin/x-api/handle-to-tweet.ts';// ---------------------------------------------------------------------------@@ -185,8 +186,12 @@ describe('getDefaultRegistry', () => {describe('url_reachable resolver', () => {const originalFetch = globalThis.fetch;+ beforeEach(() => {+ __setDnsLookupForTests((async () => [{ address: '8.8.8.8', family: 4 }]) as any);+ });afterEach(() => {globalThis.fetch = originalFetch;+ __setDnsLookupForTests(undefined);});test('available() is true', async () => {@@ -302,7 +307,7 @@ describe('url_reachable resolver', () => {context: makeCtx(),});expect(r.value.reachable).toBe(false);- expect(r.value.reason).toMatch(/redirect to blocked/i);+ expect(r.value.reason).toMatch(/blocked.*redirect/i);});test('fetch network failure → reachable=false, confidence=1', async () => {@@ -316,20 +321,37 @@ describe('url_reachable resolver', () => {expect(r.confidence).toBe(1);});- test('checkDnsRebinding: skips IP literals', async () => {+ test('abort and transport diagnostics do not disclose signed URLs or upstream errors', async () => {+ const url = 'https://example.com/private-document?signature=private-value';+ const ac = new AbortController();+ ac.abort();+ const aborted = await urlReachableResolver.resolve({ input: { url }, context: makeCtx({ signal: ac.signal }) })+ .catch(error => error);+ expect(aborted).toBeInstanceOf(ResolverError);+ expect(aborted.code).toBe('aborted');+ expect(aborted.message).not.toContain('private-');++ globalThis.fetch = (async () => { throw new Error('TLS failure for private-document?signature=private-value'); }) as unknown as typeof fetch;+ const result = await urlReachableResolver.resolve({ input: { url }, context: makeCtx() });+ expect(result.value.reachable).toBe(false);+ expect(result.value.reason).toContain('fetch error');+ expect(result.value.reason).not.toContain('private-');+ });++ test('checkDnsRebinding: validates IP literals using the shared policy', async () => {expect(await checkDnsRebinding('http://8.8.8.8/')).toBeNull();- expect(await checkDnsRebinding('http://127.0.0.1/')).toBeNull();- expect(await checkDnsRebinding('http://[::1]/')).toBeNull();+ expect(await checkDnsRebinding('http://127.0.0.1/')).toMatch(/internal|private/i);+ expect(await checkDnsRebinding('http://[::1]/')).toMatch(/internal|private/i);});- test('checkDnsRebinding: returns null for unparseable URL', async () => {- expect(await checkDnsRebinding('not a url')).toBeNull();+ test('checkDnsRebinding: rejects an unparseable URL', async () => {+ expect(await checkDnsRebinding('not a url')).toMatch(/malformed/i);});- test('checkDnsRebinding: returns null on DNS failure (surface via fetch)', async () => {- // Nonexistent TLD; DNS lookup fails, we let the fetch surface the error.+ test('checkDnsRebinding: fails closed on DNS failure', async () => {+ __setDnsLookupForTests((async () => { throw new Error('ENOTFOUND'); }) as any);const r = await checkDnsRebinding('http://definitely-not-a-real-tld.invalidtld123/');- expect(r).toBeNull();+ expect(r).toMatch(/resolve|DNS/i);});test('AbortSignal fires mid-flight → ResolverError(aborted)', async () => {diff --git a/test/retrieval-reflex-recipe-routing.test.ts b/test/retrieval-reflex-recipe-routing.test.tsindex 76a9bff91b..0d1ceb24e8 100644--- a/test/retrieval-reflex-recipe-routing.test.ts+++ b/test/retrieval-reflex-recipe-routing.test.ts@@ -18,7 +18,7 @@import { describe, expect, it } from 'bun:test';import { existsSync, readFileSync } from 'node:fs';import { join, resolve } from 'node:path';-import matter from 'gray-matter';+import { dataFrontmatter as matter } from '../src/core/data-frontmatter.ts';const REPO_ROOT = resolve(import.meta.dir, '..');const RECIPE_ROOT = join(REPO_ROOT, 'recipes', 'retrieval-reflex');diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.tsindex e000fc0674..667463456e 100644--- a/test/schema-bootstrap-coverage.test.ts+++ b/test/schema-bootstrap-coverage.test.ts@@ -139,6 +139,14 @@ const REQUIRED_BOOTSTRAP_COVERAGE: ForwardReference[] = [// v121 mask class), so the bootstrap adds them on pre-v127 brains.{ kind: 'column', table: 'oauth_clients', column: 'surface' },{ kind: 'column', table: 'oauth_clients', column: 'surface_set_by' },+ // v147 capability columns are repaired before schema replay, including+ // partial installations. Numbered migration 147 owns grant policy repair.+ { kind: 'column', table: 'oauth_clients', column: 'allowed_operations' },+ { kind: 'column', table: 'oauth_clients', column: 'delegated_slug_prefixes' },+ { kind: 'column', table: 'oauth_clients', column: 'delegated_namespace' },+ { kind: 'column', table: 'oauth_clients', column: 'grant_profile' },+ { kind: 'column', table: 'oauth_clients', column: 'grant_revision' },+ { kind: 'column', table: 'oauth_clients', column: 'grant_repair_reasons' },// v0.26.5 (v34) — promotes archive lifecycle from JSONB config to real// columns on sources. CREATE TABLE IF NOT EXISTS is a no-op on existing// sources tables, so the visibility filters in search/list_pages that@@ -205,6 +213,10 @@ const REQUIRED_BOOTSTRAP_COVERAGE: ForwardReference[] = [// Token rides the same bootstrap ALTER; registering it guards any FUTURE// blob index on it against the same wedge.{ kind: 'column', table: 'minion_jobs', column: 'private_queue_owner_token' },+ // v149 queue protocol reads both fields before numbered migrations run.+ // Authority remains nullable: bootstrap must never authorize historical work.+ { kind: 'column', table: 'minion_jobs', column: 'submission_authority' },+ { kind: 'column', table: 'minion_jobs', column: 'claim_generation' },];test('applyForwardReferenceBootstrap covers every forward reference declared in REQUIRED_BOOTSTRAP_COVERAGE', async () => {@@ -281,6 +293,12 @@ test('applyForwardReferenceBootstrap covers every forward reference declared in-- must re-add them.ALTER TABLE oauth_clients DROP COLUMN IF EXISTS surface;ALTER TABLE oauth_clients DROP COLUMN IF EXISTS surface_set_by;+ ALTER TABLE oauth_clients DROP COLUMN IF EXISTS allowed_operations;+ ALTER TABLE oauth_clients DROP COLUMN IF EXISTS delegated_slug_prefixes;+ ALTER TABLE oauth_clients DROP COLUMN IF EXISTS delegated_namespace;+ ALTER TABLE oauth_clients DROP COLUMN IF EXISTS grant_profile;+ ALTER TABLE oauth_clients DROP COLUMN IF EXISTS grant_revision;+ ALTER TABLE oauth_clients DROP COLUMN IF EXISTS grant_repair_reasons;-- v0.40.3.0 v90 + v91 column strips so applyForwardReferenceBootstrap-- has work to do. Only strip pages columns + the trigger; sources@@ -316,6 +334,8 @@ test('applyForwardReferenceBootstrap covers every forward reference declared inALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_owner_job_id;ALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_owner_token;ALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_lease_until;+ ALTER TABLE minion_jobs DROP COLUMN IF EXISTS submission_authority;+ ALTER TABLE minion_jobs DROP COLUMN IF EXISTS claim_generation;`);// Note: we don't strip sources.archived* here because they're inline in the@@ -418,6 +438,8 @@ test('after bootstrap, PGLITE_SCHEMA_SQL replays without crashing on missing forALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_owner_job_id;ALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_owner_token;ALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_lease_until;+ ALTER TABLE minion_jobs DROP COLUMN IF EXISTS submission_authority;+ ALTER TABLE minion_jobs DROP COLUMN IF EXISTS claim_generation;-- WP4 (v127) strip: surface columns + the wedge-signal index; replay-- must succeed from the pre-v127 shape.@@ -1088,7 +1110,7 @@ test('extractAlterAddColumnsFromSql handles representative migration SQL shapes'// assertion is the local half of the guard; the e2e file is the live half.// ─────────────────────────────────────────────────────────────────-test('postgres-engine.ts bootstrap carries the private-queue ALTERs and probes (guard symmetry with pglite-engine.ts)', async () => {+test('postgres bootstrap carries the private-queue and authority ALTERs and probes (PGLite symmetry)', async () => {const { readFileSync } = await import('fs');const { resolve: resolvePath } = await import('path');// #4477 peeled the Postgres forward-reference bootstrap out of the@@ -1105,6 +1127,8 @@ test('postgres-engine.ts bootstrap carries the private-queue ALTERs and probes ('ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_owner_job_id INTEGER REFERENCES minion_jobs(id) ON DELETE SET NULL;','ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_owner_token TEXT;','ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_lease_until TIMESTAMPTZ;',+ 'ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS submission_authority JSONB;',+ 'ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS claim_generation BIGINT NOT NULL DEFAULT 0;',]) {expect(normalized).toContain(stmt);}@@ -1116,11 +1140,13 @@ test('postgres-engine.ts bootstrap carries the private-queue ALTERs and probes (expect(normalized).toContain('minion_jobs_pq_token_exists');expect(normalized).toContain('minion_jobs_pq_owner_exists');expect(normalized).toContain('minion_jobs_pq_lease_exists');+ expect(normalized).toContain('minion_jobs_submission_authority_exists');+ expect(normalized).toContain('minion_jobs_claim_generation_exists');// The structural extractor sees the same three ALTERs (keeps this guard// aligned with the parser-based coverage machinery above).const pgBootstrapAdds = parseAlterAddColumns(engineSrc);- for (const column of ['private_queue_owner_job_id', 'private_queue_owner_token', 'private_queue_lease_until']) {+ for (const column of ['private_queue_owner_job_id', 'private_queue_owner_token', 'private_queue_lease_until', 'submission_authority', 'claim_generation']) {expect(pgBootstrapAdds).toContainEqual({ table: 'minion_jobs', column });}});diff --git a/test/scripts/ci-gates.test.ts b/test/scripts/ci-gates.test.tsindex ec7f8857a7..6cb2597da8 100644--- a/test/scripts/ci-gates.test.ts+++ b/test/scripts/ci-gates.test.ts@@ -40,7 +40,7 @@ describe('CI execution evidence', () => {test('unit aggregate rejects failed, cancelled or skipped required jobs', () => {expect(unit.jobs['test-status'].if).toBe('always()');expect(unit.jobs['test-status'].needs).toEqual([- 'gitleaks', 'verify', 'serial-tests', 'slow-eval-longmemeval',+ 'gitleaks', 'security-regressions', 'dependency-audit', 'verify', 'serial-tests', 'slow-eval-longmemeval','slow-entity-resolve-perf', 'slow-brainbench-e2e', 'brainbench', 'test',]);expect(aggregate(unit, 'test-status', 'pull_request', {})).toBe(0);diff --git a/test/scripts/ci-local-rendering.test.ts b/test/scripts/ci-local-rendering.test.tsindex 702d9b041d..bedbda26ac 100644--- a/test/scripts/ci-local-rendering.test.ts+++ b/test/scripts/ci-local-rendering.test.ts@@ -1,8 +1,8 @@import { describe, expect, test } from 'bun:test';import { spawnSync } from 'node:child_process';-import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { dirname, join, resolve } from 'node:path';const source = readFileSync(join(import.meta.dir, '../../scripts/ci-local.sh'), 'utf8');const templateStart = source.indexOf("INNER_CMD=$(cat <<'EOF'");@@ -189,6 +189,10 @@ describe('ci-local execution coverage', () => {const end = source.indexOf('# Pre-flight: postgres host ports');const script = `command() { if [ "$1" = -v ] && [ "\${2:-}" = gitleaks ] && [ "$SCAN_MODE" = missing ]; then return 1; fi; builtin command "$@"; }\n${source.slice(0, end)}`;const log = join(home, 'scans');+ // Keep this branch-routing fixture focused on the scanner result;+ // the real detector/configuration canary runs separately in CI.+ writeFileSync(join(home, 'scripts/test-gitleaks-config.sh'), 'exit 0\n');+ writeFileSync(join(home, 'scripts/scan-worktree-secrets.sh'), 'gitleaks dir . --redact --no-banner\n');const result = spawnSync('bash', ['-c', script, join(home, 'scripts/ci-local.sh'), '--diff'], {encoding: 'utf8', timeout: 5_000,env: { ...process.env, PATH: `${bin}:${process.env.PATH}`, SCAN_MODE: gitleaks, SCAN_LOG: log },@@ -264,3 +268,54 @@ exit "$FAKE_EXIT"});}});++describe('local test configuration through run-e2e', () => {+ for (const disabled of ['1', '0', undefined]) {+ test(`preserves configuration isolation flag ${disabled ?? '(absent)'} through the actual Bun child`, () => {+ const fixture = mkdtempSync(join(tmpdir(), 'gbrain-e2e-env-file-'));+ const repo = resolve(import.meta.dir, '../..');+ try {+ mkdirSync(join(fixture, 'scripts/lib'), { recursive: true });+ mkdirSync(join(fixture, 'test/e2e'), { recursive: true });+ // Copy the real loader into a separate fixture: its import.meta.dir+ // must resolve ONLY our synthetic .env.testing, never the checkout's.+ writeFileSync(join(fixture, 'scripts/run-e2e.sh'), readFileSync(join(repo, 'scripts/run-e2e.sh')));+ writeFileSync(join(fixture, 'scripts/lib/test-env.sh'), 'ensure_pglite_snapshot() { :; }\n');+ writeFileSync(join(fixture, 'test/e2e/helpers.ts'), readFileSync(join(repo, 'test/e2e/helpers.ts')));+ symlinkSync(join(repo, 'src'), join(fixture, 'src'), 'dir');+ symlinkSync(join(repo, 'test/helpers'), join(fixture, 'test/helpers'), 'dir');+ writeFileSync(join(fixture, '.env.testing'), 'E2E_CONFIG_FILE_CANARY=synthetic-fixture-loaded\n');+ const expected = {+ disabled: disabled ?? null,+ loaded: disabled === '1' ? null : 'synthetic-fixture-loaded',+ operatorOverride: null,+ };+ writeFileSync(join(fixture, 'test/e2e/config-file-probe.test.ts'), `+import { expect, test } from 'bun:test';+import './helpers.ts';+test('configuration file respects the parent isolation policy', () => {+ expect({+ disabled: process.env.GBRAIN_CI_DISABLE_TEST_ENV_FILE ?? null,+ loaded: process.env.E2E_CONFIG_FILE_CANARY ?? null,+ operatorOverride: process.env.GBRAIN_SOURCE ?? null,+ }).toEqual(${JSON.stringify(expected)});+});+`);+ const env: Record<string, string | undefined> = {+ ...process.env, HOME: fixture, PATH: `${dirname(process.execPath)}:${process.env.PATH}`,+ SHARD: '', COVERAGE_DIR: '', DATABASE_URL: '', GBRAIN_DATABASE_URL: '',+ GBRAIN_CI_REQUIRE_PGBOUNCER: '0', GBRAIN_SOURCE: 'ambient-must-be-removed',+ GBRAIN_CI_DISABLE_TEST_ENV_FILE: disabled,+ };+ delete env.E2E_CONFIG_FILE_CANARY;+ const result = spawnSync('bash', [join(fixture, 'scripts/run-e2e.sh'), 'test/e2e/config-file-probe.test.ts'], {+ cwd: fixture, encoding: 'utf8', timeout: 20_000, env,+ });+ expect(result.status, result.stdout + result.stderr).toBe(0);+ expect(result.stdout).toContain('1 pass');+ } finally {+ rmSync(fixture, { recursive: true, force: true });+ }+ }, 25_000);+ }+});diff --git a/test/scripts/e2e-wiring.test.ts b/test/scripts/e2e-wiring.test.tsindex 1260941edd..a3431b2dd8 100644--- a/test/scripts/e2e-wiring.test.ts+++ b/test/scripts/e2e-wiring.test.ts@@ -127,7 +127,7 @@ describe('selected-e2e job wiring', () => {* baseline shrinks (a file gets mapped or deleted), lower this constant IN* THE SAME COMMIT (the module-size ratchet's no-stale-slack convention).*/-const BASELINE_SEEDED_LENGTH = 153;+const BASELINE_SEEDED_LENGTH = 150;describe('e2e file claim ratchet', () => {const mapped = new Set(Object.values(E2E_TEST_MAP).flat());diff --git a/test/serve-http-admin-route-guard.test.ts b/test/serve-http-admin-route-guard.test.tsindex d889d2936c..844c4ca0b0 100644--- a/test/serve-http-admin-route-guard.test.ts+++ b/test/serve-http-admin-route-guard.test.ts@@ -136,7 +136,7 @@ const ALLOWLIST: AllowlistEntry[] = [// The scan, run once against the real file// ----------------------------------------------------------------------------const source = readFileSync(SRC_PATH, 'utf-8');+const source = readFileSync(SRC_PATH, 'utf-8') + '\n' + readFileSync(join(import.meta.dir, '..', 'src', 'commands', 'serve-http-oauth.ts'), 'utf-8');const all = extractRegistrations(source);const admin = adminRoutes(all);const guarded = admin.filter(r => r.guarded);@@ -153,6 +153,8 @@ describe('serve-http admin route guard (structural)', () => {['get', '/admin/api/stats'],['get', '/admin/events'],['post', '/admin/api/revoke-client'],+ ['get', '/admin/api/oauth-requests/:id'],+ ['post', '/admin/api/oauth-requests/:id'],] as const) {const hit = admin.find(r => r.method === method && r.path === path);expect(hit, `expected app.${method}('${path}') to be found by the scan`).toBeDefined();diff --git a/test/serve-http-metrics.test.ts b/test/serve-http-metrics.test.tsindex e34529b6e0..c457a59164 100644--- a/test/serve-http-metrics.test.ts+++ b/test/serve-http-metrics.test.ts@@ -145,7 +145,7 @@ describe('serve-http.ts wiring (structural — the two defects of the original Ptest('tracking middleware is mounted before the first route registration', () => {const mw = src.indexOf('metricsTrackingMiddleware(');- const firstTokenRoute = src.indexOf("app.post('/token'");+ const firstTokenRoute = src.indexOf('mountConfidentialOAuth(app,');const authRouterMount = src.indexOf('app.use(authRouter)');expect(mw).toBeGreaterThan(-1);expect(firstTokenRoute).toBeGreaterThan(-1);diff --git a/test/serve-sync-runner.serial.test.ts b/test/serve-sync-runner.serial.test.tsindex 3bf7e2c12a..d45cece4f2 100644--- a/test/serve-sync-runner.serial.test.ts+++ b/test/serve-sync-runner.serial.test.ts@@ -22,6 +22,7 @@ import { execSync } from 'child_process';import { tmpdir } from 'os';import { join } from 'path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { withSourceFilesystemLock } from '../src/core/minions/source-filesystem.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import {__deferredEmbedsPendingForTests,@@ -163,6 +164,10 @@ describe('serve-sync-runner delegated jobs', () => {expect(s.state).toBe('done');expect(s.result!.status).toBe('partial');expect(['timeout', 'pull_timeout', 'stall_timeout']).toContain(s.result!.reason!);+ expect(s.result!.filesImported).toBe(0);+ expect(await engine.getPage('topics/alpha')).toBeNull();+ const [source] = await engine.executeRaw<{ last_commit: string | null }>("SELECT last_commit FROM sources WHERE id = 'default'");+ expect(source.last_commit).toBeNull();// Resume: a fresh delegated run completes the remainder.const second = startDelegatedSync(engine, { noPull: true, timeoutSeconds: 120, sourceId: 'default' }, 'token-resume');@@ -173,6 +178,25 @@ describe('serve-sync-runner delegated jobs', () => {expect(await engine.getPage('topics/beta')).not.toBeNull();}, 60_000);+ test('abort while waiting for the filesystem lock remains a zero-work partial', async () => {+ let release!: () => void, entered!: () => void;+ const acquired = new Promise<void>(resolve => { entered = resolve; });+ const held = new Promise<void>(resolve => { release = resolve; });+ const writer = withSourceFilesystemLock(engine, repoPath, async () => { entered(); await held; });+ await acquired;+ try {+ const start = startDelegatedSync(engine, { noPull: true, timeoutSeconds: 120, sourceId: 'default' }, 'token-lock-wait');+ await new Promise(resolve => setTimeout(resolve, 100));+ expect(getDelegatedSyncStatus(start.jobId!).state).toBe('running');+ expect(abortDelegatedSync(start.jobId!).ok).toBe(true);+ const status = await waitForTerminal(start.jobId!);+ expect(status.state).toBe('done');+ expect(status.result!.status).toBe('partial');+ expect(status.result!.filesImported).toBe(0);+ expect(await engine.getPage('topics/alpha')).toBeNull();+ } finally { release(); await writer; }+ }, 60_000);+test('unknown jobId: status and abort answer unknown_job (serve restarted mid-sync)', () => {expect(getDelegatedSyncStatus('nope')).toEqual({ ok: false, protocol: 2, error: 'unknown_job' });expect(abortDelegatedSync('nope')).toEqual({ ok: false, protocol: 2, error: 'unknown_job' });diff --git a/test/source-health.test.ts b/test/source-health.test.tsindex 9e66baf9c4..b6f59b1759 100644--- a/test/source-health.test.ts+++ b/test/source-health.test.ts@@ -324,11 +324,11 @@ describe('computeAllSourceMetrics', () => {// 2 queued + 1 active embed-backfill for default; a non-backfill 'sync'// job must NOT inflate the backfill counts (only the generic queue_depth).await engine.executeRaw(- `INSERT INTO minion_jobs (name, status, data) VALUES- ('embed-backfill', 'waiting', '{"sourceId":"default"}'::jsonb),- ('embed-backfill', 'waiting', '{"sourceId":"default"}'::jsonb),- ('embed-backfill', 'active', '{"sourceId":"default"}'::jsonb),- ('sync', 'waiting', '{"sourceId":"default"}'::jsonb)`,+ `INSERT INTO minion_jobs (submission_authority, name, status, data) VALUES+ ('{"version":1,"kind":"application"}'::jsonb, 'embed-backfill', 'waiting', '{"sourceId":"default"}'::jsonb),+ ('{"version":1,"kind":"application"}'::jsonb, 'embed-backfill', 'waiting', '{"sourceId":"default"}'::jsonb),+ ('{"version":1,"kind":"application"}'::jsonb, 'embed-backfill', 'active', '{"sourceId":"default"}'::jsonb),+ ('{"version":1,"kind":"application"}'::jsonb, 'sync', 'waiting', '{"sourceId":"default"}'::jsonb)`,);const sources = await loadAllSources(engine);const dflt = (await computeAllSourceMetrics(engine, sources)).find((m) => m.source_id === 'default')!;diff --git a/test/source-scope-resolver.test.ts b/test/source-scope-resolver.test.tsindex 765c548848..0fd6a65e27 100644--- a/test/source-scope-resolver.test.ts+++ b/test/source-scope-resolver.test.ts@@ -94,10 +94,8 @@ describe('resolveRequestedScope — explicit source_id', () => {expect(resolveRequestedScope(ctxOf({ remote: false }), 'anything')).toEqual({ sourceId: 'anything' });});- test('remote with no federated grant array preserves legacy explicit source selection', () => {- // allowedSources undefined → no federated restriction to enforce; the scalar- // sourceId path governs. An explicit [] is a distinct restricted grant.- expect(resolveRequestedScope(ctxOf({ remote: true }), 'z')).toEqual({ sourceId: 'z' });+ test('remote scalar grants reject explicit sources outside their floor', () => {+ expect(() => resolveRequestedScope(ctxOf({ remote: true }), 'z')).toThrow(OperationError);});test('empty federated grant cannot escape its scalar source through an explicit request', () => {diff --git a/test/subagent-handler.test.ts b/test/subagent-handler.test.tsindex 5d664b6935..14369aeb1b 100644--- a/test/subagent-handler.test.ts+++ b/test/subagent-handler.test.ts@@ -125,6 +125,21 @@ function makeThrowingTool(name = 'broken'): ToolDef {// ── Tests ───────────────────────────────────────────────────describe('subagent handler happy path', () => {+ test('an explicit empty binding exposes no tools to the agent loop', async () => {+ const client = new FakeMessagesClient([{ content: [{ type: 'text', text: 'done' }] as any }]);+ const handler = makeSubagentHandler({ engine, client, toolRegistry: [makeEchoTool('echo')] });+ await handler(await makeCtx({ prompt: 'finish', allowed_tools: [] }));+ expect(client.calls[0]!.tools ?? []).toEqual([]);+ });++ test('malformed bindings fail before a model request', async () => {+ for (const allowed_tools of [null, 'echo', [42], ['']]) {+ const client = new FakeMessagesClient([]);+ const handler = makeSubagentHandler({ engine, client, toolRegistry: [makeEchoTool('echo')] });+ await expect(handler(await makeCtx({ prompt: 'finish', allowed_tools }))).rejects.toThrow(/allowed_tools/);+ expect(client.calls).toHaveLength(0);+ }+ });test('no-tool end_turn: returns text response + persists user + assistant rows', async () => {const client = new FakeMessagesClient([{ content: [{ type: 'text', text: 'hello world' }] as any, stop_reason: 'end_turn' },@@ -1034,7 +1049,7 @@ describe('oneshot mode dispatch (#4216)', () => {expect(oneshotCalls).toBe(0);});- test('read-only allowed_tools + mode oneshot → no write escalation (falls back tool-less)', async () => {+ test.each([['echo'], []])('oneshot tool ceiling %j prevents programmatic write escalation', async (...allowedTools) => {// A submitter that scoped its job to read-only tools must not gain// brain_put_page by flipping mode: oneshot — the oneshot registry runs// through the SAME filterAllowedTools as the loop registry.@@ -1048,7 +1063,7 @@ describe('oneshot mode dispatch (#4216)', () => {});const ctx = await makeCtx({prompt: 'synthesize', mode: 'oneshot',- allowed_tools: ['echo'],+ allowed_tools: allowedTools,allowed_slug_prefixes: PREFIXES, oneshot_slug_suffix: SUFFIX,});const result = await handler(ctx);@@ -1060,6 +1075,7 @@ describe('oneshot mode dispatch (#4216)', () => {[ctx.id],);expect(rows[0]!.n).toBe(0);+ if (allowedTools.length === 0) expect(client.calls[0]!.tools ?? []).toEqual([]);});test('crash-replayed TRUNCATED terminal turn recovers max_tokens, not end_turn (F1)', async () => {diff --git a/test/subagent-v1-v2-shim.test.ts b/test/subagent-v1-v2-shim.test.tsindex 370d11fa84..63470b33c5 100644--- a/test/subagent-v1-v2-shim.test.ts+++ b/test/subagent-v1-v2-shim.test.ts@@ -201,8 +201,8 @@ describe('loadPriorToolsV2 (D5 — synthesizes stable keys for v1 rows)', () =>it('uses gbrain_tool_use_id as stable key for v2 rows', async () => {// Seed a minion_jobs row + v2 tool execution.const job = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at)- VALUES ('subagent', 'active', '{}'::jsonb, 'default', 0, now())+ `INSERT INTO minion_jobs (submission_authority, name, status, data, queue, priority, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'active', '{}'::jsonb, 'default', 0, now())RETURNING id`,);const jobId = job[0].id;@@ -224,8 +224,8 @@ describe('loadPriorToolsV2 (D5 — synthesizes stable keys for v1 rows)', () =>it('synthesizes a legacy-prefixed stable key for v1 rows (ordinal NULL, gbrain_tool_use_id NULL)', async () => {const job = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at)- VALUES ('subagent', 'active', '{}'::jsonb, 'default', 0, now())+ `INSERT INTO minion_jobs (submission_authority, name, status, data, queue, priority, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'active', '{}'::jsonb, 'default', 0, now())RETURNING id`,);const jobId = job[0].id;@@ -243,8 +243,8 @@ describe('loadPriorToolsV2 (D5 — synthesizes stable keys for v1 rows)', () =>it('preserves status + error text for failed legacy rows', async () => {const job = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at)- VALUES ('subagent', 'active', '{}'::jsonb, 'default', 0, now())+ `INSERT INTO minion_jobs (submission_authority, name, status, data, queue, priority, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'active', '{}'::jsonb, 'default', 0, now())RETURNING id`,);const jobId = job[0].id;@@ -265,8 +265,8 @@ describe('loadPriorToolsV2 (D5 — synthesizes stable keys for v1 rows)', () =>// gateway path). loadPriorToolsV2 must surface both keyed correctly// so the reconciler's Map<stableKey, outcome> sees both.const job = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at)- VALUES ('subagent', 'active', '{}'::jsonb, 'default', 0, now())+ `INSERT INTO minion_jobs (submission_authority, name, status, data, queue, priority, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'active', '{}'::jsonb, 'default', 0, now())RETURNING id`,);const jobId = job[0].id;@@ -296,8 +296,8 @@ describe('loadPriorToolsV2 (D5 — synthesizes stable keys for v1 rows)', () =>it('ordering: rows return ORDER BY message_idx, ordinal, id (stable for replay)', async () => {const job = await engine.executeRaw<{ id: number }>(- `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at)- VALUES ('subagent', 'active', '{}'::jsonb, 'default', 0, now())+ `INSERT INTO minion_jobs (submission_authority, name, status, data, queue, priority, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'active', '{}'::jsonb, 'default', 0, now())RETURNING id`,);const jobId = job[0].id;diff --git a/test/submit-agent.test.ts b/test/submit-agent.test.tsindex 46ffc48c01..222f4a05d6 100644--- a/test/submit-agent.test.ts+++ b/test/submit-agent.test.ts@@ -3,6 +3,9 @@ import { mkdtempSync, rmSync } from 'node:fs';import { join } from 'node:path';import { tmpdir } from 'node:os';import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import { prepareRemoteAgent } from '../src/core/minions/submission-authority.ts';+import { LATEST_VERSION } from '../src/core/migrate.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import { withEnv } from './helpers/with-env.ts';import { operationsByName } from '../src/core/operations.ts';@@ -14,7 +17,7 @@ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); aafterAll(async () => { await engine.disconnect(); });beforeEach(async () => {await resetPgliteState(engine);- await engine.setConfig('version', '147');+ await engine.setConfig('version', String(LATEST_VERSION));auditDir = mkdtempSync(join(tmpdir(), 'gbrain-delegation-test-'));});afterEach(() => rmSync(auditDir, { recursive: true, force: true }));@@ -31,7 +34,7 @@ async function seed(opts: { tools?: string[]; prefixes?: string[] | null; cap?:}function ctx(extra: Record<string, unknown> = {}): any {return { engine, config: {}, logger: console, remote: true, dryRun: false,- auth: { clientId: 'client', scopes: ['agent'], sourceId: 'default' }, ...extra };+ auth: { clientId: 'client', principal: { kind: 'oauth_client', id: 'client' }, scopes: ['agent'], sourceId: 'default' }, ...extra };}async function submit(params: Record<string, unknown> = {}, context = ctx()): Promise<any> {return withEnv({ GBRAIN_AUDIT_DIR: auditDir }, () => operationsByName.submit_agent.handler(context, { prompt: 'read the fixture', ...params }));@@ -44,6 +47,14 @@ describe('delegation admission and submitted permission ceiling', () => {await expect(submit({}, ctx({ auth: undefined }))).rejects.toThrow('OAuth client');await expect(submit({}, ctx({ remote: false }))).rejects.toThrow('local CLI');});+ it('requires the verified principal for both preview and enqueue', async () => {+ await seed();+ for (const dryRun of [false, true]) {+ for (const principal of [undefined, { kind: 'legacy_token', id: 'client' }, { kind: 'oauth_client', id: 'another-client' }]) {+ await expect(submit({}, ctx({ dryRun, auth: { ...ctx().auth, principal } }))).rejects.toThrow('verified OAuth principal');+ }+ }+ });it('refuses unknown and revoked clients', async () => {await expect(submit()).rejects.toThrow('No OAuth client found');await seed();@@ -54,8 +65,11 @@ describe('delegation admission and submitted permission ceiling', () => {await expect(seed({ tools: [] })).rejects.toThrow('oauth_clients_complete_agent_grant');});it('rejects removed or unknown registry tools', async () => {- await seed({ tools: ['invented_tool'] });- await expect(submit()).rejects.toThrow('delegated_tools_unavailable');+ for (const removed of ['invented_tool', 'file_list', 'file_url']) {+ await engine.executeRaw('DELETE FROM oauth_clients');+ await seed({ tools: [removed] });+ await expect(submit()).rejects.toThrow('delegated_tools_unavailable');+ }});it('preview validates source and model without inserting work', async () => {await seed();@@ -121,11 +135,21 @@ describe('delegation admission and submitted permission ceiling', () => {expect(jobs).toHaveLength(2);expect(jobs[0].data.__delegation_grant.tools).toEqual(['get_page','put_page']);});+ it('durable remote authority enforces the client slot without a separate identity option', async () => {+ await seed();+ const snapshot = submissionSnapshot(await currentDelegationGrant(engine, 'client'), {});+ const data = { prompt: 'fixture', allowed_tools: snapshot.tools, allowed_slug_prefixes: snapshot.slugPrefixes,+ source_id: snapshot.sourceId, __owner_client_id: snapshot.clientId, __delegation_grant: snapshot };+ const authority = await prepareRemoteAgent(ctx(), data);+ const queue = new MinionQueue(engine);+ await queue.add('subagent', data, {}, { allowProtectedSubmit: true, submissionAuthority: authority });+ await expect(queue.add('subagent', data, {}, { allowProtectedSubmit: true, submissionAuthority: authority })).rejects.toThrow('quota');+ });it('counts delayed and paused jobs against the same owner cap', async () => {await seed();const first = await submit();for (const status of ['delayed','paused','waiting-children','active']) {- await engine.executeRaw('UPDATE minion_jobs SET status=$1 WHERE id=$2', [status, first.id]);+ await engine.executeRaw("UPDATE minion_jobs SET status=$1, claim_generation=claim_generation+CASE WHEN $1='active' THEN 1 ELSE 0 END WHERE id=$2", [status, first.id]);await expect(submit({ prompt: 'another request' })).rejects.toThrow();}});diff --git a/test/submit-queue-state.test.ts b/test/submit-queue-state.test.tsindex fee415800b..4c10c9867b 100644--- a/test/submit-queue-state.test.ts+++ b/test/submit-queue-state.test.ts@@ -51,8 +51,8 @@ async function seedJob(opts: {lockUntilSql?: string;} = {}): Promise<void> {await engine.executeRaw(- `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at, lock_until)- VALUES ($1, $2, '{}'::jsonb, $3, 0, ${opts.createdAtSql ?? 'now()'}, ${opts.lockUntilSql ?? 'NULL'})`,+ `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at, lock_until, submission_authority)+ VALUES ($1, $2, '{}'::jsonb, $3, 0, ${opts.createdAtSql ?? 'now()'}, ${opts.lockUntilSql ?? 'NULL'}, '{"version":1,"kind":"application"}'::jsonb)`,[opts.name ?? 'embed', opts.status ?? 'waiting', opts.queue ?? 'default'],);}@@ -144,7 +144,7 @@ describe('submit_job wiring — probe never blocks a successful enqueue', () =>config: {},logger: console,dryRun: false,- remote: true,+ remote: false,};}diff --git a/test/supervisor-wedge.test.ts b/test/supervisor-wedge.test.tsindex ce892df167..7abe8f8293 100644--- a/test/supervisor-wedge.test.ts+++ b/test/supervisor-wedge.test.ts@@ -199,8 +199,8 @@ async function seed(extra: { lockUntilSql?: string; delayUntilSql?: string; updatedAtSql?: string } = {},): Promise<void> {await engine.executeRaw(- `INSERT INTO minion_jobs (name, queue, status, lock_until, delay_until, updated_at)- VALUES ($1, $2, $3, ${extra.lockUntilSql ?? 'NULL'}, ${extra.delayUntilSql ?? 'NULL'}, ${extra.updatedAtSql ?? 'now()'})`,+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, lock_until, delay_until, updated_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, $1, $2, $3, ${extra.lockUntilSql ?? 'NULL'}, ${extra.delayUntilSql ?? 'NULL'}, ${extra.updatedAtSql ?? 'now()'})`,[name, queue, status],);}diff --git a/test/trust-boundary-contract.test.ts b/test/trust-boundary-contract.test.tsindex f66b20a10f..beff26bb2b 100644--- a/test/trust-boundary-contract.test.ts+++ b/test/trust-boundary-contract.test.ts@@ -73,18 +73,20 @@ describe('F7b — trust-boundary contract fail-closed semantics', () => {).rejects.not.toMatchObject({ code: 'permission_denied' });});- test('non-protected job names always allowed regardless of remote', async () => {- // 'default-noop' is not in PROTECTED_JOB_NAMES. The protected-name guard- // skips entirely, so we again get a downstream stub-engine error.+ test('arbitrary job names require a strictly local caller', async () => {+ // Remote generic jobs must also belong to the explicit four-kind allowlist.const cases: OperationContext[] = [castUndefinedRemoteCtx(),{ ...castUndefinedRemoteCtx(), remote: true } as OperationContext,- { ...castUndefinedRemoteCtx(), remote: false } as OperationContext,];for (const ctx of cases) {await expect(submit_job.handler(ctx, { name: 'noop-job', data: {} })- ).rejects.not.toMatchObject({ code: 'permission_denied' });+ ).rejects.toMatchObject({ code: 'permission_denied' });}+ // A trusted local caller still passes admission and reaches the stub engine.+ await expect(submit_job.handler({ ...castUndefinedRemoteCtx(), remote: false }, {+ name: 'noop-job', data: {},+ })).rejects.not.toMatchObject({ code: 'permission_denied' });});});diff --git a/test/truthful-catalog.e2e-lite.test.ts b/test/truthful-catalog.e2e-lite.test.tsindex 7ece516e82..1a9fe3ce5f 100644--- a/test/truthful-catalog.e2e-lite.test.ts+++ b/test/truthful-catalog.e2e-lite.test.ts@@ -87,6 +87,9 @@ const WALL_CLOCK_BUDGET_MS = 3 * 60 * 1000;const SKILL_FIXTURE = join(import.meta.dir, 'fixtures', 'skill-catalog', 'skills');const BOUND_PREFIX = 'e2e-bound/';const LEGACY_TOKEN = 'e5-truthful-catalog-legacy-token';+// Legacy tokens with no explicit scope column retain read/write/admin. The+// paid agent lane is a separate grant; admin does not imply agent.+const LEGACY_DEFAULT_SCOPES = ['read', 'write', 'admin'];/*** Hermetic env pins, applied via withEnv (the repo's R1-compliant pattern):@@ -173,7 +176,7 @@ async function setGates(on: boolean): Promise<void> {interface Cell {label: string;- /** OAuth token scopes; null = legacy bearer semantics (no scope checks). */+ /** Explicit token scopes; null = the legacy read/write/admin defaults. */scopes: string[] | null;surface: McpSurface;gatesOn: boolean;@@ -181,10 +184,12 @@ interface Cell {}function cellAuth(cell: Cell): AuthInfo {+ const clientId = `e5-${cell.label}`;return {token: 'e5-token',- clientId: `e5-${cell.label}`,- scopes: cell.scopes ?? [],+ clientId,+ principal: { kind: 'oauth_client', id: clientId },+ scopes: cell.scopes ?? LEGACY_DEFAULT_SCOPES,...(cell.bound ? { boundSlugPrefixes: [BOUND_PREFIX] } : {}),};}@@ -198,15 +203,14 @@ function cellAuth(cell: Cell): AuthInfo {*/function expectedVisibleSet(cell: Cell): Set<string> {const out = new Set<string>();+ const scopes = cell.scopes ?? LEGACY_DEFAULT_SCOPES;for (const op of operations) {if (op.localOnly) continue; // D7: network transportif (cell.surface === 'verbs' && op.verb !== true) continue; // frozen verb surfaceif (cell.surface === 'starter' && !STARTER_OPS.has(op.name)) continue;- if (cell.scopes !== null) {- const scopeOk = hasScope(cell.scopes, op.scope ?? 'read')- || (op.agentCallable === true && hasScope(cell.scopes, 'agent')); // FOV-4- if (!scopeOk) continue;- }+ const scopeOk = hasScope(scopes, op.scope ?? 'read')+ || (op.agentCallable === true && hasScope(scopes, 'agent')); // FOV-4+ if (!scopeOk) continue;if (cell.bound && !opAllowedForBoundClient({ boundSlugPrefixes: [BOUND_PREFIX] }, op)) continue;if (op.publishGateKey && !cell.gatesOn) continue; // WP1 honest catalogout.add(op.name);@@ -377,6 +381,15 @@ describe('E5 truthful catalog — legacy bearer transport (real HTTP, PGLite)',for (const localOnly of ['file_list', 'file_upload', 'file_url', 'sync_brain']) {expect(listed.has(localOnly)).toBe(false);}+ for (const [name, args] of [+ ['submit_agent', { prompt: 'Synthetic scope probe' }],+ ['get_agent_job', { id: 1 }],+ ] as const) {+ expect(listed.has(name)).toBe(false);+ const denied = await legacyToolCall(name, args);+ expect(denied.envelope?.error).toBe('permission_denied');+ expect(denied.envelope?.message).toBe('Tool requires agent scope');+ }});e5test('full probe sweep: every listed tool dies at validation, never at a list-level denial', async () => {diff --git a/test/url-safety.test.ts b/test/url-safety.test.tsnew file mode 100644index 0000000000..0ed1903ae5--- /dev/null+++ b/test/url-safety.test.ts@@ -0,0 +1,67 @@+import { afterEach, describe, expect, test } from 'bun:test';+import { isInternalUrl, isPrivateIpv4 } from '../src/core/url-safety.ts';+import { __setDnsLookupForTests, validateAndResolveUrl } from '../src/core/ssrf-validate.ts';++// IANA special-purpose registries, checked September 2026. These tests never dial a target.+const NONPUBLIC_V4 = [+ '0.0.0.0', '10.0.0.1', '100.64.0.1', '100.127.255.255', '127.0.0.1',+ '169.254.169.254', '172.16.0.1', '172.31.255.255', '192.0.0.0', '192.0.0.8',+ '192.0.0.11', '192.0.0.170', '192.0.0.171', '192.0.2.1', '192.88.99.1',+ '192.88.99.2', '192.168.0.1', '198.18.0.1', '198.19.255.255', '198.51.100.1',+ '203.0.113.1', '224.0.0.1', '239.255.255.255', '240.0.0.1', '255.255.255.255',+];+const PUBLIC_V4 = [+ '8.8.8.8', '1.1.1.1', '100.63.255.255', '100.128.0.0', '172.15.255.255',+ '172.32.0.0', '192.0.0.9', '192.0.0.10', '192.31.196.1', '192.52.193.1',+ '192.175.48.1', '198.17.255.255', '198.20.0.0', '198.51.99.255', '203.0.114.1',+ '223.255.255.254',+];+const NONPUBLIC_V6 = [+ '::', '::1', '::127.0.0.1', '64:ff9b:1::1', '100::1', '100:0:0:1::1',+ '2001::1', '2001:1::4', '2001:2::1', '2001:10::1', '2001:1f::1', '2001:100::1',+ '2001:db8::1', '2002:7f00:1::1', '3fff::1', '3fff:fff:ffff::1', '5f00::1',+ 'fc00::1', 'fdff:ffff::1', 'fe80::1', 'febf:ffff::1', 'fec0::1', 'feff:ffff::1',+ 'ff00::1', 'ff02::1', 'ffff:ffff::1',+];+const PUBLIC_V6 = [+ '2606:4700:4700::1111', '2001:4860:4860::8888', '2606:2800:220:1::1',+ '2001:1::1', '2001:1::2', '2001:1::3', '2001:3::1', '2001:4:112::1',+ '2001:20::1', '2001:2f:ffff::1', '2001:30::1', '2001:3f:ffff::1',+ '2001:200::1', '2620:4f:8000::1', '3fff:1000::1',+];++afterEach(() => __setDnsLookupForTests(undefined));++describe('shared public-address boundary', () => {+ for (const [blocked, addresses] of [[true, NONPUBLIC_V4], [false, PUBLIC_V4]] as const) {+ test.each(addresses)('IPv4 and mapped/translated forms preserve classification: %s', address => {+ expect(isPrivateIpv4(address.split('.').map(Number))).toBe(blocked);+ expect(isInternalUrl(`http://${address}/`)).toBe(blocked);+ // WHATWG normalization converts dotted mapped tails to hex; both inputs must agree.+ const mapped = new URL(`http://[::ffff:${address}]/`).href;+ expect(isInternalUrl(`http://[::ffff:${address}]/`)).toBe(blocked);+ expect(isInternalUrl(mapped)).toBe(blocked);+ const octets = address.split('.').map(Number);+ const tail = `${((octets[0] << 8) | octets[1]).toString(16)}:${((octets[2] << 8) | octets[3]).toString(16)}`;+ expect(isInternalUrl(`http://[64:ff9b::${tail}]/`)).toBe(blocked);+ });+ }+ test.each(NONPUBLIC_V6)('rejects nonpublic IPv6 %s', address => {+ expect(isInternalUrl(`http://[${address}]/`)).toBe(true);+ });+ test.each(PUBLIC_V6)('preserves public IPv6 %s', address => {+ expect(isInternalUrl(`http://[${address}]/`)).toBe(false);+ });+ test.each([...NONPUBLIC_V4, ...NONPUBLIC_V6])('rejects an otherwise-public DNS answer set containing %s', async address => {+ __setDnsLookupForTests((async () => [{ address: '8.8.8.8', family: 4 }, { address, family: address.includes(':') ? 6 : 4 }]) as any);+ await expect(validateAndResolveUrl('https://synthetic.example/')).rejects.toMatchObject({ code: 'DNS_RESOLVED_INTERNAL' });+ });+ test('malformed octet arrays fail closed', () => {+ for (const octets of [[], [8, 8, 8], [8, 8, 8, -1], [8, 8, 8, 256], [8, 8, 8, 1.5], [8, 8, 8, NaN]]) {+ expect(isPrivateIpv4(octets)).toBe(true);+ }+ });+ test.each(['localhost.', 'nested.localhost.', 'metadata.google.internal.', 'metadata.'])('canonical trailing-dot hostname is blocked: %s', hostname => {+ expect(isInternalUrl(`http://${hostname}/`)).toBe(true);+ });+});diff --git a/test/worker-conn-resilience-1720.test.ts b/test/worker-conn-resilience-1720.test.tsindex 594ef35418..e30db6de18 100644--- a/test/worker-conn-resilience-1720.test.ts+++ b/test/worker-conn-resilience-1720.test.ts@@ -36,6 +36,13 @@ function makeEngine(counter: { reconnects: number }): BrainEngine {return {kind: 'postgres',reconnect: async () => { counter.reconnects += 1; },+ executeRaw: async (sql: string) => {+ // These reconnect fixtures contain no unresolved legacy work. Keep the+ // real startup authority check, and reject unrelated unexpected queries.+ if (sql.includes('SELECT id, submission_authority FROM minion_jobs') &&+ sql.includes('submission_authority IS DISTINCT FROM')) return [];+ throw new Error('Unexpected SQL in worker reconnect fixture');+ },} as unknown as BrainEngine;}@@ -121,6 +128,7 @@ describe('failJob failure-recording resilience (#1720 gap 2)', () => {name: 'explode',queue: 'default',data: {},+ submission_authority: { version: 1, kind: 'application' },status: 'active',attempts_made: 2,attempts_started: 3,diff --git a/test/worker-promote-reconnect.test.ts b/test/worker-promote-reconnect.test.tsindex 3090bdd120..1387378486 100644--- a/test/worker-promote-reconnect.test.ts+++ b/test/worker-promote-reconnect.test.ts@@ -5,6 +5,13 @@ import type { BrainEngine } from '../src/core/engine.ts';function makeEngineWithReconnect(counter: { calls: number }, events: string[]): BrainEngine & { reconnect: () => Promise<void> } {return {kind: 'postgres',+ executeRaw: async (sql: string) => {+ // Startup sees no unresolved legacy work; promotion recovery below is+ // still exercised by the scripted queue error, before the next claim.+ if (sql.includes('SELECT id, submission_authority FROM minion_jobs') &&+ sql.includes('submission_authority IS DISTINCT FROM')) return [];+ throw new Error('Unexpected SQL in worker promotion fixture');+ },reconnect: async () => {counter.calls += 1;events.push('reconnect');