Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Core Services (1/3, continued)
Subsystem index · Previous entries. Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
The chat-history connector layer under src/core/connectors/, then the content-repair judgment tier under src/core/content-repair/, then the Retrieval Reflex and session-context helpers under src/core/context/.
src/core/connectors/(directory) — the LIVE chat-history connector layer (front-end to the transcripts pipeline).types.ts: theChatHistoryProvidercontract (mirror ofTranscriptAdapter— leaf module per provider;spoolFormatnames the adapter that parses its output; datedHostSpecTarget).credentials.ts: file-plane store at~/.gbrain/connectors/<provider>.json(0600, dir 0700, atomic tmp+rename), env-above-fileresolveCredentialreturning{cred, source}; credentials NEVER touch the DB /sources.config/ config planes / op payloads.classify.ts: the pure §2A/§2B response classifier — distinguishes a Cloudflare-fingerprint 403 (forbidden_fingerprint, dead-end) from an auth-expired 403 (auth_required, re-auth) and flags a parses-but-no-itemsbody asdrift.client.ts:ConnectorClientmodeled onGitHubClient(plain fetch against a hardcoded ORIGIN + off-origin guard so the cookie/bearer never leaks,redirect: 'manual'with any 3xx a terminalauth_required, browser UA, refresh-once-on-401 that is handed the client itself and never runs on a 403 (terminal, #7515), Retry-After backoff, a per-run ceilingMAX_CONNECTOR_REQUESTS_PER_RUN(10,000, lowered bymaxRequests) and adeadlineAtchecked before each request and retry wait (ConnectorRunLimitError), andprobeFailure, the one error-to-ProbeResulttable;fetchImpl/sleep/nowinjectable — NOTfetchWithSSRFGuard, which breaks SNI on Cloudflare hosts).providers/chatgpt.ts+providers/claude.ts(registry inregistry.ts; Perplexity deliberately absent — no adapter): offset/updated pagination with a per-pass 500-page cap and astopBeforewatermark break, epoch/ISO normalization, ChatGPT'sis_archivedsecond pass, Claude'schat_conversationspaged withlimit/offsetacross every chat-capable org (conversations fetched from the org that listed them; timestamps normalized with ChatGPT'stoIso), a ChatGPT walk that steps back whentotalshrinks mid-walk (a removal shifts later items to lower offsets) and yields each id once across both passes, content-block text assembly for Claude, list pages truncated to the requested size (a truncated page that also ignores offset is drift), Claude'sCLAUDE_MAX_ORGS(10; more makes the listing incomplete) andCLAUDE_MAX_REQUESTS_PER_ORG(5,000) caps, and arefreshAccessToken(ChatGPT re-mints from the cookie via/api/auth/sessionthrough the shared client and throws its terminal errors; Claude's cookie is terminal).spool.ts: writes fetched conversations in native-export shape (0600, batched, pruned in the orchestratorfinally).sync.ts:runConnectorSync— resolve credential → probe → read the per-(provider, source) config-scalar watermarkconnectors.<p>.source.<id>.watermark_iso(NOT op_checkpoint, whose 7-day GC would wipe it → full re-fetch) → list towatermark − windowDays→ skip stubs whoseupdatedAtthe source'ssyncedledger already holds and stubs quarantined in itsfailedledger (afterQUARANTINE_ATTEMPTS= 3 fetch OR ingest failures at oneupdatedAt; ingest outcomes are attributed per conversation by session id, a spool-file-level failure fails the batch; an edit or--fullretries) BEFORE the--limitcap, so capped runs progress → fetch → spool →runTranscriptsIngest→ record each successfully ingested conversation as synced → advance the watermark ONLY on a clean run (quarantined ids no longer block it;syncedentries older than the next list window are pruned,failedentries never are: #6387) →logIngestreceipt → stamp per-sourcelast_sync_at→ engine-branched embed kickoff (maybeKickoffEmbed: PostgressubmitEmbedBackfill, PGLiterunEmbedCoreinline — NEVERsubmitEmbedBackfill, which refusesno_worker_surface).failed-ledger.ts(#6387): thefailedledger entry (attempts,updatedAt,lastAttemptAt,nextRetryAt, ClaudeorgId) kept until the conversation imports, and the pureplanConnectorFetch— listed work plus due retained failures retried by id (RETRY_BUDGET10 per run, oldest-due first, slots reserved under--limit, quarantine backoff fromitem-holds.tsHOLD_BACKOFF_MS/HOLD_DAILY_MS); on aroutesByOrgprovider an entry withoutorgIdisheldfor--full. A sync with any entry left reportspartial+unresolved; aborts and auth stops are never strikes; a complete--fulllisting drops entries it no longer contains (gone);connectors status --jsonlistsunresolvedand the doctor check warns "archive incomplete" (ask-first--fullfix for held entries).config-keys.ts: theconnectors.key builders (sync progress keyed by(provider, source);auth_error_atstays per provider because it describes the shared credential),readConnectorState/writeConnectorState(a legacy per-providerwatermark_iso/last_sync_atis honored only for the scheduledconnectors.source_idsource until that source writes its own key, which retires it), and the pureisConnectorSyncStale(last, now, floor)dispatch gate. Status, doctor and the autopilot gate read the scheduled source's state.oauth-pkce.ts: dependency-free S256 PKCE loopback (Bun.serve, timing-safe state;portOverride: 0plusonListenbinds an OS-assigned port for tests while the authorize and token URLs keepredirectPort) — best-effort--try-oauthonly. Surfaces: theconnectors_status/connector_syncops (src/core/ops/connectors.ts, bothlocalOnly), thegbrain connectorscommand family (src/commands/connectors/peeled dir;connectors syncusage errors, a missing--sourcevalue or a missing/unknown provider, areinvalid_paramsexit 2 with the envelope under--jsonand afixwhose<SOURCE_ID>/<PROVIDER>input it names, andconnectors sync --helpprints the usage;test/connectors-sync-cli.test.ts), theconnector-syncminion handler (src/core/minions/handlers/connector-sync.ts, single-flight lock; rechecksauto_syncand returnsskippedunless the job isexplicit, #7515),connectors sync --all(onlyauto_syncproviders;--max-requests/--deadlinebound the invocation), the autopilotmaybeDispatchConnectorSyncsgate, and theconnectorsdoctor check. Pinned bytest/connectors-*.test.ts+test/e2e/connectors-sync-checkpoints-pglite.test.ts(per-source watermark,--limitprogress, quarantine, retitle, #6387 retained retries and the--fullupgrade-state recovery, #6388 long-message tails) +test/e2e/connectors-sync-pglite.test.ts(full pipeline against aBun.servefixture backend, keyless) +test/e2e/connector-sync-handler-pglite.test.ts+test/e2e/doctor-connectors-pglite.test.ts.src/core/context/title-matches.ts—preferEntityTitleMatches, the volunteer title arm's one-pointer-per-name-per-source rule: exact-title hits that share a candidate norm within one source collapse to the page theentitycard would pick (src/core/entities/exact-match-preference.ts, shared withverbs/entity-card.ts: explicit exact slug, then a linkable type of that source's pack, then any other page), ties broken by slug. Same-title pages in different sources are different entities and all stay. It runs after the privacy and activation gate (a private or withheld entity cannot suppress an eligible fallback) and leaves a norm an alias already resolved alone; the mention policy and packs are read only on a collision. Test:test/volunteer-title-collision.test.ts.src/core/content-repair/judgment.ts— #6377 (Lane B3) the content-repair lane's model tier for a slug conflict:judgeSlugConflictbuilds the prompt from both files' frontmatter, headings and first 60 lines of body plus every line that mentions the other's slug anywhere in either body (evidence past line 60 counts), both slugs and paths, the hold's reason and the allowed answers, and parses exactly one JSON object{"action":"remove_slug"},{"action":"merge_into","canonical":"<one of the two slugs>"}or{"action":"needs_human"}with an optionalwhysentence that reaches the run's output only, never hold metadata. The same failure classes,thinkingOffControland output ceiling as the fence tier; acanonicaloutside the two slugs isllm_malformed. Memo key: sha256 of both participants' content + both ids + model + prompt version + rules version. The model ismodels.content_repair(an explicit model always runs), elsemodels.fence_repair, elseCONTENT_REPAIR_MEASURED_MODELS(the eval's qualifiers, best first, ties to the cheaper), else the fence list. Tests:test/repair-slug-conflicts.test.ts.src/core/content-repair/llm.ts— #6377 (Lane B3) the paid call behindjudgment.ts: one gateway chat under the fence repair's caps and ledger (FENCE_REPAIR_LEDGER, so onefences.repair.max_usd_per_daycovers the whole lane and today's fence spend counts; the per-page cap applies per candidate),fences.repair.llm=falseand--no-llmturn it off, the attempt memo keeps rejected bytes from costing twice, and a transientllm_unavailabledoes not consume the memo. Spend is reported as the item'sllm_usdand carried into thecontent_repairreceipt (model,cost); prompts never include the rest of either page.src/core/context/— Retrieval Reflex (Layer 1).entity-salience.ts: pure, zero-LLM, precision-biasedextractCandidates(text)(capitalized runs +@handles, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped; a lowercase weak pass additionally emitsweak: truecandidates — lowercase words ≥3 chars on a separateMAX_WEAK_CANDIDATES=32budget that never evicts strong candidates — which downstream may resolve through the alias arm ONLY) +extractCandidatesFromWindow(turns)(merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first).retrieval-reflex.ts:resolveEntitiesToPointers(engine, sourceId, candidates, opts)— alias arm (resolveAliases, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (real slugs are namespacedpeople/xbutslugifydrops the prefix) + two lexical identity arms behindopts.lexicalArms(kill switch: configretrieval_reflex_lexical_arms/ envGBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS, default on): weak lowercase candidates probe the ALIAS arm ONLY (never title/slug-suffix, where ordinary lowercase words would fabricate pointers) and require GLOBAL uniqueness across all sources in play; the surname arm resolves a strong single capitalized token ≥3 chars via alower(title) LIKE '% <token>'predicate on the same query, with exact-arm precedence and ambiguity counted over ALL person rows carrying the surname — ambiguity in either arm injects nothing; pointers carrysource_id/arm/confidence/matchedNorm(ARM_CONFIDENCEalias 0.9 / title 0.8 / title-surname 0.72 (deliberately above the volunteer layer's 0.70 gate, below title) / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts:sourceIds?federated scope (alias arm loops per source, arm 2 usessource_id = ANY),suppression?('slug-and-title' default; 'slug-only' REQUIRED under windowing — the title rule would suppress every entity merely mentioned in a prior window turn), ambient-channel event logging is DELIVERY-side, not in-resolver —logDeliveredReflexPointers(engine, pointers)fires only once a block is actually handed to the consumer (serve's resolve-IPConDeliveredhook post-write;buildReflexAdditionpost-timeout on the direct rung), so abandoned/timed-out blocks never pollute the volunteered-vs-used stats; its event write is registered synchronously before return so the CLI background-work drain cannot miss it; synopsis runs throughstripTakesFence/stripFactsFence(the same privacy boundaryget_pageapplies) so private facts never reach the prompt;visibility: private(and derived-private) pages never resolve on any arm unless the caller passesexcludePrivate: false(default true, the caller's read policyprivatePagesFilterForCaller, the predicate get_page uses, so a bound member resolves the pages its readers allow; onlyvolunteer_contextwidens, viaresolveExcludePrivatePagesfor a trusted local caller — gbrain-evals N8-1/N8-2, pinned bytest/reflex-private-visibility.test.ts); capped atMAX_POINTERS.reflex.ts: the orchestrator + engine-aware resolver ladder (hostresolveEntities→ PGLite serve IPC → Postgres cached process-singleton → disabled), zero-candidate fast path, fail-open + timeout, heartbeat write for the doctor check,reflexEnabled(cfg)(file/env gate, default ON; DB-plane does NOT gate —assemble()is sync); windowed extraction whenwindowTurnspresent andretrieval_reflex_window_turns(default 4; 1 = single-turn behavior) > 1 — switches suppression to slug-only; accept-side reflex-channel logging fires after the per-turn timeout admits the block (direct-Postgres rung only — IPC logs server-side at delivery; host-injected resolvers are a documented gap).resolve-ipc.ts: local unix-socket resolve protocol (client + server) so PGLite resolves through the single connectiongbrain serveholds (a second opener would hit the exclusive lock; a subprocess would force-steal it past the 5-min staleness window and crash). Wired into both serve transports viasrc/mcp/resolve-ipc-binding.ts(engine-uniform; socket + secret keyed offhash12(database_url)under~/.gbrain/run, cleaned up on shutdown). A lean read-only Postgres serve binds thereadsocket kind instead (#7612);hookResolveSocketForConfigfalls back to it after the source socket, and adelegation: truecaller never targets it. Doctor surface:retrieval_reflex_healthinsrc/commands/doctor/checks/verbs-reflex.ts(reads the heartbeat for truthful runtime status; categorized indoctor-categories.ts) +volunteer_channels(engine-aware sibling: groupscontext_volunteer_eventsby channel over 7 days so operators see which push channels — reflex/op/watch/claude-code/codex — actually fire; info-only; the LOCAL doctor runs it brain-wide while the remote report path threads the caller's source scope, so a source-bound token never sees other sources' activity counts/timestamps; counts are reconciled against the hook heartbeat over the same 7-day window — a mostly-degraded week gets a CAUTION note, since a server-side delivery count isn't proof of injection; quiet-channel guidance is engine-aware — Postgres brains are told the hook lane is quiet by design rather than to chase registration — and walks both quiet classes (installed-but-unregistered vs registered-but-quiet; the check can't inspect registration itself); pre-v117 tolerant, and transient DB errors are reported as such, never as an old schema; pinned bytest/doctor-volunteer-channels.test.ts). Config:retrieval_reflex+retrieval_reflex_max_pointers+retrieval_reflex_window_turns+retrieval_reflex_lexical_armsinsrc/core/config.ts(envGBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS,GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS).volunteer.ts:parseWindow(lenientuser:/assistant:prefixes, unprefixed → one user turn),volunteerContext(extract → resolve → +0.05 multi-turn/newest-turn boost →min_confidence0.7 gate → cap 3/5; deterministic rationale strings, never raw conversation text; slug-only suppression),volunteerUsageStats(per-arm/channel precision from thepages.last_retrieved_at > volunteered_atjoin — APPROXIMATE: the 5-min last-retrieved throttle causes false negatives, unrelated reads false positives).volunteer-events.ts:insertVolunteerEvents(ONE multi-row parameterized INSERT that keeps only rows whose page still exists, probed under the page row's key-share lock, so a late write never restores a purged page; #9068),logVolunteerEventsFireAndForget+ bounded drain registered as thevolunteer-eventsbackground-work sink (order 4),purgeStaleVolunteerEvents(90-day GC, called from the dream cycle's purge phase). Policy layer ships as theretrieval-reflexrecipe (recipes/retrieval-reflex/). Pinned bytest/context/entity-salience.test.ts,test/retrieval-reflex.test.ts,test/retrieval-reflex-pre-v110.test.ts,test/context/resolve-ipc.test.ts,test/doctor-retrieval-reflex.test.ts,test/volunteer-context.test.ts,test/e2e/volunteer-context-postgres.test.ts. Checkpoint-compaction modules in this dir:corpus-segments.ts— engine-free content-addressed compaction segments (<session>.seg-<hash24>.txt, idempotent by name; parsers accept 12–64 hex), the hash-keyed per-session ledger (atomic tmp+rename, fail-open, entry order = the only ordinal),sliceBoundaryWindow/splitByBoundaries, the redactedrenderSegmentText(a segment is NEVER written unscanned — unlike the session-end full write, which degrades-and-writes), exact-setcoverageComplete/decideCorpusMode(count equality can be fooled by a duplicated boundary), the compact-timebankCompactSegmentstep (per-step deadline degrades, segment-then-ledger crash order), the openclaw tail boundary reader (readOpenclawBoundaryTail, delegates mapping to the adapter's exportedmapOpenclawLine; also returns turn-stampedtoolCalls/toolCallTurnIndexesfor the Memorable receipt — name-only v1,input: nullby design until an observation run characterizes OpenClaw's args field), and orphan-sidecar/aged-ledger GC — pinned bytest/corpus-segments.test.ts.checkpoint-harvest.ts— the serve-side prompt harvest of a segment: bounded FIFO (cap 8, 60s abort), sweep-shared claim fencing, capability-then-kill-switch gates,signal.abortedPOST-check (the pipeline returns partials on abort; an aborted run writes nothing and stays retryable), receipt sidecar before idempotent manifest publish (source-scopedgetPageverification — a link that resolves to nothing is never banked),.ingestedlast, explicitshutdownCheckpointHarvest()called by serve BEFOREengine.disconnect()(the background-work drain is CLI-exit-only by contract), a writeback turn whose facts preflight finds the canonical writer busy (writer_lock_unavailable, before any model call) re-queued after 5, 15 and 45 s (writer_busy_requeued; the retry skips admission, a pending retry dedups a re-schedule asalready_queued, shutdown clears pending retries) while a compact segment's busy refusal stays an error the sweep resumes, and error reasons that keep the error's code orreasonwithin the 48-char reason-code shape (operationerror:writer_lock_unavailable), the first failure of each reason logged to stderr once per serve run — pinned bytest/checkpoint-harvest.serial.test.ts.hook-heartbeat.ts— the hooks telemetry JSONL extracted from hook.ts (hook.ts re-exports; serve-side writers never import the command module); allowlist carries the checkpointsegment/inserted/duplicate/linkscount-only fields.session-state.tsalso carries the v132checkpoint_manifesthelpers (getCheckpointManifest/appendCheckpointManifest: newest-first, dedup-by-slug, cap 20, seg-hash completion key, fail-open on pre-v132 schema) — pinned bytest/checkpoint-manifest.test.ts.sensitivity-scan.ts+compile-view.ts— the compile-context stack: composed detector (secret-scan + orderedPII_PATTERNS+ path/blocklist families + operator pattern file; uniform.gbrain-scan-allowfingerprint escape hatch; CONTENT hits drop an entry, CONFIG/loader failures THROW so the caller aborts without writing) and the deterministic compiled-view builder (recency decay anchored to the newest candidateupdated_at, never wall-clock; total-order (score desc, slug asc); source-scoped listPages/getPage reads that skip op-layer write-backs and passexcludePrivate: trueon every arm, so private pages never reach the compiled file; whole-filepackToBudgetmath that never passes a <=0 budget) — pinned bytest/sensitivity-scan.test.ts+test/compile-view.test.ts+test/e2e/compile-context-pglite.test.ts; the CLI shell issrc/commands/compile-context.ts(targets claude-code|codex|openclaw, AGENTS.md managed-marker splice that throws on damaged markers, atomic writes,--checkrecompile-and-compare exit codes; the guide isdocs/guides/checkpoint-compaction.md). It also owns the whole Memorable seam's engine-free plumbing: the session-receipt JSONL (session-receipts.jsonl,appendSessionReceipt— dedup by post-redactioncontent_hashso a resumed session neither duplicates its receipt nor re-fires the relay; tail-rewrite compaction triggered by the 32 MB byte ceiling alone — the read fires exactly when the pass will act, with the 2000-line budget enforced inside the pass — and askipCompactionseam the openclaw compact() lane sets unconditionally: the hook lane is the ONE receipts compactor, so two processes can never race the read-filter-rename rewrite); ONE bounded adaptivereadJsonlTailreader shared bylastReceiptMatches,lastRelayResultandreadSessionReceiptsTail(a receipt line can exceed the 1 MB window — the window doubles rather than reading "empty");maybeTrimRelayResults(BOTH capture lanes trim the child-appendedmemorable-relay.jsonl— an openclaw-only host has no hook lane, and converging newest-keeping trims make concurrent trims safe: mtime-stale preferred, hard 8 MB force backstop, line-boundary cut keeping the newest lines — the child appends open-by-path, so the residual loss window is one in-flight write); the CONSENT STAMP (memorable-consent.json, 0600, written ONLY by config-set's disclosure flow — deliberately outside config.json, which the external CLI full-file-rewrites; scope-bound to the disclosure sha256 +MEMORABLE_CAPTURE_HARNESSES, so widening the capture surface invalidates old stamps);memorableGateAllowed(cfg)({allowed, reason: kill_switch|disabled|disclosure_missing} — one reason vocabulary for hook, context-engine and doctor);memorableConsentEvidence()(the CLI-side opt-in read fail-closed from ~/.memorable/config.json, dated provisional spec note, GBRAIN_MEMORABLE_CONFIG test seam);redactedToolCallsJson(the security-load-bearing span-filter + highEntropy redaction, ONE implementation for both capture lanes; string LEAVES are redacted raw before serialization — scanning the serialized JSON would let quoted secrets through via " escaping — with a post-serialization re-scan as belt-and-braces);recordAndRelayReceipt(per-receipt harness scope-binding first — a harness outsideMEMORABLE_CAPTURE_HARNESSESis refused withmemorable_harness_undisclosed→ receipt → prior-run outcome surfacing with the child's reason clamped via the sharedclampRelayCause(32 chars, so the 16-char prefix keeps composites inside the 48-char reason bound) and appended LAST → consent evidence →resolveMemorableBin→ detached spawn; never throws;spawnFntest seam); andpriorRelayFailure, which surfaces the PREVIOUS relay run's self-reported exit status so a relay that records nothing is never reported healthy.resolveMemorableBindoes the pre-spawn PATH/MEMORABLE_BINresolution so a missing CLI is a named heartbeat reason rather than a silent async ENOENT. #6195:entity-salience.extractCandidatesalso emits lowercase 2-3-word weak n-grams (multiToken, own budgetMAX_WEAK_NGRAM_CANDIDATES= 16, never across punctuation, never all stopwords/common words) that ride the exact weak-alias fold, andretrieval-reflexarm 2.6 (weak-title, 0.72, behindlexicalArms, private pages hidden by default) matches them to the exact title of a person/company/organization page whose title is globally unique; single lowercase words stay alias-only.src/core/context/hook-heartbeat.ts— the hooks telemetry plane under<gbrain home>/integrations/hooks/(heartbeat.jsonl,status.json, session receipts, the memorable relay log; directories 0700, appends 0600). Entries hold counters, durations and codes only:HEARTBEAT_ALLOWED_KEYSis the full key allowlist CI greps the fixture against, and includespattern(scanner pattern name),fingerprint(sha256:<16 hex>) andhint(fixed text) for refusals.near_duplicateis the shadow count on thewriteback_dedupevent thatfacts/capture-dedup.tsappends (lane inreason, exact drops induplicate).relayRefusalHeartbeat(hit)builds the linecontext-engine.tswrites when its high-entropy re-scan refuses a memorable relay (event: relay,outcome: degraded,reason: secret_scan_refused); the receipt and relay are skipped for that compaction window and the checkpoint is kept.memorableGateAllowedgates the relay lane; span redaction runsredactFindingswithhighEntropy: true. Tests:test/context-engine-checkpoint.serial.test.ts.src/core/context/seat.ts— seat identity for captured sessions (#4618), engine-free.resolveSeatreturns the lowercasedGBRAIN_SEATlabel when it matchesSEAT_LABEL_RE(^[a-z0-9][a-z0-9._-]{0,63}$), elsehome-<8 hex>over the realpath of the harness home (Claude Code: the directory holdingprojects/in the transcript path, thenCLAUDE_CONFIG_DIR,CODEX_HOME,~/.claude; codex:CODEX_HOMEor~/.codex; OpenClaw: the agent directory holdingsessions/), so no raw path reaches frontmatter;GBRAIN_SEAT=off(the opt-out) resolves to null and nothing is recorded.writeSeatSidecarwrites<sessionId>.seat.json({version: 1, seat, seat_source, hook_lane, harness, first_seen}, 0600, tmp+rename) unless one exists, reportingseat_conflictwhen the existing seat differs;readSeatSidecaraccepts only a valid v1 record.SEAT_REASON_HINTSholds the fixed heartbeat hints. The sidecar name and its GC live incorpus-segments.ts(seatFileName,SEAT_SIDECAR_SUFFIX).src/core/context/session-speaker.ts— who wrote a captured session's user turns (#8064), engine-free.resolveSessionSpeakerreadsGBRAIN_SESSION_AGENT(a label: agent;off: skip banking;owner: the owner, detection only noted asspeaker_owner_override_detectedbyhookSpeakerDecision; invalid: agentagent), elsedetectAgentLaunchedoverreadProcessAncestry(Linux /proc, elseps; 12 levels, 300 ms): the nearest claude/codex process runs headless (-p/--print,exec) and another claude/codex process is an ancestor, principalagent-launched; #8080: when that next harness ancestor is aclaude remote-controlserver (subcommandremote-control/rc/remote/sync/bridgeright after the binary or node entry script) and the session carries the bridge's--sdk-url, the session is the owner's.bankAsSpeakerwrites<sessionId>.speaker.json({version: 1, principal, source, harness, first_seen}, 0600, first write wins; a differing speaker notesspeaker_mismatch, and an agent in a session already banked without one banks nothing,speaker_mismatch) before the hook's compact, stop and session-end banking; a write failure banks nothing (speaker_write_failed),offrecordscapture_opt_out.corpusFileSpeaker/speakerOfgive the capture lanes (checkpoint-harvest, sweep) thespeakerthey pass torunFactsPipeline, which saves user and unattributed claims asother(asAgentSpoken), addsspeakerContextNoteto the context (facts/speaker-context.ts, also used by the managed facts batch) and names the agent in the extractor prompt. Name and GC:speakerFileName,SPEAKER_SIDECAR_SUFFIXincorpus-segments.ts. Pinned bytest/agent-session-speaker-8064.serial.test.ts.src/core/context/ipc-path.ts— engine-free local socket discovery and private Unix fallback when the complete role-specific address exceeds 103 UTF8 bytes. Hashes the physical parent plus basename under a fixed OS temporary root, verifies ownership/0700 directory/0600 client socket without following fallback symlinks, and retains a native binding claim through actual server close. Existing Unix socket accessibility is rechecked even when a runtime reports ENOENT; permission/resource probe failures never authorize stale takeover; on Windows a PGLite data-dir socket (.gbrain-<kind>.sock) over afunix's 107 UTF-8 bytes moves to%USERPROFILE%\.gbrain\run\<kind>-<hash12(canonical data dir, case-folded)>.sock(windowsLocalIpcSocketPath, the Postgres run-dir scheme; the secret stays in the data dir), andlocalIpcPathTooLongreports a resolved path still over the platform budget, whichipc-path-too-long.tsturns into the typedipc_path_too_longserve log line and doctoripc_socket_pathwarning (#6573;test/ipc-path-windows-fallback-6573.test.tson every OS, the native bind and 20-cycle stability probe intest/windows-ipc-long-path-6573.serial.test.tson windows-latest); Windows named pipes retain a native Global mutex through actual close;windows-ipc.tsnormalizes namespace prefixes while native Windows Unicode casing defines the mutex identity.test/local-ipc-path.test.tscovers concurrent real processes, SIGKILL recovery, active-connection shutdown, aliases and unsafe paths. The published CLI smoke also uses a long Unicode datastore path.src/core/entities/near-name.ts— Flag-only near-name matcher for #2942 (never merges, never writesentity_identities;entity-identity.tsstays manual-only).classifyNearNamereturnssame(normalized-equal after corporate suffixes, or a strongname-variants.tsshape),typo(Damerau distance 1 on 3–64 normalized characters) oracronym(one word equals a multi-word name's initials, at most one letter different). Candidates come from symmetric one-deletion keys plus initials keys, so recall is complete for those kinds; pastNEAR_NAME_MAX_KEYS_PER_SHARDthe index splits into shards by key hash (a pair shares a key, so it lands whole in one shard).loadEntityNamesreads one source's fact-entity pages plus the source pack's linkable types, leaving out private pages for callers that exclude them. Pinned bytest/review-lists.test.ts.src/core/review-lists.ts— The two listsextraction_pendingadds besidepending:unattributed(active facts with no entity, newest first, world-only for remote callers other than the brain owner (worldOnlyFacts, GST-2951), each with aremember+entity+replacesrelink action, never a forget) and opt-inpossible_duplicates(entity pages created in the lastsince_dayswhose name is near another entity's name or alias; pairs inaliasesordistinct_fromare skipped; each row carriesmark_distinct, the owner'sextraction-review distinctcommand). The duplicates cursor walks recent pages within a shard, then the next shard, and reportscompleteonly after the last shard; index builds are serialized per process. Pinned bytest/review-lists.test.tsand the Postgres parity file.src/core/persistence/publication-guard.ts— GBRA-215: the source-scoped guard (withPublicationGuard, agbrain_cycle_lockslease namedreview-publication:<source>) that review decisions take while they re-read a page, re-check it and publish through the page door; two decisions on one source never interleave between check and write. The wait is bounded (PUBLICATION_GUARD_WAIT_MS), thenlock_busywith a read-only locks fix; the lease TTL frees a dead holder. Pinned bytest/extraction-review-door.serial.test.tsandtest/e2e/extraction-review-door-postgres.test.ts.