Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge remote-tracking branch 'origin/master' into gbra133-pr2b

garrytana00e7fdac9f1
diff --cc docs/architecture/key-files/commit-notifier.md
index d9236b7bb4,41030cfbe1..0a6bf8b886
--- a/docs/architecture/key-files/commit-notifier.md
+++ b/docs/architecture/key-files/commit-notifier.md
@@@ -7,10 -7,8 +7,10 @@@ Current behavior and load-bearing invar
- `src/core/notifier/store.ts` — the durable rows (migration `v262-commit-notifier.ts`): `sync_wanted_markers` (source + intent freshness|pull|full, `generation` bumped on every upsert, `first_due_at` kept), `sync_notifier_leases` (one owner per host, fence bumped on takeover, release expires it now), `sync_notifier_sources` (state, retry schedule, last error and trace path, classic syncer host, coverage record). A drainer deletes only `WHERE generation =` the value it read (`clearMarker`, `settleMarkers`); freshness is due while `wanted_head IS DISTINCT FROM last_commit` (no ancestry assumption). `recordLocalSyncer` runs where `writeSyncAnchor` advances `last_commit`: records the syncer host and prunes satisfied markers (the CLI's re-check). `missingTable` lets callers on a pre-v262 brain read "nothing monitored".
- `src/core/notifier/resident.ts` + `src/core/notifier/detect.ts` — production seams and the one start path for every resident (`startResidentNotifier`: serve, serve --http through `src/core/serve-head-watcher.ts`, `gbrain jobs work`, the autopilot daemon). Never awaits: the first pass runs in the background. `GBRAIN_NOTIFIER=0` turns it off per process. Lists managed sources whose worktree this host owns and classic sources whose recorded syncer is this host (or `GBRAIN_NOTIFIER_CLASSIC_SOURCES`), skipping the rest with a reason. Starts syncs through the in-process delegated runner. Trace per source at `<gbrain home>/notifier/<source>.jsonl`. `detect.ts` resolves `--absolute-git-dir` / `--git-common-dir` (linked worktrees) and the quiet predicate. Tests: `test/pathological/s-notifier-classic-serve.test.ts`, `test/pathological/s-notifier-residents.test.ts`.
- `src/core/notifier/nudge.ts` + `src/core/notifier/handoff.ts` + `src/commands/sync/trigger.ts` — submitters and drainers of wanted markers. `recordTriggerMarker` picks the intent (managed: freshness at the checkout HEAD; classic: pull) and `recordSyncNudge` answers the versioned, acknowledged `sync_nudge` IPC kind (`src/core/context/sync-ipc.ts`, `resolve-ipc.ts`, bound in `src/mcp/resolve-ipc-binding.ts`). `handoff.ts` is the post-run re-check of the `sync` job handler and the serve's delegated runner: read before the run, settle after, at most one follow-up (a queued job with `maxWaiting: 1`, or a nudge); a lock-busy skip records a marker and completes. `gbrain sync trigger` answers queued / coalesced (`maxPending: 1`) / nudged, exit 0, with the `no_resident` notice when no resident watches the source; on PGLite a live serve takes it over IPC (`maybeTriggerThroughServe` in `src/commands/sync-delegate.ts`, which also records a busy delegated sync). The GitHub push webhook (`submitGitHubPush` in `src/commands/serve-http-webhooks.ts`) records the pushed sha first; a managed source answers 409 `refresh_required`. Tests: `test/pathological/s-notifier-marker-handoff.test.ts`.
- - `src/core/notifier/status.ts` — what users and agents see, from rows only (no git call): `readSourceFreshness` feeds the `freshness` entry of search and query responses (`src/core/ops/search.ts` `buildRetrievalResponseMeta`; current, behind, syncing, unknown, not_monitored), and `readNotifierBlock` / `formatNotifierBlock` the notifier block for sync status and doctor (resident or none with the `gbrain sync --source <id> --no-pull` fix; remote callers get no trace path, pid or host id). An owner is live by its unexpired lease (Postgres) or a running pid on this host (PGLite). Tests: `test/pathological/s-notifier-freshness-status.test.ts`.
+ - `src/core/notifier/status.ts` — what users and agents see, from rows only (no git call): `readSourceFreshness` feeds the `freshness` entry of search and query responses (`src/core/ops/search.ts` `buildRetrievalResponseMeta`; current, behind, syncing, unknown, not_monitored), and `readNotifierBlock` / `formatNotifierBlock` the notifier block for sync status and doctor (resident or none with the `gbrain sync --source <id> --no-pull` fix; remote callers get no trace path, pid or host id). An owner is live by its unexpired lease (Postgres) or a running pid on this host (PGLite). Tests: `test/pathological/s-notifier-freshness-status.test.ts`. #7189: with no live notifier owner, `readNotifierBlock` reads the drain lease holder (`readDrainHolder`, `drain_holder`, redacted by `publicDrainHolder` for remote callers) and offers no fix while it progresses, the sync-now fix only once `holderStalled`; `formatNotifierBlock` names it (`test/sync-status-coherence-7189.test.ts`).
+- `src/core/sync-pending.ts` — GBRA-133 2b.5: the oldest unsynced commit per source and the embedding backlog, read by doctor `managed_sync_latency` and `src/core/source-health.ts`. Behind = checkout HEAD differs from `sources.last_commit` (HEAD only). Dated from the reflog entry that first moved HEAD off `last_commit` (`<git dir>/logs/HEAD` read as a file, last 1 MiB), else the notifier's persisted `first_due_at` (`sync_notifier_sources` while not idle, or a due freshness marker; current incarnation only), else `unknown` with `no_reflog` or `history_rewritten`. `git: false` (a remote doctor) reads the database only; a source the notifier never recorded reads `not_observed`, never current. `readEmbedBacklog` ages live unembedded chunks from `embedding_pending_since` (keyless brains read `disabled`). `managed_sync_latency` grades a waiting commit like a p95 sample (over the target warns, over max(1 h, target) fails, unknown age warns, only with `sync.on_commit` or a target), grades classic sources on a non-managed brain, and reports `details.freshness_by_source` with `keyword_visible` and `embedded` per source (embedded is not graded). Tests: `test/pathological/s-truthful-sync-status.test.ts` + its Postgres twin, `test/sync-freshness-6858.test.ts`.
+
## Autopilot and the jobs worker
In `src/commands/autopilot.ts`: #7003: `--status` passes the daemon's sidecar verdict (`readDaemonStaleAfter`, `src/core/autopilot-heartbeat.ts`) to `classifyAutopilotStatus` as `daemon`; without a matching sidecar it keeps 6 x `--interval`. `--status --json` adds `stale_after_source` and `next_tick_at`. Tests: `test/pathological/s-7003-autopilot-heartbeat.test.ts` + its Postgres twin.
diff --cc src/commands/extract-tree.ts
index 619316b0b1,0000000000..5f285335a9
mode 100644,000000..100644
--- a/src/commands/extract-tree.ts
+++ b/src/commands/extract-tree.ts
@@@ -1,90 -1,0 +1,93 @@@
+/**
+ * The markdown tree as extraction reads it (GBRA-133 2b.1): the descent-pruned walk behind `walkMarkdownFiles`, the
+ * yielding tree index the sync hooks share per run, and the endpoint page-type lookup they extract links through.
+ * Full `gbrain extract` keeps its whole-tree page-type parse in extract.ts.
+ */
+import { readFileSync, readdirSync, lstatSync } from 'fs';
+import { join, relative } from 'path';
+import { parseMarkdown } from '../core/markdown.ts';
+import type { LinkExtractionPack } from '../core/link-extraction.ts';
- import { pathToSlug, pruneDir, isSyncable } from '../core/sync.ts';
++import { pathToSlug, pruneDir, isSyncable, DEFAULT_METAFILE_PAGES_MODE, type MetafilePagesMode } from '../core/sync.ts';
++import { diskMetafileHeads, metafilePagePredicate } from '../core/sync-metafile-pages.ts';
+
+/** The walk behind `walkMarkdownFiles`, in its order; yields after each directory it finishes. */
- export function* markdownWalk(dir: string, d: string, emit: (file: { path: string; relPath: string }) => void): Generator<void> {
++export function* markdownWalk(dir: string, d: string, emit: (file: { path: string; relPath: string }) => void,
++ metafilePages: MetafilePagesMode = DEFAULT_METAFILE_PAGES_MODE,
++ metafilePage: (path: string) => boolean = metafilePagePredicate(metafilePages, diskMetafileHeads(dir))): Generator<void> {
+ for (const entry of readdirSync(d)) {
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- d is the walk's own directory (the brain root or one of its subdirectories, never a symlink: lstat below) and entry is a directory entry read from it; moved unchanged from extract.ts walkMarkdownFiles
+ const full = join(d, entry);
+ try {
+ const st = lstatSync(full);
+ if (st.isDirectory()) {
+ // v0.37.7.0 #1169: pass parentDir so pruneDir can detect git
+ // submodule pointers (`.git` as a file inside the candidate).
+ if (!pruneDir(entry, d)) continue;
- yield* markdownWalk(dir, full, emit);
++ yield* markdownWalk(dir, full, emit, metafilePages, metafilePage);
+ } else if (entry.endsWith('.md') && !entry.startsWith('_')) {
+ const rel = relative(dir, full);
- if (!isSyncable(rel, { strategy: 'markdown' })) continue;
++ if (!isSyncable(rel, { strategy: 'markdown', metafilePage })) continue;
+ emit({ path: full, relPath: rel });
+ }
+ } catch { /* skip unreadable */ }
+ }
+ yield;
+}
+
+/** A source tree as the sync hooks read it: `walkMarkdownFiles` entries with their slugs, and `buildSlugPathIndex` of them. */
+export interface MarkdownTree { files: Array<{ path: string; relPath: string; slug: string }>; slugToPath: Map<string, string> }
+
+/**
+ * GBRA-133 2b.1/2b.3: `walkMarkdownFiles` plus `buildSlugPathIndex` for a sync, the same entries in the same order,
+ * yielding to the event loop after each directory, so a resident's commit-triggered sync never holds its event loop
+ * for the whole walk (about 0.75 s at 100k files). The sync hooks share one tree per run.
+ */
- export async function indexMarkdownTree(dir: string): Promise<MarkdownTree> {
++export async function indexMarkdownTree(dir: string, metafilePages: MetafilePagesMode = DEFAULT_METAFILE_PAGES_MODE): Promise<MarkdownTree> {
+ const tree: MarkdownTree = { files: [], slugToPath: new Map() };
+ const emit = (file: { path: string; relPath: string }) => {
+ const slug = pathToSlug(file.relPath);
+ tree.files.push({ ...file, slug });
+ indexSlugPath(tree.slugToPath, slug, file.relPath);
+ };
- for (const _ of markdownWalk(dir, dir, emit)) await new Promise<void>(resolve => setImmediate(resolve));
++ for (const _ of markdownWalk(dir, dir, emit, metafilePages)) await new Promise<void>(resolve => setImmediate(resolve));
+ return tree;
+}
+
+export function indexSlugPath(index: Map<string, string>, slug: string, relPath: string): void {
+ if (!index.has(slug) || relPath === `${slug}.md`) index.set(slug, relPath);
+}
+
+/** What link extraction reads a page type through: a whole-tree map (full `gbrain extract`) or the sync hook's endpoint lookup. */
+export type PageTypeLookup = Pick<ReadonlyMap<string, string>, 'get'>;
+
+/**
+ * GBRA-133 2b.1: the sync hook's page types, parsed from the files of the link endpoints its pages actually look up
+ * instead of from every file in the tree (`loadFsPageTypes`, which full `gbrain extract` keeps). `pass` runs the
+ * extraction against the lookup; a walked slug it asks for and has no type yet is recorded, its file parsed, and the
+ * pass repeated until one asks for nothing new (an answer can make extraction ask for more, e.g. a person target
+ * prompts the attendance candidates). Each answer is what `loadFsPageTypes` gives that slug: the parse under the
+ * active pack, `unknown` when the file cannot be read, and the last walked file on a slug collision. So the links
+ * match the whole-tree parse, held and never-imported targets included, and a pack page-type change applies at once.
+ */
+export async function withEndpointPageTypes<T>(repoPath: string, tree: MarkdownTree, pack: LinkExtractionPack | null,
+ pass: (pageTypes: PageTypeLookup) => Promise<T>): Promise<T> {
+ const { files, slugToPath } = tree;
+ const lastWalked = slugToPath.size === files.length ? null : new Map(files.map(file => [file.slug, file.relPath]));
+ const activePack = pack?.page_types ? { page_types: pack.page_types } : undefined;
+ const types = new Map<string, string>();
+ for (;;) {
+ const missing = new Set<string>();
+ const result = await pass({ get: (slug) => {
+ const type = types.get(slug);
+ if (type === undefined && slugToPath.has(slug)) missing.add(slug);
+ return type;
+ } });
+ if (!missing.size) return result;
+ for (const slug of missing) {
+ const relPath = lastWalked?.get(slug) ?? slugToPath.get(slug)!;
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- relPath is an entry of the walkMarkdownFiles(repoPath) walk the caller indexed, never caller input
+ try { types.set(slug, parseMarkdown(readFileSync(join(repoPath, relPath), 'utf-8'), relPath, { activePack }).type); }
+ catch { types.set(slug, 'unknown'); }
+ }
+ }
+}
diff --cc src/commands/extract.ts
index 350d96db86,68ecfccec7..6dc7267cbc
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@@ -76,8 -76,8 +76,8 @@@ import { managedPersistenceEnabled } fr
import { addProjectedTimelineBatch, addProjectedTimelineEntry } from '../core/trust/timeline-projection.ts';
import { createProgress } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
- import { pathToSlug, slugifyPath, slugifySegment } from '../core/sync.ts';
-import { pathToSlug, slugifyPath, slugifySegment, pruneDir, isSyncable, readMetafilePagesMode, DEFAULT_METAFILE_PAGES_MODE, type MetafilePagesMode } from '../core/sync.ts';
-import { diskMetafileHeads, metafilePagePredicate } from '../core/sync-metafile-pages.ts';
++import { pathToSlug, slugifyPath, slugifySegment, readMetafilePagesMode, DEFAULT_METAFILE_PAGES_MODE, type MetafilePagesMode } from '../core/sync.ts';
+import { indexMarkdownTree, indexSlugPath, markdownWalk, withEndpointPageTypes, type MarkdownTree, type PageTypeLookup } from './extract-tree.ts';
// v0.41.18.0: withRetry + isRetryableConnError + WithRetryOpts moved to
// src/core/retry.ts as the canonical primitive. Engine methods
// (addLinksBatch/addTimelineEntriesBatch/upsertChunks) now self-retry via
@@@ -296,8 -296,26 +296,8 @@@ export function walkMarkdownFiles(dir:
// (`.raw/`, README.md, etc.). Now: pruneDir skips entire vendor
// subtrees before recursion (saving IO), and isSyncable filters the emit
// set against the canonical markdown-strategy rules.
- const files: { path: string; relPath: string }[] = [], metafilePage = metafilePagePredicate(metafilePages, diskMetafileHeads(dir));
- function walk(d: string) {
- for (const entry of readdirSync(d)) {
- const full = join(d, entry);
- try {
- const st = lstatSync(full);
- if (st.isDirectory()) {
- // v0.37.7.0 #1169: pass parentDir so pruneDir can detect git
- // submodule pointers (`.git` as a file inside the candidate).
- if (!pruneDir(entry, d)) continue;
- walk(full);
- } else if (entry.endsWith('.md') && !entry.startsWith('_')) {
- const rel = relative(dir, full);
- if (!isSyncable(rel, { strategy: 'markdown', metafilePage })) continue;
- files.push({ path: full, relPath: rel });
- }
- } catch { /* skip unreadable */ }
- }
- }
- walk(dir);
+ const files: { path: string; relPath: string }[] = [];
- for (const _ of markdownWalk(dir, dir, file => files.push(file))) { /* one directory done */ }
++ for (const _ of markdownWalk(dir, dir, file => files.push(file), metafilePages)) { /* one directory done */ }
return files;
}
@@@ -1705,9 -1726,9 +1705,9 @@@ export async function extractLinksForSl
engine: BrainEngine,
repoPath: string,
slugs: string[],
- opts?: { sourceId?: string; includeFrontmatter?: boolean },
+ opts?: { sourceId?: string; includeFrontmatter?: boolean; tree?: MarkdownTree },
): Promise<ExtractForSlugsResult> {
- const tree = opts?.tree ?? await indexMarkdownTree(repoPath);
- const allFiles = walkMarkdownFiles(repoPath, await readMetafilePagesMode(engine));
++ const tree = opts?.tree ?? await indexMarkdownTree(repoPath, await readMetafilePagesMode(engine));
// Resolve each requested slug to its REAL path (see buildSlugPathIndex).
// The old reconstructed path missed any file whose name is not already a
// slug: `existsSync` was false, the page was skipped in silence, and the
@@@ -1790,7 -1800,7 +1790,7 @@@ export async function extractTimelineFo
): Promise<ExtractForSlugsResult> {
// Real-path resolution, same as extractLinksForSlugs. Both halves come off
// one `links_extracted_at` stamp, so both must agree on what was read.
- const slugToPath = (opts?.tree ?? await indexMarkdownTree(repoPath)).slugToPath;
- const slugToPath = buildSlugPathIndex(walkMarkdownFiles(repoPath));
++ const slugToPath = (opts?.tree ?? await indexMarkdownTree(repoPath, await readMetafilePagesMode(engine))).slugToPath;
// v0.18.0+ multi-source: source-qualify so timeline rows don't fan out
// across every source containing the slug (the addTimelineEntry's
// INSERT...SELECT-from-pages fan-out was Data R1's HIGH 2).
diff --cc src/commands/sync/finalize.ts
index 6a213a96e6,4106391001..99e8697563
--- a/src/commands/sync/finalize.ts
+++ b/src/commands/sync/finalize.ts
@@@ -8,9 -8,10 +8,10 @@@ import { chunkerStamp } from '../../cor
import { serr, slog } from '../../core/console-prefix.ts';
import type { BrainEngine } from '../../core/engine.ts';
import { clearOpCheckpoint } from '../../core/op-checkpoint.ts';
-import { commitTimeMs } from '../../core/source-health.ts';
+import { commitTimeMsAsync } from '../../core/source-health.ts';
import { writeSyncAnchor, writeChunkerVersion } from '../../core/sync-anchor.ts';
+ import { recordMetafilePagesApplied } from '../../core/sync-metafile-pages.ts';
-import { git } from '../../core/sync-git.ts';
+import { gitAsync } from '../../core/sync-git.ts';
import { buildPartialResult } from '../../core/sync-lock.ts';
import {
sanitizePathForDisplay,
@@@ -23,6 -24,6 +24,7 @@@
summarizeFailuresByCode,
isEmbeddingInfraCode,
formatFailedFileList,
++ readMetafilePagesMode,
} from '../../core/sync.ts';
import { shouldLogIngest } from '../import.ts';
import type { SyncResult } from '../sync.ts';
@@@ -66,9 -67,10 +68,10 @@@ export async function finishWithoutChan
// (#1794): advance to the PINNED target, and clear any checkpoint (a resume
// whose remaining range turned out to have no syncable changes still
// completes cleanly here).
- await writeSyncAnchor(engine, opts.sourceId, 'last_commit', pin, commitTimeMs(gitContextRoot, pin), gitContextRoot);
+ await writeSyncAnchor(engine, opts.sourceId, 'last_commit', pin, await commitTimeMsAsync(gitContextRoot, pin), gitContextRoot);
await engine.setConfig('sync.last_run', new Date().toISOString());
await writeChunkerVersion(engine, opts.sourceId, chunkerStamp());
+ if (!company) await recordMetafilePagesApplied(engine, opts.sourceId ?? DEFAULT_SOURCE_ID, metafilePages);
if (!company) { await clearOpCheckpoint(engine, ckpt.paths); await clearOpCheckpoint(engine, ckpt.target); }
// A commit whose ONLY changes are malformed filenames lands here with
// totalChanges === 0 — the anchor advances past those files forever, so
@@@ -556,13 -559,10 +560,13 @@@ async function extractAffectedPages(run
if (!opts.noExtract && totalChanges <= 100 && pagesAffected.length > 0) {
try {
const { extractLinksForSlugs, extractTimelineForSlugs, stampExtracted, slugsSafeToStamp } = await import('../extract.ts');
+ const { indexMarkdownTree } = await import('../extract-tree.ts');
// #774: pages' source_path is git-root-relative, so extract resolves
// files from gitContextRoot (== repoPath realpath when unscoped).
- const linksResult = await extractLinksForSlugs(engine, gitContextRoot, pagesAffected, extractOpts);
- const timelineResult = await extractTimelineForSlugs(engine, gitContextRoot, pagesAffected, extractOpts);
+ // GBRA-133 2b.1: one tree walk per run, shared by both hooks.
- const tree = await indexMarkdownTree(gitContextRoot);
++ const tree = await indexMarkdownTree(gitContextRoot, await readMetafilePagesMode(engine));
+ const linksResult = await extractLinksForSlugs(engine, gitContextRoot, pagesAffected, { ...extractOpts, tree });
+ const timelineResult = await extractTimelineForSlugs(engine, gitContextRoot, pagesAffected, { ...extractOpts, tree });
if (linksResult.created > 0 || timelineResult.created > 0) {
slog(` Extracted: ${linksResult.created} links, ${timelineResult.created} timeline entries`);
}
diff --cc src/core/sync-cost-gate.ts
index 26b7e54ed7,e878800746..878d07c165
--- a/src/core/sync-cost-gate.ts
+++ b/src/core/sync-cost-gate.ts
@@@ -234,7 -233,7 +235,7 @@@ export function estimateInlineNewTokens
chunker_version: string | null;
}>,
currentChunkerVersion: string,
- opts: { forceFullTree?: boolean; chunkerDriftWalks?: boolean; noPull?: boolean } = {},
- opts: { forceFullTree?: boolean; chunkerDriftWalks?: boolean; metafilePages?: MetafilePagesMode } = {},
++ opts: { forceFullTree?: boolean; chunkerDriftWalks?: boolean; noPull?: boolean; metafilePages?: MetafilePagesMode } = {},
): InlineEstimate {
let tokens = 0;
let changedSources = 0;
@@@ -554,8 -551,8 +555,9 @@@ export async function runInlineCostGate
// ── Inline path ───────────────────────────────────────────────
const inline = estimateInlineNewTokens(sources, chunkerStamp(), {
forceFullTree: ctx.includeGitignored === true,
+ noPull: ctx.noPull === true,
chunkerDriftWalks: full === true || !(await readManagedMode(engine).catch(() => false)),
+ metafilePages: await readMetafilePagesMode(engine),
});
// D7A: `--full` runs `performFullSync` → `runEmbedCore({stale:true})`, which
// sweeps the pre-existing stale backlog INLINE on top of the delta. Price it.