Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(mcp): opt-in request-log retention with exact lifetime totals
garrytanf3fc3f433ef2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8cadb056cf..71083c080d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,24 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**You can now cap the MCP request log's size without losing the dashboard's totals or the audit trail.** `gbrain serve --http` writes one `mcp_request_log` row for every call, `tools/list` included, and nothing ever deleted them, so a busy brain's log grew without limit. Retention is opt-in and off by default, so nothing changes until you run `gbrain config set cycle.purge.mcp_request_log_retention_days 90` (30 to 3650 days; 1 to 29 is refused because the built-in usage reports look back 30 days). Then the nightly cycle deletes request rows older than the window, and a PGLite brain held by a live `gbrain serve` prunes itself once an hour in short batches. The `surface_change` and `memory_setting_change` audit rows are never deleted, and each pruned row is counted per client first, so the Agents page's total requests and last-used times stay exact. A usage report whose window reaches back past deleted history says so: `gbrain auth clients --usage` names the `--days` that is complete, the advisor skips its "starter op unused for 90 days" half, and `scripts/derive-starter-ops.ts` refuses. Deleted request detail cannot be restored. `gbrain doctor` reports the log's size and suggests turning retention on once it passes about 1M rows or 1 GiB, asking you first. Proposed and first implemented by @lubosxyz (#6770).++### Itemized changes++- `src/core/mcp-request-log-retention.ts` (new): `pruneMcpRequestLog` deletes rows past the cutoff in batches of 2,000 (at most 200 per run, 400,000 rows), each batch one statement that picks the oldest rows in `created_at` order with `FOR UPDATE SKIP LOCKED`, skips `AUDIT_LOG_OPERATIONS`, deletes them and adds them to `mcp_request_log_rollup`, so a failed tally deletes nothing and two prunes at once never double-count. `runMcpLogRetention` reads `cycle.purge.mcp_request_log_retention_days` and records each run under `cycle.purge.mcp_request_log_last_prune`. `startMcpLogPruneTicker` is the hourly PGLite prune with a 3-second budget that yields between batches. `lifetimeUsage` adds kept rows and the tally.+- Migration v297 adds `mcp_request_log_rollup` (`token_name`, `requests`, `last_used_at`, `pruned_through`) with RLS on. It copies and deletes nothing.+- `src/core/cycle.ts`: the `purge` phase runs the prune when retention is set and reports `purged_mcp_request_log_count` when it removed rows.+- `src/commands/serve.ts`: both `gbrain serve` and `gbrain serve --http` start the hourly prune on PGLite, paused while a delegated sync runs.+- `src/core/mcp-usage.ts`: `readClientOpUsageWithCoverage` returns each window's coverage (`truncated`, `covered_days`, `pruned_before`) and `truncatedWindowNote` the fix and recovery sentence; `AUDIT_LOG_OPERATIONS` names the never-pruned rows. `readClientOpUsage` is unchanged.+- `gbrain auth clients --usage` prints `window truncated: ...` with the complete `--days`; `--json` adds `window_truncated`, `covered_days`, `pruned_before` and `window_note`. `scripts/derive-starter-ops.ts` exits 1 with the note on stderr for a truncated window. The advisor's `mcp-client-fit` drift finding skips its unused-member half and says why.+- Admin dashboard: `/admin/api/agents` totals and OAuth last-used read the log plus the tally; `/admin/api/requests` adds `retention_days` and `pruned_before`, which the Request Log page shows.+- `gbrain config set cycle.purge.mcp_request_log_retention_days` refuses values other than 0, `off` or a whole number from 30 to 3650, and writes nothing.+- Doctor `mcp_request_log_retention` (new, ops): log rows and size; past about 1M rows or 1 GiB with retention off it warns, and its fix asks the user before turning retention on and is never a `doctor --remediate` step. With retention on it reports the last prune and the pruned-before date, and warns when no prune ran for 48 hours.+- Docs: `docs/mcp/ADMIN.md` ("Request log retention"), `docs/operations/mcp-surface-runbook.md`, `docs/architecture/system-of-record.md`.+- Tests: `test/mcp-request-log-retention.test.ts` (PGLite and Postgres, repo-less: off by default, every row class tallied exactly, audit rows kept, capped runs resume, a failed tally deletes nothing, a missing tally table skips, `config set` refusals, the PGLite ticker under a live `serve --http`, two prunes at once on Postgres), `test/serve-http-admin-request-log-retention.test.ts`, `test/doctor-mcp-request-log-retention.test.ts`, `test/mcp-request-log-retention-cli.serial.test.ts` (`auth clients` and `derive-starter-ops` through the real entry points), and new cases in `test/mcp-usage.test.ts` and `test/advisor-mcp-client-fit.test.ts`.+## [0.60.620.0] - 2026-11-09**A diverged managed checkout now publishes its local commits on refresh by default when Git durability is on, after a secret scan of those commits.** Commits a script made with plain `git commit` in a managed checkout used to strand there whenever the remote moved: every `gbrain sources refresh` refused `refresh_diverged` and asked the user, unless `sources.refresh_publish_diverged` was set to `true`. With the setting unset, a worktree whose Git durability is on (`gbrain sources writer git-durability <source> --enable`, or the legacy hook) now publishes them itself: the local commits merged with the upstream in memory, never a rebase or force-push, then the fast-forward. The publish child scans, under its publish lock and for the exact commits it pushes, what they add: commit messages, added lines (including a value a later commit removed) and merge-commit conflict resolutions. A value that looks like a secret, added text too large to scan, or a commit that changes `.gbrain-scan-allow` or a `.gitattributes` refuses the new `publish_secret_found` naming the file, line, rule and commit, never the value, with nothing pushed; commits the scan cannot read in full refuse `publish_scan_unreadable` instead. The rewritten-upstream refusal and the `--expect-remote` bound are unchanged. `false` turns it off; `true` still publishes with durability off.diff --git a/TODOS.md b/TODOS.mdindex 1271fa7a6a..7f5f2f378a 100644--- a/TODOS.md+++ b/TODOS.md@@ -3037,7 +3037,7 @@ OUT deliberately — see the plan's "NOT in scope" list).(absent) config defaults to warn") and `test/mcp-tool-defs.test.ts` pinsboth emission states. **Effort:** small (1-line default + test updates).**Priority:** P1.-- [ ] **P2 — mcp_request_log retention/pruning.** **What:** a retention policy+- [x] **P2 — mcp_request_log retention/pruning.** **Done (#6770 rewrite):** opt-in `cycle.purge.mcp_request_log_retention_days` (30-3650) prunes in the cycle purge phase and, on PGLite, hourly inside a live serve; `surface_change` and `memory_setting_change` rows are never pruned, pruned rows are tallied per token in `mcp_request_log_rollup`, and usage windows that reach past pruned history report it (docs/mcp/ADMIN.md#request-log-retention). **What (as filed):** a retention policy(age- or row-capped prune, `gbrain maintain` hook or cron). **Why:** thetable now carries MORE than request telemetry — `surface_change` audit rows(ENG-8) and `denied_after_list` metric rows ride it — and it grows unboundeddiff --git a/admin/dist/assets/index-B9c8JuNx.js b/admin/dist/assets/index-c5YhzUcc.jssimilarity index 94%rename from admin/dist/assets/index-B9c8JuNx.jsrename to admin/dist/assets/index-c5YhzUcc.jsindex 0b7773b67b..c982f311b1 100644--- a/admin/dist/assets/index-B9c8JuNx.js+++ b/admin/dist/assets/index-c5YhzUcc.js@@ -51,4 +51,4 @@ Error generating stack: `+a.message+``))??"",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:((o=s==null?void 0:s.allowedOperations)==null?void 0:o.join(``))??"",editOperations:!1}}function Ld(s){const x=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)}:{},...x?{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 Zd(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 Vd({draft:s,setDraft:x,sources:b,catalog:o,existing:T=!1}){const _=(h,U)=>x({...s,[h]:U}),q=new Set(b.map(h=>h.id)),H=s.scopes?Oa(s.scopes).includes("agent"):["full","delegating-agent"].includes(s.profile),z={marginBottom:14};return u.jsxs(u.Fragment,{children:[u.jsxs("div",{style:z,children:[u.jsx("label",{htmlFor:"grant-profile",children:"Permission profile"}),u.jsx("select",{id:"grant-profile",value:s.profile,onChange:h=>x({...s,profile:h.target.value,applyProfile:!0,scopes:"",editOperations:!1,surface:["operator","full"].includes(h.target.value)?"full":"starter"}),children:o.profiles.map(h=>u.jsx("option",{children:h},h))}),u.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."}),T&&u.jsxs("label",{className:"checkbox-label",children:[u.jsx("input",{type:"checkbox",checked:s.applyProfile,onChange:h=>_("applyProfile",h.target.checked)}),"Apply this profile's current operation snapshot"]})]}),u.jsxs("div",{style:z,children:[u.jsx("label",{htmlFor:"grant-source",children:"Primary / write source"}),u.jsxs("select",{id:"grant-source",value:s.source,onChange:h=>_("source",h.target.value),children:[!q.has(s.source)&&u.jsxs("option",{value:s.source,children:[s.source," · unavailable"]}),b.map(h=>u.jsxs("option",{value:h.id,children:[h.name," (",h.id,")"]},h.id))]})]}),u.jsxs("fieldset",{style:{border:0,padding:0,margin:"0 0 14px"},children:[u.jsx("legend",{children:"Readable sources"}),[...b,...s.reads.filter(h=>!q.has(h)).map(h=>({id:h,name:`${h} · unavailable`}))].map(h=>u.jsxs("label",{className:"checkbox-label",children:[u.jsx("input",{type:"checkbox",checked:s.reads.includes(h.id),onChange:U=>_("reads",U.target.checked?[...s.reads,h.id]:s.reads.filter(S=>S!==h.id))}),h.name]},h.id))]}),u.jsxs("div",{style:z,children:[u.jsx("label",{htmlFor:"grant-direct-prefixes",children:"Direct write prefixes (one per line)"}),u.jsx("textarea",{id:"grant-direct-prefixes",rows:2,value:s.directPrefixes,onChange:h=>_("directPrefixes",h.target.value),placeholder:"work-example/"}),u.jsx("p",{className:"grant-help",children:"Blank grants the whole primary source. Coding agent requires an explicit prefix."})]}),H&&u.jsxs("fieldset",{style:{border:"1px solid var(--border)",padding:12,marginBottom:14},children:[u.jsx("legend",{children:"Delegated jobs"}),u.jsx("p",{className:"grant-help",children:"Choose every tool explicitly. Jobs stay in the primary source; existing jobs retain their original limits."}),u.jsx("div",{className:"checkbox-group",style:{maxHeight:180,overflowY:"auto"},children:[...new Set([...o.delegatedTools,...s.tools])].map(h=>u.jsxs("label",{className:"checkbox-label",children:[u.jsx("input",{type:"checkbox",checked:s.tools.includes(h),onChange:U=>_("tools",U.target.checked?[...s.tools,h]:s.tools.filter(S=>S!==h))}),h,o.delegatedTools.includes(h)?"":" · unavailable"]},h))}),u.jsx("label",{htmlFor:"grant-namespace",children:"Delegated write namespace"}),u.jsxs("select",{id:"grant-namespace",value:s.namespace,onChange:h=>_("namespace",h.target.value),children:[u.jsx("option",{value:"job",children:"Each job's own wiki/agents/ directory"}),u.jsx("option",{value:"prefixes",children:"Explicit prefixes"})]}),s.namespace==="prefixes"&&u.jsx("textarea",{"aria-label":"Delegated prefixes",rows:2,value:s.delegatedPrefixes,onChange:h=>_("delegatedPrefixes",h.target.value),placeholder:"work-example/"})]}),u.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,...z},children:[u.jsxs("div",{children:[u.jsx("label",{htmlFor:"grant-concurrency",children:"Concurrent jobs"}),u.jsx("input",{id:"grant-concurrency",type:"number",min:1,step:1,value:s.concurrency,onChange:h=>_("concurrency",h.target.value)})]}),u.jsxs("div",{children:[u.jsx("label",{htmlFor:"grant-budget",children:"Daily delegated spend (USD)"}),u.jsx("input",{id:"grant-budget",value:s.budget,onChange:h=>_("budget",h.target.value),placeholder:"unlimited"}),u.jsx("p",{className:"grant-help",children:"Use unlimited for no spending cap, or an amount such as 2.50."})]})]}),u.jsxs("div",{style:z,children:[u.jsx("label",{htmlFor:"grant-ttl",children:"Future access token lifetime (seconds)"}),u.jsx("input",{id:"grant-ttl",type:"number",min:0,max:7776e3,step:1,value:s.ttl,onChange:h=>_("ttl",h.target.value)}),u.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."})]}),u.jsxs("details",{style:z,children:[u.jsx("summary",{children:"Advanced permissions"}),u.jsx("label",{htmlFor:"grant-scopes",children:"Scope override"}),u.jsx("input",{id:"grant-scopes",value:s.scopes,onChange:h=>_("scopes",h.target.value),placeholder:"Use profile scopes"}),u.jsx("p",{className:"grant-help",children:"Scopes allow eligible brain operations. Admin does not grant owner dashboard access or delegation."}),u.jsx("label",{htmlFor:"grant-surface",children:"Visible tool catalog"}),u.jsx("select",{id:"grant-surface",value:s.surface,onChange:h=>_("surface",h.target.value),children:["verbs","starter","full","default"].map(h=>u.jsx("option",{children:h},h))}),u.jsx("p",{className:"grant-help",children:"Full shows all eligible tools; it does not grant additional authority."}),u.jsxs("label",{className:"checkbox-label",children:[u.jsx("input",{type:"checkbox",checked:s.editOperations,onChange:h=>_("editOperations",h.target.checked)}),"Replace operation authority snapshot"]}),s.editOperations&&u.jsxs(u.Fragment,{children:[u.jsx("textarea",{"aria-label":"Allowed operations",rows:5,value:s.operationSnapshot,onChange:h=>_("operationSnapshot",h.target.value)}),u.jsx("p",{className:"grant-help",children:"One operation name per line. An empty list denies every operation, including delegated tools."})]})]})]})}const Ry=[["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 Uy(s,x){return s===null?x==="budgetUsdPerDay"?"Unlimited":x==="allowedOperations"?"Legacy scope-based catalog":"Unset":Array.isArray(s)?s.join(", ")||"(none)":String(s)}function Bd({grant:s,field:x}){const b=s[x];return x==="allowedOperations"&&Array.isArray(b)&&b.length>8?u.jsxs("details",{children:[u.jsxs("summary",{children:[b.length," operations · inspect list"]}),u.jsx("div",{style:{maxHeight:160,overflowY:"auto",marginTop:8},children:b.join(", ")})]}):u.jsx(u.Fragment,{children:Uy(b,x)})}function Kd({preview:s}){return u.jsxs("div",{"aria-live":"polite",style:{margin:"16px 0"},children:[u.jsx("h3",{children:"Review permissions"}),u.jsx("div",{style:{overflowX:"auto"},children:u.jsxs("table",{children:[u.jsx("thead",{children:u.jsxs("tr",{children:[u.jsx("th",{children:"Permission"}),s.before&&u.jsx("th",{children:"Current"}),u.jsx("th",{children:"Proposed"})]})}),u.jsx("tbody",{children:Ry.filter(([,x])=>!s.before||JSON.stringify(s.before[x])!==JSON.stringify(s.after[x])).map(([x,b])=>u.jsxs("tr",{children:[u.jsx("th",{children:x}),s.before&&u.jsx("td",{style:{overflowWrap:"anywhere",maxWidth:200},children:u.jsx(Bd,{grant:s.before,field:b})}),u.jsx("td",{style:{overflowWrap:"anywhere",maxWidth:280},children:u.jsx(Bd,{grant:s.after,field:b})})]},b))})]})}),u.jsx("p",{className:"grant-help",children:s.tokenImplications})]})}function qy({clientId:s,sources:x,sourcesReady:b=!0,onRescoped:o}){const[T,_]=R.useState(),[q,H]=R.useState(),[z,h]=R.useState(),[U,S]=R.useState(),[C,Y]=R.useState(""),[G,Z]=R.useState(!1),[W,ae]=R.useState(!1),[$,le]=R.useState(!1),ne=async(k=!1)=>{Z(!0),ae(!1);try{const[V,xe]=await Promise.all([Oe.clientGrant(s),Oe.grantCatalog()]);_(V.grant),H(bs(V.grant)),h(xe),S(void 0),Y(""),le(!1),k&&o(V.grant)}finally{Z(!1)}};R.useEffect(()=>{ne().catch(k=>Y(k.message))},[s]);const be=async()=>{if(!(!q||!T||!b||$)){Z(!0),Y(""),ae(!1);try{const k=await Oe.updateClientGrant(s,{...U?Zd(U.after):Ld(q),expectedRevision:T.revision,dryRun:!U});U?(_(k.after),H(bs(k.after)),S(void 0),ae(!0),o(k.after)):S(k)}catch(k){const V=!!U&&Ss(k);le(V||k instanceof An&&k.status===409),S(void 0),Y(`${k instanceof Error?k.message:"Grant update failed."}${V?" The change may have completed. Reload the current grant before editing permissions again.":""}`)}finally{Z(!1)}}};return u.jsxs("section",{children:[u.jsx("div",{className:"section-title",children:"Permissions"}),T&&u.jsxs("p",{className:"grant-help",children:["Revision ",T.revision,". Review source access, direct tools, and delegated work independently."]}),T&&u.jsx(Hy,{clientId:s,revision:T.revision}),!!(T!=null&&T.repairReasons.length)&&u.jsxs("p",{role:"status",style:{color:"var(--warning)"},children:["Delegation needs repair: ",T.repairReasons.join(", "),". Review and explicitly grant the missing bindings below."]}),!b&&u.jsx("p",{role:"alert",children:"Current sources are unavailable. Retry sources before editing permissions."}),u.jsx("fieldset",{disabled:G||!b||$,style:{border:0,padding:0},children:q&&z&&u.jsx(Vd,{draft:q,catalog:z,sources:x,existing:!0,setDraft:k=>{H(k),S(void 0),ae(!1)}})}),C&&u.jsxs("p",{role:"alert",style:{color:"var(--error)"},children:[C," ",u.jsx("button",{type:"button",className:"btn btn-secondary",disabled:G,onClick:()=>void ne(!0).catch(k=>Y(k.message)),children:"Reload current grant"})]}),U&&u.jsx(Kd,{preview:U}),W&&u.jsx("p",{role:"status",children:"Permissions saved. Credentials are unchanged."}),u.jsx("button",{type:"button",className:"btn btn-primary",disabled:G||!q||!z||!b||$,onClick:()=>void be(),children:G?"Checking…":U?"Apply reviewed changes":"Preview changes"})]})}function Hy({clientId:s,revision:x}){const[b,o]=R.useState(),[T,_]=R.useState(!1);return R.useEffect(()=>{let q=!0;const H=()=>void Oe.agentsSpend().then(h=>{q&&(o(h.find(U=>U.client_id===s)),_(!1))}).catch(()=>{q&&_(!0)});H();const z=setInterval(H,2e4);return()=>{q=!1,clearInterval(z)}},[s,x]),T?u.jsx("p",{role:"status",children:"Delegated spend is unavailable. Reload to check before starting more work."}):b?u.jsxs("div",{style:{border:"1px solid var(--border)",padding:12,marginBottom:14},children:[u.jsx("strong",{children:"Delegated work"}),u.jsxs("p",{children:[b.inflight_count," unfinished jobs · Daily cap: ",b.cap_usd_per_day===null?"Unlimited":`$${b.cap_usd_per_day.toFixed(2)}`]}),u.jsxs("p",{className:"grant-help",children:["Recorded today: $",(b.spent_cents_today/100).toFixed(2),". Known outstanding reservations: $",(b.pending_cents/100).toFixed(2),", including overdue calls from earlier days."]}),b.unknown_count>0&&u.jsxs("p",{role:"status",style:{color:"var(--warning)"},children:[b.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 By(s,x){const b=URL.createObjectURL(new Blob([JSON.stringify(s,null,2)],{type:"application/json"})),o=document.createElement("a");o.href=b,o.download=x,o.click(),URL.revokeObjectURL(b)}function Jd({clientId:s,grantTypes:x,revoked:b=!1,grantRevision:o}){const[T,_]=R.useState("generic"),q=x.includes("authorization_code")&&x.includes("client_credentials"),[H,z]=R.useState(q?"":x.includes("authorization_code")?"authorization-code":"client-credentials"),[h,U]=R.useState(),[S,C]=R.useState(),[Y,G]=R.useState([]),[Z,W]=R.useState(""),[ae,$]=R.useState(!1),[le,ne]=R.useState(!1),[be,k]=R.useState(!1),[V,xe]=R.useState(0);R.useEffect(()=>{if(b)return;let se=!0;if(C(void 0),G([]),W(""),ne(!1),k(!1),!!H)return Promise.all([Oe.clientSetup(s,T,H),Oe.grantCatalog()]).then(([F,de])=>{se&&(C(F.setup),G(F.instructions),U(de))}).catch(F=>{se&&W(F instanceof Error?F.message:"Setup instructions are unavailable.")}),()=>{se=!1}},[s,T,H,b,o,V]);const Se=async()=>{if(S){$(!0),W("");try{const se=await Oe.recoverClient(s,T,H),F=H==="authorization-code"?se.oauthSetup:se.credentials;if(!F)throw new Error("No matching setup file was returned. Ask the host administrator to inspect this client’s credential delivery.");By(F,`${s}-${H==="authorization-code"?"oauth-setup":"credentials"}.json`),ne(!0)}catch(se){W(se instanceof Error?se.message:"Download failed. Existing permissions are unchanged.")}finally{$(!1)}}};return u.jsxs("section",{"aria-labelledby":"client-setup-title",children:[u.jsx("h3",{id:"client-setup-title",className:"section-title",children:"Set up this client"}),b?u.jsx("p",{children:"This client is revoked. Register a new client to connect another harness."}):u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"grant-help",children:"Registration grants access. Configure the intended harness, then verify an actual memory round trip there."}),u.jsx("label",{htmlFor:"setup-harness",children:"Harness"}),u.jsxs("select",{id:"setup-harness",value:T,onChange:se=>_(se.target.value),disabled:ae,children:[!h&&u.jsx("option",{value:"generic",children:"Generic MCP client"}),h==null?void 0:h.harnesses.map(se=>u.jsx("option",{value:se.id,children:se.label},se.id))]}),q&&u.jsxs(u.Fragment,{children:[u.jsx("label",{htmlFor:"setup-flow",children:"Connection flow"}),u.jsxs("select",{id:"setup-flow",value:H,onChange:se=>z(se.target.value),disabled:ae,children:[u.jsx("option",{value:"",children:"Choose the flow supported by your harness"}),u.jsx("option",{value:"authorization-code",children:"Browser sign-in with PKCE"}),u.jsx("option",{value:"client-credentials",children:"Machine credentials"})]})]}),S&&u.jsxs(u.Fragment,{children:[u.jsxs("dl",{className:"oauth-consent-details",style:{marginTop:16},children:[u.jsx("dt",{children:"MCP URL"}),u.jsx("dd",{children:u.jsx("code",{children:S.mcp_url})}),u.jsx("dt",{children:"OAuth issuer"}),u.jsx("dd",{children:u.jsx("code",{children:S.issuer_url})}),u.jsx("dt",{children:"Client ID"}),u.jsx("dd",{children:u.jsx("code",{children:S.client.client_id})}),u.jsx("dt",{children:"Scopes"}),u.jsx("dd",{children:S.scopes.join(" ")||"None"}),u.jsx("dt",{children:"Authentication"}),u.jsx("dd",{children:S.client.token_endpoint_auth_method==="none"?"Public client — PKCE, no client secret":S.client.token_endpoint_auth_method}),S.flow==="authorization-code"&&u.jsxs(u.Fragment,{children:[u.jsx("dt",{children:"Redirect URIs"}),u.jsx("dd",{children:S.client.redirect_uris.map(se=>u.jsx("div",{children:u.jsx("code",{children:se})},se))})]})]}),u.jsx("ol",{children:Y.map((se,F)=>u.jsx("li",{style:{marginBottom:8,overflowWrap:"anywhere"},children:se},F))}),u.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",marginTop:16},children:[u.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>{navigator.clipboard.writeText(Y.join(``)).then(()=>k(!0)).catch(()=>W("Clipboard unavailable. Select and copy the instructions above."))},children:be?"Instructions copied":"Copy setup instructions"}),u.jsx("button",{type:"button",className:"btn btn-primary",disabled:ae,onClick:()=>void Se(),children:ae?"Preparing download…":S.flow==="authorization-code"?"Download OAuth setup":"Download credentials"})]}),u.jsx("p",{className:"grant-help",children:"Keep downloaded files private. Set permissions to 0600 on the target computer. A setup download does not verify the harness."})]}),!H&&u.jsx("p",{role:"status",children:"This client supports both flows. Choose one before requesting setup instructions."}),H&&!S&&!Z&&u.jsx("p",{role:"status",children:"Loading setup instructions…"}),le&&u.jsx("p",{role:"status",children:"Setup file delivered to your browser. Harness verification is still required."}),Z&&u.jsxs("p",{role:"alert",style:{color:"var(--error)"},children:[Z," ",u.jsx("button",{type:"button",className:"btn btn-secondary",disabled:ae,onClick:()=>xe(se=>se+1),children:"Retry setup"})]})]})]})}const gs={"invalidate-tokens":"Invalidate tokens",revoke:"Revoke client",delete:"Delete client"};function Yy({clientId:s,name:x,revoked:b,onChanged:o,onBusyChange:T}){const[_,q]=R.useState(),[H,z]=R.useState(!1),[h,U]=R.useState(""),[S,C]=R.useState(!1),Y=async Z=>{z(!0),U(""),q(void 0);try{q(await Oe.clientLifecycle(s,{action:Z,dryRun:!0}))}catch(W){U(W instanceof Error?W.message:"Could not preview this action. Retry after checking the client.")}finally{z(!1)}},G=async()=>{if(_){z(!0),T==null||T(!0),U("");try{await Oe.clientLifecycle(s,{action:_.action,dryRun:!1,yes:!0,expectedRevision:_.before.revision}),o()}catch(Z){const W=Ss(Z);U(`${Z instanceof Error?Z.message:"Request failed."} ${W?"The action may have completed. Reload the client and inspect its current state before requesting another action.":"The request was refused. Review a fresh preview before applying an action."}`),C(W),q(void 0)}finally{z(!1),T==null||T(!1)}}};return u.jsxs("section",{"aria-labelledby":"client-lifecycle-title",style:{marginTop:28},children:[u.jsx("h3",{id:"client-lifecycle-title",className:"section-title",children:"Client access"}),u.jsx("p",{className:"grant-help",children:"Invalidating tokens keeps the client and its secret. Revoking ends access and keeps a visible registration. Deleting removes the registration. Memory and audit history remain."}),!_&&u.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:["invalidate-tokens","revoke","delete"].filter(Z=>!b||Z==="delete").map(Z=>u.jsx("button",{type:"button",className:"btn btn-secondary",disabled:H||S,onClick:()=>void Y(Z),children:gs[Z]},Z))}),_&&u.jsxs("div",{"aria-live":"polite",style:{border:"1px solid var(--border)",padding:16},children:[u.jsxs("h4",{style:{margin:"0 0 12px"},children:[gs[_.action],": ",x]}),u.jsxs("p",{children:[u.jsx("code",{children:s})," · Revision ",_.before.revision]}),u.jsx("ul",{children:(Array.isArray(_.consequences)?_.consequences:[_.consequences]).map((Z,W)=>u.jsx("li",{children:Z},W))}),u.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end",marginTop:16},children:[u.jsx("button",{type:"button",className:"btn btn-secondary",disabled:H,onClick:()=>q(void 0),children:"Cancel"}),u.jsx("button",{type:"button",className:"btn btn-danger",disabled:H,onClick:()=>void G(),children:H?"Applying…":`Confirm ${gs[_.action].toLowerCase()}`})]})]}),h&&u.jsxs("p",{role:"alert",style:{color:"var(--error)"},children:[h," ",S&&u.jsx("button",{type:"button",className:"btn btn-secondary",onClick:o,children:"Reload client list"})]})]})}function _n({title:s,titleId:x,children:b,onClose:o,busy:T=!1,drawer:_=!1}){const q=R.useRef(null),H=R.useRef(o);H.current=o;const z=R.useRef(T);z.current=T;const[h]=R.useState(()=>document.activeElement instanceof HTMLElement?document.activeElement:null);return R.useEffect(()=>{const U=q.current;if(!U)return;(U.querySelector("[data-autofocus]")??U).focus();const S=C=>{if(C.key==="Escape"&&(C.preventDefault(),z.current||H.current()),C.key!=="Tab")return;const Y=[...U.querySelectorAll('button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), a[href], summary, [tabindex="0"]')].filter(W=>W.getClientRects().length>0&&!W.closest("fieldset:disabled")),G=Y[0],Z=Y[Y.length-1];if(!G){C.preventDefault(),U.focus();return}C.shiftKey&&(document.activeElement===G||document.activeElement===U)?(C.preventDefault(),Z.focus()):!C.shiftKey&&(document.activeElement===Z||document.activeElement===U)&&(C.preventDefault(),G.focus())};return U.addEventListener("keydown",S),()=>{U.removeEventListener("keydown",S),h!=null&&h.isConnected&&h.focus()}},[h]),u.jsx("div",{className:_?"drawer-overlay":"modal-overlay",onClick:()=>{T||o()},children:u.jsxs("div",{ref:q,role:"dialog","aria-modal":"true","aria-labelledby":x,"aria-busy":T,tabIndex:-1,className:_?"drawer":"modal",onClick:U=>U.stopPropagation(),style:_?{width:"min(640px, 95vw)"}:{maxWidth:760,width:"92vw",minWidth:0,maxHeight:"90vh",overflowY:"auto"},children:[u.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:16,alignItems:"start",marginBottom:20},children:[u.jsx("h2",{id:x,className:"modal-title",style:{margin:0},children:s}),u.jsx("button",{type:"button",className:"btn btn-secondary","aria-label":`Close ${s}`,disabled:T,onClick:o,children:"Close"})]}),b]})})}function wy(s){const x=s.kind!=="machine",b=x?s.redirectUris.split(`-`).map(o=>o.trim()).filter(Boolean):[];if(x&&!b.length)throw new Error("Enter the exact redirect URI from your MCP client settings, one per line.");for(const o of b)try{new URL(o)}catch{throw new Error("Each redirect URI must be a complete URI. Copy it exactly from your MCP client settings.")}return{grantTypes:x?["authorization_code","refresh_token"]:["client_credentials"],redirectUris:b,tokenEndpointAuthMethod:s.kind==="public-pkce"?"none":s.kind==="machine"?"client_secret_post":s.confidentialMethod}}function Gy(s){const x=Math.floor((Date.now()-s.getTime())/1e3);return x<60?"just now":x<3600?Math.floor(x/60)+"m ago":x<86400?Math.floor(x/3600)+"h ago":Math.floor(x/86400)+"d ago"}function Xy(){const[s,x]=R.useState([]),[b,o]=R.useState([]),[T,_]=R.useState(!1),[q,H]=R.useState(!1),[z,h]=R.useState(""),[U,S]=R.useState(""),[C,Y]=R.useState(!0),[G,Z]=R.useState(!0),[W,ae]=R.useState(!1),[$,le]=R.useState(!1),[ne,be]=R.useState(),[k,V]=R.useState(),[xe,Se]=R.useState(!1),[se,F]=R.useState(),de=R.useRef(0),we=R.useRef(0),Ne=async()=>{const N=++de.current;Y(!0);try{const w=await Oe.agents();if(N!==de.current)return;x(w),_(!0),h("")}catch(w){N===de.current&&h(w instanceof Error?w.message:"Clients are unavailable.")}finally{N===de.current&&Y(!1)}},Ze=async()=>{const N=++we.current;Z(!0);try{const w=await Oe.sources();if(N!==we.current)return;o(w),H(!0),S("")}catch(w){N===we.current&&(H(!1),S(w instanceof Error?w.message:"Sources are unavailable."))}finally{N===we.current&&Z(!1)}};R.useEffect(()=>(Ne(),Ze(),()=>{de.current++,we.current++}),[]);const E=s.filter(N=>!W||N.status!=="revoked");return u.jsxs(u.Fragment,{children:[u.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12,flexWrap:"wrap",alignItems:"center",marginBottom:24},children:[u.jsx("h1",{className:"page-title",style:{marginBottom:0},children:"Agents"}),u.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[u.jsxs("label",{className:"checkbox-label",children:[u.jsx("input",{type:"checkbox",checked:W,onChange:N=>ae(N.target.checked)}),"Hide revoked"]}),u.jsx("button",{type:"button",className:"btn btn-secondary",disabled:C,onClick:()=>void Ne(),children:"Refresh clients"}),u.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>Se(!0),children:"+ API Key"}),u.jsx("button",{type:"button",className:"btn btn-primary",disabled:!q||!b.length||G,onClick:()=>le(!0),children:"+ OAuth Client"})]})]}),u.jsx("p",{className:"grant-help",style:{marginBottom:16},children:"Owner administration uses this dashboard’s login. An OAuth client’s admin scope allows eligible brain operations; it does not open this dashboard."}),z&&u.jsxs("p",{role:"alert",style:{marginBottom:16,color:"var(--error)"},children:[T?"Showing previously loaded clients. ":"Could not load clients. ",z," ",u.jsx("button",{type:"button",className:"btn btn-secondary",disabled:C,onClick:()=>void Ne(),children:"Retry clients"})]}),U&&u.jsxs("p",{role:"alert",style:{marginBottom:16,color:"var(--error)"},children:["Could not load current sources. Registration and permission changes are unavailable. ",U," ",u.jsx("button",{type:"button",className:"btn btn-secondary",disabled:G,onClick:()=>void Ze(),children:"Retry sources"})]}),!U&&!q&&u.jsx("p",{role:"status",children:"Loading sources before registration…"}),q&&!b.length&&u.jsx("p",{role:"status",children:"No active sources are available. Add or unarchive a source on the host before registering a client."}),!T&&!z&&u.jsx("p",{role:"status",children:"Loading clients…"}),T&&!s.length&&u.jsx("p",{style:{textAlign:"center",padding:48},children:"No clients registered. Register a client to grant access to a harness."}),T&&s.length>0&&!E.length&&u.jsx("p",{style:{textAlign:"center",padding:48},children:"All clients are revoked. Uncheck “Hide revoked” to view them."}),E.length>0&&u.jsxs("div",{style:{overflowX:"auto"},children:[u.jsxs("table",{children:[u.jsx("thead",{children:u.jsxs("tr",{children:[u.jsx("th",{children:"Name"}),u.jsx("th",{children:"Type"}),u.jsx("th",{children:"Scopes"}),u.jsx("th",{children:"Sources"}),u.jsx("th",{children:"Status"}),u.jsx("th",{children:"Requests"}),u.jsx("th",{children:"Last used"})]})}),u.jsx("tbody",{children:E.map(N=>u.jsxs("tr",{onClick:()=>V(N),style:{cursor:"pointer"},children:[u.jsx("td",{children:u.jsx("button",{type:"button",className:"client-name-button",onClick:w=>{w.stopPropagation(),V(N)},children:N.name||N.client_name})}),u.jsx("td",{children:u.jsx("span",{className:"badge "+(N.auth_type==="oauth"?"badge-read":"badge-write"),children:N.auth_type==="oauth"?"OAuth":"API key"})}),u.jsx("td",{children:(N.scope||"").split(" ").filter(Boolean).map(w=>u.jsx("span",{className:"badge badge-"+w,style:{marginRight:4},children:w},w))}),u.jsx("td",{children:N.auth_type==="oauth"?(N.source_id||"none")+" · "+(N.federated_read||[]).length+" readable":"Unscoped"}),u.jsx("td",{children:u.jsx("span",{className:"badge "+(N.status==="active"?"badge-success":"badge-danger"),children:N.status})}),u.jsxs("td",{children:[N.requests_today||0,u.jsxs("span",{style:{color:"var(--text-muted)"},children:[" / ",N.total_requests||0]})]}),u.jsx("td",{children:N.last_used_at?Gy(new Date(N.last_used_at)):"Never"})]},N.auth_type+":"+N.id))})]}),u.jsxs("p",{className:"grant-help",style:{marginTop:12},children:[s.filter(N=>N.status==="active").length," active / ",s.length," total"]})]}),$&&u.jsx(Qy,{sources:b,sourcesReady:q,onClose:()=>le(!1),onRegistered:N=>{le(!1),be(N),Ne()}}),ne&&u.jsxs(_n,{title:"Client registered",titleId:"registered-client-title",onClose:()=>be(void 0),children:[u.jsxs("p",{role:"status",style:{marginBottom:16},children:[ne.name," is registered. Its harness connection has not been verified."]}),u.jsx(Jd,{clientId:ne.clientId,grantTypes:ne.grantTypes})]}),k&&u.jsx(Ly,{agent:k,sources:b,sourcesReady:q,onClose:()=>V(void 0),onChanged:()=>{V(void 0),Ne()},onRescoped:N=>{V(w=>w&&{...w,source_id:N.sourceId,federated_read:N.federatedRead,scope:N.scopes.join(" "),token_ttl:N.tokenTtlSeconds}),Ne()}},k.id),xe&&u.jsx(Vy,{onClose:()=>Se(!1),onCreated:N=>{Se(!1),F(N),Ne()}}),se&&u.jsx(Ky,{token:se,onClose:()=>F(void 0)})]})}function Qy({sources:s,sourcesReady:x,onClose:b,onRegistered:o}){const[T,_]=R.useState(""),[q,H]=R.useState(()=>bs()),[z,h]=R.useState({kind:"machine",redirectUris:"",confidentialMethod:"client_secret_post"}),[U,S]=R.useState(),[C,Y]=R.useState(""),[G,Z]=R.useState(),[W,ae]=R.useState(!1),[$,le]=R.useState(""),[ne,be]=R.useState(),[k,V]=R.useState(!1),xe=()=>{Y(""),Oe.grantCatalog().then(S).catch(F=>Y(F instanceof Error?F.message:"Permission catalog unavailable."))};R.useEffect(xe,[]);const Se=F=>{h(F),Z(void 0)},se=async F=>{if(F.preventDefault(),!(!x||!U||k)){if(!T.trim()){le("Enter a client name.");return}ae(!0),le("");try{const de=(G==null?void 0:G.oauth)??wy(z),we=(G==null?void 0:G.name)??T.trim(),Ne=await Oe.registerClient({...G?Zd(G.grant.after):Ld(q),...de,name:we,dryRun:!G});G?o({clientId:Ne.clientId,name:we,grantTypes:de.grantTypes}):Z({grant:Ne,oauth:de,name:we})}catch(de){le(de instanceof Error?de.message:"Registration failed.");const we=!!G&&Ss(de);if(V(we),G&&(we||de instanceof An&&de.status===409))try{const Ne=(await Oe.agents()).filter(Ze=>Ze.auth_type==="oauth"&&Ze.status==="active"&&(Ze.name||Ze.client_name)===G.name);Ne.length===1&&(be({clientId:Ne[0].id||Ne[0].client_id,name:G.name,grantTypes:Ne[0].grant_types}),V(!0))}catch{}Z(void 0)}finally{ae(!1)}}};return u.jsx(_n,{title:"Register OAuth client",titleId:"register-client-title",onClose:b,busy:W,children:u.jsxs("form",{onSubmit:se,children:[u.jsxs("fieldset",{disabled:W||k,style:{border:0,padding:0},children:[u.jsx("label",{htmlFor:"agent-name",children:"Client name"}),u.jsx("input",{id:"agent-name","data-autofocus":!0,value:T,placeholder:"agent-example",onChange:F=>{_(F.target.value),Z(void 0)}}),u.jsx("label",{htmlFor:"oauth-connection-kind",style:{marginTop:16},children:"Connection type"}),u.jsxs("select",{id:"oauth-connection-kind",value:z.kind,onChange:F=>Se({...z,kind:F.target.value}),children:[u.jsx("option",{value:"machine",children:"Machine credentials"}),u.jsx("option",{value:"public-pkce",children:"Browser sign-in: public client with PKCE"}),u.jsx("option",{value:"confidential-pkce",children:"Browser sign-in: confidential client with PKCE"})]}),u.jsx("p",{className:"grant-help",children:"Choose the method required by your MCP client. Browser sign-in requires the owner’s approval. Public clients use PKCE without a client secret."}),z.kind!=="machine"&&u.jsxs(u.Fragment,{children:[u.jsx("label",{htmlFor:"oauth-redirect-uris",children:"Exact redirect URIs (one per line)"}),u.jsx("textarea",{id:"oauth-redirect-uris",rows:3,value:z.redirectUris,onChange:F=>Se({...z,redirectUris:F.target.value}),placeholder:"https://client.example.com/oauth/callback"}),u.jsx("p",{className:"grant-help",children:"Copy these from the client’s OAuth settings. Keep the complete path and query. GBrain uses S256 PKCE."})]}),z.kind==="confidential-pkce"&&u.jsxs(u.Fragment,{children:[u.jsx("label",{htmlFor:"oauth-client-auth",children:"Client secret authentication"}),u.jsxs("select",{id:"oauth-client-auth",value:z.confidentialMethod,onChange:F=>Se({...z,confidentialMethod:F.target.value}),children:[u.jsx("option",{value:"client_secret_post",children:"client_secret_post (request body)"}),u.jsx("option",{value:"client_secret_basic",children:"client_secret_basic (HTTP Basic)"})]})]}),z.kind==="machine"&&u.jsx("p",{className:"grant-help",children:"Machine handoffs use client_secret_post to renew their access tokens."}),u.jsx("div",{style:{marginTop:24},children:U&&u.jsx(Vd,{draft:q,setDraft:F=>{H(F),Z(void 0)},catalog:U,sources:s})})]}),C&&u.jsxs("p",{role:"alert",style:{color:"var(--error)"},children:[C," ",u.jsx("button",{type:"button",className:"btn btn-secondary",onClick:xe,children:"Retry permissions"})]}),!x&&u.jsx("p",{role:"alert",children:"Current sources are unavailable. Close this form and retry sources before registration."}),G&&u.jsxs(u.Fragment,{children:[u.jsx(Kd,{preview:G.grant}),u.jsxs("div",{"aria-live":"polite",children:[u.jsx("h3",{children:"Review connection"}),u.jsxs("dl",{className:"oauth-consent-details",children:[u.jsx("dt",{children:"Client name"}),u.jsx("dd",{children:G.name}),u.jsx("dt",{children:"Grant types"}),u.jsx("dd",{children:G.oauth.grantTypes.join(", ")}),u.jsx("dt",{children:"Authentication"}),u.jsx("dd",{children:G.oauth.tokenEndpointAuthMethod}),G.oauth.redirectUris.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("dt",{children:"Exact redirect URIs"}),u.jsx("dd",{children:G.oauth.redirectUris.map(F=>u.jsx("div",{children:u.jsx("code",{children:F})},F))})]})]})]})]}),$&&u.jsx("p",{role:"alert",style:{color:"var(--error)",margin:"16px 0"},children:$}),ne&&u.jsxs("div",{role:"status",children:[u.jsxs("p",{children:["A client named ",ne.name," is registered. Open its setup instructions and recover its existing download."]}),u.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>o(ne),children:"Open existing client setup"})]}),k&&!ne&&u.jsx("p",{role:"status",children:"Registration may have completed. Close this form and refresh clients before trying again. No automatic retry was made."}),u.jsxs("div",{style:{display:"flex",gap:12,justifyContent:"flex-end",marginTop:20},children:[u.jsx("button",{type:"button",className:"btn btn-secondary",disabled:W,onClick:b,children:"Cancel"}),u.jsx("button",{type:"submit",className:"btn btn-primary",disabled:W||!U||!x||k,children:W?"Checking…":G?"Register with reviewed permissions":"Preview permissions"})]})]})})}function Ly({agent:s,sources:x,sourcesReady:b,onClose:o,onChanged:T,onRescoped:_}){const q=s.id||s.client_id||"",H=s.name||s.client_name||q,[z,h]=R.useState(),[U,S]=R.useState(""),[C,Y]=R.useState(0),[G,Z]=R.useState(!1),[W,ae]=R.useState(!1);return R.useEffect(()=>{if(s.auth_type!=="oauth")return;let $=!0;return S(""),Oe.clientDetails(q).then(le=>{$&&h(le)}).catch(le=>{$&&S(le instanceof Error?le.message:"Client details unavailable.")}),()=>{$=!1}},[q,s.auth_type,C]),u.jsxs(_n,{title:H,titleId:"client-details-title",onClose:o,drawer:!0,busy:W,children:[u.jsx("span",{className:"badge "+(s.status==="active"?"badge-success":"badge-danger"),children:s.status}),u.jsxs("dl",{className:"oauth-consent-details",style:{marginTop:16},children:[u.jsx("dt",{children:"Client ID"}),u.jsx("dd",{children:u.jsx("code",{children:q})}),u.jsx("dt",{children:"Scopes"}),u.jsx("dd",{children:s.scope||"None"}),u.jsx("dt",{children:"Registered"}),u.jsx("dd",{children:new Date(s.created_at).toLocaleString()}),u.jsx("dt",{children:"Token lifetime"}),u.jsx("dd",{children:s.token_ttl?s.token_ttl+" seconds":"Server default (future tokens)"}),z&&u.jsxs(u.Fragment,{children:[u.jsx("dt",{children:"Grant types"}),u.jsx("dd",{children:z.client.grant_types.join(", ")}),u.jsx("dt",{children:"Authentication"}),u.jsx("dd",{children:z.client.token_endpoint_auth_method})]})]}),s.auth_type==="oauth"?u.jsxs(u.Fragment,{children:[U&&u.jsxs("p",{role:"alert",style:{color:"var(--error)"},children:[U," ",u.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>Y($=>$+1),children:"Retry client details"})]}),!z&&!U&&u.jsx("p",{role:"status",children:"Loading client details…"}),z&&u.jsxs(u.Fragment,{children:[u.jsx(Jd,{clientId:q,grantTypes:z.client.grant_types,revoked:s.status==="revoked",grantRevision:z.grant.revision}),s.status==="active"&&u.jsxs("details",{style:{marginTop:24},children:[u.jsx("summary",{style:{cursor:"pointer",fontWeight:600},children:"Edit access levels"}),u.jsx(qy,{clientId:q,sources:x,sourcesReady:b,onRescoped:$=>{h(le=>le&&{...le,grant:$}),_($)}})]}),u.jsx(Yy,{clientId:q,name:H,revoked:s.status==="revoked",onChanged:T,onBusyChange:ae})]})]}):u.jsxs(u.Fragment,{children:[u.jsx("h3",{className:"section-title",children:"API key"}),u.jsx("p",{children:"Use this key as a bearer token in a client that supports static authentication. Its value is available only in the original private handoff."}),s.status==="active"&&u.jsxs("div",{style:{marginTop:20},children:[G?u.jsxs(u.Fragment,{children:[u.jsxs("p",{children:["Revoke the API key ",H," (",q,")? Only this key stops working. Memory remains."]}),u.jsx("button",{type:"button",className:"btn btn-secondary",disabled:W,onClick:()=>Z(!1),children:"Cancel"})," ",u.jsx("button",{type:"button",className:"btn btn-danger",disabled:W,onClick:()=>{ae(!0),Oe.revokeApiKey(q).then(T).catch($=>S($ instanceof Error?$.message:"Revoke failed. Refresh the client list before retrying.")).finally(()=>ae(!1))},children:"Confirm revoke"})]}):u.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>Z(!0),children:"Revoke API key"}),U&&u.jsx("p",{role:"alert",children:U})]})]})]})}const Zy=[{id:"read",label:"Read",help:"Search and read memory."},{id:"write",label:"Write",help:"Add and edit memory."},{id:"admin",label:"Admin",help:"Brain administration operations. Grant only to fully trusted clients."}];function Vy({onClose:s,onCreated:x}){const[b,o]=R.useState(""),[T,_]=R.useState(!1),[q,H]=R.useState(""),[z,h]=R.useState(["read","write"]),U=async S=>{if(S.preventDefault(),!b.trim()){H("Enter a key name.");return}if(z.length===0){H("Choose at least one access level.");return}_(!0),H("");try{const C=await Oe.createApiKey(b.trim(),z);x({name:C.name,token:C.token})}catch(C){H(C instanceof Error?C.message:"Key creation failed. Inspect the clients list before retrying.")}finally{_(!1)}};return u.jsx(_n,{title:"Create API key",titleId:"create-api-key-title",onClose:s,busy:T,children:u.jsxs("form",{onSubmit:U,children:[u.jsx("p",{className:"grant-help",children:"API keys default to read and write. Admin is granted only when you check it. Choose an OAuth client for per-source or per-operation access. This key cannot log into the owner dashboard."}),u.jsx("label",{htmlFor:"api-key-name",children:"Key name"}),u.jsx("input",{id:"api-key-name","data-autofocus":!0,value:b,maxLength:128,disabled:T,onChange:S=>o(S.target.value)}),u.jsxs("fieldset",{style:{marginTop:16},children:[u.jsx("legend",{children:"Access levels"}),Zy.map(S=>u.jsxs("label",{style:{display:"block"},children:[u.jsx("input",{type:"checkbox",checked:z.includes(S.id),disabled:T,onChange:C=>h(Y=>C.target.checked?[...Y,S.id]:Y.filter(G=>G!==S.id))})," ",S.label," ",u.jsx("span",{className:"grant-help",children:S.help})]},S.id))]}),q&&u.jsx("p",{role:"alert",children:q}),u.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:12,marginTop:20},children:[u.jsx("button",{type:"button",className:"btn btn-secondary",disabled:T,onClick:s,children:"Cancel"}),u.jsx("button",{type:"submit",className:"btn btn-primary",disabled:T,children:T?"Creating…":"Create key"})]})]})})}function Ky({token:s,onClose:x}){const[b,o]=R.useState(!1),[T,_]=R.useState("");return u.jsxs(_n,{title:"API key created",titleId:"api-key-created-title",onClose:x,children:[u.jsx("p",{children:s.name}),u.jsx("label",{htmlFor:"new-api-key",children:"Bearer token"}),u.jsx("textarea",{id:"new-api-key",rows:3,readOnly:!0,value:s.token}),u.jsx("p",{className:"grant-help",children:"Save this token privately now. It will not be shown again. A key’s creation does not verify your harness connection."}),u.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>{navigator.clipboard.writeText(s.token).then(()=>o(!0)).catch(()=>_("Clipboard unavailable. Select and copy the token above."))},children:b?"Copied":"Copy token"}),T&&u.jsx("p",{role:"alert",children:T}),u.jsx("button",{type:"button",className:"btn btn-primary",style:{marginLeft:12},onClick:x,children:"Done"})]})}function Jy(){const[s,x]=R.useState({rows:[],total:0,page:1,pages:1}),[b,o]=R.useState(1),[T,_]=R.useState("all"),[q,H]=R.useState(null);R.useEffect(()=>{z(b)},[b,T]);const z=C=>{const Y=T!=="all"?`&agent=${encodeURIComponent(T)}`:"";Oe.requests(C,Y).then(x).catch(()=>{})},h=C=>{const Y=Date.now()-new Date(C).getTime();return Y<6e4?`${Math.floor(Y/1e3)}s ago`:Y<36e5?`${Math.floor(Y/6e4)} min ago`:Y<864e5?`${Math.floor(Y/36e5)}h ago`:new Date(C).toLocaleDateString()},U=C=>{if(!C)return null;const{query:Y,slug:G,partial:Z,limit:W,...ae}=C,$=[];return Y&&$.push(`"${Y}"`),G&&$.push(G),Z&&$.push(`~${Z}`),W&&$.push(`limit=${W}`),Object.keys(ae).length>0&&$.push(`+${Object.keys(ae).length} params`),$.join(" ")},S=new Map;return s.rows.forEach(C=>{C.token_name&&S.set(C.token_name,C.agent_name||C.token_name)}),u.jsxs(u.Fragment,{children:[u.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:24},children:[u.jsx("h1",{className:"page-title",style:{marginBottom:0},children:"Request Log"}),u.jsxs("select",{value:T,onChange:C=>{_(C.target.value),o(1)},style:{background:"var(--bg-secondary)",color:"var(--text-primary)",border:"1px solid var(--border)",borderRadius:6,padding:"4px 8px",fontSize:13},children:[u.jsx("option",{value:"all",children:"All agents"}),[...S.entries()].map(([C,Y])=>u.jsx("option",{value:C,children:Y},C))]})]}),s.rows.length===0?u.jsx("div",{style:{textAlign:"center",padding:48,color:"var(--text-muted)"},children:"No requests yet."}):u.jsxs(u.Fragment,{children:[u.jsxs("table",{children:[u.jsx("thead",{children:u.jsxs("tr",{children:[u.jsx("th",{children:"Time"}),u.jsx("th",{children:"Agent"}),u.jsx("th",{children:"Operation"}),u.jsx("th",{children:"Params"}),u.jsx("th",{children:"Latency"}),u.jsx("th",{children:"Status"})]})}),u.jsx("tbody",{children:s.rows.map(C=>u.jsxs(Xd.Fragment,{children:[u.jsxs("tr",{onClick:()=>H(q===C.id?null:C.id),style:{cursor:"pointer"},children:[u.jsx("td",{style:{color:"var(--text-secondary)",whiteSpace:"nowrap"},children:h(C.created_at)}),u.jsx("td",{children:u.jsx("a",{style:{color:"var(--text-link, #88aaff)",cursor:"pointer",textDecoration:"none",fontWeight:500},onClick:Y=>{Y.stopPropagation(),_(C.token_name),o(1)},children:C.agent_name||C.token_name})}),u.jsx("td",{className:"mono",children:C.operation}),u.jsx("td",{style:{color:"var(--text-secondary)",fontSize:12,maxWidth:200,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:U(C.params)}),u.jsxs("td",{className:"mono",children:[C.latency_ms,"ms"]}),u.jsx("td",{children:u.jsx("span",{className:`badge badge-${C.status}`,children:C.status})})]}),q===C.id&&u.jsx("tr",{children:u.jsx("td",{colSpan:6,style:{background:"var(--bg-secondary, #0f0f1a)",padding:16},children:u.jsxs("div",{style:{display:"grid",gridTemplateColumns:"100px 1fr",gap:"6px 12px",fontSize:13},children:[u.jsx("span",{style:{color:"var(--text-muted)"},children:"Time"}),u.jsx("span",{children:new Date(C.created_at).toLocaleString()}),u.jsx("span",{style:{color:"var(--text-muted)"},children:"Agent"}),u.jsx("span",{className:"mono",children:C.token_name}),u.jsx("span",{style:{color:"var(--text-muted)"},children:"Operation"}),u.jsx("span",{className:"mono",children:C.operation}),u.jsx("span",{style:{color:"var(--text-muted)"},children:"Latency"}),u.jsxs("span",{children:[C.latency_ms,"ms"]}),C.params&&u.jsxs(u.Fragment,{children:[u.jsx("span",{style:{color:"var(--text-muted)"},children:"Params"}),u.jsx("pre",{className:"mono",style:{margin:0,whiteSpace:"pre-wrap",fontSize:12},children:JSON.stringify(C.params,null,2)})]}),C.error_message&&u.jsxs(u.Fragment,{children:[u.jsx("span",{style:{color:"var(--error, #ff6b6b)"},children:"Error"}),u.jsx("span",{style:{color:"var(--error, #ff6b6b)"},children:C.error_message})]})]})})})]},C.id))})]}),u.jsxs("div",{className:"pagination",children:[u.jsxs("span",{children:["Page ",s.page," of ",s.pages," (",s.total," total)"]}),u.jsxs("div",{style:{display:"flex",gap:8},children:[u.jsx("button",{disabled:s.page<=1,onClick:()=>o(C=>C-1),children:"Previous"}),u.jsx("button",{disabled:s.page>=s.pages,onClick:()=>o(C=>C+1),children:"Next"})]})]})]})]})}function ky({markup:s}){return u.jsx("div",{style:{width:"100%",overflow:"auto"},dangerouslySetInnerHTML:{__html:s}})}function Vi({type:s,ariaLabel:x}){const[b,o]=R.useState(""),[T,_]=R.useState("");return R.useEffect(()=>{let q=!1;return Oe.calibrationChart(s).then(H=>{q||o(H)}).catch(H=>{q||_(H.message??"fetch failed")}),()=>{q=!0}},[s]),T?u.jsxs("div",{style:{padding:16,color:"var(--error)"},role:"alert",children:[x,": ",T]}):b?u.jsx(ky,{markup:b}):u.jsxs("div",{style:{padding:16,color:"var(--text-muted)"},children:[x," loading..."]})}function Wy(){const[s,x]=R.useState(null),[b,o]=R.useState(!0),[T,_]=R.useState("");if(R.useEffect(()=>{Oe.calibrationProfile().then(z=>{x(z),o(!1)}).catch(z=>{_(z.message??"fetch failed"),o(!1)})},[]),b)return u.jsx("div",{style:{padding:24,color:"var(--text-secondary)"},children:"Loading calibration profile…"});if(T)return u.jsxs("div",{style:{padding:24,color:"var(--error)"},role:"alert",children:["Could not load calibration profile: ",T]});if(!s)return u.jsxs("div",{style:{padding:24,maxWidth:700},children:[u.jsx("h1",{style:{marginBottom:16},children:"Calibration"}),u.jsx("p",{style:{color:"var(--text-secondary)"},children:"No calibration profile yet. Builds after 5+ resolved takes."}),u.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 q=new Date(s.generated_at),H=Math.floor((Date.now()-q.getTime())/(1e3*60*60*24));return u.jsxs("div",{style:{padding:32,maxWidth:720},children:[u.jsx("h1",{style:{marginBottom:8},children:"Calibration"}),u.jsxs("div",{style:{color:"var(--text-muted)",fontSize:13,marginBottom:24},children:["Holder: ",s.holder," · ","Updated ",H===0?"today":`${H}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"]}),u.jsx("section",{style:{marginBottom:32},children:u.jsx(Vi,{type:"brier-trend",ariaLabel:"Brier trend"})}),u.jsxs("section",{style:{marginBottom:32},children:[u.jsx("h2",{style:{fontSize:14,color:"var(--text-secondary)",marginBottom:12,fontWeight:400},children:"Pattern statements"}),u.jsx(Vi,{type:"pattern-statements",ariaLabel:"Pattern statements"})]}),u.jsx("section",{style:{marginBottom:32},children:u.jsx(Vi,{type:"domain-bars",ariaLabel:"Per-domain accuracy"})}),u.jsx("section",{style:{marginBottom:32},children:u.jsx(Vi,{type:"abandoned-threads",ariaLabel:"Abandoned threads"})}),s.active_bias_tags.length>0&&u.jsxs("section",{style:{marginBottom:32,color:"var(--text-muted)",fontSize:13},children:["Active bias tags: ",s.active_bias_tags.join(", ")]})]})}function $y(s){return s===0?"var(--accent-success, #2ea043)":s>=100?"var(--accent-danger, #f85149)":"var(--accent-warn, #d29922)"}function Yd(s){return`$${(s/100).toFixed(2)}`}function Fy(){const[s,x]=R.useState(null),[b,o]=R.useState(null);if(R.useEffect(()=>{let _=!0,q=null;const H=async()=>{try{const z=await Oe.jobsWatch();_&&(x(z),o(null))}catch(z){_&&o(z instanceof Error?z.message:String(z))}_&&(q=setTimeout(H,1e3))};return H(),()=>{_=!1,q&&clearTimeout(q)}},[]),b)return u.jsxs("div",{style:{padding:24,color:"var(--accent-danger, #f85149)"},children:[u.jsx("h2",{children:"Jobs Watch — error"}),u.jsx("pre",{style:{whiteSpace:"pre-wrap"},children:b})]});if(!s)return u.jsx("div",{style:{padding:24,color:"var(--text-muted, #777)"},children:"Loading jobs watch…"});const T=new Date(s.ts_ms).toLocaleTimeString();return u.jsxs("div",{style:{padding:24,fontFamily:'var(--font-mono, "JetBrains Mono", monospace)'},children:[u.jsxs("h1",{style:{fontSize:18,marginBottom:4},children:["Jobs Watch",u.jsxs("span",{style:{marginLeft:12,color:"var(--text-muted, #777)",fontSize:12,fontWeight:"normal"},children:["updated ",T]})]}),u.jsxs("section",{style:{marginTop:24},children:[u.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Queue"}),u.jsxs("div",{children:["waiting=",u.jsx("b",{children:s.queue_health.waiting})," ","active=",u.jsx("b",{children:s.queue_health.active})," ","stalled=",u.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&&u.jsxs("section",{style:{marginTop:24},children:[u.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"By type (24h)"}),u.jsxs("table",{style:{borderCollapse:"collapse"},children:[u.jsx("thead",{children:u.jsxs("tr",{style:{color:"var(--text-muted, #777)",fontSize:12},children:[u.jsx("th",{style:{textAlign:"left",padding:"4px 12px 4px 0"},children:"name"}),u.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"total"}),u.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"done"}),u.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"fail"}),u.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"dead"})]})}),u.jsx("tbody",{children:s.by_type.slice(0,6).map(_=>u.jsxs("tr",{children:[u.jsx("td",{style:{padding:"4px 12px 4px 0"},children:_.name}),u.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.total}),u.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.completed}),u.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.failed}),u.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.dead})]},_.name))})]})]}),u.jsxs("section",{style:{marginTop:24},children:[u.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Lease pressure (1h)"}),u.jsxs("div",{style:{color:$y(s.lease_pressure_1h)},children:[s.lease_pressure_1h," bounce",s.lease_pressure_1h===1?"":"s"]})]}),s.top_errors.length>0&&u.jsxs("section",{style:{marginTop:24},children:[u.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Top errors (24h)"}),u.jsx("table",{style:{borderCollapse:"collapse"},children:u.jsx("tbody",{children:s.top_errors.slice(0,5).map(_=>u.jsxs("tr",{children:[u.jsxs("td",{style:{textAlign:"right",padding:"4px 12px 4px 0",color:"var(--text-muted, #777)"},children:[_.count,"×"]}),u.jsx("td",{style:{padding:"4px 12px 4px 0"},children:_.cluster})]},_.cluster))})})]}),s.budget_owners.length>0&&u.jsxs("section",{style:{marginTop:24},children:[u.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Budget owners"}),u.jsxs("table",{style:{borderCollapse:"collapse"},children:[u.jsx("thead",{children:u.jsxs("tr",{style:{color:"var(--text-muted, #777)",fontSize:12},children:[u.jsx("th",{style:{textAlign:"left",padding:"4px 12px 4px 0"},children:"owner"}),u.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"spent"}),u.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"remaining"})]})}),u.jsx("tbody",{children:s.budget_owners.slice(0,5).map(_=>u.jsxs("tr",{children:[u.jsx("td",{style:{padding:"4px 12px 4px 0"},children:_.owner_id}),u.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:Yd(_.total_spent_cents)}),u.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:Yd(_.remaining_cents)})]},_.owner_id))})]})]})]})}function Iy(){var h,U;const[s,x]=R.useState(),[b,o]=R.useState(""),[T,_]=R.useState(!1),[q,H]=R.useState("");R.useEffect(()=>{let S=!0;const C=Ki();if(!C){o("No pending authorization request. Restart the connection from your client.");return}return Oe.oauthRequest(C).then(Y=>{S&&(x(Y),H(Y.sourceId??""))}).catch(Y=>{S&&o(Y.message)}),()=>{S=!1}},[]);const z=async S=>{if(!(!s||T)){_(!0),o("");try{const C=S==="approve"&&s.sourceChoice.editable&&q!==s.sourceId?q:void 0,Y=await Oe.decideOAuthRequest(s.id,S,s.csrf,C);Hd(),window.location.assign(Y.redirectUrl)}catch(C){o(C instanceof Error?C.message:"Approval failed. Restart the connection from your client."),x(void 0),_(!1)}}};return u.jsxs("section",{"aria-labelledby":"consent-title",style:{maxWidth:760},children:[u.jsx("h1",{id:"consent-title",children:"Approve client access"}),u.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."}),b&&u.jsx("div",{role:"alert",className:"login-error",style:{marginBottom:16},children:b}),!s&&!b&&u.jsx("p",{role:"status",children:"Loading authorization request…"}),s&&u.jsxs(u.Fragment,{children:[u.jsxs("dl",{className:"oauth-consent-details",children:[u.jsx("dt",{children:"Client"}),u.jsx("dd",{children:s.clientName}),u.jsx("dt",{children:"Client ID"}),u.jsx("dd",{children:u.jsx("code",{children:s.clientId})}),u.jsx("dt",{children:"Redirect destination"}),u.jsx("dd",{children:u.jsx("code",{children:s.redirectUri})}),u.jsx("dt",{children:"Permissions"}),u.jsx("dd",{children:s.scopes.length?s.scopes.map(S=>u.jsx("span",{className:`badge ${S.includes("admin")?"badge-error":""}`,style:{marginRight:8},children:S},S)):"No permissions"}),u.jsx("dt",{children:"Administrative brain operations"}),u.jsx("dd",{children:s.scopes.some(S=>S==="admin")?"Eligible operations within the grant below. This does not grant owner dashboard access.":s.scopes.some(S=>S.endsWith("_admin"))?"The named administrative brain operations. This does not grant owner dashboard access.":"None"}),u.jsx("dt",{children:"Allowed operations"}),u.jsx("dd",{children:s.allowedOperations===null?"All operations permitted by these scopes and the server policy":s.allowedOperations.join(", ")||"None"}),u.jsx("dt",{children:"Write paths"}),u.jsx("dd",{children:s.boundSlugPrefixes===null?"Within the granted source":s.boundSlugPrefixes.join(", ")||"None"}),s.scopes.includes("agent")&&u.jsxs(u.Fragment,{children:[u.jsx("dt",{children:"Delegated tools"}),u.jsx("dd",{children:((h=s.delegatedTools)==null?void 0:h.join(", "))||"None"}),u.jsx("dt",{children:"Delegated write paths"}),u.jsx("dd",{children:s.delegatedNamespace==="job"?"A separate namespace for each job":((U=s.delegatedSlugPrefixes)==null?void 0:U.join(", "))||"None"})]}),s.sourceChoice.editable?u.jsxs(u.Fragment,{children:[u.jsx("dt",{children:u.jsx("label",{htmlFor:"consent-source",children:"Write source"})}),u.jsxs("dd",{children:[u.jsx("select",{id:"consent-source",value:q,disabled:T,onChange:S=>H(S.target.value),children:s.sourceChoice.options.map(S=>u.jsx("option",{value:S.id,children:S.name===S.id?S.id:`${S.name} (${S.id})`},S.id))}),u.jsxs("div",{style:{color:"var(--text-secondary)",marginTop:4},children:["This client reads and writes only this source. Change it later on the Agents page or with ",u.jsx("code",{children:"gbrain auth rescope --client"}),"."]})]}),u.jsx("dt",{children:"Read sources"}),u.jsx("dd",{children:q})]}):u.jsxs(u.Fragment,{children:[u.jsx("dt",{children:"Write source"}),u.jsx("dd",{children:s.sourceId??"Not configured"}),u.jsx("dt",{children:"Read sources"}),u.jsx("dd",{children:s.allowedSources.length?s.allowedSources.join(", "):s.sourceId??"Not configured"})]}),u.jsx("dt",{children:"Resource"}),u.jsx("dd",{children:u.jsx("code",{children:s.resource??"No resource binding requested"})}),u.jsx("dt",{children:"Request expires"}),u.jsx("dd",{children:new Date(s.expiresAt).toLocaleTimeString()})]}),u.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:12,marginTop:24},children:[u.jsx("button",{className:"btn",disabled:T,onClick:()=>z("deny"),children:"Deny"}),u.jsx("button",{className:"btn btn-primary",disabled:T,onClick:()=>z("approve"),children:T?"Completing request…":"Approve access"})]})]}),b&&u.jsx("button",{className:"btn",onClick:()=>{Hd(),window.location.hash="agents"},children:"Return to agents"})]})}function wd(){const s=window.location.hash.replace("#","")||"dashboard";return Ki()&&s==="dashboard"?"oauth-consent":["login","dashboard","agents","log","calibration","jobs","oauth-consent"].includes(s)?s:"dashboard"}function Py(){const[s,x]=R.useState(wd);R.useEffect(()=>{const T=()=>x(wd());return window.addEventListener("hashchange",T),()=>window.removeEventListener("hashchange",T)},[]);const b=T=>{window.location.hash=T,x(T)};if(s==="login")return u.jsx(Ny,{onLogin:()=>b(Ki()?"oauth-consent":"dashboard")});const o=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 Oe.signOutEverywhere()}catch{}b("login")}};return u.jsxs("div",{className:"app",children:[u.jsxs("nav",{className:"sidebar",children:[u.jsx("div",{className:"sidebar-logo",children:"GBrain"}),u.jsxs("div",{className:"sidebar-nav",children:[u.jsx("a",{className:`nav-item ${s==="dashboard"?"active":""}`,onClick:()=>b("dashboard"),children:"Dashboard"}),u.jsx("a",{className:`nav-item ${s==="agents"?"active":""}`,onClick:()=>b("agents"),children:"Agents"}),u.jsx("a",{className:`nav-item ${s==="log"?"active":""}`,onClick:()=>b("log"),children:"Request Log"}),u.jsx("a",{className:`nav-item ${s==="calibration"?"active":""}`,onClick:()=>b("calibration"),children:"Calibration"}),u.jsx("a",{className:`nav-item ${s==="jobs"?"active":""}`,onClick:()=>b("jobs"),children:"Jobs Watch"})]}),u.jsx("div",{style:{marginTop:"auto",padding:"16px 12px",borderTop:"1px solid var(--border)"},children:u.jsx("button",{onClick:o,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"})})]}),u.jsxs("main",{className:"main",children:[s==="dashboard"&&u.jsx(My,{}),s==="agents"&&u.jsx(Xy,{}),s==="log"&&u.jsx(Jy,{}),s==="calibration"&&u.jsx(Wy,{}),s==="jobs"&&u.jsx(Fy,{}),s==="oauth-consent"&&u.jsx(Iy,{})]})]})}zy.createRoot(document.getElementById("root")).render(u.jsx(Xd.StrictMode,{children:u.jsx(Py,{})}));+`).map(o=>o.trim()).filter(Boolean):[];if(x&&!b.length)throw new Error("Enter the exact redirect URI from your MCP client settings, one per line.");for(const o of b)try{new URL(o)}catch{throw new Error("Each redirect URI must be a complete URI. Copy it exactly from your MCP client settings.")}return{grantTypes:x?["authorization_code","refresh_token"]:["client_credentials"],redirectUris:b,tokenEndpointAuthMethod:s.kind==="public-pkce"?"none":s.kind==="machine"?"client_secret_post":s.confidentialMethod}}function Gy(s){const x=Math.floor((Date.now()-s.getTime())/1e3);return x<60?"just now":x<3600?Math.floor(x/60)+"m ago":x<86400?Math.floor(x/3600)+"h ago":Math.floor(x/86400)+"d ago"}function Xy(){const[s,x]=R.useState([]),[b,o]=R.useState([]),[T,_]=R.useState(!1),[q,H]=R.useState(!1),[z,h]=R.useState(""),[U,S]=R.useState(""),[C,Y]=R.useState(!0),[G,Z]=R.useState(!0),[W,ae]=R.useState(!1),[$,le]=R.useState(!1),[ne,be]=R.useState(),[k,V]=R.useState(),[xe,Se]=R.useState(!1),[se,F]=R.useState(),de=R.useRef(0),we=R.useRef(0),Ne=async()=>{const N=++de.current;Y(!0);try{const w=await Oe.agents();if(N!==de.current)return;x(w),_(!0),h("")}catch(w){N===de.current&&h(w instanceof Error?w.message:"Clients are unavailable.")}finally{N===de.current&&Y(!1)}},Ze=async()=>{const N=++we.current;Z(!0);try{const w=await Oe.sources();if(N!==we.current)return;o(w),H(!0),S("")}catch(w){N===we.current&&(H(!1),S(w instanceof Error?w.message:"Sources are unavailable."))}finally{N===we.current&&Z(!1)}};R.useEffect(()=>(Ne(),Ze(),()=>{de.current++,we.current++}),[]);const E=s.filter(N=>!W||N.status!=="revoked");return u.jsxs(u.Fragment,{children:[u.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12,flexWrap:"wrap",alignItems:"center",marginBottom:24},children:[u.jsx("h1",{className:"page-title",style:{marginBottom:0},children:"Agents"}),u.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[u.jsxs("label",{className:"checkbox-label",children:[u.jsx("input",{type:"checkbox",checked:W,onChange:N=>ae(N.target.checked)}),"Hide revoked"]}),u.jsx("button",{type:"button",className:"btn btn-secondary",disabled:C,onClick:()=>void Ne(),children:"Refresh clients"}),u.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>Se(!0),children:"+ API Key"}),u.jsx("button",{type:"button",className:"btn btn-primary",disabled:!q||!b.length||G,onClick:()=>le(!0),children:"+ OAuth Client"})]})]}),u.jsx("p",{className:"grant-help",style:{marginBottom:16},children:"Owner administration uses this dashboard’s login. An OAuth client’s admin scope allows eligible brain operations; it does not open this dashboard."}),z&&u.jsxs("p",{role:"alert",style:{marginBottom:16,color:"var(--error)"},children:[T?"Showing previously loaded clients. ":"Could not load clients. ",z," ",u.jsx("button",{type:"button",className:"btn btn-secondary",disabled:C,onClick:()=>void Ne(),children:"Retry clients"})]}),U&&u.jsxs("p",{role:"alert",style:{marginBottom:16,color:"var(--error)"},children:["Could not load current sources. Registration and permission changes are unavailable. ",U," ",u.jsx("button",{type:"button",className:"btn btn-secondary",disabled:G,onClick:()=>void Ze(),children:"Retry sources"})]}),!U&&!q&&u.jsx("p",{role:"status",children:"Loading sources before registration…"}),q&&!b.length&&u.jsx("p",{role:"status",children:"No active sources are available. Add or unarchive a source on the host before registering a client."}),!T&&!z&&u.jsx("p",{role:"status",children:"Loading clients…"}),T&&!s.length&&u.jsx("p",{style:{textAlign:"center",padding:48},children:"No clients registered. Register a client to grant access to a harness."}),T&&s.length>0&&!E.length&&u.jsx("p",{style:{textAlign:"center",padding:48},children:"All clients are revoked. Uncheck “Hide revoked” to view them."}),E.length>0&&u.jsxs("div",{style:{overflowX:"auto"},children:[u.jsxs("table",{children:[u.jsx("thead",{children:u.jsxs("tr",{children:[u.jsx("th",{children:"Name"}),u.jsx("th",{children:"Type"}),u.jsx("th",{children:"Scopes"}),u.jsx("th",{children:"Sources"}),u.jsx("th",{children:"Status"}),u.jsx("th",{children:"Requests"}),u.jsx("th",{children:"Last used"})]})}),u.jsx("tbody",{children:E.map(N=>u.jsxs("tr",{onClick:()=>V(N),style:{cursor:"pointer"},children:[u.jsx("td",{children:u.jsx("button",{type:"button",className:"client-name-button",onClick:w=>{w.stopPropagation(),V(N)},children:N.name||N.client_name})}),u.jsx("td",{children:u.jsx("span",{className:"badge "+(N.auth_type==="oauth"?"badge-read":"badge-write"),children:N.auth_type==="oauth"?"OAuth":"API key"})}),u.jsx("td",{children:(N.scope||"").split(" ").filter(Boolean).map(w=>u.jsx("span",{className:"badge badge-"+w,style:{marginRight:4},children:w},w))}),u.jsx("td",{children:N.auth_type==="oauth"?(N.source_id||"none")+" · "+(N.federated_read||[]).length+" readable":"Unscoped"}),u.jsx("td",{children:u.jsx("span",{className:"badge "+(N.status==="active"?"badge-success":"badge-danger"),children:N.status})}),u.jsxs("td",{children:[N.requests_today||0,u.jsxs("span",{style:{color:"var(--text-muted)"},children:[" / ",N.total_requests||0]})]}),u.jsx("td",{children:N.last_used_at?Gy(new Date(N.last_used_at)):"Never"})]},N.auth_type+":"+N.id))})]}),u.jsxs("p",{className:"grant-help",style:{marginTop:12},children:[s.filter(N=>N.status==="active").length," active / ",s.length," total"]})]}),$&&u.jsx(Qy,{sources:b,sourcesReady:q,onClose:()=>le(!1),onRegistered:N=>{le(!1),be(N),Ne()}}),ne&&u.jsxs(_n,{title:"Client registered",titleId:"registered-client-title",onClose:()=>be(void 0),children:[u.jsxs("p",{role:"status",style:{marginBottom:16},children:[ne.name," is registered. Its harness connection has not been verified."]}),u.jsx(Jd,{clientId:ne.clientId,grantTypes:ne.grantTypes})]}),k&&u.jsx(Ly,{agent:k,sources:b,sourcesReady:q,onClose:()=>V(void 0),onChanged:()=>{V(void 0),Ne()},onRescoped:N=>{V(w=>w&&{...w,source_id:N.sourceId,federated_read:N.federatedRead,scope:N.scopes.join(" "),token_ttl:N.tokenTtlSeconds}),Ne()}},k.id),xe&&u.jsx(Vy,{onClose:()=>Se(!1),onCreated:N=>{Se(!1),F(N),Ne()}}),se&&u.jsx(Ky,{token:se,onClose:()=>F(void 0)})]})}function Qy({sources:s,sourcesReady:x,onClose:b,onRegistered:o}){const[T,_]=R.useState(""),[q,H]=R.useState(()=>bs()),[z,h]=R.useState({kind:"machine",redirectUris:"",confidentialMethod:"client_secret_post"}),[U,S]=R.useState(),[C,Y]=R.useState(""),[G,Z]=R.useState(),[W,ae]=R.useState(!1),[$,le]=R.useState(""),[ne,be]=R.useState(),[k,V]=R.useState(!1),xe=()=>{Y(""),Oe.grantCatalog().then(S).catch(F=>Y(F instanceof Error?F.message:"Permission catalog unavailable."))};R.useEffect(xe,[]);const Se=F=>{h(F),Z(void 0)},se=async F=>{if(F.preventDefault(),!(!x||!U||k)){if(!T.trim()){le("Enter a client name.");return}ae(!0),le("");try{const de=(G==null?void 0:G.oauth)??wy(z),we=(G==null?void 0:G.name)??T.trim(),Ne=await Oe.registerClient({...G?Zd(G.grant.after):Ld(q),...de,name:we,dryRun:!G});G?o({clientId:Ne.clientId,name:we,grantTypes:de.grantTypes}):Z({grant:Ne,oauth:de,name:we})}catch(de){le(de instanceof Error?de.message:"Registration failed.");const we=!!G&&Ss(de);if(V(we),G&&(we||de instanceof An&&de.status===409))try{const Ne=(await Oe.agents()).filter(Ze=>Ze.auth_type==="oauth"&&Ze.status==="active"&&(Ze.name||Ze.client_name)===G.name);Ne.length===1&&(be({clientId:Ne[0].id||Ne[0].client_id,name:G.name,grantTypes:Ne[0].grant_types}),V(!0))}catch{}Z(void 0)}finally{ae(!1)}}};return u.jsx(_n,{title:"Register OAuth client",titleId:"register-client-title",onClose:b,busy:W,children:u.jsxs("form",{onSubmit:se,children:[u.jsxs("fieldset",{disabled:W||k,style:{border:0,padding:0},children:[u.jsx("label",{htmlFor:"agent-name",children:"Client name"}),u.jsx("input",{id:"agent-name","data-autofocus":!0,value:T,placeholder:"agent-example",onChange:F=>{_(F.target.value),Z(void 0)}}),u.jsx("label",{htmlFor:"oauth-connection-kind",style:{marginTop:16},children:"Connection type"}),u.jsxs("select",{id:"oauth-connection-kind",value:z.kind,onChange:F=>Se({...z,kind:F.target.value}),children:[u.jsx("option",{value:"machine",children:"Machine credentials"}),u.jsx("option",{value:"public-pkce",children:"Browser sign-in: public client with PKCE"}),u.jsx("option",{value:"confidential-pkce",children:"Browser sign-in: confidential client with PKCE"})]}),u.jsx("p",{className:"grant-help",children:"Choose the method required by your MCP client. Browser sign-in requires the owner’s approval. Public clients use PKCE without a client secret."}),z.kind!=="machine"&&u.jsxs(u.Fragment,{children:[u.jsx("label",{htmlFor:"oauth-redirect-uris",children:"Exact redirect URIs (one per line)"}),u.jsx("textarea",{id:"oauth-redirect-uris",rows:3,value:z.redirectUris,onChange:F=>Se({...z,redirectUris:F.target.value}),placeholder:"https://client.example.com/oauth/callback"}),u.jsx("p",{className:"grant-help",children:"Copy these from the client’s OAuth settings. Keep the complete path and query. GBrain uses S256 PKCE."})]}),z.kind==="confidential-pkce"&&u.jsxs(u.Fragment,{children:[u.jsx("label",{htmlFor:"oauth-client-auth",children:"Client secret authentication"}),u.jsxs("select",{id:"oauth-client-auth",value:z.confidentialMethod,onChange:F=>Se({...z,confidentialMethod:F.target.value}),children:[u.jsx("option",{value:"client_secret_post",children:"client_secret_post (request body)"}),u.jsx("option",{value:"client_secret_basic",children:"client_secret_basic (HTTP Basic)"})]})]}),z.kind==="machine"&&u.jsx("p",{className:"grant-help",children:"Machine handoffs use client_secret_post to renew their access tokens."}),u.jsx("div",{style:{marginTop:24},children:U&&u.jsx(Vd,{draft:q,setDraft:F=>{H(F),Z(void 0)},catalog:U,sources:s})})]}),C&&u.jsxs("p",{role:"alert",style:{color:"var(--error)"},children:[C," ",u.jsx("button",{type:"button",className:"btn btn-secondary",onClick:xe,children:"Retry permissions"})]}),!x&&u.jsx("p",{role:"alert",children:"Current sources are unavailable. Close this form and retry sources before registration."}),G&&u.jsxs(u.Fragment,{children:[u.jsx(Kd,{preview:G.grant}),u.jsxs("div",{"aria-live":"polite",children:[u.jsx("h3",{children:"Review connection"}),u.jsxs("dl",{className:"oauth-consent-details",children:[u.jsx("dt",{children:"Client name"}),u.jsx("dd",{children:G.name}),u.jsx("dt",{children:"Grant types"}),u.jsx("dd",{children:G.oauth.grantTypes.join(", ")}),u.jsx("dt",{children:"Authentication"}),u.jsx("dd",{children:G.oauth.tokenEndpointAuthMethod}),G.oauth.redirectUris.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("dt",{children:"Exact redirect URIs"}),u.jsx("dd",{children:G.oauth.redirectUris.map(F=>u.jsx("div",{children:u.jsx("code",{children:F})},F))})]})]})]})]}),$&&u.jsx("p",{role:"alert",style:{color:"var(--error)",margin:"16px 0"},children:$}),ne&&u.jsxs("div",{role:"status",children:[u.jsxs("p",{children:["A client named ",ne.name," is registered. Open its setup instructions and recover its existing download."]}),u.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>o(ne),children:"Open existing client setup"})]}),k&&!ne&&u.jsx("p",{role:"status",children:"Registration may have completed. Close this form and refresh clients before trying again. No automatic retry was made."}),u.jsxs("div",{style:{display:"flex",gap:12,justifyContent:"flex-end",marginTop:20},children:[u.jsx("button",{type:"button",className:"btn btn-secondary",disabled:W,onClick:b,children:"Cancel"}),u.jsx("button",{type:"submit",className:"btn btn-primary",disabled:W||!U||!x||k,children:W?"Checking…":G?"Register with reviewed permissions":"Preview permissions"})]})]})})}function Ly({agent:s,sources:x,sourcesReady:b,onClose:o,onChanged:T,onRescoped:_}){const q=s.id||s.client_id||"",H=s.name||s.client_name||q,[z,h]=R.useState(),[U,S]=R.useState(""),[C,Y]=R.useState(0),[G,Z]=R.useState(!1),[W,ae]=R.useState(!1);return R.useEffect(()=>{if(s.auth_type!=="oauth")return;let $=!0;return S(""),Oe.clientDetails(q).then(le=>{$&&h(le)}).catch(le=>{$&&S(le instanceof Error?le.message:"Client details unavailable.")}),()=>{$=!1}},[q,s.auth_type,C]),u.jsxs(_n,{title:H,titleId:"client-details-title",onClose:o,drawer:!0,busy:W,children:[u.jsx("span",{className:"badge "+(s.status==="active"?"badge-success":"badge-danger"),children:s.status}),u.jsxs("dl",{className:"oauth-consent-details",style:{marginTop:16},children:[u.jsx("dt",{children:"Client ID"}),u.jsx("dd",{children:u.jsx("code",{children:q})}),u.jsx("dt",{children:"Scopes"}),u.jsx("dd",{children:s.scope||"None"}),u.jsx("dt",{children:"Registered"}),u.jsx("dd",{children:new Date(s.created_at).toLocaleString()}),u.jsx("dt",{children:"Token lifetime"}),u.jsx("dd",{children:s.token_ttl?s.token_ttl+" seconds":"Server default (future tokens)"}),z&&u.jsxs(u.Fragment,{children:[u.jsx("dt",{children:"Grant types"}),u.jsx("dd",{children:z.client.grant_types.join(", ")}),u.jsx("dt",{children:"Authentication"}),u.jsx("dd",{children:z.client.token_endpoint_auth_method})]})]}),s.auth_type==="oauth"?u.jsxs(u.Fragment,{children:[U&&u.jsxs("p",{role:"alert",style:{color:"var(--error)"},children:[U," ",u.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>Y($=>$+1),children:"Retry client details"})]}),!z&&!U&&u.jsx("p",{role:"status",children:"Loading client details…"}),z&&u.jsxs(u.Fragment,{children:[u.jsx(Jd,{clientId:q,grantTypes:z.client.grant_types,revoked:s.status==="revoked",grantRevision:z.grant.revision}),s.status==="active"&&u.jsxs("details",{style:{marginTop:24},children:[u.jsx("summary",{style:{cursor:"pointer",fontWeight:600},children:"Edit access levels"}),u.jsx(qy,{clientId:q,sources:x,sourcesReady:b,onRescoped:$=>{h(le=>le&&{...le,grant:$}),_($)}})]}),u.jsx(Yy,{clientId:q,name:H,revoked:s.status==="revoked",onChanged:T,onBusyChange:ae})]})]}):u.jsxs(u.Fragment,{children:[u.jsx("h3",{className:"section-title",children:"API key"}),u.jsx("p",{children:"Use this key as a bearer token in a client that supports static authentication. Its value is available only in the original private handoff."}),s.status==="active"&&u.jsxs("div",{style:{marginTop:20},children:[G?u.jsxs(u.Fragment,{children:[u.jsxs("p",{children:["Revoke the API key ",H," (",q,")? Only this key stops working. Memory remains."]}),u.jsx("button",{type:"button",className:"btn btn-secondary",disabled:W,onClick:()=>Z(!1),children:"Cancel"})," ",u.jsx("button",{type:"button",className:"btn btn-danger",disabled:W,onClick:()=>{ae(!0),Oe.revokeApiKey(q).then(T).catch($=>S($ instanceof Error?$.message:"Revoke failed. Refresh the client list before retrying.")).finally(()=>ae(!1))},children:"Confirm revoke"})]}):u.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>Z(!0),children:"Revoke API key"}),U&&u.jsx("p",{role:"alert",children:U})]})]})]})}const Zy=[{id:"read",label:"Read",help:"Search and read memory."},{id:"write",label:"Write",help:"Add and edit memory."},{id:"admin",label:"Admin",help:"Brain administration operations. Grant only to fully trusted clients."}];function Vy({onClose:s,onCreated:x}){const[b,o]=R.useState(""),[T,_]=R.useState(!1),[q,H]=R.useState(""),[z,h]=R.useState(["read","write"]),U=async S=>{if(S.preventDefault(),!b.trim()){H("Enter a key name.");return}if(z.length===0){H("Choose at least one access level.");return}_(!0),H("");try{const C=await Oe.createApiKey(b.trim(),z);x({name:C.name,token:C.token})}catch(C){H(C instanceof Error?C.message:"Key creation failed. Inspect the clients list before retrying.")}finally{_(!1)}};return u.jsx(_n,{title:"Create API key",titleId:"create-api-key-title",onClose:s,busy:T,children:u.jsxs("form",{onSubmit:U,children:[u.jsx("p",{className:"grant-help",children:"API keys default to read and write. Admin is granted only when you check it. Choose an OAuth client for per-source or per-operation access. This key cannot log into the owner dashboard."}),u.jsx("label",{htmlFor:"api-key-name",children:"Key name"}),u.jsx("input",{id:"api-key-name","data-autofocus":!0,value:b,maxLength:128,disabled:T,onChange:S=>o(S.target.value)}),u.jsxs("fieldset",{style:{marginTop:16},children:[u.jsx("legend",{children:"Access levels"}),Zy.map(S=>u.jsxs("label",{style:{display:"block"},children:[u.jsx("input",{type:"checkbox",checked:z.includes(S.id),disabled:T,onChange:C=>h(Y=>C.target.checked?[...Y,S.id]:Y.filter(G=>G!==S.id))})," ",S.label," ",u.jsx("span",{className:"grant-help",children:S.help})]},S.id))]}),q&&u.jsx("p",{role:"alert",children:q}),u.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:12,marginTop:20},children:[u.jsx("button",{type:"button",className:"btn btn-secondary",disabled:T,onClick:s,children:"Cancel"}),u.jsx("button",{type:"submit",className:"btn btn-primary",disabled:T,children:T?"Creating…":"Create key"})]})]})})}function Ky({token:s,onClose:x}){const[b,o]=R.useState(!1),[T,_]=R.useState("");return u.jsxs(_n,{title:"API key created",titleId:"api-key-created-title",onClose:x,children:[u.jsx("p",{children:s.name}),u.jsx("label",{htmlFor:"new-api-key",children:"Bearer token"}),u.jsx("textarea",{id:"new-api-key",rows:3,readOnly:!0,value:s.token}),u.jsx("p",{className:"grant-help",children:"Save this token privately now. It will not be shown again. A key’s creation does not verify your harness connection."}),u.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>{navigator.clipboard.writeText(s.token).then(()=>o(!0)).catch(()=>_("Clipboard unavailable. Select and copy the token above."))},children:b?"Copied":"Copy token"}),T&&u.jsx("p",{role:"alert",children:T}),u.jsx("button",{type:"button",className:"btn btn-primary",style:{marginLeft:12},onClick:x,children:"Done"})]})}function Jy(){const[s,x]=R.useState({rows:[],total:0,page:1,pages:1}),[b,o]=R.useState(1),[T,_]=R.useState("all"),[q,H]=R.useState(null);R.useEffect(()=>{z(b)},[b,T]);const z=C=>{const Y=T!=="all"?`&agent=${encodeURIComponent(T)}`:"";Oe.requests(C,Y).then(x).catch(()=>{})},h=C=>{const Y=Date.now()-new Date(C).getTime();return Y<6e4?`${Math.floor(Y/1e3)}s ago`:Y<36e5?`${Math.floor(Y/6e4)} min ago`:Y<864e5?`${Math.floor(Y/36e5)}h ago`:new Date(C).toLocaleDateString()},U=C=>{if(!C)return null;const{query:Y,slug:G,partial:Z,limit:W,...ae}=C,$=[];return Y&&$.push(`"${Y}"`),G&&$.push(G),Z&&$.push(`~${Z}`),W&&$.push(`limit=${W}`),Object.keys(ae).length>0&&$.push(`+${Object.keys(ae).length} params`),$.join(" ")},S=new Map;return s.rows.forEach(C=>{C.token_name&&S.set(C.token_name,C.agent_name||C.token_name)}),u.jsxs(u.Fragment,{children:[u.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:24},children:[u.jsx("h1",{className:"page-title",style:{marginBottom:0},children:"Request Log"}),u.jsxs("select",{value:T,onChange:C=>{_(C.target.value),o(1)},style:{background:"var(--bg-secondary)",color:"var(--text-primary)",border:"1px solid var(--border)",borderRadius:6,padding:"4px 8px",fontSize:13},children:[u.jsx("option",{value:"all",children:"All agents"}),[...S.entries()].map(([C,Y])=>u.jsx("option",{value:C,children:Y},C))]})]}),s.rows.length===0?u.jsx("div",{style:{textAlign:"center",padding:48,color:"var(--text-muted)"},children:"No requests yet."}):u.jsxs(u.Fragment,{children:[u.jsxs("table",{children:[u.jsx("thead",{children:u.jsxs("tr",{children:[u.jsx("th",{children:"Time"}),u.jsx("th",{children:"Agent"}),u.jsx("th",{children:"Operation"}),u.jsx("th",{children:"Params"}),u.jsx("th",{children:"Latency"}),u.jsx("th",{children:"Status"})]})}),u.jsx("tbody",{children:s.rows.map(C=>u.jsxs(Xd.Fragment,{children:[u.jsxs("tr",{onClick:()=>H(q===C.id?null:C.id),style:{cursor:"pointer"},children:[u.jsx("td",{style:{color:"var(--text-secondary)",whiteSpace:"nowrap"},children:h(C.created_at)}),u.jsx("td",{children:u.jsx("a",{style:{color:"var(--text-link, #88aaff)",cursor:"pointer",textDecoration:"none",fontWeight:500},onClick:Y=>{Y.stopPropagation(),_(C.token_name),o(1)},children:C.agent_name||C.token_name})}),u.jsx("td",{className:"mono",children:C.operation}),u.jsx("td",{style:{color:"var(--text-secondary)",fontSize:12,maxWidth:200,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:U(C.params)}),u.jsxs("td",{className:"mono",children:[C.latency_ms,"ms"]}),u.jsx("td",{children:u.jsx("span",{className:`badge badge-${C.status}`,children:C.status})})]}),q===C.id&&u.jsx("tr",{children:u.jsx("td",{colSpan:6,style:{background:"var(--bg-secondary, #0f0f1a)",padding:16},children:u.jsxs("div",{style:{display:"grid",gridTemplateColumns:"100px 1fr",gap:"6px 12px",fontSize:13},children:[u.jsx("span",{style:{color:"var(--text-muted)"},children:"Time"}),u.jsx("span",{children:new Date(C.created_at).toLocaleString()}),u.jsx("span",{style:{color:"var(--text-muted)"},children:"Agent"}),u.jsx("span",{className:"mono",children:C.token_name}),u.jsx("span",{style:{color:"var(--text-muted)"},children:"Operation"}),u.jsx("span",{className:"mono",children:C.operation}),u.jsx("span",{style:{color:"var(--text-muted)"},children:"Latency"}),u.jsxs("span",{children:[C.latency_ms,"ms"]}),C.params&&u.jsxs(u.Fragment,{children:[u.jsx("span",{style:{color:"var(--text-muted)"},children:"Params"}),u.jsx("pre",{className:"mono",style:{margin:0,whiteSpace:"pre-wrap",fontSize:12},children:JSON.stringify(C.params,null,2)})]}),C.error_message&&u.jsxs(u.Fragment,{children:[u.jsx("span",{style:{color:"var(--error, #ff6b6b)"},children:"Error"}),u.jsx("span",{style:{color:"var(--error, #ff6b6b)"},children:C.error_message})]})]})})})]},C.id))})]}),u.jsxs("div",{className:"pagination",children:[u.jsxs("span",{children:["Page ",s.page," of ",s.pages," (",s.total," total",s.retention_days?`, details kept for ${s.retention_days} days`:"",")",s.pruned_before?` · older requests were pruned before ${new Date(s.pruned_before).toLocaleDateString()}`:""]}),u.jsxs("div",{style:{display:"flex",gap:8},children:[u.jsx("button",{disabled:s.page<=1,onClick:()=>o(C=>C-1),children:"Previous"}),u.jsx("button",{disabled:s.page>=s.pages,onClick:()=>o(C=>C+1),children:"Next"})]})]})]})]})}function ky({markup:s}){return u.jsx("div",{style:{width:"100%",overflow:"auto"},dangerouslySetInnerHTML:{__html:s}})}function Vi({type:s,ariaLabel:x}){const[b,o]=R.useState(""),[T,_]=R.useState("");return R.useEffect(()=>{let q=!1;return Oe.calibrationChart(s).then(H=>{q||o(H)}).catch(H=>{q||_(H.message??"fetch failed")}),()=>{q=!0}},[s]),T?u.jsxs("div",{style:{padding:16,color:"var(--error)"},role:"alert",children:[x,": ",T]}):b?u.jsx(ky,{markup:b}):u.jsxs("div",{style:{padding:16,color:"var(--text-muted)"},children:[x," loading..."]})}function Wy(){const[s,x]=R.useState(null),[b,o]=R.useState(!0),[T,_]=R.useState("");if(R.useEffect(()=>{Oe.calibrationProfile().then(z=>{x(z),o(!1)}).catch(z=>{_(z.message??"fetch failed"),o(!1)})},[]),b)return u.jsx("div",{style:{padding:24,color:"var(--text-secondary)"},children:"Loading calibration profile…"});if(T)return u.jsxs("div",{style:{padding:24,color:"var(--error)"},role:"alert",children:["Could not load calibration profile: ",T]});if(!s)return u.jsxs("div",{style:{padding:24,maxWidth:700},children:[u.jsx("h1",{style:{marginBottom:16},children:"Calibration"}),u.jsx("p",{style:{color:"var(--text-secondary)"},children:"No calibration profile yet. Builds after 5+ resolved takes."}),u.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 q=new Date(s.generated_at),H=Math.floor((Date.now()-q.getTime())/(1e3*60*60*24));return u.jsxs("div",{style:{padding:32,maxWidth:720},children:[u.jsx("h1",{style:{marginBottom:8},children:"Calibration"}),u.jsxs("div",{style:{color:"var(--text-muted)",fontSize:13,marginBottom:24},children:["Holder: ",s.holder," · ","Updated ",H===0?"today":`${H}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"]}),u.jsx("section",{style:{marginBottom:32},children:u.jsx(Vi,{type:"brier-trend",ariaLabel:"Brier trend"})}),u.jsxs("section",{style:{marginBottom:32},children:[u.jsx("h2",{style:{fontSize:14,color:"var(--text-secondary)",marginBottom:12,fontWeight:400},children:"Pattern statements"}),u.jsx(Vi,{type:"pattern-statements",ariaLabel:"Pattern statements"})]}),u.jsx("section",{style:{marginBottom:32},children:u.jsx(Vi,{type:"domain-bars",ariaLabel:"Per-domain accuracy"})}),u.jsx("section",{style:{marginBottom:32},children:u.jsx(Vi,{type:"abandoned-threads",ariaLabel:"Abandoned threads"})}),s.active_bias_tags.length>0&&u.jsxs("section",{style:{marginBottom:32,color:"var(--text-muted)",fontSize:13},children:["Active bias tags: ",s.active_bias_tags.join(", ")]})]})}function $y(s){return s===0?"var(--accent-success, #2ea043)":s>=100?"var(--accent-danger, #f85149)":"var(--accent-warn, #d29922)"}function Yd(s){return`$${(s/100).toFixed(2)}`}function Fy(){const[s,x]=R.useState(null),[b,o]=R.useState(null);if(R.useEffect(()=>{let _=!0,q=null;const H=async()=>{try{const z=await Oe.jobsWatch();_&&(x(z),o(null))}catch(z){_&&o(z instanceof Error?z.message:String(z))}_&&(q=setTimeout(H,1e3))};return H(),()=>{_=!1,q&&clearTimeout(q)}},[]),b)return u.jsxs("div",{style:{padding:24,color:"var(--accent-danger, #f85149)"},children:[u.jsx("h2",{children:"Jobs Watch — error"}),u.jsx("pre",{style:{whiteSpace:"pre-wrap"},children:b})]});if(!s)return u.jsx("div",{style:{padding:24,color:"var(--text-muted, #777)"},children:"Loading jobs watch…"});const T=new Date(s.ts_ms).toLocaleTimeString();return u.jsxs("div",{style:{padding:24,fontFamily:'var(--font-mono, "JetBrains Mono", monospace)'},children:[u.jsxs("h1",{style:{fontSize:18,marginBottom:4},children:["Jobs Watch",u.jsxs("span",{style:{marginLeft:12,color:"var(--text-muted, #777)",fontSize:12,fontWeight:"normal"},children:["updated ",T]})]}),u.jsxs("section",{style:{marginTop:24},children:[u.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Queue"}),u.jsxs("div",{children:["waiting=",u.jsx("b",{children:s.queue_health.waiting})," ","active=",u.jsx("b",{children:s.queue_health.active})," ","stalled=",u.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&&u.jsxs("section",{style:{marginTop:24},children:[u.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"By type (24h)"}),u.jsxs("table",{style:{borderCollapse:"collapse"},children:[u.jsx("thead",{children:u.jsxs("tr",{style:{color:"var(--text-muted, #777)",fontSize:12},children:[u.jsx("th",{style:{textAlign:"left",padding:"4px 12px 4px 0"},children:"name"}),u.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"total"}),u.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"done"}),u.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"fail"}),u.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"dead"})]})}),u.jsx("tbody",{children:s.by_type.slice(0,6).map(_=>u.jsxs("tr",{children:[u.jsx("td",{style:{padding:"4px 12px 4px 0"},children:_.name}),u.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.total}),u.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.completed}),u.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.failed}),u.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.dead})]},_.name))})]})]}),u.jsxs("section",{style:{marginTop:24},children:[u.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Lease pressure (1h)"}),u.jsxs("div",{style:{color:$y(s.lease_pressure_1h)},children:[s.lease_pressure_1h," bounce",s.lease_pressure_1h===1?"":"s"]})]}),s.top_errors.length>0&&u.jsxs("section",{style:{marginTop:24},children:[u.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Top errors (24h)"}),u.jsx("table",{style:{borderCollapse:"collapse"},children:u.jsx("tbody",{children:s.top_errors.slice(0,5).map(_=>u.jsxs("tr",{children:[u.jsxs("td",{style:{textAlign:"right",padding:"4px 12px 4px 0",color:"var(--text-muted, #777)"},children:[_.count,"×"]}),u.jsx("td",{style:{padding:"4px 12px 4px 0"},children:_.cluster})]},_.cluster))})})]}),s.budget_owners.length>0&&u.jsxs("section",{style:{marginTop:24},children:[u.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Budget owners"}),u.jsxs("table",{style:{borderCollapse:"collapse"},children:[u.jsx("thead",{children:u.jsxs("tr",{style:{color:"var(--text-muted, #777)",fontSize:12},children:[u.jsx("th",{style:{textAlign:"left",padding:"4px 12px 4px 0"},children:"owner"}),u.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"spent"}),u.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"remaining"})]})}),u.jsx("tbody",{children:s.budget_owners.slice(0,5).map(_=>u.jsxs("tr",{children:[u.jsx("td",{style:{padding:"4px 12px 4px 0"},children:_.owner_id}),u.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:Yd(_.total_spent_cents)}),u.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:Yd(_.remaining_cents)})]},_.owner_id))})]})]})]})}function Iy(){var h,U;const[s,x]=R.useState(),[b,o]=R.useState(""),[T,_]=R.useState(!1),[q,H]=R.useState("");R.useEffect(()=>{let S=!0;const C=Ki();if(!C){o("No pending authorization request. Restart the connection from your client.");return}return Oe.oauthRequest(C).then(Y=>{S&&(x(Y),H(Y.sourceId??""))}).catch(Y=>{S&&o(Y.message)}),()=>{S=!1}},[]);const z=async S=>{if(!(!s||T)){_(!0),o("");try{const C=S==="approve"&&s.sourceChoice.editable&&q!==s.sourceId?q:void 0,Y=await Oe.decideOAuthRequest(s.id,S,s.csrf,C);Hd(),window.location.assign(Y.redirectUrl)}catch(C){o(C instanceof Error?C.message:"Approval failed. Restart the connection from your client."),x(void 0),_(!1)}}};return u.jsxs("section",{"aria-labelledby":"consent-title",style:{maxWidth:760},children:[u.jsx("h1",{id:"consent-title",children:"Approve client access"}),u.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."}),b&&u.jsx("div",{role:"alert",className:"login-error",style:{marginBottom:16},children:b}),!s&&!b&&u.jsx("p",{role:"status",children:"Loading authorization request…"}),s&&u.jsxs(u.Fragment,{children:[u.jsxs("dl",{className:"oauth-consent-details",children:[u.jsx("dt",{children:"Client"}),u.jsx("dd",{children:s.clientName}),u.jsx("dt",{children:"Client ID"}),u.jsx("dd",{children:u.jsx("code",{children:s.clientId})}),u.jsx("dt",{children:"Redirect destination"}),u.jsx("dd",{children:u.jsx("code",{children:s.redirectUri})}),u.jsx("dt",{children:"Permissions"}),u.jsx("dd",{children:s.scopes.length?s.scopes.map(S=>u.jsx("span",{className:`badge ${S.includes("admin")?"badge-error":""}`,style:{marginRight:8},children:S},S)):"No permissions"}),u.jsx("dt",{children:"Administrative brain operations"}),u.jsx("dd",{children:s.scopes.some(S=>S==="admin")?"Eligible operations within the grant below. This does not grant owner dashboard access.":s.scopes.some(S=>S.endsWith("_admin"))?"The named administrative brain operations. This does not grant owner dashboard access.":"None"}),u.jsx("dt",{children:"Allowed operations"}),u.jsx("dd",{children:s.allowedOperations===null?"All operations permitted by these scopes and the server policy":s.allowedOperations.join(", ")||"None"}),u.jsx("dt",{children:"Write paths"}),u.jsx("dd",{children:s.boundSlugPrefixes===null?"Within the granted source":s.boundSlugPrefixes.join(", ")||"None"}),s.scopes.includes("agent")&&u.jsxs(u.Fragment,{children:[u.jsx("dt",{children:"Delegated tools"}),u.jsx("dd",{children:((h=s.delegatedTools)==null?void 0:h.join(", "))||"None"}),u.jsx("dt",{children:"Delegated write paths"}),u.jsx("dd",{children:s.delegatedNamespace==="job"?"A separate namespace for each job":((U=s.delegatedSlugPrefixes)==null?void 0:U.join(", "))||"None"})]}),s.sourceChoice.editable?u.jsxs(u.Fragment,{children:[u.jsx("dt",{children:u.jsx("label",{htmlFor:"consent-source",children:"Write source"})}),u.jsxs("dd",{children:[u.jsx("select",{id:"consent-source",value:q,disabled:T,onChange:S=>H(S.target.value),children:s.sourceChoice.options.map(S=>u.jsx("option",{value:S.id,children:S.name===S.id?S.id:`${S.name} (${S.id})`},S.id))}),u.jsxs("div",{style:{color:"var(--text-secondary)",marginTop:4},children:["This client reads and writes only this source. Change it later on the Agents page or with ",u.jsx("code",{children:"gbrain auth rescope --client"}),"."]})]}),u.jsx("dt",{children:"Read sources"}),u.jsx("dd",{children:q})]}):u.jsxs(u.Fragment,{children:[u.jsx("dt",{children:"Write source"}),u.jsx("dd",{children:s.sourceId??"Not configured"}),u.jsx("dt",{children:"Read sources"}),u.jsx("dd",{children:s.allowedSources.length?s.allowedSources.join(", "):s.sourceId??"Not configured"})]}),u.jsx("dt",{children:"Resource"}),u.jsx("dd",{children:u.jsx("code",{children:s.resource??"No resource binding requested"})}),u.jsx("dt",{children:"Request expires"}),u.jsx("dd",{children:new Date(s.expiresAt).toLocaleTimeString()})]}),u.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:12,marginTop:24},children:[u.jsx("button",{className:"btn",disabled:T,onClick:()=>z("deny"),children:"Deny"}),u.jsx("button",{className:"btn btn-primary",disabled:T,onClick:()=>z("approve"),children:T?"Completing request…":"Approve access"})]})]}),b&&u.jsx("button",{className:"btn",onClick:()=>{Hd(),window.location.hash="agents"},children:"Return to agents"})]})}function wd(){const s=window.location.hash.replace("#","")||"dashboard";return Ki()&&s==="dashboard"?"oauth-consent":["login","dashboard","agents","log","calibration","jobs","oauth-consent"].includes(s)?s:"dashboard"}function Py(){const[s,x]=R.useState(wd);R.useEffect(()=>{const T=()=>x(wd());return window.addEventListener("hashchange",T),()=>window.removeEventListener("hashchange",T)},[]);const b=T=>{window.location.hash=T,x(T)};if(s==="login")return u.jsx(Ny,{onLogin:()=>b(Ki()?"oauth-consent":"dashboard")});const o=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 Oe.signOutEverywhere()}catch{}b("login")}};return u.jsxs("div",{className:"app",children:[u.jsxs("nav",{className:"sidebar",children:[u.jsx("div",{className:"sidebar-logo",children:"GBrain"}),u.jsxs("div",{className:"sidebar-nav",children:[u.jsx("a",{className:`nav-item ${s==="dashboard"?"active":""}`,onClick:()=>b("dashboard"),children:"Dashboard"}),u.jsx("a",{className:`nav-item ${s==="agents"?"active":""}`,onClick:()=>b("agents"),children:"Agents"}),u.jsx("a",{className:`nav-item ${s==="log"?"active":""}`,onClick:()=>b("log"),children:"Request Log"}),u.jsx("a",{className:`nav-item ${s==="calibration"?"active":""}`,onClick:()=>b("calibration"),children:"Calibration"}),u.jsx("a",{className:`nav-item ${s==="jobs"?"active":""}`,onClick:()=>b("jobs"),children:"Jobs Watch"})]}),u.jsx("div",{style:{marginTop:"auto",padding:"16px 12px",borderTop:"1px solid var(--border)"},children:u.jsx("button",{onClick:o,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"})})]}),u.jsxs("main",{className:"main",children:[s==="dashboard"&&u.jsx(My,{}),s==="agents"&&u.jsx(Xy,{}),s==="log"&&u.jsx(Jy,{}),s==="calibration"&&u.jsx(Wy,{}),s==="jobs"&&u.jsx(Fy,{}),s==="oauth-consent"&&u.jsx(Iy,{})]})]})}zy.createRoot(document.getElementById("root")).render(u.jsx(Xd.StrictMode,{children:u.jsx(Py,{})}));diff --git a/admin/dist/index.html b/admin/dist/index.htmlindex 19a2513a9c..ded37f4272 100644--- a/admin/dist/index.html+++ b/admin/dist/index.html@@ -7,7 +7,7 @@<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-B9c8JuNx.js"></script>+ <script type="module" crossorigin src="/admin/assets/index-c5YhzUcc.js"></script><link rel="stylesheet" crossorigin href="/admin/assets/index-BB8hJoAN.css"></head><body>diff --git a/admin/src/pages/RequestLog.tsx b/admin/src/pages/RequestLog.tsxindex fe495252b8..748a0a5494 100644--- a/admin/src/pages/RequestLog.tsx+++ b/admin/src/pages/RequestLog.tsx@@ -14,7 +14,7 @@ interface LogEntry {}export function RequestLogPage() {- const [data, setData] = useState<{ rows: LogEntry[]; total: number; page: number; pages: number }>({+ const [data, setData] = useState<{ rows: LogEntry[]; total: number; page: number; pages: number; retention_days?: number | null; pruned_before?: string | null }>({rows: [], total: 0, page: 1, pages: 1,});const [page, setPage] = useState(1);@@ -137,7 +137,10 @@ export function RequestLogPage() {</table><div className="pagination">- <span>Page {data.page} of {data.pages} ({data.total} total)</span>+ <span>+ Page {data.page} of {data.pages} ({data.total} total{data.retention_days ? `, details kept for ${data.retention_days} days` : ''})+ {data.pruned_before ? ` · older requests were pruned before ${new Date(data.pruned_before).toLocaleDateString()}` : ''}+ </span><div style={{ display: 'flex', gap: 8 }}><button disabled={data.page <= 1} onClick={() => setPage(p => p - 1)}>Previous</button><button disabled={data.page >= data.pages} onClick={() => setPage(p => p + 1)}>Next</button>diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex b3ef3ebc8b..2ec2be5a5c 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -15,7 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/anomalies.ts` — `gbrain anomalies [--since YYYY-MM-DD] [--lookback-days N] [--sigma N] [--json]`: cohort-level activity outliers. Calls `engine.findAnomalies(opts)`. Two cohort kinds: tag, type. At most 20 `page_slugs` per cohort (`page_slugs_complete: false`; local `--all` lists all; `test/anomalies-bounded-7246.test.ts`).-- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`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`), federated reads (`federated_read`) and the operation snapshot — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `clientOperationsView` reports four distinct operation states (SQL NULL = `operations: "all"` with `includes_future_operations: true` and a re-pin `fix` naming `auth rescope --client <id> --operations <list>` or `--profile`; `[]` = deny-all; an explicit list; `unavailable` when the schema predates `allowed_operations`) and marks soft-revoked clients (`deleted_at`) `revoked` with no fix (`test/auth-clients-operations.test.ts`, both engines); `tokenLifetimeClampedClients` reads the migration's `clamp_token_ttl` / `shorten_access_tokens` audit rows so the listing marks clients whose access-token lifetime an upgrade brought inside 90 days (`token_lifetime_clamped` in `--json`); the `TOKEN_TTL_*` bounds are re-exported from `src/core/grants/model.ts`; `--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`. F3: `gbrain auth rescope` (`runRescope`) is the one grant editor for tokens (`--token`/`--id`) and OAuth clients (`--client`), with a bare-name resolver, `--migrate-legacy [--dry-run]`, and refusals printed as JSON on stdout under `--json`; `rescope-token`, `rescope-client` and `permissions set-takes-holders` are aliases routed through it.+- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`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`), federated reads (`federated_read`) and the operation snapshot — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `clientOperationsView` reports four distinct operation states (SQL NULL = `operations: "all"` with `includes_future_operations: true` and a re-pin `fix` naming `auth rescope --client <id> --operations <list>` or `--profile`; `[]` = deny-all; an explicit list; `unavailable` when the schema predates `allowed_operations`) and marks soft-revoked clients (`deleted_at`) `revoked` with no fix (`test/auth-clients-operations.test.ts`, both engines); `tokenLifetimeClampedClients` reads the migration's `clamp_token_ttl` / `shorten_access_tokens` audit rows so the listing marks clients whose access-token lifetime an upgrade brought inside 90 days (`token_lifetime_clamped` in `--json`); the `TOKEN_TTL_*` bounds are re-exported from `src/core/grants/model.ts`; `--usage` joins op-call counts and coverage 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`. F3: `gbrain auth rescope` (`runRescope`) is the one grant editor for tokens (`--token`/`--id`) and OAuth clients (`--client`), with a bare-name resolver, `--migrate-legacy [--dry-run]`, and refusals printed as JSON on stdout under `--json`; `rescope-token`, `rescope-client` and `permissions set-takes-holders` are aliases routed through it.- `src/commands/autopilot-retry-global.ts` — `gbrain autopilot --retry-global [--phase <name>] [--json]` (GBRA-130 A-10): clears `retry_at` on the backed-off phase streaks in `autopilot.global_maintenance.progress` (one phase, or all), keeping each count, so the next brain-wide pass runs the phase again; names a running `autopilot-global-maintenance` job, whose next progress save can restore the back-off. Test: `test/pathological/a10-global-maintenance-stamp.test.ts`.- `src/commands/autopilot-pause.ts` — engine-free `gbrain autopilot pause [--reason <text>]` / `resume`: writes or removes the operator marker `autopilot-operator-paused` (`autopilotOperatorPauseMarkerPath` in `src/core/autopilot-paths.ts`, with `autopilotPaused()` and `autopilotPauseReason()`). The daemon loop and job workers honor it like the migration hold; `--install` (and so `gbrain upgrade`) clears only a leaked migration hold, and resume never clears a migration or restore hold. Test: `test/autopilot-operator-pause.test.ts`.diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex 396aff9731..8c1dbf0fe4 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -24,7 +24,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/serve-http.ts` — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. The legacy `POST /ingest` queue refuses operation-snapshot clients; they use approved MCP writes so execution stays inside the shared grant contract. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]`. OAuth discovery's `scopes_supported` (RFC 8414 AS metadata and both RFC 9728 protected-resource documents, one value through the SDK router) comes from `scopesSupportedForDiscovery({ enableDcr })` in `src/core/scope.ts`: with `--enable-dcr` it is exactly the self-registration ceiling (`read write`), so a client that copies discovery into its `/register` request succeeds; without DCR it is every scope except operator-only `agent`. The DCR ceiling still rejects an explicit privileged request, and operator-registered clients are never narrowed by the advertisement. Combines MCP SDK's `mcpAuthRouter` (authorize/token/register/revoke), a custom `client_credentials` handler running BEFORE the router (SDK's token endpoint throws `UnsupportedGrantTypeError` for CC; custom handler falls through for `auth_code` / `refresh_token`), `requireBearerAuth` middleware for `/mcp` with scope enforcement + `localOnly` rejection before op dispatch, and per-IP `express-rate-limit` buckets: the MCP SDK's defaults on `/authorize` (100 / 15 min), `/register` (20 / hour) and `/token` (50 / 15 min) because `authRouterOptions` passes no `rateLimit: false`, the custom `client_credentials` handler's `ccRateLimiter`, and independent owner limits: 60 total authentication requests/min/IP, 10 failed authentications/min/IP (verified authority, independent of response status), and 60 consent requests/min/authenticated session in `serve-http-admin-limits.ts`. Admin no-store, no-referrer and framing headers precede login/link handlers. Explicit pending IDs survive fresh-browser links; invalid or restarted requests require native authorization to restart. Serves the built admin SPA from `admin/dist/` with SPA fallback. `/admin/events` SSE broadcasts every MCP request. `cookie-parser` wired (Express 5 has no built-in). Startup logging prints port, engine, issuer URL (honors `--public-url`), client count, DCR status, and the admin bootstrap token line — but the generated token's raw value only prints when stderr is an interactive TTY (`shouldSuppressBootstrapPrint`): a non-TTY (containerized/piped) start hides it so the secret never lands in centralized log storage, env-sourced tokens (`$GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) are always hidden, `--print-admin-token` forces the raw value on a trusted terminal, and `--suppress-bootstrap-token` hides everything. The `/mcp` request handler's OperationContext literal sets `remote: true` explicitly (without it `submit_job`'s protected-name guard would see a falsy undefined and a `read+write`-scoped OAuth token could submit `shell` jobs). `summarizeMcpParams` from `src/mcp/dispatch.ts` feeds both `mcp_request_log` writes and the SSE feed by default (raw via `--log-full-params`). Cookie `Secure` flag set behind HTTPS or a public-URL proxy; magic-link nonce store LRU-bounded; DCR disable routes through the `GBrainOAuthProvider` `dcrDisabled` constructor option (not a router monkey-patch); `transport.handleRequest` wrapped in try/catch to return a JSON-RPC 500 envelope; OperationError + unexpected exceptions unified through `buildError` / `serializeError` so `/mcp` always returns the same envelope. `/health` is liveness-only via `probeLiveness(engine, engineName, version, timeoutMs)` racing `engine.executeRaw('SELECT 1', undefined, { signal })` against the exported `HEALTH_TIMEOUT_MS = 3000`; when the timeout wins, an `AbortController` cancels the Postgres query (PGLite can only discard its eventual result) before the same tagged `ProbeHealthResult` 503 envelope is returned (single timer-cleanup site); body shape `{status, version, engine}` only. Full stats live at admin-only `/admin/api/full-stats` (gated by `requireAdmin`, calls `probeHealth(engine, ...)`) — keeps `getStats()`'s 6× count(*) off the public route so a saturated pool doesn't trigger orchestrator restart cascades. OAuth/admin/audit SQL outside the abortable liveness probe routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` so it works against PGLite; the four `mcp_request_log.params` INSERT sites (success / auth_failed / scope_denied / server-error) go through `executeRawJsonb(engine, ...)` so the column stores real objects (`params->>'op'` returns `search`, not the quoted string). `--bind HOST` defaults `127.0.0.1` (self-hosters pass `--bind 0.0.0.0`); a stderr WARN fires when `--public-url` is set without `--bind`; the banner prints a `Bind:` line. `AuthInfo.sourceId` + `AuthInfo.allowedSources` + `AuthInfo.takesHoldersAllowList` are the typed source of truth, populated by `oauth-provider.ts:verifyAccessToken` (source scope from the `oauth_clients` row; takes-holders from `access_tokens.permissions.takes_holders` for legacy bearer tokens). The `/mcp` dispatch site reads `authInfo.takesHoldersAllowList ?? ['world']` — absent grants (OAuth-client tokens, pre-v29 brains) fail closed to world-only takes visibility, while an explicit `[]` grant is preserved as deny-all; pinned end-to-end by `test/e2e/serve-http-takes-holders.test.ts`. The HTTP MCP `tools/list` handler at `:837-849` uses `paramDefToSchema(v)` from `src/mcp/tool-defs.ts` so array params keep `items` (strict-mode OAuth clients otherwise reject the whole tool list). `POST /ingest` enforces the slug-prefix write fence at the ROUTE, not the op layer: the route hands its payload to the `ingest_capture` minion handler, which deliberately bypasses `put_page`, so no `OperationContext` exists and `enforceClientSlugFence` never runs — a slug-bound client must therefore supply `X-Gbrain-Slug` and it must satisfy `slugUnderBoundPrefixes`, else 403 (without the check a bound client could overwrite any page inside its granted source). The write source is resolved server-side as `authInfo.sourceId ?? 'default'` and travels on the job as `job.data.sourceId`; the caller-supplied `X-Gbrain-Source-Id` header routes nothing and only names the emitter (`webhook-<clientId>`), which is what the event's `source_id` and the 202's back-compat `source_id` field carry. The 202 additionally reports the routed destination as `write_source_id`, and the write source and normalized target slug (hashed) join the queue idempotency key, so a rescoped client or a second slug gets its own capture, and a slug over 1024 bytes gets 400 `invalid_slug` (`test/serve-http-ingest-write-loss.test.ts`). confidential revoke: a pre-router `/revoke` handler validates the RFC 7009 body, verifies hash-only secrets for both `client_secret_post` and `client_secret_basic`, rejects mixed authentication, preserves the SDK path for public clients, and separates opaque client-auth failures from retryable/backend failures. OAuth metadata advertises both confidential methods. Pinned by `test/e2e/serve-http-oauth.test.ts`. three admin routes: `/admin/api/calibration/profile`, `/admin/api/calibration/charts/:type` (image/svg+xml; type in {brier-trend, domain-bars, pattern-statements, abandoned-threads}), `/admin/api/calibration/pattern/:id` (drill-down). The manual mint route `/admin/api/register-client` in `serve-http-registration.ts` accepts optional `source` + `federatedRead` bindings mirroring the CLI's `--source`/`--federated-read` (validated via `normalizeSourceInput`/`normalizeFederatedReadInput` from `src/core/source-id.ts`; omitting both preserves the default binding `source_id='default'` / `federated_read=[source_id]`, invalid values return a structured 400 `invalid_source`), so an admin SPA or provisioning proxy can mint a source-confined client over HTTP. The route mirrors the CLI lane end to end: structured 400s for `unknown_source` / `archived_source` (one batched `ANY($1::text[])` existence check), `invalid_token_ttl` (shared `TOKEN_TTL_MIN/MAX_SECONDS` bounds, integer-validated BEFORE the tx), and `brain_too_old` (column pre-flight OUTSIDE the tx — a pre-scoped-clients brain refuses up front instead of aborting mid-transaction); the duplicate-name pre-check + INSERT run in ONE transaction under the SAME name-scoped advisory lock the CLI takes (`registerClientNameLockKey`), returning 409 `duplicate_name` with the existing `client_id`; the INSERT composes `registerScopedClient` (the CLI's registration core) so the two paths cannot drift; any post-commit failure includes the created `client_id` so the operator can revoke (never a false "nothing was created"). Pinned by `test/register-client-source-normalize.test.ts`. The `/mcp` tools/list is the honest catalog: per-request filters (token scope incl. the `agentCallable` carve-out, bound-client fence via `opAllowedForBoundClient`, publish gates via `disabledOpsForPublishGates`) over the surface-filtered op set, schemas via `buildToolDefs` (strict emission when `mcp.strict_params` resolves reject); the tools/list `mcp_request_log` row records the listed size as `params.tool_count`. Call-time op-level denials the list should have prevented — the inline scope deny, publish-gate backstop (`config_key=...`), fence op-level deny (`fence=op`, classified via `isListLevelDenialEnvelope`) — log `status='denied_after_list'` instead of `'error'` (the trend-to-zero honest-catalog metric, see docs/operations/mcp-surface-runbook.md) — every tools/call row's status resolves through `requestLogStatusForResult` (dispatch.ts) on BOTH transports. The admin health-indicators error rate counts `status NOT IN ('success','success_with_warnings')` and excludes `operation='surface_change'` audit rows from numerator AND denominator (audit rows record operator/self actions, not traffic). Per-request surface resolution lives in `resolveEffectiveSurface`: a `verbs` ceiling skips the default-surface config read, and a failed read applies the last successfully read default per process (fail-closed — a transient config outage cannot widen a NULL-surface client). OAuth protected-resource metadata (RFC 9728) names `/mcp` as the resource (`resourceServerUrl`), so the SDK mounts the PRM at `/.well-known/oauth-protected-resource/mcp` and the 401 `resource_metadata` URL is derived from the same value; the bare root path is kept as an alias by rewriting `req.url` onto the SDK's handler (same document, same CORS). Shutdown: `waitForHttpServerLifecycle` tracks accepted sockets weakly (`trackServerSockets`; Bun never emits socket `close`, so a strong set leaked one per request), severs the still-reachable ones right after `server.close()`, and bounds the close wait at `CLOSE_TIMEOUT_MS` (5s) — a collected keep-alive wrapper whose native handle keeps `close()` from returning gets one stderr line and shutdown proceeds instead of hanging. DCR startup copy: the SECURITY WARNING states self-registered clients are limited to read/write (read-only for `client_credentials` under `--enable-dcr-insecure`) and that every authorization_code connection needs owner approval in the admin UI; banner `DCR:` values are `enabled (consent; DCR max read write)` / `enabled (INSECURE: read-only M2M)` / `disabled`.Layout: `runServeHttp` binds through `listenOrRefuse` (`serve-http-listen.ts`: `serve_port_in_use` on a taken port; with `options.adoptServer` from status-only recovery it hands the app to the already-bound listener instead of binding). `buildServeHttpApp` builds one shared `ServeHttpContext` (sessions, nonce stores, limiters, `requireAdmin`, SSE fan-out, OAuth provider, resource verifier, non-`localOnly` op list) and mounts in registration order `serve-http-oauth.ts` (CORS gates, DCR TTL hook, confidential credentials, SDK router, discovery, owner login links, consent), `serve-http-metrics.ts` (`/health`, `/metrics`, probes), `serve-http-admin-api.ts` (`requireAdmin`, `/admin/login`, `/admin/api/*`, `/admin/events`), `serve-http-spa.ts`, `serve-http-mcp.ts` (`/mcp`; writes `[gbrain-serve] dispatch op=<name> args_sha256=<16 hex>` to stderr before each tool call so a stall's last line names its request, never the arguments) and `serve-http-webhooks.ts` (`/ingest`, which maps a legacy-authority `permission_denied` from submission to 409 `{error, message, hint, docs_url}` (`test/serve-http-ingest-legacy.test.ts`), answers 429 `ingest_backlog_full` when the 50-capture waiting cap hands back another job, and every other submission error to 500; `legacyIngestJob` answers a retried POST /ingest recorded under the pre-v0.60.609.0 key (no slug) when that row's slug matches (`test/serve-http-ingest-legacy-key-retry.test.ts`, `test/e2e/serve-http-ingest-legacy-key-retry-postgres.test.ts`); the queue key dedupes only while the job row exists, and the `ingest_capture` handler (`minions/handlers/ingest-capture.ts`) applies a capture once per job idempotency key for 90 days through `ingest_applied_captures` (`ingestion/applied-captures.ts`, migration v296), even after `gbrain jobs prune`: the row is inserted in the page write's transaction (`importFromContent`'s `beforeCommit`; a run that loses the insert rolls its write back and returns the stored result) or after a committed managed door write, whose per-attempt `request_id` (`ingest-capture:<key sha256 prefix>:<attempt>`) lets a committed request in `persistence_requests` count as applied and backfill the row; tombstones and keyless jobs are unchanged, and the purge phase drops rows past 90 days (`test/ingest-capture-applied-once.test.ts`, `test/e2e/ingest-capture-applied-once-postgres.test.ts`); `/webhooks/github`, which HMACs every body, with a throwaway key when there is no source or secret); `runServeHttp` keeps listen, banner, resolve-IPC binding and shutdown, and the façade re-exports moved symbols. Order is pinned by `test/serve-http-route-golden.test.ts` (AST) and `test/serve-http-route-runtime-golden.test.ts` (router stack). Size ceiling: `scripts/module-size-limits.tsv`.-- `src/commands/serve.ts` — `gbrain serve` stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Surface: stdio resolves `GBRAIN_SURFACE` > `--surface` > config > full (`resolveStdioSurface`; an invalid env value is ignored with a stderr line and handed to `startMcpServer` as `invalidSurfaceEnv`), `--http` resolves `--surface` > config > full and says on stderr that it ignores `GBRAIN_SURFACE`; both print `surface=<x> (source: …)` at start. `--http --token-ttl` goes through `parseTokenTtl` (`src/commands/auth.ts`) and refuses anything outside 60 to 7,776,000 seconds before the server starts. 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`); it targets the source `resolveMcpStdioSourceScope` resolves (GBRAIN_SOURCE > `.gbrain-source` dotfile > local_path > `sources.default` > …) — the SAME ladder as stdio dispatch and the startup sweep, so dotfile/local_path-scoped serves reconcile their in-session MCP writes (pinned by `test/serve-idle-sweep-source.serial.test.ts`). #7599: `lean` (`readOnlyServeSkipsResidentDuties`, a read-only stdio serve on Postgres; PGLite keeps both) turns off the idle sweep and `installResidentTickers` (facts drain, movement watch, on-commit head watcher). 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. The boot-readiness deadline (`GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS`, default 60, 0 disables) measures time WITHOUT boot progress: every `onBootPhase` change and every `noteForwardProgress()` note (`src/core/forward-progress.ts`; progress ticks and each completed stdio request via `trackStdioRpc` in `src/mcp/server.ts`) restarts the window, so a large brain's slow but advancing boot is never killed; only a full window without progress releases the engine and exits 1 with the `serve_boot_timeout` line (stuck phase, pool pressure, seconds since boot started). Pinned by `test/serve-stdio-lifecycle.test.ts` (boot-readiness block). #6543: after the pool stall watch, `recordServeTransport` (`src/commands/serve-health.ts`) reads the read pool's transport once (live `prepare`/`max_pipeline` with `max_pipeline_reason`, the doctor probe's `SHOW statement_timeout` and its ALTER ROLE fix when a configured timeout reads 0, `application_name` when Supavisor), logs one `[gbrain serve] transport` line and caches it for `/health?deep=1` (never re-read per probe). `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=<n>` (>= 120, else `invalid_params` at start) arms `installRestartRequiredExit`: an in-process `restart_required` held continuously for n seconds (the hold resets when it clears) disconnects under a 5 s deadline and exits `SERVE_UNHEALTHY_EXIT_CODE` (69, `serve_unhealthy_exit`); a durable ledger (`serve-self-exit.json` under the gbrain home) suppresses the exit after 3 within an hour (`serve_self_exit_suppressed`, `self_exit_suppressed` in the deep 503). `probeDeepHealth` (`serve-http-metrics.ts`) answers 503 `persistence_restart_required` before its pooled probe, `pool_inflight_over_budget` or `deep_health_probe_failed` (`reason`), each with `fix`/`docs` from the registry and the cached `transport`, no request ids. Pinned by `test/serve-health-6543.test.ts` (a real `PersistenceConsumer` driven to restart_required).+- `src/commands/serve.ts` — `gbrain serve` stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Surface: stdio resolves `GBRAIN_SURFACE` > `--surface` > config > full (`resolveStdioSurface`; an invalid env value is ignored with a stderr line and handed to `startMcpServer` as `invalidSurfaceEnv`), `--http` resolves `--surface` > config > full and says on stderr that it ignores `GBRAIN_SURFACE`; both print `surface=<x> (source: …)` at start. `--http --token-ttl` goes through `parseTokenTtl` (`src/commands/auth.ts`) and refuses anything outside 60 to 7,776,000 seconds before the server starts. 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`); it targets the source `resolveMcpStdioSourceScope` resolves (GBRAIN_SOURCE > `.gbrain-source` dotfile > local_path > `sources.default` > …) — the SAME ladder as stdio dispatch and the startup sweep, so dotfile/local_path-scoped serves reconcile their in-session MCP writes (pinned by `test/serve-idle-sweep-source.serial.test.ts`). #7599: `lean` (`readOnlyServeSkipsResidentDuties`, a read-only stdio serve on Postgres; PGLite keeps both) turns off the idle sweep and `installResidentTickers` (facts drain, movement watch, on-commit head watcher, request-log retention ticker). Both lanes start the hourly request-log retention prune (`installMcpLogPrune`, `src/core/mcp-request-log-retention.ts`; PGLite only, vetoed while a delegated sync runs) and stop it at shutdown; seam `ServeOptions.mcpLogPrune`. 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. The boot-readiness deadline (`GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS`, default 60, 0 disables) measures time WITHOUT boot progress: every `onBootPhase` change and every `noteForwardProgress()` note (`src/core/forward-progress.ts`; progress ticks and each completed stdio request via `trackStdioRpc` in `src/mcp/server.ts`) restarts the window, so a large brain's slow but advancing boot is never killed; only a full window without progress releases the engine and exits 1 with the `serve_boot_timeout` line (stuck phase, pool pressure, seconds since boot started). Pinned by `test/serve-stdio-lifecycle.test.ts` (boot-readiness block). #6543: after the pool stall watch, `recordServeTransport` (`src/commands/serve-health.ts`) reads the read pool's transport once (live `prepare`/`max_pipeline` with `max_pipeline_reason`, the doctor probe's `SHOW statement_timeout` and its ALTER ROLE fix when a configured timeout reads 0, `application_name` when Supavisor), logs one `[gbrain serve] transport` line and caches it for `/health?deep=1` (never re-read per probe). `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=<n>` (>= 120, else `invalid_params` at start) arms `installRestartRequiredExit`: an in-process `restart_required` held continuously for n seconds (the hold resets when it clears) disconnects under a 5 s deadline and exits `SERVE_UNHEALTHY_EXIT_CODE` (69, `serve_unhealthy_exit`); a durable ledger (`serve-self-exit.json` under the gbrain home) suppresses the exit after 3 within an hour (`serve_self_exit_suppressed`, `self_exit_suppressed` in the deep 503). `probeDeepHealth` (`serve-http-metrics.ts`) answers 503 `persistence_restart_required` before its pooled probe, `pool_inflight_over_budget` or `deep_health_probe_failed` (`reason`), each with `fix`/`docs` from the registry and the cached `transport`, no request ids. Pinned by `test/serve-health-6543.test.ts` (a real `PersistenceConsumer` driven to restart_required).- `src/commands/skillify-check.ts` — `gbrain skillpack-check` agent-readable health report. Exit 0/1/2 for CI gating; JSON for debugging. Wraps `check-resolvable --json`, `doctor --json`, and migration ledger into one payload. Required item 12 (`brain_first_compliance`) calls `analyzeSkillBrainFirst()` on the candidate SKILL.md; exits 1 when the verdict is `missing_brain_first` (external-lookup pattern present, no callout, no `brain_first: exempt`). The scaffold path in `src/core/skillify/templates.ts` pre-inserts the canonical Convention callout into new SKILL.md files so freshly-scaffolded skills pass item 12.diff --git a/docs/architecture/key-files/core-cycle-primitive.md b/docs/architecture/key-files/core-cycle-primitive.mdindex e02fa635e7..a1083f8cce 100644--- a/docs/architecture/key-files/core-cycle-primitive.md+++ b/docs/architecture/key-files/core-cycle-primitive.md@@ -3,4 +3,4 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/cycle.ts` — brain maintenance cycle primitive (`ALL_PHASES` is the ordered source of truth; `fence_repair` follows `sync` and runs the `fences` repair kind through `cycle/fence-repair.ts`). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantic order along the core spine lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → embed → orphans, with the extraction/graph/consolidation phases (extract_facts, extract_atoms, resolve_symbol_edges, …) slotted between per the ordering comments on `ALL_PHASES`. `synthesize` runs after sync (cross-references see a fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default, so extract is the canonical materialization); `recompute_emotional_weight` sees the union of `syncPagesAffected` + `synthesizeWrittenSlugs` + the source window's slugs (`cycle/source-window.ts`: a per-source cycle that runs no sync works on at most 2,000 pages changed since its previous cycle, #6803, #8573) incrementally, or all pages when none of those anchors is set (full backfill via `gbrain dream --phase recompute_emotional_weight`). `CycleReport.schema_version: "1"` is stable; `totals` is additive (`pages_emotional_weight_recomputed`, `transcripts_processed`, `synth_pages_written`, `patterns_written`). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon inline path, the Minions `autopilot-cycle` handler. `runPhaseLint` skips with `status: 'skipped'` and `details.reason: 'disabled'` before any scan when `cycle.lint.enabled` is explicitly false (#6369, `cycleLintPhaseEnabled` in `cycle/lint-fix-setting.ts`; `onceForPhase === 'lint'` threads through as `opts.once` and bypasses it for one run; `gbrain lint` never reads it), repairs with `fix: true` unless DB config `cycle.lint_fix` is explicitly false (report-only; `gbrain lint --fix` unaffected); `cycle.lint_exclude` (#6134, `cycle/lint-fix-setting.ts` `cycleLintExcludes`/`parseCycleLintExclude`) lists basenames the lint phase and the `lint`/`lint-fix` minion handlers skip (`details.excluded`; `config set` refuses a path); managed repairs left pending keep the phase at `warn` and surface as `details.pending` (`test/managed-lint.test.ts`). Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite; the two handles compose into ONE lock whose `refresh()` treats the fenced DB row as the authoritative multi-writer identity and the file half as best-effort freshness — the file lock is refreshed ONLY while the fenced DB refresh reports ownership, so a losing holder can never clobber the successor's file lock on the very tick it detects the steal. A dedicated serialized refresher — `startCycleLockRefresher(lock, controller, lockId)` (exported; unref'd `setInterval` at `max(15s, TTL/6)`, env-only override `GBRAIN_CYCLE_LOCK_REFRESH_MS`, in-flight guard so a slow refresh never overlaps the next tick) — heartbeats the lock through long phases (synthesis/patterns/consolidation waits routinely outlive the TTL with no other heartbeat). A fenced miss aborts the controller with `LockStolenError`; that steal signal combines with the worker's external signal via the exported `anyAbortSignal(signals)` (`src/core/abort-signals.ts`, re-exported; duck-type-tolerant — stubs without `addEventListener` are observed by poll; returns `{signal, dispose}` and dispose detaches the caller-signal listener + clears the poll timer so daemons don't leak), and the run stops at the next phase boundary with a structured partial report carrying `reason: 'lock_stolen'` (for the 5 long phases — synthesize / extract_atoms / patterns / synthesize_concepts / consolidate — the steal races the phase promise and stops the WAIT immediately; extract_atoms also receives the cycle signal as a real `AbortSignal` and stops at its next item, the others run to their own bounded timeout). A busy DB lock's `cycle_already_running` skip carries `lock_holder` (`id`, `holder_pid`, `holder_host`, `age_ms`). A source-scoped cycle that selects a brain-wide phase (in NEEDS_LOCK and not `source` scope) also tries the shared `gbrain-cycle` lease through `cycle/lock-set.ts`; when another cycle holds it, the source phases run and each brain-wide phase is reported `skipped` with `maintenance_lock_busy` (an all-skipped selection reports `skipped`). Transient refresh errors log and retry next tick (the TTL stays the backstop). `yieldBetweenPhases` runs between phases; `yieldDuringPhase` is in-phase keepalive; `onPhaseStart(phase, index, count)` is awaited inside `timePhase` as each selected phase starts its work (index and count within the resolved selection; a throwing hook is logged, never fatal), which the `autopilot-cycle` handler turns into job progress. Engine nullable; lock-skip on read-only phase selections. `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal with `checkAborted()` between every phase. `CycleOpts.deadlineAtMs` (the enclosing minion job's ABSOLUTE wall-clock deadline, threaded from `MinionJobContext.deadlineAtMs` by the autopilot-cycle handler; null for direct `gbrain dream` callers) flows into patterns, propose_takes, synthesize AND fence_repair so time-spending phases derive their deadlines from the REAL remaining job budget instead of duplicated literals that collide with the job's own kill timer. Pinned by `test/cycle-lock-steal.serial.test.ts` (mid-run steal → partial report, no further phases, successor row intact) + `test/cycle-any-abort-signal.test.ts` + `test/db-lock-fencing.test.ts`. `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult` (threaded to `runPhaseExtract` as the 4th arg) and takes `willRunExtractPhase: boolean` setting `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. The extract phase calls `runExtractCore` and `extractStaleFromDB` with `quiet: true` (and `jsonMode: false`), so the helpers' human summaries never land on stdout ahead of the `dream --json` CycleReport while batch-loss diagnostics stay human-readable on stderr (`quiet` is its own knob on `ExtractOpts` — using `jsonMode: true` as a stand-in flipped the stderr channel to JSON events in a plain `gbrain dream`); `totals.pages_extracted` counts pages (`pages_processed` from the targeted pass + `stale_pages_drained`), not links created. `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor (not the drift-prone global `config.sync.last_commit`). It matches only an absolute `local_path`; with no match the sync phase checks `default` and fails `sync_anchor_relative` (with its fix) while that path is relative. `CycleOpts.brainDir` is `string | null`; when null (checkout-less postgres/Supabase brain, or a connector source) the 5 filesystem phases (lint/backlinks/sync/synthesize/patterns) skip with `details.reason: 'no_brain_dir'`, extract runs the database-only stale drain (`cycle/connector-extract.ts`), and the DB-only phases run; `resolveSourceForDir` is null-tolerant. `cycleSourceId = opts.sourceId ?? resolveSourceForDir(engine, brainDir)` is the canonical per-source scope for `extract_facts`/`extract_atoms`/calibration — and for `synthesize` (threaded as `SynthesizePhaseOpts.sourceId` so synthesized pages land in the cycle's resolved source, not `'default'`) — so `gbrain dream --source repo-a` reconciles repo-a's facts even with no checkout (instead of scoping to `'default'` while stamping repo-a fresh). `deriveStatus` counts `edges_resolved`/`edges_ambiguous` as work so an edges-only cycle reports `ok` not `clean`, and scores ONLY attempted phases — the implicit source-cycle exclusion skip-records are bookkeeping and never dilute failure aggregation; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out along the `PHASE_SCOPE` taxonomy in `src/core/cycle/phase-scope.ts` (see its entry): cycle.ts derives `SOURCE_PHASES` / `MIXED_PHASES` / `GLOBAL_PHASES` / `MAINTENANCE_PHASES` (mixed ∪ global, original cycle order) plus `SOURCE_FRESHNESS_PHASES` (deterministic, non-LLM: lint/backlinks/sync/extract/extract_facts/recompute_emotional_weight — defined in phase-scope.ts) and `SOURCE_BACKGROUND_PHASES` (LLM-backed/unbounded source work = SOURCE minus FRESHNESS). `resolveCyclePhases(requested, sourceId)` at the shared runCycle boundary: default/no-source → `requested ?? ALL_PHASES` (the canonical `default` cycle remains full); a named non-default source with NO explicit phases → `SOURCE_FRESHNESS_PHASES` only (the freshness keeper's implicit `dream --source X` path must stamp freshness without first draining LLM-backed maintenance); explicit phase lists are honored VERBATIM — `dream --source X --phase synthesize` (and `--input <file>`, which implies synthesize) is deliberate operator intent, and `--phase orphans --source X` still narrows orphans via `forceGlobalOrphans`. The N-way duplication guard lives at the QUEUE boundary instead: the `autopilot-cycle` handler intersects queued per-source payloads with `SOURCE_FRESHNESS_PHASES` (queued payloads may carry mixed+background phases; an all-rejected or empty list is an explicit no-op skip with reason `all_phases_rejected_by_normalization`, never an implicit run, and rejected phases surface on the job result as `phases_rejected_by_normalization`). On the implicit path, excluded phases surface as `skipped` with `details.reason: 'excluded_from_implicit_source_cycle'` + `phase_scope`. Per-source `autopilot-cycle` jobs enqueue `phases: SOURCE_FRESHNESS_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `MAINTENANCE_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). SOURCE_BACKGROUND phases have NO automatic lane on multi-source brains (the legacy full-cycle job fires only when the brain has no sources rows) — run them explicitly (`gbrain dream --source X --phase extract_atoms`) until the background lane lands (see TODOS). The freshness stamp gate is `opts.sourceId && phases.length > 0 && engine && !dryRun && !aborted && status ∈ {ok, clean, partial}`; `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (not a gate for the brain-wide phases). A lost filesystem-walk or incremental extract write (`ExtractBatchWriteError`, code `extract_write_lost`, `src/core/extract-watermark.ts`) leaves only its pages unstamped and makes the extract phase warn, like a GBRA-130 A-1 stale drain failure; the same cycle's stale drain retries those pages. Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.test.ts` + `test/autopilot-global-maintenance.test.ts` + `test/cycle-enabled-phase-completeness.test.ts`. `runPhaseLint` + `runPhaseBacklinks` carry the `export` keyword so behavioral tests can drive them directly (internal helpers exposed for test-only consumption; downstream code should NOT depend on them). Pinned by `test/cycle-legacy-phases.test.ts` (11 cases across both phases: clean run → status='ok', partial fix → status='warn' with `dryRun` in details, dry-run path doesn't write, throw-from-lib → status='fail' with the wrapper's try/catch envelope populated). with `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts`: six daily-driver ops behaviors. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) answers in one batched SQL roundtrip (never a per-hash loop) returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Cycle lock TTL + heartbeat: `LOCK_TTL_MINUTES = 5`; `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock within one short TTL, while the dedicated `startCycleLockRefresher` interval (see the coordination sentence above) keeps a healthy long-running cycle alive even across a single multi-minute `await chat(...)` — the timer fires during awaits, so no single slow call can silently expire the lock. (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash (`hashGazetteer` in `src/core/by-mention.ts` — every entry's source_id/slug/title/tokens, not just the first-token bucket keys, so a new "Acme Labs" beside an existing "Acme Corp" moves it) is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); `findMentionedEntities` keys its self-link guard and first-mention dedup on `(source_id, slug)`, so under `link_resolution.cross_source` a foreign namesake of the scanning page is a real target and same-slug pages in two sources both link; the gazetteer itself is entity-page titles PLUS live-verified `page_aliases` entries joined to entity-typed pages (ambiguous aliases and alias-vs-title collisions within a source are skipped), so body mentions of a documented alias link too; `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; a managed brain (`managedPersistenceEnabled`, false when `persistence_brain` is missing) sees `gbrain sync --all --no-pull --hard-deadline 13m` every 15 minutes on the owner host with `gbrain sources refresh <id>;` chained first for remote-tracking checkouts; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/core/cycle.serial.test.ts` (5-minute DB-lock and file-lock TTL behavior), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`. `synthesize_concepts` writes concept pages through `importFromContent` (the same parse→chunk→embed pipeline put_page uses, with put_page's `isAvailable('embedding')` → `noEmbed` gate) so `concepts/` pages carry `content_chunks` + embeddings and are reachable by retrieval (where `source-boost.ts` weights them 1.3×). `purge` phase (soft-delete TTLs) also GCs stale `op_checkpoints` rows older than 7 days. Non-fatal on pre-v67 brains (DROP-target-table check before DELETE). The cycle threads its abort signal into the embed phase (`runPhaseEmbed(engine, dryRun, signal)`) so a timed-out cycle's long embed phase honors cancellation and releases `gbrain_cycle_locks` right away instead of after a full backlog run. The `extract_facts` phase runs the S9 conflict sweep as its tail (`ai/decide/sweep.ts` `conflictSweepTail`) only when `decide.slots.conflict.mode` is not off, adding `details.decide_conflict`; with the slot off the phase output is unchanged. The extract_atoms / synthesize_concepts pack gate (#6393) is `src/core/cycle/pack-phase-gate.ts` ([Core Cycle (continued)](core-cycle-continued.md)); `packDeclaresPhase(engine, phase, sourceId?)` delegates to it.+- `src/core/cycle.ts` — brain maintenance cycle primitive (`ALL_PHASES` is the ordered source of truth; `fence_repair` follows `sync` and runs the `fences` repair kind through `cycle/fence-repair.ts`). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantic order along the core spine lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → embed → orphans, with the extraction/graph/consolidation phases (extract_facts, extract_atoms, resolve_symbol_edges, …) slotted between per the ordering comments on `ALL_PHASES`. `synthesize` runs after sync (cross-references see a fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default, so extract is the canonical materialization); `recompute_emotional_weight` sees the union of `syncPagesAffected` + `synthesizeWrittenSlugs` + the source window's slugs (`cycle/source-window.ts`: a per-source cycle that runs no sync works on at most 2,000 pages changed since its previous cycle, #6803, #8573) incrementally, or all pages when none of those anchors is set (full backfill via `gbrain dream --phase recompute_emotional_weight`). `CycleReport.schema_version: "1"` is stable; `totals` is additive (`pages_emotional_weight_recomputed`, `transcripts_processed`, `synth_pages_written`, `patterns_written`). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon inline path, the Minions `autopilot-cycle` handler. `runPhaseLint` skips with `status: 'skipped'` and `details.reason: 'disabled'` before any scan when `cycle.lint.enabled` is explicitly false (#6369, `cycleLintPhaseEnabled` in `cycle/lint-fix-setting.ts`; `onceForPhase === 'lint'` threads through as `opts.once` and bypasses it for one run; `gbrain lint` never reads it), repairs with `fix: true` unless DB config `cycle.lint_fix` is explicitly false (report-only; `gbrain lint --fix` unaffected); `cycle.lint_exclude` (#6134, `cycle/lint-fix-setting.ts` `cycleLintExcludes`/`parseCycleLintExclude`) lists basenames the lint phase and the `lint`/`lint-fix` minion handlers skip (`details.excluded`; `config set` refuses a path); managed repairs left pending keep the phase at `warn` and surface as `details.pending` (`test/managed-lint.test.ts`). Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite; the two handles compose into ONE lock whose `refresh()` treats the fenced DB row as the authoritative multi-writer identity and the file half as best-effort freshness — the file lock is refreshed ONLY while the fenced DB refresh reports ownership, so a losing holder can never clobber the successor's file lock on the very tick it detects the steal. A dedicated serialized refresher — `startCycleLockRefresher(lock, controller, lockId)` (exported; unref'd `setInterval` at `max(15s, TTL/6)`, env-only override `GBRAIN_CYCLE_LOCK_REFRESH_MS`, in-flight guard so a slow refresh never overlaps the next tick) — heartbeats the lock through long phases (synthesis/patterns/consolidation waits routinely outlive the TTL with no other heartbeat). A fenced miss aborts the controller with `LockStolenError`; that steal signal combines with the worker's external signal via the exported `anyAbortSignal(signals)` (`src/core/abort-signals.ts`, re-exported; duck-type-tolerant — stubs without `addEventListener` are observed by poll; returns `{signal, dispose}` and dispose detaches the caller-signal listener + clears the poll timer so daemons don't leak), and the run stops at the next phase boundary with a structured partial report carrying `reason: 'lock_stolen'` (for the 5 long phases — synthesize / extract_atoms / patterns / synthesize_concepts / consolidate — the steal races the phase promise and stops the WAIT immediately; extract_atoms also receives the cycle signal as a real `AbortSignal` and stops at its next item, the others run to their own bounded timeout). A busy DB lock's `cycle_already_running` skip carries `lock_holder` (`id`, `holder_pid`, `holder_host`, `age_ms`). A source-scoped cycle that selects a brain-wide phase (in NEEDS_LOCK and not `source` scope) also tries the shared `gbrain-cycle` lease through `cycle/lock-set.ts`; when another cycle holds it, the source phases run and each brain-wide phase is reported `skipped` with `maintenance_lock_busy` (an all-skipped selection reports `skipped`). Transient refresh errors log and retry next tick (the TTL stays the backstop). `yieldBetweenPhases` runs between phases; `yieldDuringPhase` is in-phase keepalive; `onPhaseStart(phase, index, count)` is awaited inside `timePhase` as each selected phase starts its work (index and count within the resolved selection; a throwing hook is logged, never fatal), which the `autopilot-cycle` handler turns into job progress. Engine nullable; lock-skip on read-only phase selections. `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal with `checkAborted()` between every phase. `CycleOpts.deadlineAtMs` (the enclosing minion job's ABSOLUTE wall-clock deadline, threaded from `MinionJobContext.deadlineAtMs` by the autopilot-cycle handler; null for direct `gbrain dream` callers) flows into patterns, propose_takes, synthesize AND fence_repair so time-spending phases derive their deadlines from the REAL remaining job budget instead of duplicated literals that collide with the job's own kill timer. Pinned by `test/cycle-lock-steal.serial.test.ts` (mid-run steal → partial report, no further phases, successor row intact) + `test/cycle-any-abort-signal.test.ts` + `test/db-lock-fencing.test.ts`. `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult` (threaded to `runPhaseExtract` as the 4th arg) and takes `willRunExtractPhase: boolean` setting `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. The extract phase calls `runExtractCore` and `extractStaleFromDB` with `quiet: true` (and `jsonMode: false`), so the helpers' human summaries never land on stdout ahead of the `dream --json` CycleReport while batch-loss diagnostics stay human-readable on stderr (`quiet` is its own knob on `ExtractOpts` — using `jsonMode: true` as a stand-in flipped the stderr channel to JSON events in a plain `gbrain dream`); `totals.pages_extracted` counts pages (`pages_processed` from the targeted pass + `stale_pages_drained`), not links created. `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor (not the drift-prone global `config.sync.last_commit`). It matches only an absolute `local_path`; with no match the sync phase checks `default` and fails `sync_anchor_relative` (with its fix) while that path is relative. `CycleOpts.brainDir` is `string | null`; when null (checkout-less postgres/Supabase brain, or a connector source) the 5 filesystem phases (lint/backlinks/sync/synthesize/patterns) skip with `details.reason: 'no_brain_dir'`, extract runs the database-only stale drain (`cycle/connector-extract.ts`), and the DB-only phases run; `resolveSourceForDir` is null-tolerant. `cycleSourceId = opts.sourceId ?? resolveSourceForDir(engine, brainDir)` is the canonical per-source scope for `extract_facts`/`extract_atoms`/calibration — and for `synthesize` (threaded as `SynthesizePhaseOpts.sourceId` so synthesized pages land in the cycle's resolved source, not `'default'`) — so `gbrain dream --source repo-a` reconciles repo-a's facts even with no checkout (instead of scoping to `'default'` while stamping repo-a fresh). `deriveStatus` counts `edges_resolved`/`edges_ambiguous` as work so an edges-only cycle reports `ok` not `clean`, and scores ONLY attempted phases — the implicit source-cycle exclusion skip-records are bookkeeping and never dilute failure aggregation; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out along the `PHASE_SCOPE` taxonomy in `src/core/cycle/phase-scope.ts` (see its entry): cycle.ts derives `SOURCE_PHASES` / `MIXED_PHASES` / `GLOBAL_PHASES` / `MAINTENANCE_PHASES` (mixed ∪ global, original cycle order) plus `SOURCE_FRESHNESS_PHASES` (deterministic, non-LLM: lint/backlinks/sync/extract/extract_facts/recompute_emotional_weight — defined in phase-scope.ts) and `SOURCE_BACKGROUND_PHASES` (LLM-backed/unbounded source work = SOURCE minus FRESHNESS). `resolveCyclePhases(requested, sourceId)` at the shared runCycle boundary: default/no-source → `requested ?? ALL_PHASES` (the canonical `default` cycle remains full); a named non-default source with NO explicit phases → `SOURCE_FRESHNESS_PHASES` only (the freshness keeper's implicit `dream --source X` path must stamp freshness without first draining LLM-backed maintenance); explicit phase lists are honored VERBATIM — `dream --source X --phase synthesize` (and `--input <file>`, which implies synthesize) is deliberate operator intent, and `--phase orphans --source X` still narrows orphans via `forceGlobalOrphans`. The N-way duplication guard lives at the QUEUE boundary instead: the `autopilot-cycle` handler intersects queued per-source payloads with `SOURCE_FRESHNESS_PHASES` (queued payloads may carry mixed+background phases; an all-rejected or empty list is an explicit no-op skip with reason `all_phases_rejected_by_normalization`, never an implicit run, and rejected phases surface on the job result as `phases_rejected_by_normalization`). On the implicit path, excluded phases surface as `skipped` with `details.reason: 'excluded_from_implicit_source_cycle'` + `phase_scope`. Per-source `autopilot-cycle` jobs enqueue `phases: SOURCE_FRESHNESS_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `MAINTENANCE_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). SOURCE_BACKGROUND phases have NO automatic lane on multi-source brains (the legacy full-cycle job fires only when the brain has no sources rows) — run them explicitly (`gbrain dream --source X --phase extract_atoms`) until the background lane lands (see TODOS). The freshness stamp gate is `opts.sourceId && phases.length > 0 && engine && !dryRun && !aborted && status ∈ {ok, clean, partial}`; `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (not a gate for the brain-wide phases). A lost filesystem-walk or incremental extract write (`ExtractBatchWriteError`, code `extract_write_lost`, `src/core/extract-watermark.ts`) leaves only its pages unstamped and makes the extract phase warn, like a GBRA-130 A-1 stale drain failure; the same cycle's stale drain retries those pages. Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.test.ts` + `test/autopilot-global-maintenance.test.ts` + `test/cycle-enabled-phase-completeness.test.ts`. `runPhaseLint` + `runPhaseBacklinks` carry the `export` keyword so behavioral tests can drive them directly (internal helpers exposed for test-only consumption; downstream code should NOT depend on them). Pinned by `test/cycle-legacy-phases.test.ts` (11 cases across both phases: clean run → status='ok', partial fix → status='warn' with `dryRun` in details, dry-run path doesn't write, throw-from-lib → status='fail' with the wrapper's try/catch envelope populated). with `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts`: six daily-driver ops behaviors. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) answers in one batched SQL roundtrip (never a per-hash loop) returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Cycle lock TTL + heartbeat: `LOCK_TTL_MINUTES = 5`; `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock within one short TTL, while the dedicated `startCycleLockRefresher` interval (see the coordination sentence above) keeps a healthy long-running cycle alive even across a single multi-minute `await chat(...)` — the timer fires during awaits, so no single slow call can silently expire the lock. (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash (`hashGazetteer` in `src/core/by-mention.ts` — every entry's source_id/slug/title/tokens, not just the first-token bucket keys, so a new "Acme Labs" beside an existing "Acme Corp" moves it) is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); `findMentionedEntities` keys its self-link guard and first-mention dedup on `(source_id, slug)`, so under `link_resolution.cross_source` a foreign namesake of the scanning page is a real target and same-slug pages in two sources both link; the gazetteer itself is entity-page titles PLUS live-verified `page_aliases` entries joined to entity-typed pages (ambiguous aliases and alias-vs-title collisions within a source are skipped), so body mentions of a documented alias link too; `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; a managed brain (`managedPersistenceEnabled`, false when `persistence_brain` is missing) sees `gbrain sync --all --no-pull --hard-deadline 13m` every 15 minutes on the owner host with `gbrain sources refresh <id>;` chained first for remote-tracking checkouts; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/core/cycle.serial.test.ts` (5-minute DB-lock and file-lock TTL behavior), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`. `synthesize_concepts` writes concept pages through `importFromContent` (the same parse→chunk→embed pipeline put_page uses, with put_page's `isAvailable('embedding')` → `noEmbed` gate) so `concepts/` pages carry `content_chunks` + embeddings and are reachable by retrieval (where `source-boost.ts` weights them 1.3×). `purge` phase (soft-delete TTLs) also GCs stale `op_checkpoints` rows older than 7 days and, when `cycle.purge.mcp_request_log_retention_days` is set, prunes the request log (`runMcpLogRetention`; `purged_mcp_request_log_count` in details only when above 0). Non-fatal on pre-v67 brains (DROP-target-table check before DELETE). The cycle threads its abort signal into the embed phase (`runPhaseEmbed(engine, dryRun, signal)`) so a timed-out cycle's long embed phase honors cancellation and releases `gbrain_cycle_locks` right away instead of after a full backlog run. The `extract_facts` phase runs the S9 conflict sweep as its tail (`ai/decide/sweep.ts` `conflictSweepTail`) only when `decide.slots.conflict.mode` is not off, adding `details.decide_conflict`; with the slot off the phase output is unchanged. The extract_atoms / synthesize_concepts pack gate (#6393) is `src/core/cycle/pack-phase-gate.ts` ([Core Cycle (continued)](core-cycle-continued.md)); `packDeclaresPhase(engine, phase, sourceId?)` delegates to it.diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 7a321d7383..533a4291f7 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -62,7 +62,7 @@ The `src/core/cycle.ts` entry is on its own page: [Core Cycle primitive](core-cy- `src/core/latin-fold.ts` — leaf text primitive (no engine/graph imports): `NON_DECOMPOSING_LATIN`, the lowercase-keyed table of the eleven Latin stroke/bar/ligature letters Unicode gives no decomposition (đ ð ø ł ħ ŧ ı ß æ œ þ), + `foldNonDecomposingLatin(s)`. Call it AFTER lowercasing and AFTER the combining-mark strip so composed forms reduce in one pass (ǿ → ø → o). Consumers: `entities/resolve.ts:slugify` (entity fallback slugs — pre-fold `Đăng Example` collided onto `ang-example` and an all-stroke name slugged to empty) and `link-extraction.ts:normalizeBasename` (basename-index keys + dir-hint candidates). Deliberately NOT applied to `sync.ts:slugifySegment` — the page-slug grammar keeps these letters (#3417) — so the dir-hint candidate step in `makeResolver` / the FS resolver tries both forms.-- `src/core/mcp-usage.ts` — `readClientOpUsage(engine, {days})`: the ONE shared reader over `mcp_request_log`, consumed by `gbrain auth clients --usage`, the advisor `mcp-client-fit` collector, and `scripts/derive-starter-ops.ts`. Encodes the row-hygiene rules once (`normalizeLoggedOperation`): JSON-RPC method rows (`tools/list`, `initialize`, …) and `surface_change` audit rows drop; the legacy `tools/call:<name>` prefix strips to the op name, and the hygiene check re-runs on the stripped name (`tools/call:tools/list` is still not an op call). Only `status IN ('success','success_with_warnings')` rows count as usage — denied or erroring traffic cannot "use" its way into starter derivation or advisor fit findings. Windows on `created_at` (rides `idx_mcp_log_time_agent`); plain SQL through `engine.executeRaw`, both engines. Behavioral automation classification: `likely_automation` = >90% of calls are `context_pack`/`delta` boundary verbs (the hook lane is stdio and never logs, so there is no name convention to key on). Sees HTTP clients ONLY — stdio never writes the log. Pinned by test/mcp-usage.test.ts.+- `src/core/mcp-usage.ts` — `readClientOpUsage(engine, {days})`: the ONE shared reader over `mcp_request_log`, consumed by `gbrain auth clients --usage`, the advisor `mcp-client-fit` collector and `scripts/derive-starter-ops.ts`, each through `readClientOpUsageWithCoverage` (adds `coverage`: truncated when the window reaches past `max(mcp_request_log_rollup.pruned_through)`; `truncatedWindowNote` names the complete `--days`). Hygiene once (`normalizeLoggedOperation`): method rows (`tools/list`, …) and `AUDIT_LOG_OPERATIONS` rows drop; `tools/call:<name>` strips to the op name and re-runs the check. Only success statuses count, so denied traffic cannot "use" its way into derivation. Windows on `created_at`; both engines. `likely_automation` = >90% `context_pack`/`delta` calls. HTTP clients ONLY (stdio never logs). Pinned by test/mcp-usage.test.ts.- `src/core/npm-squat-check.ts` — doctor's `npm_squat`: classifies `gbrain` on PATH plus `npm root -g` and Bun global packages. Foreign winner: ask_user remove (npm/bun only from its own global dir, else the user's step); `#stable` + #218 only when no gbrain is left. Windows: MSYS paths, `.exe`. Tests: `npm-squat-check`, `doctor-npm-squat`.diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.mdindex eb58819954..299206e7b1 100644--- a/docs/architecture/key-files/mcp.md+++ b/docs/architecture/key-files/mcp.md@@ -30,3 +30,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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, and on object `properties` (closed with `additionalProperties: false`, member `required` keys). Key ordering (type, description, enum, default, items, properties) is intentional so `JSON.stringify` output stays byte-stable. `toolAnnotations(op)` is the one annotation rule: curated op annotations win; else `readOnlyHint: true` for a read-scope op tagged `mutating: false`, `readOnlyHint: false` for one tagged `mutating: true`, nothing for untagged ops. `test/mcp-tool-defs.test.ts` has a `findArrayWithoutItems` walker that fails on any `type: 'array'` lacking `items.type`. Annotations: curated `op.annotations` win; else `readOnlyHint: true` iff `mutating === false`, `readOnlyHint: false` (+ `idempotentHint: true` when `idempotent`) iff `mutating === true`; every op declares both tags (`test/ops-mutation-tags.test.ts`).- `src/mcp/validate-params.ts` — param normalization + validation for dispatch (direct unit surface). `validateParams` (required/type/enum — enum membership is a TYPE error in BOTH strict modes; the caller's raw value is never echoed into the message), `normalizeOptionalParams` (null/`''` optional-param idioms become truly absent, and so do the values a param's schema rules out: `0` below `minimum`/`exclusiveMinimum`, `[]` under `minItems`, `{}` on an object with a required member, `false` on an `actsWhenTrue` flag, then any param whose `appliesWith` param is absent (GST-927); required params untouched, copy-on-write), `findUnknownParams` (unknown top-level keys on the NORMALIZED object; `UNKNOWN_PARAM_ALLOWLIST` = `_meta` + `dry_run`; per-op did-you-mean from the op's OWN declared params only, plus the explicit `PARAM_ALIAS_HINTS` aliases edit distance cannot reach, e.g. `add_timeline_entry` `content` → `detail` and `remember` `facts` → `items`, `text` → `fact`; dispatch rejects unknown keys on every `mutating` op regardless of `mcp.strict_params`, so a typo never commits a write, and appends the op's optional `callShape` (a valid call with placeholder values, set only by `remember`, GST-1493) to the suggestion), `buildUnknownParamWarnBlock` (the model-visible warn notice), `resolveStrictParamsMode(engine, config)` (dual-plane `mcp.strict_params`, DB > file > `'warn'`; a failed DB read applies the LAST successfully read DB mode, held per engine — fail-closed, so a transient config outage on a reject-mode server cannot re-open the warn grace period; test seam `resetStrictParamsModeCache()`). Privacy: raw unknown key names reach the CALLER only, never `mcp_request_log`. Pinned by test/validate-params.test.ts. Every path that hands arguments to an op handler runs normalize → validate first: `dispatchToolCall`, `handleToolCall` (`gbrain call`) and the SkillOpt rollout and write-capture registries, so a model that sends `""` or `null` for every optional argument reads the same as one that omits them (`test/tool-args-empty-optional-sol.test.ts`). On a remote call the audience and attested-actor checks in `dispatchToolCall` read the normalized arguments, so `acting_user: ""` or `null` counts as omitted.+- `src/core/mcp-request-log-retention.ts` — opt-in request-log retention (`cycle.purge.mcp_request_log_retention_days`: unset/0/off = off, 30-3650; `mcpLogRetentionRefusal` is the `config set` refusal). `pruneMcpRequestLog` runs batches of 2,000 (200 per run, the cutoff fixed once), each ONE statement: oldest rows past the cutoff in `created_at` order `FOR UPDATE SKIP LOCKED`, minus `AUDIT_LOG_OPERATIONS`, deleted and added to `mcp_request_log_rollup` (requests, last_used_at, `pruned_through` = newest pruned row; NULL token under `''`), so a failed tally deletes nothing; a missing tally table skips. `runMcpLogRetention` reads the key and records `{at, deleted, capped}` under `cycle.purge.mcp_request_log_last_prune`; callers: the cycle purge phase and `startMcpLogPruneTicker` (PGLite only, hourly, 3 s budget, yields between batches) in both serve lanes. `lifetimeUsage` = kept rows + tally in one statement (admin Agents totals). Pinned by `test/mcp-request-log-retention.test.ts` (both engines) and `test/serve-http-admin-request-log-retention.test.ts`.+- `src/commands/doctor/checks/mcp-request-log.ts` — doctor `mcp_request_log_retention` (ops): log rows (reltuples on Postgres, a bounded count on PGLite) and size; retention off past 1M rows or 1 GiB warns with an `ask_user` + `destructive` fix (`config set … 90`), never a remediation step; retention on reports `pruned_before` and the last run, and warns when no prune ran for 48 hours (or none ever ran while rows past the window wait). Pinned by `test/doctor-mcp-request-log-retention.test.ts`.diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex c16e814c2d..15e9de68ff 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -87,7 +87,7 @@ also contain knowledge absent from canonical files and must be backed up.| `raw_data` | Webhook/transcript sidecars; not user-authored knowledge. || `subagent_messages` / `subagent_tool_executions` / `subagent_rate_leases` | Runtime job state. Replay-only, not persistent knowledge. || `oauth_clients` / `oauth_tokens` / `access_tokens` | Credentials. Not in source control by definition. |-| `mcp_request_log` | Audit trail. Volatile by design. |+| `mcp_request_log` | Audit trail. Volatile by design; opt-in retention (`cycle.purge.mcp_request_log_retention_days`) prunes request rows past its window into the per-token tally `mcp_request_log_rollup` and keeps audit rows. || `minion_jobs` / `minion_inbox` / `minion_attachments` | Job queue. Restarts re-enqueue or drop. || `eval_candidates` / `eval_capture_failures` | Contributor-mode dev loop; opt-in capture. || `dream_verdicts` | Scored triage cache (salience score, quotes, entities, judging model + prompt version). Rows carry a 30-day `expires_at` TTL: reads treat expired rows as misses and the synthesize phase sweeps them, so nothing lives forever. Rebuildable via `gbrain dream retriage --force`. |diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex 664f96c23f..d2feb5afac 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -695,7 +695,49 @@ not revoke server access.Jobs accepted before token invalidation continue under their existing grantchecks. Revocation or deletion denies those jobs at their nextauthority check; external work already admitted may complete. All three actions-retain request history, audit records, spending reservations, and settlement.+retain request history within the request-log retention window, audit records,+spending reservations, and settlement.++## Request log retention++`gbrain serve --http` writes one `mcp_request_log` row per call, `tools/list`+included, so the log grows without limit. Retention is off by default. Turn it+on with a window of 30 to 3650 days:++```bash+gbrain config set cycle.purge.mcp_request_log_retention_days 90+```++Values from 1 to 29 are refused, because the built-in usage readers look back+30 days. `0`, `off` or `gbrain config unset` turns it off again.++With retention on, the cycle `purge` phase (autopilot or `gbrain dream`)+deletes rows older than the window. On a PGLite brain held by a live+`gbrain serve` or `gbrain serve --http`, the serve prunes once an hour instead,+in short batches between requests. Each run deletes at most 400,000 rows; the+next run continues.++The prune keeps these:++- `surface_change` and `memory_setting_change` audit rows, which are never+ pruned.+- Per-client lifetime totals. Pruned rows are counted per token in+ `mcp_request_log_rollup`, so the dashboard's total requests and last-used+ times stay exact.++Deleted request detail (operation, status, parameters, errors) cannot be+restored, and raising the window later does not bring it back. A usage report+whose window reaches past pruned history says so: `gbrain auth clients --usage`+prints `window truncated` with the `--days` value that is complete (its `--json`+carries `window_truncated`, `covered_days`, `pruned_before` and `window_note`),+and `scripts/derive-starter-ops.ts` refuses with exit 1. Retention caps growth;+it does not shrink a PGLite file that already grew.++`gbrain doctor --only mcp_request_log_retention` reports the log's size and,+with retention on, when the last prune ran and what it removed. It warns when+the log passes about 1M rows or 1 GiB with retention off, and when no prune+has run for 48 hours. Its fix that turns retention on asks the user first and+is never part of `gbrain doctor --remediate`.## Recover a failed stepdiff --git a/docs/operations/mcp-surface-runbook.md b/docs/operations/mcp-surface-runbook.mdindex cfd5b97580..fd63f38957 100644--- a/docs/operations/mcp-surface-runbook.md+++ b/docs/operations/mcp-surface-runbook.md@@ -122,7 +122,9 @@ surface) lists that surface in full.lists in a long-lived session go stale until it does.- An audit row lands in `mcp_request_log` (`operation='surface_change'`,params carrying actor/old/new/via) — every surface mutation writes one- (rescope CLI, admin endpoint, request_tools persist):+ (rescope CLI, admin endpoint, request_tools persist). Request-log retention+ never prunes these rows; other request rows older than its window are gone+ ([retention](../mcp/ADMIN.md#request-log-retention)):```sqlSELECT created_at, params FROM mcp_request_logdiff --git a/scripts/derive-starter-ops.ts b/scripts/derive-starter-ops.tsindex 160f68bec7..7473c333e1 100644--- a/scripts/derive-starter-ops.ts+++ b/scripts/derive-starter-ops.ts@@ -19,6 +19,10 @@* slices (VERB_NAMES spread + whoami + request_tools + the agent lane) are* composed in surface.ts itself and excluded from the proposal.*+ * A window that reaches back past pruned request-log history (retention,+ * src/core/mcp-request-log-retention.ts) is refused: exit 1, the truncation+ * note on stderr naming the --days that is complete.+ ** Caveats printed with the proposal:* - HTTP clients only (stdio never writes mcp_request_log).* - BRAIN_TOOL_ALLOWLIST cross-check (D12): allowlist members missing from@@ -29,7 +33,7 @@import { loadConfig, toEngineConfig } from '../src/core/config.ts';import { createEngine } from '../src/core/engine-factory.ts';-import { readClientOpUsage, MCP_USAGE_DEFAULT_WINDOW_DAYS } from '../src/core/mcp-usage.ts';+import { readClientOpUsageWithCoverage, truncatedWindowNote, MCP_USAGE_DEFAULT_WINDOW_DAYS, type ClientOpUsage } from '../src/core/mcp-usage.ts';import { operations } from '../src/core/operations.ts';import { ALWAYS_INCLUDED_STARTER_OPS } from '../src/mcp/surface.ts';import { BRAIN_TOOL_ALLOWLIST } from '../src/core/minions/tools/brain-allowlist.ts';@@ -80,9 +84,15 @@ const engine = await createEngine(engineConfig);await engine.connect(engineConfig);async function run(): Promise<number> {- let usage: Awaited<ReturnType<typeof readClientOpUsage>>;+ let usage: ClientOpUsage[];try {- usage = await readClientOpUsage(engine, { days });+ const read = await readClientOpUsageWithCoverage(engine, { days });+ // Partial data must never derive the starter surface: refuse a window that reaches past pruned history.+ if (read.coverage.truncated) {+ console.error(truncatedWindowNote(read.coverage));+ return 1;+ }+ usage = read.clients;} catch (e) {// A brain that never served remote MCP may lack the table entirely.console.error('Could not read mcp_request_log — has this brain ever served remote MCP?');diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 91c4fa72d0..4901d756fb 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -13,7 +13,7 @@ src/commands/jobs.ts 693 ratchet refactor wave 1 split target (W4 jobs, cut linesrc/commands/serve-http.ts 947 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts); +5 #6858 ask 6: on-commit HEAD watcher start/stop (watcher in core/serve-head-watcher.ts); +4 GBRA-199: serve --http --advertise parse, help line and pass-through (logic in mcp/surface.ts parseAdvertiseFlag); +6 GBRA-283 B3a: runServeHttp enters the local scope (withLocalScope; scope store in core/engine-scope-store.ts), the entry wrapper and its import cannot movesrc/core/ai/gateway.ts 4571 ratchet +5 GBRA-274 B1.3: withoutBudgetTracker export (runs a rollout hook outside the run's budget scope; the budget AsyncLocalStorage is gateway-private, so it cannot move); +2 #6997: ChatResult.fallbackReason (interface field + doc; recorded in ai/chat-fallback.ts); +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +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); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text; +5 #7176: expand() writes its chat_usage_log row (phase expansion) beside the budget record, and the guardedExpansion instance that names its invocation gateway.expand (ledger in ai/chat-usage.ts); +2 PR 4 (Wave B incremental derivation, transcripts) 4b round 4: chat() forwards a metered page step's providerRetries (BudgetTracker) as the SDK's maxRetries, so every attempt is one it reserved for; +24 GBRA-283 B2 (#8456): per-engine gateway state, the gw() accessor every config and model-cache read goes through (an embedded engine state or the process state), configure split into gatewayConfigOf, and configFor at the provider-resolution sites so a provider the engine lacks refuses before any call (state and refusal live in ai/engine-gateway.ts); +1 GBRA-283 B2: embedding diagnosis refuses a provider the embedded engine was not given; +1 GBRA-283 B2 (#8499 item 1): requireConfig refuses an unscoped call in a process holding embedded engines (engine_scope_missing; predicate in engine-scope.ts); +7 GBRA-283 B3a: every embed/chat/expand/rerank/toolLoop entry and requireConfig/configFor call refuseUnscoped (predicate and refusal in ai/engine-gateway.ts), the unscoped state, and the shrink/no_key/structured-output memory read through gw() (state in ai/engine-gateway.ts GatewayState)src/commands/sync.ts 566 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight; +2 #6693: SyncResult.replayedRemembers interface field (the post-sync replay lives in commands/sync/perform.ts and repair/failed-writes.ts); +12 #6712 PR 1: SyncResult.leaseHeld / inherited_options / cursorAdopted / cursorFanIn and SyncOpts.drainHolder / followDrainLease interface fields (the lease lives in persistence/sync-lease.ts, adoption in persistence/sync-cursor-key.ts and sync-admitted.ts); +2 #6712 PR 2 (L5): SyncResult.tail interface field (the tail lives in persistence/sync-tail.ts); +2 #6712 PR 2 integration: L4 ghostPages and L5 tail SyncResult interface fields both land (each lane raised 542->544 alone); +2 #6948: SyncResult.origin_twins_resolved interface field (the heal lives in repair/origin-twins-heal.ts); +5 #6712 PR 4b: SyncResult.pass / reconcile and SyncOpts.costApproved interface fields (an interface field cannot move; the pass summary and the pass reason union live in persistence/sync-pass-row.ts, the remote reconcile in sync-pass-apply.ts); lowered to 546 #6712 PR 4b lane C: SyncResult.cursorAdopted / cursorFanIn retired with the cursor engine; +2 #7167: SyncResult.writer interface field (a managed dry run reports the writer instead of waiting on it; the read lives in persistence/sync-dry-run-writer.ts); +6 G8a git-canonical: SyncOpts.canonicalOverride interface field and its doc comment (internal: only the conversion apply in persistence/git-conversion.ts passes it; applied in persistence/sync-discovery.ts); +2 #7866: SyncOpts.fullRound interface field and its doc comment (internal: the conversion strict passes in persistence/git-conversion.ts set it; read in persistence/sync-pass-run.ts); +1 #8007: SyncResult.storage_invalid_kept interface field (the keep lives in persistence/sync-discovery.ts); +2 GBRA-287: SyncResult.reexport_failures interface field (the re-export lives in commands/sync/full.ts); re-summed at the memory train #8481 merge with v0.60.576.0 (564 measured); +2 convergence PR A: SyncOpts.conversionBinding interface field and its doc comment (internal: only the conversion apply in persistence/git-conversion.ts passes it; applied in persistence/sync-pass.ts bindConversion)-src/core/cycle.ts 3351 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); 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:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left due; +5 #7241: CycleOpts.onPhaseStart and its best-effort call in timePhase, so the autopilot-cycle job writes its current phase to minion_jobs.progress; +1 GBRA-133: the extract phase passes the stale-drain budget to its targeted pass when sync gave no slug list; +7 #7630 (GBRA-207): the sync phase refuses sync_anchor_relative when no source matches its directory and default's local_path is relative; re-summed at the memory train #8481 merge with v0.60.576.0 (3348 measured); +3 GST-1856: the purge phase drops applied-capture records past 90 days (logic in ingestion/applied-captures.ts purgeStaleAppliedCaptures)+src/core/cycle.ts 3355 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); 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:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left due; +5 #7241: CycleOpts.onPhaseStart and its best-effort call in timePhase, so the autopilot-cycle job writes its current phase to minion_jobs.progress; +1 GBRA-133: the extract phase passes the stale-drain budget to its targeted pass when sync gave no slug list; +7 #7630 (GBRA-207): the sync phase refuses sync_anchor_relative when no source matches its directory and default's local_path is relative; re-summed at the memory train #8481 merge with v0.60.576.0 (3348 measured); +3 GST-1856: the purge phase drops applied-capture records past 90 days (logic in ingestion/applied-captures.ts purgeStaleAppliedCaptures); +4 #6770: the purge phase runs the opt-in request-log retention prune (logic in mcp-request-log-retention.ts runMcpLogRetention)src/core/cycle/synthesize.ts 3244 ratchet +3 #7805: each captured session synthesizes only into its own frozen source (routing import, the outer wrapper, the routing parameter; logic in cycle/synthesize-source-routing.ts); +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); 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); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts; +6 GBRA-130 B-6 (#6860): surrogate-safe triage cuts (truncateUtf8) and the per-transcript verdict-cache write call site (logic in triage-backoff.ts VerdictCacheWrites); +2 GBRA-161 PR 4 (#7065): the synthesize phase activates each synthesized transcript's outputs as its generation (activateSynthesisGenerations import and call site; logic in cycle/synthesize-generations.ts); +8 GBRA-161 PR 5 (S-2): the dream summary publishes as a single-item dream_summary generation bound to its pre-run revision (publishSinglePage with a generation_fenced skip); +1 GBRA-60: a managed synthesis child carries dream_output (verify and stamp before put_page; cycle/synthesize-child-verify.ts)src/core/cycle/extract-atoms.ts 1658 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 once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +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 once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count; GBRA-130 A-42 (#6804): dot-led atom stems and the legacy-slug adoption guardsrc/core/engine.ts 2874 ratchet +5 #7191: findPages/countPagesBy signatures and type imports (SQL in engine-sql/page-lookup.ts); 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); 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; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9; +9 GBRA-177: TakesListOpts.oldestFirst/sinceOnOrBefore/ungradedFirst for the grade_takes window (interface fields cannot move; SQL in engine-sql/takes.ts): 2832 + 9; +6 GBRA-156: TransactionOptions.pipelineFirst (the declaration goes out with BEGIN behind a transaction-mode pooler; predicate in persistence/protocol.ts); interface fields cannot move; +1 GBRA-161 PR 2: deprecation notes on insertFacts({ deleteForPageFirst }), deleteFactsForPage and expireFact (interface docs cannot move); +7 GBRA-156: TransactionOptions.pipelineEarly (search read bodies go out behind BEGIN; predicate in postgres-engine/search-settings.ts); interface fields cannot move; +2 GBRA-156: TransactionOptions.readOnly (search read transactions open BEGIN READ ONLY; 2858 measured); grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); re-summed at the Wave B PR 4 merge with v0.60.452.0 (2866 measured); re-summed at the memory train #8481 merge with v0.60.576.0 (2874 measured)@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1996 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts); +13 GBRA-188 per-turn brain-first rule: user-prompt emission and its HookIo seam (rule and ledger read in core/setup/brain-first.ts); +3 GBRA-188 plugin lane: GBRAIN_HOOK_LANE=plugin yields to another gbrain lane wiring the event (import, comment and guard; detection in bootstrap/plugin-lanes.ts otherLaneWiresHook); +5 GBRA-243 turn-rule lane: GBRAIN_HOOK_LANE=turn-rule yields to every other lane and answers rule-only (import, two guards and comments; logic in core/setup/turn-hook.ts), user-prompt passes cwd to the scope-aware rule; +34 #8064/#8016/#8028: the session-speaker banking decision at compact, stop and session-end (logic in context/session-speaker.ts), the harness-prompt skip and the lane-scoped parser_drift clear; +1 #8424: hookSessionCwd import (the session directory the hook launcher records; logic in core/setup/hook-launcher.ts); +1 #8424 review: runHook captures the launcher-recorded session directory first (logic in setup/hook-launcher.ts captureHookSessionCwd); +7 #8427: the hook git probes skip core.fsmonitor and run only in the workspace the install receipt namessrc/core/chunkers/code.ts 1602 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_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout-src/core/config.ts 2021 ratchet +1 GBRA-154 #7175: search.keyword_phrase KNOWN_CONFIG_KEYS row; +1 search.saved_facts_supersede KNOWN_CONFIG_KEYS row (read in search/saved-facts-match.ts; re-summed at the #7703 merge: 2014 + 1); +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); 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-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured); +2 GBRA-205: search.evidence_titles / query_budget_unit / query_facts_block / fact_source_pages KNOWN_CONFIG_KEYS rows (read in search/evidence-date.ts, evidence-packing.ts, facts-arm.ts); +1 GBRA-156: search.remote_page_cap KNOWN_CONFIG_KEYS row (read in search/remote-page-cap.ts); re-summed at the memory train #8481 merge with v0.60.576.0 (2021 measured)+src/core/config.ts 2022 ratchet +1 GBRA-154 #7175: search.keyword_phrase KNOWN_CONFIG_KEYS row; +1 search.saved_facts_supersede KNOWN_CONFIG_KEYS row (read in search/saved-facts-match.ts; re-summed at the #7703 merge: 2014 + 1); +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); 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-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured); +2 GBRA-205: search.evidence_titles / query_budget_unit / query_facts_block / fact_source_pages KNOWN_CONFIG_KEYS rows (read in search/evidence-date.ts, evidence-packing.ts, facts-arm.ts); +1 GBRA-156: search.remote_page_cap KNOWN_CONFIG_KEYS row (read in search/remote-page-cap.ts); re-summed at the memory train #8481 merge with v0.60.576.0 (2021 measured); +1 #6770: cycle.purge.mcp_request_log_retention_days KNOWN_CONFIG_KEYS rowsrc/core/persistence/sync-run.ts 1697 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts); +1 #7886: the import of persistence/sync-receipt-wait.ts, where the managed sync receipt waits and their test seam live; +3 #7931: the freeze drift screen also accepts a file that holds the page as prepareFileTarget reads it (fileMatchesSnapshot import, comment, the split condition line); +5 GBRA-218: performManagedSync wraps every managed pass (sync, drain, sources refresh, git conversion, owner slice) in withCommittedPolicy (logic in access/policy-git.ts) and keeps the lease path in performLeasedPass; re-summed at the memory train #8481 merge with v0.60.576.0 (1696 measured); +1 convergence nightly fix: the sync:passed_over fault point after the pass-over cursor save (a kill seam sits where its cursor commits, so it cannot move)src/core/bootstrap/harness.ts 2630 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; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments); +13 brain-first block lane: --no-instructions flag field + parse, opencodeAgentsPath dep (field + default) and the step-10b / remove call sites (logic lives in harness-brain-first.ts); +7 GBRA-243 per-turn rule hook: consent-block interface field, step-10c call site, turn_hooks JSON field, exit code and the remove arm (writer, host list and consent text live in harness-brain-first.ts); +2 #8428: the harness lane Claude Code and Codex SessionEnd hooks start gbrain through the hook launcher; +16 GBRA-194 skills index lane: --skill-loading flag field + parse, step-10b and remove call sites, skills_index JSON field and exit-code wiring (logic lives in harness-skills-index.ts and setup/skills-block.ts)src/core/oauth-provider.ts 1237 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; +1 #5222 resourceUrl option; +1 GST-1113 transactional token mint@@ -45,6 +45,7 @@ src/core/search/mode.ts 1730 ratchet +12 #7175 (train R): search.keyword_phrasesrc/commands/eval-longmemeval.ts 1545 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter); +1 #7619: parseArgs refuses a value on a switch (--judge=false turned the paid judge on)src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge); +1 #7145: content_hash_duplicates reads one group past its list to report a floor ("at least 50")src/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)-src/commands/config.ts 1526 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)+src/commands/config.ts 1527 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal); +1 #6770: set-time refusal hook for cycle.purge.mcp_request_log_retention_days (refusal in core/mcp-request-log-retention.ts)+src/commands/auth.ts 1504 ratchet new row: crossed the 1500 unlisted cap with #6770 (auth clients --usage reports window coverage after a request-log prune: one JSON spread, one note line, one help line; logic in core/mcp-usage.ts)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)src/core/behavior-change-notice.ts 1687 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default rowdiff --git a/src/admin-embedded.ts b/src/admin-embedded.tsindex 35edbd9080..2ff93b465c 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_B9c8JuNx_js from '../admin/dist/assets/index-B9c8JuNx.js' with { type: 'file' };+import A_0_assets_index_BB8hJoAN_css from '../admin/dist/assets/index-BB8hJoAN.css' with { type: 'file' };// @ts-ignore — type: 'file' is Bun ESM, not in lib.d.ts-import A_1_assets_index_BB8hJoAN_css from '../admin/dist/assets/index-BB8hJoAN.css' with { type: 'file' };+import A_1_assets_index_c5YhzUcc_js from '../admin/dist/assets/index-c5YhzUcc.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-B9c8JuNx.js": { path: A_0_assets_index_B9c8JuNx_js as unknown as string, mime: "application/javascript; charset=utf-8" },- "/admin/assets/index-BB8hJoAN.css": { path: A_1_assets_index_BB8hJoAN_css as unknown as string, mime: "text/css; charset=utf-8" },+ "/admin/assets/index-BB8hJoAN.css": { path: A_0_assets_index_BB8hJoAN_css as unknown as string, mime: "text/css; charset=utf-8" },+ "/admin/assets/index-c5YhzUcc.js": { path: A_1_assets_index_c5YhzUcc_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/commands/auth.ts b/src/commands/auth.tsindex 5d9604589e..f24ec2a8db 100644--- a/src/commands/auth.ts+++ b/src/commands/auth.ts@@ -1188,8 +1188,9 @@ async function clientsCmd(args: string[]) {const clients = await listClientRows(engine);const lifetimeClamped = await tokenLifetimeClampedClients(engine);- const { readClientOpUsage } = await import('../core/mcp-usage.ts');- const usage = parsed.usage ? await readClientOpUsage(engine, { days: parsed.days }) : [];+ const { readClientOpUsageWithCoverage, truncatedWindowNote } = await import('../core/mcp-usage.ts');+ const { clients: usage, coverage } = parsed.usage ? await readClientOpUsageWithCoverage(engine, { days: parsed.days }) : { clients: [], coverage: null };+ const windowNote = coverage?.truncated ? truncatedWindowNote(coverage) : null;const usageByToken = new Map(usage.map(u => [u.token_name, u]));const clientIds = new Set(clients.map(c => c.client_id));const legacyUsage = usage.filter(u => !clientIds.has(u.token_name));@@ -1198,6 +1199,7 @@ async function clientsCmd(args: string[]) {console.log(JSON.stringify({window_days: parsed.days,usage_included: parsed.usage,+ ...(coverage ? { window_truncated: coverage.truncated, covered_days: coverage.covered_days, pruned_before: coverage.pruned_before, window_note: windowNote } : {}),clients: clients.map(c => ({client_id: c.client_id,client_name: c.client_name,@@ -1222,6 +1224,7 @@ async function clientsCmd(args: string[]) {console.log('No OAuth clients registered. Register one: gbrain auth register-client "my-client"');return;}+ if (windowNote) console.log(`${windowNote}\n`);const fmtTop = (u: (typeof usage)[number]) =>Object.entries(u.ops).slice(0, 5).map(([op, n]) => `${op}(${n})`).join(', ');for (const c of clients) {@@ -1421,7 +1424,8 @@ Usage:joins per-client op-call counts, top ops, and last-seenfrom mcp_request_log (default 30d window; HTTP clientsonly — stdio use is not logged). Automation-shaped- clients (>90% context_pack/delta) are flagged.+ clients (>90% context_pack/delta) are flagged. A window+ reaching past pruned request-log history says so.gbrain auth revoke-client <client_id> Hard-delete an OAuth 2.1 client (cascades to tokens + codes)gbrain auth local-writer list|register|revoke Manage durable local CLI/stdio writers (see --help)gbrain auth test <url> --token <token> Smoke-test a remote MCP serverdiff --git a/src/commands/config.ts b/src/commands/config.tsindex ade7bb21ad..3a3838dff6 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -411,6 +411,7 @@ async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value:if (key === 'sync.slug_conflicts.auto_remove') { const err = (await import('../core/repair/slug-autoheal.ts')).slugAutoRemoveValueRefusal(value); if (err) { console.error(`[config] ${err}`); process.exit(1); } }if (key === 'sync.origin_twins.auto_resolve') { const err = (await import('../core/repair/origin-twins-heal.ts')).originAutoResolveValueRefusal(value); if (err) { console.error(`[config] ${err}`); process.exit(1); } }if (key === 'sync.repo_path') { const err = (await import('../core/sync-config-keys.ts')).syncRepoPathRefusal(value); if (err) { console.error(`[config] ${err}`); process.exit(1); } }+ if (key === 'cycle.purge.mcp_request_log_retention_days') { const err = (await import('../core/mcp-request-log-retention.ts')).mcpLogRetentionRefusal(value); if (err) { console.error(`[config] ${err}`); process.exit(1); } }if (key.startsWith('search.')) (await import('./config/keyword-timeout-value.ts')).refuseInvalidKeywordTimeoutValue(key, value);if (key === 'persistence.max_claim_ms') {const { validateMaxClaimConfigValue } = await import('../core/persistence/claim-phase.ts');diff --git a/src/commands/doctor/checks/mcp-request-log.ts b/src/commands/doctor/checks/mcp-request-log.tsnew file mode 100644index 0000000000..185f6975d5--- /dev/null+++ b/src/commands/doctor/checks/mcp-request-log.ts@@ -0,0 +1,103 @@+/**+ * mcp_request_log_retention (#6770 rewrite): request-log growth and the opt-in+ * retention prune (src/core/mcp-request-log-retention.ts).+ *+ * Retention off: information while the log is small; past about 1M rows or+ * 1 GiB, a warn whose fix turns 90-day retention on. That fix deletes request+ * detail that cannot be restored, so it is `ask_user` with consent+ * `destructive` and never a remediation step (`doctor --remediate` builds its+ * plan from the brain score and repair kinds, not from check fixes).+ * Retention on: the pruned-before date and the last run (time, rows, whether+ * it hit the 400,000-row per-run cap); a warn when no prune ran for 48 hours,+ * or when none ever ran and rows past the window are waiting (a PGLite brain+ * whose serve stopped, a cycle that never runs).+ *+ * Row count: pg_class.reltuples on Postgres, a bounded count on PGLite (no+ * autovacuum, so its estimate is not kept fresh). Size: pg_total_relation_size.+ * Read-only; behaves the same on a repo-less brain.+ */+import type { Action } from '../../../core/agent-output.ts';+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { doctorVerify } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { AUDIT_LOG_OPERATIONS, readMcpUsageCoverage } from '../../../core/mcp-usage.ts';+import {+ MCP_LOG_PRUNE_BATCH, MCP_LOG_PRUNE_MAX_BATCHES, MCP_LOG_RETENTION_KEY, readLastMcpLogPrune, readMcpLogRetentionDays,+} from '../../../core/mcp-request-log-retention.ts';++export const MCP_LOG_WARN_ROWS = 1_000_000;+export const MCP_LOG_WARN_BYTES = 1024 ** 3;+const STALE_PRUNE_MS = 48 * 3_600_000;+const SUGGESTED_DAYS = 90;+const DOCS = 'docs/mcp/ADMIN.md#request-log-retention';++const mb = (bytes: number) => (bytes / 1024 ** 2).toFixed(1);++export async function mcpRequestLogRetentionResult(+ engine: BrainEngine,+ opts: { warnRows?: number; warnBytes?: number } = {},+): Promise<Omit<Check, 'name'>> {+ const warnRows = opts.warnRows ?? MCP_LOG_WARN_ROWS;+ const warnBytes = opts.warnBytes ?? MCP_LOG_WARN_BYTES;+ const [size] = await engine.executeRaw<{ bytes: string }>("SELECT pg_total_relation_size('mcp_request_log')::text AS bytes");+ const [count] = engine.kind === 'postgres'+ ? await engine.executeRaw<{ rows: string }>("SELECT GREATEST(reltuples, 0)::bigint::text AS rows FROM pg_class WHERE oid = to_regclass('mcp_request_log')")+ : await engine.executeRaw<{ rows: string }>('SELECT count(*)::text AS rows FROM (SELECT 1 FROM mcp_request_log LIMIT $1) t', [warnRows + 1]);+ const rows = Number(count?.rows ?? 0);+ const bytes = Number(size?.bytes ?? 0);+ const rowsText = `${engine.kind === 'postgres' ? '~' : ''}${rows}${engine.kind !== 'postgres' && rows > warnRows ? '+' : ''} row(s) (${mb(bytes)} MB)`;+ const days = await readMcpLogRetentionDays(engine);+ const details: Record<string, unknown> = { retention_days: days, rows, rows_exact: engine.kind !== 'postgres' && rows <= warnRows, bytes, docs: DOCS };++ if (days === null) {+ const enable: Action = {+ argv: ['gbrain', 'config', 'set', MCP_LOG_RETENTION_KEY, String(SUGGESTED_DAYS)], consent: ['destructive'], actor: 'agent', ask_user: true,+ requires_exclusive: false, docs: DOCS, verify: doctorVerify('mcp_request_log_retention'),+ why: `Turns on the request-log prune: the next cycle purge phase (or, on a PGLite brain, a live serve within the hour) deletes request rows older than ${SUGGESTED_DAYS} days. Per-client lifetime totals and the surface/memory-setting audit rows are kept.`,+ user_message: `Your MCP request log holds ${rowsText} and nothing prunes it. Turn on ${SUGGESTED_DAYS}-day retention? Request details older than ${SUGGESTED_DAYS} days (operation, status, parameters, errors) will be deleted and cannot be restored; per-client totals and audit rows are kept.`,+ };+ if (rows >= warnRows || bytes >= warnBytes) {+ return { status: 'warn', details, fix: enable,+ message: `The MCP request log holds ${rowsText} and grows with every HTTP MCP call; request-log retention is off, so nothing prunes it. Turning it on deletes old request detail for good, so ask the user first.` };+ }+ return { status: 'ok', severity: 'info', readiness_state: 'disabled_by_choice', details, fix: enable,+ message: `The MCP request log holds ${rowsText}; request-log retention is off, so it keeps every request.` };+ }++ const last = await readLastMcpLogPrune(engine);+ const coverage = await readMcpUsageCoverage(engine, days);+ const [pending] = await engine.executeRaw<{ waiting: boolean }>(+ `SELECT EXISTS (SELECT 1 FROM mcp_request_log WHERE created_at < now() - ($1::int * interval '1 day') AND operation <> ALL($2::text[])) AS waiting`,+ [days, [...AUDIT_LOG_OPERATIONS]]);+ Object.assign(details, { last_prune: last, pruned_before: coverage.pruned_before, rows_past_window: pending?.waiting === true });+ const stale = last ? Date.now() - Date.parse(last.at) > STALE_PRUNE_MS : pending?.waiting === true;+ if (stale) {+ return { status: 'warn', details,+ message: `Request-log retention is ${days} days, but no prune has run in the last 48 hours (last run: ${last?.at ?? 'never'}), so the log keeps growing. ` ++ 'The prune runs in the cycle purge phase (autopilot or gbrain dream) and, on a PGLite brain, hourly inside a live gbrain serve.',+ fix: { argv: ['gbrain', 'dream', '--phase', 'purge'], consent: ['destructive'], actor: 'agent', ask_user: true, requires_exclusive: false, docs: DOCS,+ verify: doctorVerify('mcp_request_log_retention'),+ why: 'Runs the cycle purge phase now, which applies the retention the user already turned on.',+ user_message: `The MCP request log has not been pruned for over 48 hours. Run the maintenance purge now? It deletes request detail older than ${days} days and also removes pages deleted more than the restore window ago, as the nightly cycle does.` } };+ }+ const capNote = last?.capped ? ` It hit the per-run cap of ${(MCP_LOG_PRUNE_BATCH * MCP_LOG_PRUNE_MAX_BATCHES).toLocaleString('en-US')} rows, so older rows are still waiting; each later run continues.` : '';+ return { status: 'ok', details,+ message: `Request-log retention is ${days} days; the log holds ${rowsText}. ` ++ (last ? `The last prune (${last.at}) removed ${last.deleted} row(s).${capNote}` : 'No prune has run yet.') ++ (coverage.pruned_before ? ` Request detail before ${coverage.pruned_before} was pruned; per-client totals and audit rows are kept.` : '') };+}++async function runMcpRequestLogRetention(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ const checks: Check[] = [];+ try {+ checks.push({ name: 'mcp_request_log_retention', ...await mcpRequestLogRetentionResult(engine) });+ } catch (error) {+ checks.push({ name: 'mcp_request_log_retention', status: 'warn', fix_unavailable_reason: 'check_errored', details: { health: 'unknown' },+ message: `Could not read the MCP request log size or retention state: ${error instanceof Error ? error.message : String(error)}` });+ }+ return checks;+}++export const mcpRequestLogRetentionEntry: DoctorEntry = { name: 'mcp_request_log_retention', emits: ['mcp_request_log_retention'], run: runMcpRequestLogRetention };diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 88f1a8a799..c09afd7743 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -130,6 +130,7 @@ import { chatFallbackChainEntry } from './checks/chat-fallback.ts';import { providerConsentEntry } from './checks/provider-consent.ts';import { behaviorChangesEntry } from './checks/behavior-changes.ts';import { fenceIntegrityEntry } from './checks/fence-integrity.ts';+import { mcpRequestLogRetentionEntry } from './checks/mcp-request-log.ts';import { outsideContentFencesEntry } from './checks/outside-content-fences.ts';import { dbAheadOfGitEntry } from './checks/db-ahead-of-git.ts';import { gitIndexLagEntry } from './checks/git-index-lag.ts';@@ -327,6 +328,8 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [ownerHostStaleEntry,embeddingPlaneDisagreementEntry,fenceIntegrityEntry,+ // #6770: MCP request-log size and the opt-in retention prune (read-only; the enable fix asks the user).+ mcpRequestLogRetentionEntry,searchModeEntry,];diff --git a/src/commands/serve-http-admin-api.ts b/src/commands/serve-http-admin-api.tsindex fe6721d6ba..7f088d355f 100644--- a/src/commands/serve-http-admin-api.ts+++ b/src/commands/serve-http-admin-api.ts@@ -12,6 +12,8 @@ import { normalizeTokenScopes } from '../core/legacy-token-scope.ts';import { rescopeClientGrant } from '../core/grants/service.ts';import { resolveOwnerHolder } from '../core/owner-holder.ts';import { sqlQueryForEngine } from '../core/sql-query.ts';+import { lifetimeUsage, readMcpLogRetentionDays } from '../core/mcp-request-log-retention.ts';+import { readMcpUsageCoverage } from '../core/mcp-usage.ts';import { VERSION } from '../version.ts';import { mountAdminApiKeys } from './serve-http-api-keys.ts';import { mountAdminClients } from './serve-http-clients.ts';@@ -257,8 +259,6 @@ function mountAdminOverviewApi(app: Express, ctx: ServeHttpContext): void {c.grant_types, c.scope, c.source_id, c.federated_read,c.created_at, c.token_ttl,CASE WHEN c.deleted_at IS NOT NULL THEN 'revoked' ELSE 'active' END as status,- (SELECT max(created_at) FROM mcp_request_log WHERE token_name = c.client_id) as last_used_at,- (SELECT count(*)::int FROM mcp_request_log WHERE token_name = c.client_id) as total_requests,(SELECT count(*)::int FROM mcp_request_log WHERE token_name = c.client_id AND created_at > now() - interval '24 hours') as requests_todayFROM oauth_clients c ORDER BY c.created_at DESC`;@@ -269,14 +269,16 @@ function mountAdminOverviewApi(app: Express, ctx: ServeHttpContext): void {a.created_at, null as token_ttl,CASE WHEN a.revoked_at IS NOT NULL THEN 'revoked' ELSE 'active' END as status,a.last_used_at,- (SELECT count(*)::int FROM mcp_request_log WHERE token_name = a.name) as total_requests,(SELECT count(*)::int FROM mcp_request_log WHERE token_name = a.name AND created_at > now() - interval '24 hours') as requests_todayFROM access_tokens a ORDER BY a.created_at DESC`;+ // #6770: lifetime totals = rows still in the log + the pruned tally (mcp-request-log-retention.ts).+ const lifetime = await lifetimeUsage(engine, [...oauthClients.map(c => String(c.id)), ...legacyKeys.map(k => String(k.name))]);res.json([- ...oauthClients,+ ...oauthClients.map(c => ({ ...c, last_used_at: lifetime.get(String(c.id))?.last_used_at ?? null, total_requests: lifetime.get(String(c.id))?.requests ?? 0 })),...legacyKeys.map(({ scopes, ...key }) => ({...key,+ total_requests: lifetime.get(String(key.name))?.requests ?? 0,// The SAME normalizer the verify path uses — the dashboard must// never display a grant the serve doesn't enforce (NULL =// grandfathered full access; damaged/deny rows show empty).@@ -579,7 +581,8 @@ function mountAdminKeyApi(app: Express, ctx: ServeHttpContext): void {WHERE 1=1 ${filterSql}`,params,);- res.json({ rows, total: countResult.total, page, pages: Math.ceil(countResult.total / limit) });+ const [retention_days, pruned_before] = await Promise.all([readMcpLogRetentionDays(engine), readMcpUsageCoverage(engine, 1).then(c => c.pruned_before)]);+ res.json({ rows, total: countResult.total, page, pages: Math.ceil(countResult.total / limit), retention_days, pruned_before });} catch {res.status(503).json({ error: 'service_unavailable' });}diff --git a/src/commands/serve.ts b/src/commands/serve.tsindex 5a6f98ca23..6f79e44dc1 100644--- a/src/commands/serve.ts+++ b/src/commands/serve.ts@@ -13,6 +13,7 @@ import { redirectStdoutLoggingToStderr } from '../core/console-prefix.ts';import { startFactsDrainScheduler, type FactsDrainScheduler, type FactsDrainSchedulerOpts } from '../core/facts/drain-scheduler.ts';import { startMovementWatch, type MovementWatch } from '../core/persistence/sync-movement.ts';import { startServeHeadWatcher } from '../core/serve-head-watcher.ts';+import { startMcpLogPruneTicker, type McpLogPruneTicker, type McpLogPruneTickerOpts } from '../core/mcp-request-log-retention.ts';import { isReadOnlyServeArgs, readOnlyServeSkipsResidentDuties } from '../core/direct-pool-profile.ts';import { onForwardProgress } from '../core/forward-progress.ts';import { foregroundWindow } from '../core/foreground-activity.ts';@@ -179,6 +180,8 @@ export interface ServeOptions {// Test seam for the automatic facts drain (src/core/facts/drain-scheduler.ts):// false disables it; an object overrides its timer and run body.factsDrain?: false | Pick<FactsDrainSchedulerOpts, 'run' | 'tickMs' | 'maxGapMs' | 'now'>;+ // Test seam for the request-log retention ticker (src/core/mcp-request-log-retention.ts): false disables it; an object overrides its timer.+ mcpLogPrune?: false | Pick<McpLogPruneTickerOpts, 'setInterval' | 'clearInterval' | 'tickMs'>;}/**@@ -396,6 +399,7 @@ async function serveBrain(// waited for a hand-run sweep and then for retention GC.const { armCorpusDrain } = await import('../core/sweep.ts');const corpusDrain = (opts.armCorpusDrain ?? armCorpusDrain)(engine, { sourceId: process.env.GBRAIN_SOURCE || undefined });+ const mcpLogPrune = installMcpLogPrune(engine, opts, httpLog, () => false);const cliSocket = cliSocketOn ? await (await import('../core/cli-socket/server.ts')).startCliSocket(engine, httpLog) : null;try {@@ -403,6 +407,7 @@ async function serveBrain(} finally {stallWatchdog?.dispose();corpusDrain?.cancel();+ mcpLogPrune?.stop();cliSocket?.close();}@@ -631,12 +636,20 @@ function installFactsDrain(engine: BrainEngine, opts: ServeOptions, deps: StdioL* the on-commit HEAD watcher (`sync.on_commit`, core/serve-head-watcher.ts)* stops with them, before shutdownDelegatedSync aborts the sync it started.*/+/** #6770: the PGLite lock owner's request-log retention prune, hourly (a no-op on Postgres or while retention is off). */+function installMcpLogPrune(engine: BrainEngine, opts: ServeOptions, log: (line: string) => void, shuttingDown: () => boolean): McpLogPruneTicker | null {+ if (opts.mcpLogPrune === false) return null;+ return startMcpLogPruneTicker(engine, { log, ...(opts.mcpLogPrune ?? {}),+ canRun: async () => !shuttingDown() && !isEngineDegradedForServe(engine) && !(await loadSyncRunner()).isDelegatedSyncRunning() });+}+function installResidentTickers(engine: BrainEngine, opts: ServeOptions, deps: StdioLifecycleDeps, shuttingDown: () => boolean): { stop(): Promise<void> } {const factsDrain = installFactsDrain(engine, opts, deps, shuttingDown);+ const mcpLogPrune = installMcpLogPrune(engine, opts, deps.log, shuttingDown);// The watch keeps its own unref'd timer: the injected lifecycle timers are the parent watchdog's and the idle sweep's, which tests count.const movementWatch: MovementWatch = startMovementWatch(engine, { log: deps.log });const headWatcher = startServeHeadWatcher(engine, { log: deps.log });- return { stop: async () => { const settled = headWatcher.stop(); movementWatch.stop(); await settled; await factsDrain?.stop(); } };+ return { stop: async () => { const settled = headWatcher.stop(); movementWatch.stop(); mcpLogPrune?.stop(); await settled; await factsDrain?.stop(); } };}function installStdioLifecycle(diff --git a/src/core/advisor/collect-mcp-client-fit.ts b/src/core/advisor/collect-mcp-client-fit.tsindex a2ce6fca2c..0974819bcb 100644--- a/src/core/advisor/collect-mcp-client-fit.ts+++ b/src/core/advisor/collect-mcp-client-fit.ts@@ -42,7 +42,7 @@import { gbrainPath } from '../config.ts';import { operations } from '../operations.ts';-import { readClientOpUsage, type ClientOpUsage } from '../mcp-usage.ts';+import { readClientOpUsage, readClientOpUsageWithCoverage, type ClientOpUsage } from '../mcp-usage.ts';import {STARTER_OPS,ALWAYS_INCLUDED_STARTER_OPS,@@ -208,7 +208,7 @@ export const collectMcpClientFit: AdvisorCollector = {const localOnlyOps = new Set(operations.filter((o) => o.localOnly).map((o) => o.name));const missingFromStarter = topOps.filter((op) => !STARTER_OPS.has(op) && !localOnlyOps.has(op));- const usage90 = await readClientOpUsage(ctx.engine, { days: DRIFT_UNUSED_WINDOW_DAYS });+ const { clients: usage90, coverage: coverage90 } = await readClientOpUsageWithCoverage(ctx.engine, { days: DRIFT_UNUSED_WINDOW_DAYS });const seen90 = new Set<string>();for (const u of usage90) {if (u.likely_automation) continue;@@ -216,8 +216,9 @@ export const collectMcpClientFit: AdvisorCollector = {}// Always-included-by-construction members (shared with surface.ts +// derive-starter-ops) never count as drift — including the agent lane,- // whose usage would otherwise flag it "unused" forever.- const unusedStarter = [...STARTER_OPS]+ // whose usage would otherwise flag it "unused" forever. A 90-day window+ // cut short by request-log retention cannot show a member unused.+ const unusedStarter = coverage90.truncated ? [] : [...STARTER_OPS].filter((op) => !ALWAYS_INCLUDED_STARTER_OPS.has(op) && !seen90.has(op)).sort();@@ -244,6 +245,9 @@ export const collectMcpClientFit: AdvisorCollector = {title: `STARTER_OPS has drifted from production usage (${parts.length === 2 ? 'both directions' : parts[0]!.split(':')[0]}).`,detail:parts.join('; ') ++ (coverage90.truncated+ ? `. The unused-member check was skipped: request-log history before ${coverage90.pruned_before} was pruned, so the last ${DRIFT_UNUSED_WINDOW_DAYS} days are incomplete`+ : '') +'. Re-derive with `bun run scripts/derive-starter-ops.ts` and paste the proposed ' +'block into src/mcp/surface.ts (the monotonicity test pins verbs ⊆ starter ⊆ full). ' +'Automation-shaped clients are excluded from these stats.',diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 9d2f51389f..83f2a9e3e5 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -52,7 +52,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--claims', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scan-secrets', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--days', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scan-secrets', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],diff --git a/src/core/config.ts b/src/core/config.tsindex aeeea74b96..7c6ff4251a 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1752,6 +1752,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['sync.admission', // #6712 PR 4b: normal | imports_only | classify_only, what a managed pass admits (persistence/sync-admission.ts)'sync.max_deletes', 'sync.max_delete_ratio', 'sync.apply_held_deletions', // #7130 delete caps (sync-reconcile.ts), GBRA-133 held-deletion switch (persistence/sync-held-deletions.ts); per source: <key>.source.<id>'purge.retention_hours', // #7130: hours a soft-deleted page waits before the autopilot purge phase may purge it (default 72)+ 'cycle.purge.mcp_request_log_retention_days', // #6770: opt-in request-log retention, 30-3650 days (mcp-request-log-retention.ts)'sync.federated_v2','sync.include_working_tree','sync.metafile_pages', // GBRA-150: typed (default) | off, whether a nested folder-scaffolding file with type:/title: frontmatter is a page (core/sync.ts)diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex d4d8b785ac..4c09459c5f 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -1825,6 +1825,9 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise<Phasconst purgedAppliedCaptures = await (await import('./ingestion/applied-captures.ts')).purgeStaleAppliedCaptures(engine);let purgedFeedback = { events: 0, weights: 0 };try { purgedFeedback = await (await import('./feedback/store.ts')).pruneRetrievalFeedback(engine, (await (await import('./feedback/settings.ts')).loadFeedbackSettings(engine)).eventRetentionDays); } catch { /* pre-v207 brain */ }+ // #6770: request-log rows past cycle.purge.mcp_request_log_retention_days, when set (logic in mcp-request-log-retention.ts).+ let purgedMcpLog = 0;+ try { purgedMcpLog = (await (await import('./mcp-request-log-retention.ts')).runMcpLogRetention(engine))?.deleted ?? 0; } catch (e) { console.warn(`[cycle] request-log retention skipped: ${e instanceof Error ? e.message : String(e)}`); }return {phase: 'purge',status: purgePhaseStatus(purgedPages), error: purgedPages.error, // #6741: a writer in recovery or a parked page warns@@ -1852,6 +1855,7 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise<Phas...(purgedDecisionReceipts > 0 ? { purged_decision_receipts_count: purgedDecisionReceipts } : {}),...(purgedAppliedCaptures > 0 ? { purged_applied_captures_count: purgedAppliedCaptures } : {}),...(purgedFeedback.events + purgedFeedback.weights > 0 ? { purged_retrieval_feedback_events_count: purgedFeedback.events, purged_retrieval_weights_count: purgedFeedback.weights } : {}),+ ...(purgedMcpLog > 0 ? { purged_mcp_request_log_count: purgedMcpLog } : {}),},};} catch (e) {diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsindex 9a28847f38..858cf4d5d0 100644--- a/src/core/deletion-inventory.ts+++ b/src/core/deletion-inventory.ts@@ -103,6 +103,7 @@ const ROWS: readonly Row[] = [['links', 'out_of_scope', 'probed_reported', 'link_type context link_source link_kind origin_field resolution_type assertion_tense', 'context'],['loop_suppressions', 'out_of_scope', 'no_memory_text', 'source_id kind value'],['mcp_request_log', 'out_of_scope', 'probed_reported', 'token_name agent_name operation status params error_message', 'params error_message'],+ ['mcp_request_log_rollup', 'out_of_scope', 'no_memory_text', 'token_name'],['mcp_spend_log', 'out_of_scope', 'no_memory_text', 'client_id token_name operation provider model budget_key'],['mcp_spend_reservations', 'out_of_scope', 'no_memory_text', 'client_id model provider status usage_unknown_reason budget_key'],['mention_gazetteer_entries', 'out_of_scope', 'no_memory_text', 'source_id name_norm target_slug'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 7f676f4c6a..b9ec44f1b8 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -319,6 +319,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['url_source_origin',// F4b: PGLite row-delta planner statistics / Postgres autovacuum ANALYZE lag on the hot tables.'planner_stats_stale',+ // #6770: MCP request-log size and the opt-in retention prune (mcp-request-log-retention.ts).+ 'mcp_request_log_retention','alternative_providers','autopilot_fanout_concurrency','autopilot_lock_scope',diff --git a/src/core/mcp-request-log-retention.ts b/src/core/mcp-request-log-retention.tsnew file mode 100644index 0000000000..7003c20a60--- /dev/null+++ b/src/core/mcp-request-log-retention.ts@@ -0,0 +1,220 @@+/**+ * Request-log retention (#6770 rewrite; proposed by @lubosxyz): the opt-in+ * prune of `mcp_request_log` rows older than+ * `cycle.purge.mcp_request_log_retention_days` (unset, 0 or off = off; never+ * fewer than 30 days, so every built-in 30-day usage window stays complete).+ *+ * Each batch is ONE statement: pick the oldest rows past the cutoff (index+ * order on created_at, FOR UPDATE SKIP LOCKED so two prunes never take the+ * same row), delete them, and add them to the per-token tally+ * `mcp_request_log_rollup` (count, newest time, pruned_through). A failed+ * tally rolls its delete back, so lifetime totals (kept rows plus the tally)+ * stay exact. Audit rows (AUDIT_LOG_OPERATIONS) are never pruned. A NULL+ * token_name counts under ''. The cutoff is fixed once per run.+ *+ * It runs in two places: the cycle purge phase (Postgres, and PGLite with no+ * live serve), and a resident hourly ticker in the process that holds a PGLite+ * brain's lock (`gbrain serve` and `gbrain serve --http`), under a small+ * wall-clock budget that yields between batches so live MCP traffic keeps the+ * single connection. Each run records its time, count and cap state+ * (`cycle.purge.mcp_request_log_last_prune`) for doctor's+ * `mcp_request_log_retention` check.+ *+ * Operational data only: it never touches git or page content, and a+ * repo-less brain behaves the same. Deletion caps growth; it does not shrink+ * a PGLite file that already grew (that needs VACUUM FULL).+ */+import type { BrainEngine } from './engine.ts';+import { AUDIT_LOG_OPERATIONS } from './mcp-usage.ts';++export const MCP_LOG_RETENTION_KEY = 'cycle.purge.mcp_request_log_retention_days';+export const MCP_LOG_LAST_PRUNE_KEY = 'cycle.purge.mcp_request_log_last_prune';+export const MIN_MCP_LOG_RETENTION_DAYS = 30;+export const MAX_MCP_LOG_RETENTION_DAYS = 3650;+export const MCP_LOG_PRUNE_BATCH = 2_000;+/** 200 batches of 2,000: at most 400,000 rows per run; the next run continues. */+export const MCP_LOG_PRUNE_MAX_BATCHES = 200;+export const MCP_LOG_PRUNE_TICK_MS = 60 * 60_000;+export const MCP_LOG_PRUNE_RESIDENT_BUDGET_MS = 3_000;++const OFF_VALUES = new Set(['', '0', 'off']);++/** Days in effect, or null when retention is off (unset, 0, off, or an unreadable value). */+export function parseMcpLogRetentionDays(raw: string | null | undefined): number | null {+ const text = raw?.trim().toLowerCase() ?? '';+ if (OFF_VALUES.has(text)) return null;+ const days = Number(text);+ return Number.isInteger(days) && days >= MIN_MCP_LOG_RETENTION_DAYS && days <= MAX_MCP_LOG_RETENTION_DAYS ? days : null;+}++/** `config set` refusal text, or null when the value is valid. */+export function mcpLogRetentionRefusal(value: string): string | null {+ if (OFF_VALUES.has(value.trim().toLowerCase()) || parseMcpLogRetentionDays(value) !== null) return null;+ return `${MCP_LOG_RETENTION_KEY} must be a whole number of days from ${MIN_MCP_LOG_RETENTION_DAYS} to ${MAX_MCP_LOG_RETENTION_DAYS} ` ++ `(or 0 / off for no retention); nothing was written. Example: gbrain config set ${MCP_LOG_RETENTION_KEY} 90`;+}++/** Retention in effect; a config read failure reads as off. */+export async function readMcpLogRetentionDays(engine: BrainEngine): Promise<number | null> {+ try { return parseMcpLogRetentionDays(await engine.getConfig(MCP_LOG_RETENTION_KEY)); } catch { return null; }+}++export interface McpLogPruneResult {+ deleted: number;+ /** True when the run stopped at its batch cap or wall-clock budget with rows still past the cutoff. */+ capped: boolean;+ skipped: 'no_rollup_table' | null;+ /** ISO time of the newest row this run pruned (null when it pruned nothing). */+ pruned_through: string | null;+}++export interface McpLogPruneOpts {+ batchSize?: number;+ maxBatches?: number;+ /** Stop after this much wall-clock time (the resident ticker); the cycle runs to the batch cap. */+ budgetMs?: number;+ /** Yield to the event loop between batches (the resident ticker shares PGLite's one connection). */+ yieldBetweenBatches?: boolean;+}++async function rollupTablePresent(engine: BrainEngine): Promise<boolean> {+ const [row] = await engine.executeRaw<{ present: boolean }>("SELECT to_regclass('mcp_request_log_rollup') IS NOT NULL AS present");+ return row?.present === true;+}++const iso = (v: unknown): string => (v instanceof Date ? v : new Date(String(v))).toISOString();++const PRUNE_BATCH_SQL = `+WITH victims AS MATERIALIZED (+ SELECT id FROM mcp_request_log+ WHERE created_at < $1::timestamptz AND operation <> ALL($2::text[])+ ORDER BY created_at+ LIMIT $3+ FOR UPDATE SKIP LOCKED+), deleted AS (+ DELETE FROM mcp_request_log l USING victims v WHERE l.id = v.id+ RETURNING l.token_name, l.created_at+), agg AS (+ SELECT COALESCE(token_name, '') AS token_name, count(*)::bigint AS n, max(created_at) AS newest+ FROM deleted GROUP BY 1+), tallied AS (+ INSERT INTO mcp_request_log_rollup AS r (token_name, requests, last_used_at, pruned_through)+ SELECT token_name, n, newest, newest FROM agg+ ON CONFLICT (token_name) DO UPDATE SET+ requests = r.requests + EXCLUDED.requests,+ last_used_at = GREATEST(r.last_used_at, EXCLUDED.last_used_at),+ pruned_through = GREATEST(r.pruned_through, EXCLUDED.pruned_through)+ RETURNING 1+)+SELECT (SELECT count(*) FROM deleted)::int AS deleted, (SELECT max(created_at) FROM deleted) AS newest, (SELECT count(*) FROM tallied)::int AS tallied`;++/** Prune rows older than `days` in bounded batches. Throws on a database error (each batch's statement rolls back whole). */+export async function pruneMcpRequestLog(engine: BrainEngine, days: number, opts: McpLogPruneOpts = {}): Promise<McpLogPruneResult> {+ if (!(await rollupTablePresent(engine))) {+ console.warn('[mcp-request-log] retention is on but mcp_request_log_rollup does not exist yet (run gbrain apply-migrations); nothing was pruned');+ return { deleted: 0, capped: false, skipped: 'no_rollup_table', pruned_through: null };+ }+ const batchSize = opts.batchSize ?? MCP_LOG_PRUNE_BATCH;+ const maxBatches = opts.maxBatches ?? MCP_LOG_PRUNE_MAX_BATCHES;+ const started = Date.now();+ const [{ cutoff }] = await engine.executeRaw<{ cutoff: unknown }>("SELECT now() - ($1::int * interval '1 day') AS cutoff", [days]);+ const cutoffIso = iso(cutoff);+ const audit = [...AUDIT_LOG_OPERATIONS];+ let deleted = 0;+ let newest: string | null = null;+ for (let batch = 0; batch < maxBatches; batch++) {+ const [row] = await engine.executeRaw<{ deleted: number; newest: unknown }>(PRUNE_BATCH_SQL, [cutoffIso, audit, batchSize]);+ const n = Number(row?.deleted ?? 0);+ deleted += n;+ const batchNewest = n > 0 && row?.newest ? iso(row.newest) : null;+ if (batchNewest !== null && (newest === null || batchNewest > newest)) newest = batchNewest;+ if (n < batchSize) return { deleted, capped: false, skipped: null, pruned_through: newest };+ if (opts.budgetMs !== undefined && Date.now() - started >= opts.budgetMs) break;+ if (opts.yieldBetweenBatches) await new Promise<void>((resolve) => setImmediate(resolve));+ }+ return { deleted, capped: true, skipped: null, pruned_through: newest };+}++export interface McpLogLastPrune { at: string; deleted: number; capped: boolean }++/** The last recorded run, or null (never ran, or an unreadable record). */+export async function readLastMcpLogPrune(engine: BrainEngine): Promise<McpLogLastPrune | null> {+ try {+ const parsed = JSON.parse((await engine.getConfig(MCP_LOG_LAST_PRUNE_KEY)) ?? 'null') as Partial<McpLogLastPrune> | null;+ if (!parsed || typeof parsed.at !== 'string' || Number.isNaN(Date.parse(parsed.at))) return null;+ return { at: parsed.at, deleted: Number(parsed.deleted) || 0, capped: parsed.capped === true };+ } catch { return null; }+}++/** One retention run: null when retention is off; records the run for doctor. Throws on a database error. */+export async function runMcpLogRetention(engine: BrainEngine, opts: McpLogPruneOpts = {}): Promise<McpLogPruneResult | null> {+ const days = await readMcpLogRetentionDays(engine);+ if (days === null) return null;+ const result = await pruneMcpRequestLog(engine, days, opts);+ if (!result.skipped) {+ await engine.setConfig(MCP_LOG_LAST_PRUNE_KEY, JSON.stringify({ at: new Date().toISOString(), deleted: result.deleted, capped: result.capped }));+ }+ return result;+}++/**+ * Lifetime requests and last use per token: the rows still in the log plus+ * the pruned tally, in one statement. Before the tally table exists, the log+ * alone (nothing was pruned).+ */+export async function lifetimeUsage(engine: BrainEngine, tokenNames: string[]): Promise<Map<string, { requests: number; last_used_at: string | null }>> {+ if (tokenNames.length === 0) return new Map();+ const kept = `SELECT token_name, count(*)::bigint AS n, max(created_at) AS newest FROM mcp_request_log WHERE token_name = ANY($1::text[]) GROUP BY token_name`;+ const rows = await engine.executeRaw<{ token_name: string; requests: string | number; last_used_at: unknown }>(+ (await rollupTablePresent(engine))+ ? `SELECT token_name, sum(n)::bigint AS requests, max(newest) AS last_used_at FROM (+ ${kept}+ UNION ALL+ SELECT token_name, requests, last_used_at FROM mcp_request_log_rollup WHERE token_name = ANY($1::text[])+ ) u GROUP BY token_name`+ : `SELECT token_name, n AS requests, newest AS last_used_at FROM (${kept}) k`,+ [tokenNames],+ );+ return new Map(rows.map((r) => [r.token_name, { requests: Number(r.requests), last_used_at: r.last_used_at ? iso(r.last_used_at) : null }]));+}++export interface McpLogPruneTickerOpts {+ tickMs?: number;+ budgetMs?: number;+ /** Owner veto for this tick (a delegated sync owns the event loop). */+ canRun?: () => boolean | Promise<boolean>;+ setInterval?: (fn: () => unknown, ms: number) => unknown;+ clearInterval?: (handle: unknown) => void;+ log?: (line: string) => void;+}++export interface McpLogPruneTicker {+ tick(): Promise<McpLogPruneResult | null>;+ stop(): void;+}++/**+ * The lock owner's resident prune: PGLite only (Postgres brains prune in the+ * cycle purge phase). One run in flight at a time; its own unref'd timer.+ */+export function startMcpLogPruneTicker(engine: BrainEngine, opts: McpLogPruneTickerOpts = {}): McpLogPruneTicker {+ let inflight: Promise<McpLogPruneResult | null> | null = null;+ let stopped = false;+ const tick = async (): Promise<McpLogPruneResult | null> => {+ if (stopped || inflight || engine.kind !== 'pglite') return null;+ try { if (opts.canRun && !(await opts.canRun())) return null; } catch { return null; }+ inflight = runMcpLogRetention(engine, { budgetMs: opts.budgetMs ?? MCP_LOG_PRUNE_RESIDENT_BUDGET_MS, yieldBetweenBatches: true })+ .then((result) => {+ if (result && result.deleted > 0) opts.log?.(`[mcp-request-log] pruned ${result.deleted} request-log row(s) past retention${result.capped ? ' (more remain; the next tick continues)' : ''}`);+ return result;+ })+ .catch((e: unknown) => { opts.log?.(`[mcp-request-log] prune failed: ${e instanceof Error ? e.message : String(e)}`); return null; })+ .finally(() => { inflight = null; });+ return inflight;+ };+ const set = opts.setInterval ?? ((fn: () => unknown, ms: number) => setInterval(fn, ms));+ const clear = opts.clearInterval ?? ((h: unknown) => clearInterval(h as ReturnType<typeof setInterval>));+ const handle = engine.kind === 'pglite' ? set(() => tick(), opts.tickMs ?? MCP_LOG_PRUNE_TICK_MS) : null;+ (handle as { unref?: () => void } | null)?.unref?.();+ return { tick, stop: () => { stopped = true; if (handle !== null) clear(handle); } };+}diff --git a/src/core/mcp-usage.ts b/src/core/mcp-usage.tsindex a526193a03..ad4d2cea8b 100644--- a/src/core/mcp-usage.ts+++ b/src/core/mcp-usage.ts@@ -2,7 +2,8 @@* mcp-usage.ts — the ONE shared reader over `mcp_request_log` (amendment 30).** Consumed by three surfaces that must never disagree on what counts as an- * "operation call":+ * "operation call" (each reads it through readClientOpUsageWithCoverage, so a+ * window that reaches back past pruned history says so):* - `gbrain auth clients --usage` (E4, src/commands/auth.ts)* - the advisor starter-fit collector (E3, src/core/advisor/collect-mcp-client-fit.ts)* - `scripts/derive-starter-ops.ts` (amendment 23 / D12)@@ -36,6 +37,13 @@* (`context_pack` / `delta`) is flagged `likely_automation` and excluded from* starter-set derivation + advisor fit findings. The threshold and op set are* exported so consumers cite one definition.+ *+ * Retention (src/core/mcp-request-log-retention.ts): an opt-in prune removes+ * rows past cycle.purge.mcp_request_log_retention_days (never fewer than 30+ * days, so the built-in 30-day windows stay complete) and never the+ * AUDIT_LOG_OPERATIONS rows. Coverage reads the newest pruned row+ * (mcp_request_log_rollup.pruned_through); a brain that never pruned reports+ * every window complete.*/import type { BrainEngine } from './engine.ts';@@ -43,16 +51,20 @@ import type { BrainEngine } from './engine.ts';/** Default trailing window for every usage-derived surface. */export const MCP_USAGE_DEFAULT_WINDOW_DAYS = 30;+/**+ * Operator audit rows that ride the request log and are never pruned: ENG-8+ * surface changes (src/core/surface-audit.ts) and GBRA-219 memory setting+ * changes (src/core/facts/writeback-settings.ts).+ */+export const AUDIT_LOG_OPERATIONS: ReadonlySet<string> = new Set(['surface_change', 'memory_setting_change']);+/** JSON-RPC method / server-plane rows that are not operation calls. */export const NON_OP_LOG_ROWS: ReadonlySet<string> = new Set(['tools/list','initialize','notifications/initialized','ping',- // ENG-8 surface-change audit rows (src/core/surface-audit.ts).- 'surface_change',- // GBRA-219 memory settings audit rows (src/core/facts/writeback-settings.ts).- 'memory_setting_change',+ ...AUDIT_LOG_OPERATIONS,]);/** Legacy bearer transport row prefix — 'tools/call:query' means op 'query'. */@@ -174,3 +186,44 @@ export async function readClientOpUsage(out.sort((a, b) => b.total_calls - a.total_calls || (a.token_name < b.token_name ? -1 : 1));return out;}++/** How much of a requested usage window the request log still holds in detail. */+export interface McpUsageCoverage {+ requested_days: number;+ /** Whole days back from now the log holds in full (requested_days when not truncated). */+ covered_days: number;+ truncated: boolean;+ /** ISO time of the newest pruned row; null on a brain that never pruned. */+ pruned_before: string | null;+}++const DAY_MS = 86_400_000;++/** Coverage of a trailing window. A brain without the tally table (before its migration) never pruned. */+export async function readMcpUsageCoverage(engine: BrainEngine, days: number): Promise<McpUsageCoverage> {+ const [probe] = await engine.executeRaw<{ present: boolean; now: unknown }>(+ "SELECT to_regclass('mcp_request_log_rollup') IS NOT NULL AS present, now() AS now");+ const [row] = probe?.present+ ? await engine.executeRaw<{ pruned_before: unknown }>('SELECT max(pruned_through) AS pruned_before FROM mcp_request_log_rollup')+ : [];+ if (!row?.pruned_before) return { requested_days: days, covered_days: days, truncated: false, pruned_before: null };+ const prunedBefore = toIso(row.pruned_before);+ const keptDays = Math.floor((Date.parse(toIso(probe!.now)) - Date.parse(prunedBefore)) / DAY_MS);+ const truncated = keptDays < days;+ return { requested_days: days, covered_days: truncated ? Math.max(1, keptDays) : days, truncated, pruned_before: prunedBefore };+}++/** readClientOpUsage plus the window's coverage, for every surface that shows a window to a person. */+export async function readClientOpUsageWithCoverage(+ engine: BrainEngine,+ opts: { days?: number } = {},+): Promise<{ clients: ClientOpUsage[]; coverage: McpUsageCoverage }> {+ const clients = await readClientOpUsage(engine, opts);+ return { clients, coverage: await readMcpUsageCoverage(engine, opts.days ?? MCP_USAGE_DEFAULT_WINDOW_DAYS) };+}++/** The one truncation sentence: what was pruned, the exact window that is complete, and that raising retention restores nothing. */+export function truncatedWindowNote(coverage: McpUsageCoverage): string {+ return `window truncated: details before ${coverage.pruned_before} were pruned, so the ${coverage.requested_days}-day window holds only the last ${coverage.covered_days} day(s) in full. ` ++ `For an exact report use --days ${coverage.covered_days}. Raising cycle.purge.mcp_request_log_retention_days cannot restore pruned detail.`;+}diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.tsindex d21c31504b..cdddc9a791 100644--- a/src/core/persistence/graduation-inventory.ts+++ b/src/core/persistence/graduation-inventory.ts@@ -97,6 +97,7 @@ export const GRADUATION_INVENTORY: Inventory = {carry('link_transitions', 'user_data', 'Dated start/end evidence for relationships, including manual add_link dates that exist nowhere else.'),carry('loop_suppressions', 'user_data', 'Open-loop mutes the user chose.'),carry('mcp_request_log', 'operational', 'MCP request log.'),+ carry('mcp_request_log_rollup', 'operational', 'Per-token tally of request-log rows the retention prune removed; the dashboard\'s lifetime totals and the usage windows\' pruned-before date read it.'),carry('mcp_spend_log', 'operational', 'MCP spend log.'),carry('mcp_spend_reservations', 'operational', 'Pending and unresolved MCP charges; admission counts them and late settlement needs them.'),carry('mention_gazetteer_entries', 'operational', 'Entity mention index: the linkable names the last mention pass used per source; a name change rescans only affected pages.'),diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex a8fdb37405..23b6b67130 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 296;+export const LATEST_SCHEMA_VERSION = 297;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 852ba0067c..20d5738f2e 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -297,6 +297,7 @@ import { v293 } from './v293-qm-attest-sources.ts';import { v294 } from './v294-refresh-barrier-import-deferral.ts';import { v295 } from './v295-refresh-retry-hint-history-index.ts';import { v296 } from './v296-ingest-applied-captures.ts';+import { v297 } from './v297-mcp-request-log-rollup.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -592,4 +593,5 @@ export const MIGRATIONS: Migration[] = [v294,v295,v296,+ v297,];diff --git a/src/core/schema-migrations/v297-mcp-request-log-rollup.ts b/src/core/schema-migrations/v297-mcp-request-log-rollup.tsnew file mode 100644index 0000000000..6eb215d88e--- /dev/null+++ b/src/core/schema-migrations/v297-mcp-request-log-rollup.ts@@ -0,0 +1,35 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// #6770 rewrite: mcp_request_log_rollup is the per-token tally of request-log+// rows the opt-in retention prune (src/core/mcp-request-log-retention.ts,+// cycle.purge.mcp_request_log_retention_days) removed: how many, the newest+// one's time (lifetime last-used) and pruned_through, the newest pruned row,+// which tells a usage window whether it reaches back past pruned detail. A row+// with a NULL token_name counts under ''. The prune deletes and tallies in one+// statement. This migration only creates the table: it copies no rows and+// deletes nothing, so retention stays off until an operator sets the key.+// Operational state, not brain content: a repo-less brain gets it unchanged.+// RLS is enabled here (v275's list is frozen). No schema.sql mirror: like+// v282-v296, it exists only through migrations. Provisional number:+// renumbered at the merge slot.+export const v297: Migration = {+ version: 297,+ name: 'mcp_request_log_rollup',+ idempotent: true,+ sql: `+CREATE TABLE IF NOT EXISTS mcp_request_log_rollup (+ token_name TEXT PRIMARY KEY,+ requests BIGINT NOT NULL DEFAULT 0,+ last_used_at TIMESTAMPTZ,+ pruned_through TIMESTAMPTZ+);+DO $rls$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles pr WHERE pg_has_role(current_user, pr.oid, 'USAGE') AND (pr.rolbypassrls OR pr.rolsuper)) THEN+ ALTER TABLE mcp_request_log_rollup ENABLE ROW LEVEL SECURITY;+ END IF;+END $rls$;+`,+};diff --git a/test/advisor-mcp-client-fit.test.ts b/test/advisor-mcp-client-fit.test.tsindex 7e21ced413..c5bb854373 100644--- a/test/advisor-mcp-client-fit.test.ts+++ b/test/advisor-mcp-client-fit.test.ts@@ -233,3 +233,23 @@ describe('nag snooze (escalate-then-suppress)', () => {}});});++describe('request-log retention: a truncated 90-day window', () => {+ for (const remote of [false, true]) {+ test(`remote=${remote}: no "unused" half when pruned history cuts into the window, and the finding says why`, async () => {+ await engine.executeRaw(+ `INSERT INTO mcp_request_log_rollup (token_name, requests, last_used_at, pruned_through)+ VALUES ('pruned-client', 50, now() - interval '10 days', now() - interval '10 days')`);+ try {+ const findings = await collectMcpClientFit.collect(ctx({ remote }));+ const drift = findings.find((f) => f.id === 'mcp_starter_ops_drift');+ expect(drift).toBeDefined();+ expect(drift!.detail).toContain(nonStarterOp);+ expect(drift!.detail).not.toContain('unused for 90d');+ expect(drift!.detail).toContain('pruned');+ } finally {+ await engine.executeRaw("DELETE FROM mcp_request_log_rollup WHERE token_name = 'pruned-client'");+ }+ });+ }+});diff --git a/test/doctor-mcp-request-log-retention.test.ts b/test/doctor-mcp-request-log-retention.test.tsnew file mode 100644index 0000000000..7e87d1036b--- /dev/null+++ b/test/doctor-mcp-request-log-retention.test.ts@@ -0,0 +1,121 @@+/**+ * mcp_request_log_retention doctor check (#6770 rewrite).+ *+ * Authoring gate: (1) protects what the operator is told about request-log+ * growth and retention: past the size threshold with retention off, a warn+ * whose fix turns retention on only after asking the user (the deletion+ * cannot be undone), never an automatic remediation step; with retention on,+ * the pruned-before date, the per-run cap state, and a warn when no prune ran+ * for 48 hours (a PGLite brain whose serve stopped, a cycle that never runs);+ * (2) fails when the fix becomes agent-runnable, when remediate picks it up,+ * or when a stalled prune reads as healthy; (3) the check is new; (4) the row+ * and byte thresholds are parameters so a test need not insert a million rows.+ *+ * Repo-less in-memory PGLite.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { mcpRequestLogRetentionEntry, mcpRequestLogRetentionResult } from '../src/commands/doctor/checks/mcp-request-log.ts';+import { finalizeCheckFixes } from '../src/commands/doctor/check-fix.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';+import { computeRemediationPlan } from '../src/core/remediation/plan.ts';+import { MCP_LOG_LAST_PRUNE_KEY, MCP_LOG_RETENTION_KEY, runMcpLogRetention } from '../src/core/mcp-request-log-retention.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 120_000);++afterAll(async () => { await engine.disconnect(); });++beforeEach(async () => {+ await engine.executeRaw('DELETE FROM mcp_request_log');+ await engine.executeRaw('DELETE FROM mcp_request_log_rollup');+ await engine.unsetConfig(MCP_LOG_RETENTION_KEY);+ await engine.unsetConfig(MCP_LOG_LAST_PRUNE_KEY);+});++async function seed(count: number, daysAgo: number): Promise<void> {+ await engine.executeRaw(+ `INSERT INTO mcp_request_log (token_name, operation, status, created_at)+ SELECT 'alice-client', 'query', 'success', now() - ($2::int * interval '1 day') - (g * interval '1 second') FROM generate_series(1, $1::int) g`,+ [count, daysAgo]);+}++const SMALL = { warnRows: 5, warnBytes: 2 ** 40 };++describe('mcp_request_log_retention', () => {+ test('registered, categorized as ops, and its entry runs on a connected engine', async () => {+ expect(categorizeCheck('mcp_request_log_retention')).toBe('ops');+ expect(mcpRequestLogRetentionEntry.emits).toContain('mcp_request_log_retention');+ const checks = await mcpRequestLogRetentionEntry.run({ engine } as unknown as DoctorContext);+ expect(Array.isArray(checks) && checks.map(c => c.name)).toEqual(['mcp_request_log_retention']);+ });++ test('retention off and a small log: information, nothing to do', async () => {+ await seed(2, 1);+ const check = await mcpRequestLogRetentionResult(engine, SMALL);+ expect(check).toMatchObject({ status: 'ok', severity: 'info', readiness_state: 'disabled_by_choice' });+ expect(check.details).toMatchObject({ retention_days: null, rows: 2 });+ });++ test('retention off past the threshold: warn, and the fix asks the user before any deletion', async () => {+ await seed(6, 1);+ const check = await mcpRequestLogRetentionResult(engine, SMALL);+ expect(check.status).toBe('warn');+ expect(check.message).toContain('6');+ const fix = check.fix as { argv: string[]; ask_user?: true; consent: string[]; user_message?: string };+ expect(fix.argv).toEqual(['gbrain', 'config', 'set', MCP_LOG_RETENTION_KEY, '90']);+ expect(fix.ask_user).toBe(true);+ expect(fix.consent).toContain('destructive');+ expect(fix.user_message).toContain('cannot be restored');+ const [rendered] = finalizeCheckFixes([{ name: 'mcp_request_log_retention', ...check }]);+ expect((rendered!.fix as { next: string }).next).toBe('ask_user');+ });++ test('doctor --remediate never runs it: the remediation plan names no retention step', async () => {+ await seed(6, 1);+ expect((await mcpRequestLogRetentionResult(engine, SMALL)).status).toBe('warn');+ const plan = await computeRemediationPlan(engine, { repairs: { noEmbed: true } });+ expect(JSON.stringify(plan)).not.toContain('mcp_request_log_retention');+ });++ test('retention on with a recent prune: ok, with the pruned-before date and the cap state', async () => {+ await seed(3, 60);+ await engine.setConfig(MCP_LOG_RETENTION_KEY, '30');+ await runMcpLogRetention(engine);+ const check = await mcpRequestLogRetentionResult(engine, SMALL);+ expect(check.status).toBe('ok');+ expect(check.details).toMatchObject({ retention_days: 30, last_prune: { deleted: 3, capped: false } });+ expect(Date.parse((check.details as { pruned_before: string }).pruned_before)).toBeLessThan(Date.now() - 59 * 86_400_000);+ });++ test('retention on but no prune for 48 hours: warn', async () => {+ await engine.setConfig(MCP_LOG_RETENTION_KEY, '30');+ await engine.setConfig(MCP_LOG_LAST_PRUNE_KEY, JSON.stringify({ at: new Date(Date.now() - 49 * 3_600_000).toISOString(), deleted: 0, capped: false }));+ const check = await mcpRequestLogRetentionResult(engine, SMALL);+ expect(check.status).toBe('warn');+ expect(check.message).toContain('48 hours');+ expect(check.fix).toBeDefined();+ });++ test('retention on and never pruned: warn only once rows past the window are waiting', async () => {+ await engine.setConfig(MCP_LOG_RETENTION_KEY, '30');+ await seed(2, 1);+ expect((await mcpRequestLogRetentionResult(engine, SMALL)).status).toBe('ok');+ await seed(2, 40);+ expect((await mcpRequestLogRetentionResult(engine, SMALL)).status).toBe('warn');+ });++ test('a run that hit the per-run cap reports that older rows are still waiting', async () => {+ await engine.setConfig(MCP_LOG_RETENTION_KEY, '30');+ await engine.setConfig(MCP_LOG_LAST_PRUNE_KEY, JSON.stringify({ at: new Date().toISOString(), deleted: 400_000, capped: true }));+ const check = await mcpRequestLogRetentionResult(engine, SMALL);+ expect(check.status).toBe('ok');+ expect(check.message).toContain('still waiting');+ });+});diff --git a/test/e2e/mcp-request-log-retention-postgres.test.ts b/test/e2e/mcp-request-log-retention-postgres.test.tsnew file mode 100644index 0000000000..2a5775ad68--- /dev/null+++ b/test/e2e/mcp-request-log-retention-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../mcp-request-log-retention.test.ts'));diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex fa40c9aaf8..502792b5eb 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -194,6 +194,7 @@"loop_suppressions.loop_suppressions_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","loop_suppressions.loop_suppressions_uniq": "u UNIQUE (source_id, kind, value)","mcp_request_log.mcp_request_log_pkey": "p PRIMARY KEY (id)",+ "mcp_request_log_rollup.mcp_request_log_rollup_pkey": "p PRIMARY KEY (token_name)","mcp_spend_log.mcp_spend_log_one_budget_owner": "c CHECK (((client_id IS NULL) OR (budget_key IS NULL)))","mcp_spend_log.mcp_spend_log_pkey": "p PRIMARY KEY (id)","mcp_spend_reservations.mcp_spend_reservations_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",@@ -841,6 +842,9 @@"mcp_request_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "mcp_request_log_rollup": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"mcp_spend_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1434,6 +1438,7 @@"loop_suppressions_pkey": "CREATE UNIQUE INDEX loop_suppressions_pkey ON public.loop_suppressions USING btree (id)","loop_suppressions_uniq": "CREATE UNIQUE INDEX loop_suppressions_uniq ON public.loop_suppressions USING btree (source_id, kind, value)","mcp_request_log_pkey": "CREATE UNIQUE INDEX mcp_request_log_pkey ON public.mcp_request_log USING btree (id)",+ "mcp_request_log_rollup_pkey": "CREATE UNIQUE INDEX mcp_request_log_rollup_pkey ON public.mcp_request_log_rollup USING btree (token_name)","mcp_spend_log_pkey": "CREATE UNIQUE INDEX mcp_spend_log_pkey ON public.mcp_spend_log USING btree (id)","mcp_spend_reservations_pkey": "CREATE UNIQUE INDEX mcp_spend_reservations_pkey ON public.mcp_spend_reservations USING btree (reservation_id)","mention_gazetteer_entries_pkey": "CREATE UNIQUE INDEX mention_gazetteer_entries_pkey ON public.mention_gazetteer_entries USING btree (source_id, name_norm, target_slug, case_sensitive)",@@ -2854,6 +2859,15 @@],"flags": "relkind=r rls=false force_rls=false"},+ "mcp_request_log_rollup": {+ "columns": [+ "1 token_name text/text NOT NULL",+ "2 requests bigint/int8 NOT NULL DEFAULT 0",+ "3 last_used_at timestamp with time zone/timestamptz NULL",+ "4 pruned_through timestamp with time zone/timestamptz NULL"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"mcp_spend_log": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('mcp_spend_log_id_seq'::regclass)",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex aa2c137aab..1fdda45e23 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -194,6 +194,7 @@"loop_suppressions.loop_suppressions_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","loop_suppressions.loop_suppressions_uniq": "u UNIQUE (source_id, kind, value)","mcp_request_log.mcp_request_log_pkey": "p PRIMARY KEY (id)",+ "mcp_request_log_rollup.mcp_request_log_rollup_pkey": "p PRIMARY KEY (token_name)","mcp_spend_log.mcp_spend_log_one_budget_owner": "c CHECK (((client_id IS NULL) OR (budget_key IS NULL)))","mcp_spend_log.mcp_spend_log_pkey": "p PRIMARY KEY (id)","mcp_spend_reservations.mcp_spend_reservations_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",@@ -841,6 +842,9 @@"mcp_request_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "mcp_request_log_rollup": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"mcp_spend_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1434,6 +1438,7 @@"loop_suppressions_pkey": "CREATE UNIQUE INDEX loop_suppressions_pkey ON public.loop_suppressions USING btree (id)","loop_suppressions_uniq": "CREATE UNIQUE INDEX loop_suppressions_uniq ON public.loop_suppressions USING btree (source_id, kind, value)","mcp_request_log_pkey": "CREATE UNIQUE INDEX mcp_request_log_pkey ON public.mcp_request_log USING btree (id)",+ "mcp_request_log_rollup_pkey": "CREATE UNIQUE INDEX mcp_request_log_rollup_pkey ON public.mcp_request_log_rollup USING btree (token_name)","mcp_spend_log_pkey": "CREATE UNIQUE INDEX mcp_spend_log_pkey ON public.mcp_spend_log USING btree (id)","mcp_spend_reservations_pkey": "CREATE UNIQUE INDEX mcp_spend_reservations_pkey ON public.mcp_spend_reservations USING btree (reservation_id)","mention_gazetteer_entries_pkey": "CREATE UNIQUE INDEX mention_gazetteer_entries_pkey ON public.mention_gazetteer_entries USING btree (source_id, name_norm, target_slug, case_sensitive)",@@ -2854,6 +2859,15 @@],"flags": "relkind=r rls=false force_rls=false"},+ "mcp_request_log_rollup": {+ "columns": [+ "1 token_name text/text NOT NULL",+ "2 requests bigint/int8 NOT NULL DEFAULT 0",+ "3 last_used_at timestamp with time zone/timestamptz NULL",+ "4 pruned_through timestamp with time zone/timestamptz NULL"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"mcp_spend_log": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('mcp_spend_log_id_seq'::regclass)",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex 22ea6da123..9275f45b33 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -194,6 +194,7 @@"loop_suppressions.loop_suppressions_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","loop_suppressions.loop_suppressions_uniq": "u UNIQUE (source_id, kind, value)","mcp_request_log.mcp_request_log_pkey": "p PRIMARY KEY (id)",+ "mcp_request_log_rollup.mcp_request_log_rollup_pkey": "p PRIMARY KEY (token_name)","mcp_spend_log.mcp_spend_log_one_budget_owner": "c CHECK (((client_id IS NULL) OR (budget_key IS NULL)))","mcp_spend_log.mcp_spend_log_pkey": "p PRIMARY KEY (id)","mcp_spend_reservations.mcp_spend_reservations_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",@@ -841,6 +842,9 @@"mcp_request_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "mcp_request_log_rollup": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"mcp_spend_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1430,6 +1434,7 @@"loop_suppressions_pkey": "CREATE UNIQUE INDEX loop_suppressions_pkey ON public.loop_suppressions USING btree (id)","loop_suppressions_uniq": "CREATE UNIQUE INDEX loop_suppressions_uniq ON public.loop_suppressions USING btree (source_id, kind, value)","mcp_request_log_pkey": "CREATE UNIQUE INDEX mcp_request_log_pkey ON public.mcp_request_log USING btree (id)",+ "mcp_request_log_rollup_pkey": "CREATE UNIQUE INDEX mcp_request_log_rollup_pkey ON public.mcp_request_log_rollup USING btree (token_name)","mcp_spend_log_pkey": "CREATE UNIQUE INDEX mcp_spend_log_pkey ON public.mcp_spend_log USING btree (id)","mcp_spend_reservations_pkey": "CREATE UNIQUE INDEX mcp_spend_reservations_pkey ON public.mcp_spend_reservations USING btree (reservation_id)","mention_gazetteer_entries_pkey": "CREATE UNIQUE INDEX mention_gazetteer_entries_pkey ON public.mention_gazetteer_entries USING btree (source_id, name_norm, target_slug, case_sensitive)",@@ -2850,6 +2855,15 @@],"flags": "relkind=r rls=false force_rls=false"},+ "mcp_request_log_rollup": {+ "columns": [+ "1 token_name text/text NOT NULL",+ "2 requests bigint/int8 NOT NULL DEFAULT 0",+ "3 last_used_at timestamp with time zone/timestamptz NULL",+ "4 pruned_through timestamp with time zone/timestamptz NULL"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"mcp_spend_log": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('mcp_spend_log_id_seq'::regclass)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 8f965096b2..2d5b701842 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -197,6 +197,7 @@"loop_suppressions.loop_suppressions_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","loop_suppressions.loop_suppressions_uniq": "u UNIQUE (source_id, kind, value)","mcp_request_log.mcp_request_log_pkey": "p PRIMARY KEY (id)",+ "mcp_request_log_rollup.mcp_request_log_rollup_pkey": "p PRIMARY KEY (token_name)","mcp_spend_log.mcp_spend_log_one_budget_owner": "c CHECK (((client_id IS NULL) OR (budget_key IS NULL)))","mcp_spend_log.mcp_spend_log_pkey": "p PRIMARY KEY (id)","mcp_spend_reservations.mcp_spend_reservations_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",@@ -848,6 +849,9 @@"mcp_request_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "mcp_request_log_rollup": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"mcp_spend_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1437,6 +1441,7 @@"loop_suppressions_pkey": "CREATE UNIQUE INDEX loop_suppressions_pkey ON public.loop_suppressions USING btree (id)","loop_suppressions_uniq": "CREATE UNIQUE INDEX loop_suppressions_uniq ON public.loop_suppressions USING btree (source_id, kind, value)","mcp_request_log_pkey": "CREATE UNIQUE INDEX mcp_request_log_pkey ON public.mcp_request_log USING btree (id)",+ "mcp_request_log_rollup_pkey": "CREATE UNIQUE INDEX mcp_request_log_rollup_pkey ON public.mcp_request_log_rollup USING btree (token_name)","mcp_spend_log_pkey": "CREATE UNIQUE INDEX mcp_spend_log_pkey ON public.mcp_spend_log USING btree (id)","mcp_spend_reservations_pkey": "CREATE UNIQUE INDEX mcp_spend_reservations_pkey ON public.mcp_spend_reservations USING btree (reservation_id)","mention_gazetteer_entries_pkey": "CREATE UNIQUE INDEX mention_gazetteer_entries_pkey ON public.mention_gazetteer_entries USING btree (source_id, name_norm, target_slug, case_sensitive)",@@ -2866,6 +2871,15 @@],"flags": "relkind=r rls=true force_rls=false"},+ "mcp_request_log_rollup": {+ "columns": [+ "1 token_name text/text NOT NULL",+ "2 requests bigint/int8 NOT NULL DEFAULT 0",+ "3 last_used_at timestamp with time zone/timestamptz NULL",+ "4 pruned_through timestamp with time zone/timestamptz NULL"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"mcp_spend_log": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('mcp_spend_log_id_seq'::regclass)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 1015bc6397..a5baa13aa9 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -197,6 +197,7 @@"loop_suppressions.loop_suppressions_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","loop_suppressions.loop_suppressions_uniq": "u UNIQUE (source_id, kind, value)","mcp_request_log.mcp_request_log_pkey": "p PRIMARY KEY (id)",+ "mcp_request_log_rollup.mcp_request_log_rollup_pkey": "p PRIMARY KEY (token_name)","mcp_spend_log.mcp_spend_log_one_budget_owner": "c CHECK (((client_id IS NULL) OR (budget_key IS NULL)))","mcp_spend_log.mcp_spend_log_pkey": "p PRIMARY KEY (id)","mcp_spend_reservations.mcp_spend_reservations_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",@@ -848,6 +849,9 @@"mcp_request_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "mcp_request_log_rollup": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"mcp_spend_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1437,6 +1441,7 @@"loop_suppressions_pkey": "CREATE UNIQUE INDEX loop_suppressions_pkey ON public.loop_suppressions USING btree (id)","loop_suppressions_uniq": "CREATE UNIQUE INDEX loop_suppressions_uniq ON public.loop_suppressions USING btree (source_id, kind, value)","mcp_request_log_pkey": "CREATE UNIQUE INDEX mcp_request_log_pkey ON public.mcp_request_log USING btree (id)",+ "mcp_request_log_rollup_pkey": "CREATE UNIQUE INDEX mcp_request_log_rollup_pkey ON public.mcp_request_log_rollup USING btree (token_name)","mcp_spend_log_pkey": "CREATE UNIQUE INDEX mcp_spend_log_pkey ON public.mcp_spend_log USING btree (id)","mcp_spend_reservations_pkey": "CREATE UNIQUE INDEX mcp_spend_reservations_pkey ON public.mcp_spend_reservations USING btree (reservation_id)","mention_gazetteer_entries_pkey": "CREATE UNIQUE INDEX mention_gazetteer_entries_pkey ON public.mention_gazetteer_entries USING btree (source_id, name_norm, target_slug, case_sensitive)",@@ -2866,6 +2871,15 @@],"flags": "relkind=r rls=true force_rls=false"},+ "mcp_request_log_rollup": {+ "columns": [+ "1 token_name text/text NOT NULL",+ "2 requests bigint/int8 NOT NULL DEFAULT 0",+ "3 last_used_at timestamp with time zone/timestamptz NULL",+ "4 pruned_through timestamp with time zone/timestamptz NULL"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"mcp_spend_log": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('mcp_spend_log_id_seq'::regclass)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex bfd82d703f..24191cff53 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -197,6 +197,7 @@"loop_suppressions.loop_suppressions_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","loop_suppressions.loop_suppressions_uniq": "u UNIQUE (source_id, kind, value)","mcp_request_log.mcp_request_log_pkey": "p PRIMARY KEY (id)",+ "mcp_request_log_rollup.mcp_request_log_rollup_pkey": "p PRIMARY KEY (token_name)","mcp_spend_log.mcp_spend_log_one_budget_owner": "c CHECK (((client_id IS NULL) OR (budget_key IS NULL)))","mcp_spend_log.mcp_spend_log_pkey": "p PRIMARY KEY (id)","mcp_spend_reservations.mcp_spend_reservations_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",@@ -848,6 +849,9 @@"mcp_request_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "mcp_request_log_rollup": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"mcp_spend_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1433,6 +1437,7 @@"loop_suppressions_pkey": "CREATE UNIQUE INDEX loop_suppressions_pkey ON public.loop_suppressions USING btree (id)","loop_suppressions_uniq": "CREATE UNIQUE INDEX loop_suppressions_uniq ON public.loop_suppressions USING btree (source_id, kind, value)","mcp_request_log_pkey": "CREATE UNIQUE INDEX mcp_request_log_pkey ON public.mcp_request_log USING btree (id)",+ "mcp_request_log_rollup_pkey": "CREATE UNIQUE INDEX mcp_request_log_rollup_pkey ON public.mcp_request_log_rollup USING btree (token_name)","mcp_spend_log_pkey": "CREATE UNIQUE INDEX mcp_spend_log_pkey ON public.mcp_spend_log USING btree (id)","mcp_spend_reservations_pkey": "CREATE UNIQUE INDEX mcp_spend_reservations_pkey ON public.mcp_spend_reservations USING btree (reservation_id)","mention_gazetteer_entries_pkey": "CREATE UNIQUE INDEX mention_gazetteer_entries_pkey ON public.mention_gazetteer_entries USING btree (source_id, name_norm, target_slug, case_sensitive)",@@ -2862,6 +2867,15 @@],"flags": "relkind=r rls=true force_rls=false"},+ "mcp_request_log_rollup": {+ "columns": [+ "1 token_name text/text NOT NULL",+ "2 requests bigint/int8 NOT NULL DEFAULT 0",+ "3 last_used_at timestamp with time zone/timestamptz NULL",+ "4 pruned_through timestamp with time zone/timestamptz NULL"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"mcp_spend_log": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('mcp_spend_log_id_seq'::regclass)",diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 5dc7b9d4bb..02cadb75e6 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -1068,7 +1068,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "All 175 table(s) the applied migrations create exist.",+ "message": "All 176 table(s) the applied migrations create exist.","name": "schema_missing_tables","status": "ok"},@@ -3609,6 +3609,54 @@"name": "fence_integrity","status": "ok"},+ {+ "category": "ops",+ "details": {+ "bytes": 32768,+ "docs": "docs/mcp/ADMIN.md#request-log-retention",+ "retention_days": null,+ "rows": 0,+ "rows_exact": true+ },+ "elapsed_ms": "<volatile>",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "config",+ "set",+ "cycle.purge.mcp_request_log_retention_days",+ "90",+ "--brain",+ "host"+ ],+ "command": "gbrain config set cycle.purge.mcp_request_log_retention_days 90 --brain host",+ "consent": [+ "destructive"+ ],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/mcp/ADMIN.md#request-log-retention",+ "next": "ask_user",+ "requires_exclusive": false,+ "user_message": "Your MCP request log holds 0 row(s) (0.0 MB) and nothing prunes it. Turn on 90-day retention? Request details older than 90 days (operation, status, parameters, errors) will be deleted and cannot be restored; per-client totals and audit rows are kept.",+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "mcp_request_log_retention",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Turns on the request-log prune: the next cycle purge phase (or, on a PGLite brain, a live serve within the hour) deletes request rows older than 90 days. Per-client lifetime totals and the surface/memory-setting audit rows are kept."+ },+ "message": "The MCP request log holds 0 row(s) (0.0 MB); request-log retention is off, so it keeps every request.",+ "name": "mcp_request_log_retention",+ "readiness_state": "disabled_by_choice",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex fe956f3135..41f730b9d5 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1115,7 +1115,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "All 175 table(s) the applied migrations create exist.",+ "message": "All 176 table(s) the applied migrations create exist.","name": "schema_missing_tables","status": "ok"},@@ -3654,6 +3654,54 @@"name": "fence_integrity","status": "ok"},+ {+ "category": "ops",+ "details": {+ "bytes": 32768,+ "docs": "docs/mcp/ADMIN.md#request-log-retention",+ "retention_days": null,+ "rows": 0,+ "rows_exact": true+ },+ "elapsed_ms": "<volatile>",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "config",+ "set",+ "cycle.purge.mcp_request_log_retention_days",+ "90",+ "--brain",+ "host"+ ],+ "command": "gbrain config set cycle.purge.mcp_request_log_retention_days 90 --brain host",+ "consent": [+ "destructive"+ ],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/mcp/ADMIN.md#request-log-retention",+ "next": "ask_user",+ "requires_exclusive": false,+ "user_message": "Your MCP request log holds 0 row(s) (0.0 MB) and nothing prunes it. Turn on 90-day retention? Request details older than 90 days (operation, status, parameters, errors) will be deleted and cannot be restored; per-client totals and audit rows are kept.",+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "mcp_request_log_retention",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Turns on the request-log prune: the next cycle purge phase (or, on a PGLite brain, a live serve within the hour) deletes request rows older than 90 days. Per-client lifetime totals and the surface/memory-setting audit rows are kept."+ },+ "message": "The MCP request log holds 0 row(s) (0.0 MB); request-log retention is off, so it keeps every request.",+ "name": "mcp_request_log_retention",+ "readiness_state": "disabled_by_choice",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 4c4b47af54..4283788654 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -1083,7 +1083,7 @@{"category": "ops","elapsed_ms": "<volatile>",- "message": "RLS enabled on 174/174 public tables",+ "message": "RLS enabled on 175/175 public tables","name": "rls","status": "ok"},@@ -1111,7 +1111,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "All 174 table(s) the applied migrations create exist.",+ "message": "All 175 table(s) the applied migrations create exist.","name": "schema_missing_tables","status": "ok"},@@ -3657,6 +3657,54 @@"name": "fence_integrity","status": "ok"},+ {+ "category": "ops",+ "details": {+ "bytes": 32768,+ "docs": "docs/mcp/ADMIN.md#request-log-retention",+ "retention_days": null,+ "rows": 0,+ "rows_exact": false+ },+ "elapsed_ms": "<volatile>",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "config",+ "set",+ "cycle.purge.mcp_request_log_retention_days",+ "90",+ "--brain",+ "host"+ ],+ "command": "gbrain config set cycle.purge.mcp_request_log_retention_days 90 --brain host",+ "consent": [+ "destructive"+ ],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/mcp/ADMIN.md#request-log-retention",+ "next": "ask_user",+ "requires_exclusive": false,+ "user_message": "Your MCP request log holds ~0 row(s) (0.0 MB) and nothing prunes it. Turn on 90-day retention? Request details older than 90 days (operation, status, parameters, errors) will be deleted and cannot be restored; per-client totals and audit rows are kept.",+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "mcp_request_log_retention",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Turns on the request-log prune: the next cycle purge phase (or, on a PGLite brain, a live serve within the hour) deletes request rows older than 90 days. Per-client lifetime totals and the surface/memory-setting audit rows are kept."+ },+ "message": "The MCP request log holds ~0 row(s) (0.0 MB); request-log retention is off, so it keeps every request.",+ "name": "mcp_request_log_retention",+ "readiness_state": "disabled_by_choice",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 51e19e3824..cf31c23daf 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -1097,6 +1097,10 @@"category": "brain","name": "fence_integrity"},+ {+ "category": "ops",+ "name": "mcp_request_log_retention"+ },{"category": "ops","name": "search_mode"diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 5f3094c3a8..f8876d901d 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 291,+ "count": 292,"gaps": [17,18,@@ -97,7 +97,7 @@"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67","withSchemaLockTimeout": "95605bd3004955e11e936c7a4aa6889319b401098abf9db18ef3e48da2c3fc59"},- "latest": 296,+ "latest": 297,"records": [{"handler": {@@ -4826,6 +4826,19 @@"transaction": "absent","verify": "absent","version": 296+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "mcp_request_log_rollup",+ "sql": {+ "length": 415,+ "sha256": "fbbd86c93e5131171c0749954ad969cd518b0d08f0acd45743360f2dfd5b1210"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 297}],"versions": [@@ -5119,7 +5132,8 @@293,294,295,- 296+ 296,+ 297]},"normalizer": "migrations-record-v1"diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex 10bacf4139..81682e2da4 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -194,6 +194,7 @@"loop_suppressions.loop_suppressions_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","loop_suppressions.loop_suppressions_uniq": "u UNIQUE (source_id, kind, value)","mcp_request_log.mcp_request_log_pkey": "p PRIMARY KEY (id)",+ "mcp_request_log_rollup.mcp_request_log_rollup_pkey": "p PRIMARY KEY (token_name)","mcp_spend_log.mcp_spend_log_one_budget_owner": "c CHECK (((client_id IS NULL) OR (budget_key IS NULL)))","mcp_spend_log.mcp_spend_log_pkey": "p PRIMARY KEY (id)","mcp_spend_reservations.mcp_spend_reservations_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",@@ -841,6 +842,9 @@"mcp_request_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "mcp_request_log_rollup": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"mcp_spend_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1434,6 +1438,7 @@"loop_suppressions_pkey": "CREATE UNIQUE INDEX loop_suppressions_pkey ON public.loop_suppressions USING btree (id)","loop_suppressions_uniq": "CREATE UNIQUE INDEX loop_suppressions_uniq ON public.loop_suppressions USING btree (source_id, kind, value)","mcp_request_log_pkey": "CREATE UNIQUE INDEX mcp_request_log_pkey ON public.mcp_request_log USING btree (id)",+ "mcp_request_log_rollup_pkey": "CREATE UNIQUE INDEX mcp_request_log_rollup_pkey ON public.mcp_request_log_rollup USING btree (token_name)","mcp_spend_log_pkey": "CREATE UNIQUE INDEX mcp_spend_log_pkey ON public.mcp_spend_log USING btree (id)","mcp_spend_reservations_pkey": "CREATE UNIQUE INDEX mcp_spend_reservations_pkey ON public.mcp_spend_reservations USING btree (reservation_id)","mention_gazetteer_entries_pkey": "CREATE UNIQUE INDEX mention_gazetteer_entries_pkey ON public.mention_gazetteer_entries USING btree (source_id, name_norm, target_slug, case_sensitive)",@@ -2854,6 +2859,15 @@],"flags": "relkind=r rls=false force_rls=false"},+ "mcp_request_log_rollup": {+ "columns": [+ "1 token_name text/text NOT NULL",+ "2 requests bigint/int8 NOT NULL DEFAULT 0",+ "3 last_used_at timestamp with time zone/timestamptz NULL",+ "4 pruned_through timestamp with time zone/timestamptz NULL"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"mcp_spend_log": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('mcp_spend_log_id_seq'::regclass)",diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.tsindex c1cf3cf422..98d5318eff 100644--- a/test/graduation-inventory.test.ts+++ b/test/graduation-inventory.test.ts@@ -60,7 +60,7 @@ describe('graduation inventory', () => {expect(new Set(names).size).toBe(names.length);const counts: Record<string, number> = {};for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;- expect(counts).toEqual({ carry: 159, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });+ expect(counts).toEqual({ carry: 160, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });for (const e of GRADUATION_INVENTORY.entries) {expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres }).toEqual({ relation: e.relation, reason: true, present: true });diff --git a/test/mcp-request-log-retention-cli.serial.test.ts b/test/mcp-request-log-retention-cli.serial.test.tsnew file mode 100644index 0000000000..beec4f829c--- /dev/null+++ b/test/mcp-request-log-retention-cli.serial.test.ts@@ -0,0 +1,102 @@+/**+ * Truncated usage windows after a request-log prune (#6770 rewrite), through+ * the real CLI and script entry points.+ *+ * Authoring gate: (1) protects what an operator reads when a usage window+ * reaches back past pruned history: `gbrain auth clients --usage` prints the+ * truncation with the exact `--days` that is complete and the recovery note,+ * its `--json` carries the same facts in keys only (stdout stays one JSON+ * document), and `scripts/derive-starter-ops.ts` refuses on stderr with a+ * non-zero exit instead of deriving the starter surface from partial data;+ * (2) fails when a truncated window reads as complete; (3) no test spawned+ * either entry point before; (4) no production seam.+ *+ * Repo-less: a disk PGLite brain with no git checkout, reached through+ * GBRAIN_HOME's config.json.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { createEngine } from '../src/core/engine-factory.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';++const ROOT = resolve(import.meta.dir, '..');+let root: string, home: string, db: string;++function env(): Record<string, string> {+ const out: Record<string, string> = {};+ for (const [key, value] of Object.entries(process.env)) if (value !== undefined) out[key] = value;+ for (const key of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_BRAIN_ID', 'GBRAIN_SOURCE', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'VOYAGE_API_KEY']) delete out[key];+ return { ...out, HOME: home, GBRAIN_HOME: home, GBRAIN_SELF_UPGRADE_MODE: 'off', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SWEEP: '0' };+}++async function run(argv: string[]) {+ const proc = Bun.spawn(['bun', 'run', ...argv], { cwd: root, env: env(), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);+ return { stdout, stderr, exitCode };+}+const cli = (args: string[]) => run([join(ROOT, 'src', 'cli.ts'), ...args]);+const derive = (args: string[]) => run([join(ROOT, 'scripts', 'derive-starter-ops.ts'), ...args]);++beforeAll(async () => {+ root = mkdtempSync(join(tmpdir(), 'gb-mcp-log-retention-'));+ home = join(root, 'home');+ db = join(root, 'db');+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: db }));+ const config = { engine: 'pglite' as const, database_path: db };+ const engine = await createEngine(config);+ await engine.connect(config);+ try {+ await engine.initSchema();+ await engine.executeRaw("INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read) VALUES ('alice-client', 'alice-client', 'read', 'default', ARRAY['default'])");+ await engine.executeRaw(+ `INSERT INTO mcp_request_log (token_name, agent_name, operation, latency_ms, status, created_at)+ SELECT 'alice-client', 'alice-client', 'query', 5, 'success', now() - (g * interval '1 hour') FROM generate_series(1, 12) g`);+ // A prune already ran: the newest pruned row is 40 days old.+ await engine.executeRaw(+ `INSERT INTO mcp_request_log_rollup (token_name, requests, last_used_at, pruned_through)+ VALUES ('alice-client', 30, now() - interval '40 days', now() - interval '40 days')`);+ } finally { await disposePersistenceConsumer(engine); await engine.disconnect(); }+}, 120_000);++afterAll(() => { rmSync(root, { recursive: true, force: true }); });++describe('usage windows that reach past pruned history (repo-less PGLite)', () => {+ test('auth clients --usage --days 365 --json carries the truncation in JSON keys only', async () => {+ const r = await cli(['auth', 'clients', '--usage', '--days', '365', '--json']);+ expect(r.exitCode).toBe(0);+ const doc = JSON.parse(r.stdout);+ expect(doc).toMatchObject({ window_days: 365, window_truncated: true, covered_days: 40 });+ expect(Date.parse(doc.pruned_before)).toBeLessThan(Date.now() - 39 * 86_400_000);+ expect(doc.window_note).toContain('--days 40');+ expect(doc.window_note).toContain('cannot restore');+ expect(r.stderr).not.toContain('window truncated');+ }, 60_000);++ test('auth clients --usage --days 365 prints the truncation with the fix and the recovery note', async () => {+ const r = await cli(['auth', 'clients', '--usage', '--days', '365']);+ expect(r.exitCode).toBe(0);+ expect(r.stdout).toContain('window truncated: details before');+ expect(r.stdout).toContain('--days 40');+ expect(r.stdout).toContain('cannot restore');+ }, 60_000);++ test('a window inside the kept history is complete', async () => {+ const r = await cli(['auth', 'clients', '--usage', '--days', '30', '--json']);+ expect(r.exitCode).toBe(0);+ expect(JSON.parse(r.stdout)).toMatchObject({ window_truncated: false, covered_days: 30, pruned_before: expect.any(String) });+ }, 60_000);++ test('derive-starter-ops refuses a truncated window on stderr with a non-zero exit', async () => {+ const refused = await derive(['--days', '365']);+ expect(refused.exitCode).not.toBe(0);+ expect(refused.stderr).toContain('window truncated');+ expect(refused.stderr).toContain('--days 40');+ expect(refused.stderr).toContain('cannot restore');+ expect(refused.stdout).not.toContain('Proposed block');+ const ok = await derive(['--days', '30']);+ expect(ok.exitCode).toBe(0);+ }, 120_000);+});diff --git a/test/mcp-request-log-retention.test.ts b/test/mcp-request-log-retention.test.tsnew file mode 100644index 0000000000..ed6eab5ff4--- /dev/null+++ b/test/mcp-request-log-retention.test.ts@@ -0,0 +1,290 @@+/**+ * Request-log retention (#6770 rewrite): `cycle.purge.mcp_request_log_retention_days`+ * prunes `mcp_request_log` rows past the window into the per-token tally+ * `mcp_request_log_rollup`, in the same statement that deletes them.+ *+ * Authoring gate: (1) protects the opt-in deletion contract (off by default,+ * 30-day minimum, audit rows never pruned, lifetime totals exact, a failed+ * tally deletes nothing, a capped run resumes and never overstates how far it+ * pruned) and the two places it runs (the cycle purge phase, and the PGLite+ * lock owner's resident ticker under a live `serve --http`); (2) fails when a+ * prune drops rows without counting them, touches an audit row or a row inside+ * the window, or runs with retention unset; (3) nothing pruned this table+ * before; (4) the prune takes batch-size and cap options that production+ * leaves at their defaults.+ *+ * Repo-less: every brain here is a database with no git checkout, the default+ * keyless install. PGLite always; PostgreSQL too when DATABASE_URL is set+ * (test/e2e/mcp-request-log-retention-postgres.test.ts), which adds the+ * two-prunes-at-once case.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runCycle } from '../src/core/cycle.ts';+import { runConfig } from '../src/commands/config.ts';+import { runServe } from '../src/commands/serve.ts';+import {+ MCP_LOG_RETENTION_KEY,+ lifetimeUsage,+ mcpLogRetentionRefusal,+ pruneMcpRequestLog,+ readLastMcpLogPrune,+ readMcpLogRetentionDays,+ runMcpLogRetention,+ startMcpLogPruneTicker,+} from '../src/core/mcp-request-log-retention.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++async function seed(engine: BrainEngine, token: string | null, operation: string, count: number, daysAgo: number, status = 'success'): Promise<void> {+ for (let i = 0; i < count; i++) {+ await engine.executeRaw(+ `INSERT INTO mcp_request_log (token_name, agent_name, operation, latency_ms, status, created_at)+ VALUES ($1, $1, $2, 5, $3, now() - ($4::float8 * interval '1 day') - ($5::int * interval '1 second'))`,+ [token, operation, status, daysAgo, i],+ );+ }+}++async function logCount(engine: BrainEngine, where = 'TRUE'): Promise<number> {+ const [row] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM mcp_request_log WHERE ${where}`);+ return row!.n;+}++async function rollup(engine: BrainEngine): Promise<Map<string, { requests: number; last_used_at: string | null; pruned_through: string | null }>> {+ const rows = await engine.executeRaw<{ token_name: string; requests: string | number; last_used_at: unknown; pruned_through: unknown }>(+ 'SELECT token_name, requests, last_used_at, pruned_through FROM mcp_request_log_rollup');+ const iso = (v: unknown) => (v === null ? null : new Date(v as string).toISOString());+ return new Map(rows.map(r => [r.token_name, { requests: Number(r.requests), last_used_at: iso(r.last_used_at), pruned_through: iso(r.pruned_through) }]));+}++async function purgeDetails(engine: BrainEngine): Promise<Record<string, unknown>> {+ const report = await runCycle(engine, { brainDir: mkdtempSync(join(tmpdir(), 'gb-mcp-log-cycle-')), phases: ['purge'] });+ const phase = report.phases.find(p => p.phase === 'purge')!;+ expect(phase.status).not.toBe('fail');+ return phase.details;+}++for (const kind of testBackends()) {+ describe(`request-log retention (${kind}, repo-less)`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ beforeAll(async () => {+ if (kind === 'postgres') {+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ } else {+ const pglite = new PGLiteEngine();+ await pglite.connect({});+ await pglite.initSchema();+ engine = pglite;+ close = () => pglite.disconnect();+ }+ }, 120_000);+ afterAll(async () => { await close?.(); });+ beforeEach(async () => {+ await engine.executeRaw('DELETE FROM mcp_request_log');+ await engine.executeRaw('DELETE FROM mcp_request_log_rollup');+ await engine.unsetConfig(MCP_LOG_RETENTION_KEY);+ });++ test('retention is off by default: the cycle purge deletes nothing and reports nothing', async () => {+ await seed(engine, 'alice-client', 'query', 5, 400);+ expect(await readMcpLogRetentionDays(engine)).toBeNull();+ const details = await purgeDetails(engine);+ expect(details.purged_mcp_request_log_count).toBeUndefined();+ expect(await logCount(engine)).toBe(5);+ expect((await rollup(engine)).size).toBe(0);+ expect(await runMcpLogRetention(engine)).toBeNull();+ }, 60_000);++ test('retention 30: the cycle purge moves every row class past the window into the tally and lifetime totals stay exact', async () => {+ // Every row class the dashboard's total_requests counts today.+ await seed(engine, 'alice-client', 'query', 3, 40);+ await seed(engine, 'alice-client', 'tools/list', 2, 41);+ await seed(engine, 'alice-client', 'advisor', 1, 42, 'denied_after_list');+ await seed(engine, 'alice-client', 'search', 1, 43, 'error');+ await seed(engine, 'alice-client', 'webhook_ingest', 1, 44);+ await seed(engine, 'alice-client', 'tools/call:search', 1, 45);+ await seed(engine, 'alice-client', 'query', 2, 5);+ await seed(engine, null, 'tools/list', 2, 50);+ await seed(engine, 'acme-client', 'query', 1, 10);+ const before = new Map((await engine.executeRaw<{ token_name: string; n: number; last: unknown }>(+ `SELECT token_name, count(*)::int AS n, max(created_at) AS last FROM mcp_request_log WHERE token_name IS NOT NULL GROUP BY token_name`))+ .map(r => [r.token_name, { requests: r.n, last_used_at: new Date(r.last as string).toISOString() }]));++ await engine.setConfig(MCP_LOG_RETENTION_KEY, '30');+ const details = await purgeDetails(engine);+ expect(details.purged_mcp_request_log_count).toBe(11);+ expect(await logCount(engine)).toBe(3);+ expect(await logCount(engine, "created_at < now() - interval '30 days'")).toBe(0);++ const after = await lifetimeUsage(engine, ['alice-client', 'acme-client']);+ expect(after.get('alice-client')).toEqual(before.get('alice-client'));+ expect(after.get('acme-client')).toEqual(before.get('acme-client'));+ const tally = await rollup(engine);+ expect(tally.get('alice-client')?.requests).toBe(9);+ // A NULL token_name counts under '' so the pruned-before date is never lost.+ expect(tally.get('')?.requests).toBe(2);+ expect(tally.has('acme-client')).toBe(false);++ const last = await readLastMcpLogPrune(engine);+ expect(last).toMatchObject({ deleted: 11, capped: false });+ expect(Date.now() - Date.parse(last!.at)).toBeLessThan(60_000);+ }, 60_000);++ test('surface_change and memory_setting_change audit rows survive past the window', async () => {+ await seed(engine, 'alice-client', 'surface_change', 2, 400);+ await seed(engine, 'alice-client', 'memory_setting_change', 1, 400);+ await seed(engine, 'alice-client', 'query', 4, 400);+ await engine.setConfig(MCP_LOG_RETENTION_KEY, '30');+ expect((await runMcpLogRetention(engine))?.deleted).toBe(4);+ expect(await logCount(engine, "operation IN ('surface_change', 'memory_setting_change')")).toBe(3);+ expect(await logCount(engine)).toBe(3);+ }, 60_000);++ test('a capped run leaves the rest for the next run, and pruned_through never passes the oldest surviving row', async () => {+ await seed(engine, 'alice-client', 'query', 10, 60);+ const first = await pruneMcpRequestLog(engine, 30, { batchSize: 3, maxBatches: 2 });+ expect(first).toMatchObject({ deleted: 6, capped: true, skipped: null });+ const [oldest] = await engine.executeRaw<{ at: unknown }>('SELECT min(created_at) AS at FROM mcp_request_log');+ const through = (await rollup(engine)).get('alice-client')!.pruned_through!;+ expect(Date.parse(through)).toBeLessThanOrEqual(new Date(oldest!.at as string).getTime());+ expect(first.pruned_through).toBe(through);+ const second = await pruneMcpRequestLog(engine, 30);+ expect(second).toMatchObject({ deleted: 4, capped: false });+ expect(await logCount(engine)).toBe(0);+ expect((await rollup(engine)).get('alice-client')!.requests).toBe(10);+ }, 60_000);++ test('a failure inside the delete-and-tally statement deletes nothing', async () => {+ await seed(engine, 'alice-client', 'query', 5, 60);+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION mcp_rollup_test_fail() RETURNS trigger LANGUAGE plpgsql AS $$+ BEGIN RAISE EXCEPTION 'forced tally failure'; END $$`);+ await engine.executeRaw('CREATE TRIGGER mcp_rollup_test_fail BEFORE INSERT ON mcp_request_log_rollup FOR EACH ROW EXECUTE FUNCTION mcp_rollup_test_fail()');+ try {+ await expect(pruneMcpRequestLog(engine, 30)).rejects.toThrow('forced tally failure');+ expect(await logCount(engine)).toBe(5);+ expect((await rollup(engine)).size).toBe(0);+ } finally {+ await engine.executeRaw('DROP TRIGGER mcp_rollup_test_fail ON mcp_request_log_rollup');+ await engine.executeRaw('DROP FUNCTION mcp_rollup_test_fail()');+ }+ }, 60_000);++ test('a brain without the tally table (not migrated yet) skips the prune and deletes nothing', async () => {+ await seed(engine, 'alice-client', 'query', 5, 60);+ await engine.executeRaw('ALTER TABLE mcp_request_log_rollup RENAME TO mcp_request_log_rollup_hidden');+ try {+ const warn = spyOn(console, 'warn').mockImplementation(() => {});+ try {+ expect(await pruneMcpRequestLog(engine, 30)).toMatchObject({ deleted: 0, capped: false, skipped: 'no_rollup_table' });+ } finally { warn.mockRestore(); }+ expect(await logCount(engine)).toBe(5);+ expect((await lifetimeUsage(engine, ['alice-client'])).get('alice-client')?.requests).toBe(5);+ } finally {+ await engine.executeRaw('ALTER TABLE mcp_request_log_rollup_hidden RENAME TO mcp_request_log_rollup');+ }+ }, 60_000);++ test('config set refuses 1-29, fractions and values above 3650; nothing is written', async () => {+ for (const bad of ['1', '7', '29', '45.5', '3651', 'thirty']) {+ const refusal = mcpLogRetentionRefusal(bad);+ expect(refusal).toContain('nothing was written');+ expect(refusal).toContain('30');+ }+ for (const ok of ['30', '90', '3650', '0', 'off', 'OFF']) expect(mcpLogRetentionRefusal(ok)).toBeNull();++ const errs: string[] = [];+ let exit: number | null = null;+ const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errs.push(a.join(' ')); });+ const logSpy = spyOn(console, 'log').mockImplementation(() => {});+ const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => { exit = code ?? 0; throw new Error(`EXIT:${code}`); }) as never);+ try { await runConfig(engine, ['set', MCP_LOG_RETENTION_KEY, '7']); }+ catch (e) { if (!(e as Error).message.startsWith('EXIT:')) throw e; }+ finally { errSpy.mockRestore(); logSpy.mockRestore(); exitSpy.mockRestore(); }+ expect(exit).not.toBeNull();+ expect(exit).not.toBe(0);+ expect(errs.join('\n')).toContain('nothing was written');+ expect(await engine.getConfig(MCP_LOG_RETENTION_KEY)).toBeNull();++ await engine.setConfig(MCP_LOG_RETENTION_KEY, 'off');+ expect(await readMcpLogRetentionDays(engine)).toBeNull();+ await engine.setConfig(MCP_LOG_RETENTION_KEY, '0');+ expect(await readMcpLogRetentionDays(engine)).toBeNull();+ await engine.setConfig(MCP_LOG_RETENTION_KEY, '90');+ expect(await readMcpLogRetentionDays(engine)).toBe(90);+ }, 60_000);++ test('the resident prune ticker arms only on PGLite, where a live serve owns the lock', async () => {+ await seed(engine, 'alice-client', 'query', 4, 60);+ await engine.setConfig(MCP_LOG_RETENTION_KEY, '30');+ const armed: number[] = [];+ const ticker = startMcpLogPruneTicker(engine, { setInterval: (_fn, ms) => { armed.push(ms); return armed.length; }, clearInterval: () => {} });+ try {+ if (kind === 'pglite') {+ expect(armed).toHaveLength(1);+ expect((await ticker.tick())?.deleted).toBe(4);+ expect(await logCount(engine)).toBe(0);+ } else {+ expect(armed).toHaveLength(0);+ expect(await ticker.tick()).toBeNull();+ expect(await logCount(engine)).toBe(4);+ }+ } finally { ticker.stop(); }+ }, 60_000);++ if (kind === 'postgres') {+ test('two prunes at once never double-count (SKIP LOCKED)', async () => {+ await engine.executeRaw(+ `INSERT INTO mcp_request_log (token_name, operation, status, created_at)+ SELECT 'alice-client', 'query', 'success', now() - interval '60 days' - (g * interval '1 second') FROM generate_series(1, 6000) g`);+ const [a, b] = await Promise.all([pruneMcpRequestLog(engine, 30, { batchSize: 500 }), pruneMcpRequestLog(engine, 30, { batchSize: 500 })]);+ expect(a.deleted + b.deleted).toBe(6000);+ expect(await logCount(engine)).toBe(0);+ expect((await rollup(engine)).get('alice-client')!.requests).toBe(6000);+ }, 120_000);+ }+ });+}++if (!testBackends().every(kind => kind === 'postgres')) {+ describe('a PGLite brain under a live serve --http prunes on its own (repo-less)', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ }, 120_000);+ afterAll(async () => { await engine.disconnect().catch(() => {}); });++ test('the serve lane arms the ticker while the HTTP server runs and stops it after', async () => {+ await seed(engine, 'alice-client', 'query', 3, 60);+ await seed(engine, 'alice-client', 'query', 2, 1);+ await engine.setConfig(MCP_LOG_RETENTION_KEY, '30');+ const ticks: Array<() => unknown> = [];+ let cleared = 0;+ let deletedWhileServing = -1;+ const errSpy = spyOn(console, 'error').mockImplementation(() => {});+ try {+ await runServe(engine as unknown as BrainEngine, ['--http'], {+ exit: () => {},+ log: () => {},+ stallWatchdogMs: 0,+ armCorpusDrain: () => null,+ mcpLogPrune: { setInterval: (fn) => { ticks.push(fn); return ticks.length; }, clearInterval: () => { cleared++; } },+ runServeHttp: async () => {+ expect(ticks).toHaveLength(1);+ await ticks[0]!();+ deletedWhileServing = 3 - (await logCount(engine, "created_at < now() - interval '30 days'"));+ },+ });+ } finally { errSpy.mockRestore(); }+ expect(deletedWhileServing).toBe(3);+ expect(cleared).toBe(1);+ }, 60_000);+ });+}diff --git a/test/mcp-usage.test.ts b/test/mcp-usage.test.tsindex d3b69c50d5..1ae82b306b 100644--- a/test/mcp-usage.test.ts+++ b/test/mcp-usage.test.ts@@ -16,9 +16,13 @@ import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import {readClientOpUsage,+ readClientOpUsageWithCoverage,+ truncatedWindowNote,normalizeLoggedOperation,+ AUDIT_LOG_OPERATIONS,AUTOMATION_FRACTION_THRESHOLD,MCP_USAGE_DEFAULT_WINDOW_DAYS,+ NON_OP_LOG_ROWS,} from '../src/core/mcp-usage.ts';let engine: PGLiteEngine;@@ -166,3 +170,35 @@ describe('readClientOpUsage', () => {await expect(readClientOpUsage(engine, { days: 10_000 })).rejects.toThrow(/days must be an integer/);});});++describe('readClientOpUsageWithCoverage (request-log retention)', () => {+ test('a brain that never pruned reports a complete window, with the same clients readClientOpUsage returns', async () => {+ const { clients, coverage } = await readClientOpUsageWithCoverage(engine, { days: 90 });+ expect(coverage).toEqual({ requested_days: 90, covered_days: 90, truncated: false, pruned_before: null });+ expect(clients).toEqual(await readClientOpUsage(engine, { days: 90 }));+ });++ test('a window that starts before the newest pruned row is truncated to the days it covers, and says what to do', async () => {+ await engine.executeRaw(+ `INSERT INTO mcp_request_log_rollup (token_name, requests, last_used_at, pruned_through)+ VALUES ('client-pruned', 5, now() - interval '40 days', now() - interval '40 days')`);+ try {+ const wide = await readClientOpUsageWithCoverage(engine, { days: 365 });+ expect(wide.coverage).toMatchObject({ requested_days: 365, covered_days: 40, truncated: true });+ expect(Date.parse(wide.coverage.pruned_before!)).toBeLessThan(Date.now() - 39 * 86_400_000);+ expect(wide.clients).toEqual(await readClientOpUsage(engine, { days: 365 }));+ const note = truncatedWindowNote(wide.coverage);+ expect(note).toContain('window truncated');+ expect(note).toContain('--days 40');+ expect(note).toContain('cannot restore');+ expect((await readClientOpUsageWithCoverage(engine, { days: 30 })).coverage.truncated).toBe(false);+ } finally {+ await engine.executeRaw("DELETE FROM mcp_request_log_rollup WHERE token_name = 'client-pruned'");+ }+ });++ test('audit rows are named once: the prune exemption and the usage hygiene read the same set', () => {+ expect([...AUDIT_LOG_OPERATIONS].sort()).toEqual(['memory_setting_change', 'surface_change']);+ for (const op of AUDIT_LOG_OPERATIONS) expect(NON_OP_LOG_ROWS.has(op)).toBe(true);+ });+});diff --git a/test/serve-http-admin-request-log-retention.test.ts b/test/serve-http-admin-request-log-retention.test.tsnew file mode 100644index 0000000000..3a5c87edfc--- /dev/null+++ b/test/serve-http-admin-request-log-retention.test.ts@@ -0,0 +1,89 @@+/**+ * Admin dashboard request-log retention (#6770 rewrite).+ *+ * Authoring gate: (1) protects the Agents page's lifetime totals (total+ * requests, OAuth last-used) across a prune, and the Request Log endpoint's+ * retention fields the page shows; (2) fails when the dashboard counts only+ * the rows still in mcp_request_log, so a prune would silently shrink every+ * agent's total; (3) no existing test covers /admin/api/agents or+ * /admin/api/requests; (4) no production seam: the admin area is mounted on a+ * bare express app with a stub context, as CONTRIBUTING describes.+ *+ * Repo-less PGLite (no git checkout).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import express from 'express';+import type { Server } from 'node:http';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { mountAdminApi } from '../src/commands/serve-http-admin-api.ts';+import type { ServeHttpContext } from '../src/commands/serve-http.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { MCP_LOG_RETENTION_KEY, runMcpLogRetention } from '../src/core/mcp-request-log-retention.ts';++let engine: PGLiteEngine;+let server: Server;+let base: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const app = express();+ const ctx = {+ engine, config: { engine: 'pglite' }, sql: sqlQueryForEngine(engine),+ requireAdmin: (_req: unknown, _res: unknown, next: () => void) => next(),+ adminSessions: new Map(), sseClients: new Set(), oauthProvider: {},+ issuerUrl: new URL('http://127.0.0.1/'), mcpResourceUrl: new URL('http://127.0.0.1/mcp'),+ } as unknown as ServeHttpContext;+ mountAdminApi(app, ctx);+ server = app.listen(0, '127.0.0.1');+ base = `http://127.0.0.1:${(server.address() as { port: number }).port}`;+}, 120_000);++afterAll(async () => {+ server.closeAllConnections();+ await new Promise<void>(r => server.close(() => r()));+ await engine.disconnect();+});++async function seed(token: string, count: number, daysAgo: number): Promise<void> {+ for (let i = 0; i < count; i++) {+ await engine.executeRaw(+ `INSERT INTO mcp_request_log (token_name, agent_name, operation, latency_ms, status, created_at)+ VALUES ($1, $1, 'query', 5, 'success', now() - ($2::int * interval '1 day') - ($3::int * interval '1 minute'))`,+ [token, daysAgo, i]);+ }+}++const getJson = async (path: string) => (await fetch(`${base}${path}`)).json() as Promise<any>;++describe('admin dashboard across a request-log prune', () => {+ test('Agents totals and OAuth last-used survive the prune; the Request Log reports the retention window', async () => {+ await engine.executeRaw("INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read) VALUES ('alice-client', 'alice-client', 'read', 'default', ARRAY['default'])");+ await engine.executeRaw("INSERT INTO access_tokens (name, token_hash) VALUES ('acme-key', 'hash-acme-key')");+ await seed('alice-client', 4, 90);+ await seed('alice-client', 2, 2);+ await seed('acme-key', 3, 120);++ const before = await getJson('/admin/api/agents');+ const pick = (rows: any[], name: string) => rows.find(r => r.name === name);+ expect(pick(before, 'alice-client').total_requests).toBe(6);+ expect(pick(before, 'acme-key').total_requests).toBe(3);+ const lastUsedBefore = pick(before, 'alice-client').last_used_at;+ expect((await getJson('/admin/api/requests')).retention_days).toBeNull();++ await engine.setConfig(MCP_LOG_RETENTION_KEY, '30');+ expect((await runMcpLogRetention(engine))?.deleted).toBe(7);++ const after = await getJson('/admin/api/agents');+ expect(pick(after, 'alice-client').total_requests).toBe(6);+ expect(pick(after, 'acme-key').total_requests).toBe(3);+ expect(pick(after, 'alice-client').last_used_at).toBe(lastUsedBefore);+ expect(pick(after, 'alice-client').requests_today).toBe(0);++ const log = await getJson('/admin/api/requests');+ expect(log.total).toBe(2);+ expect(log.retention_days).toBe(30);+ expect(Date.parse(log.pruned_before)).toBeLessThan(Date.now() - 30 * 86_400_000);+ }, 60_000);+});