Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.60.16.0 fix(persistence): bound async git children so a lost exit cannot strand consumer shutdown (#5787)

Garry Tanbdc36d5a7e5a
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index f7987c25c5..7c1463dd55 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.60.15.0",
+ "version": "0.60.16.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index e4d12f4a4d..8cbf78e360 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.60.15.0",
+ "version": "0.60.16.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 3cc6a54190..e82668eb6b 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.60.15.0 -->
+<!-- gbrain-runbook-stamp: 0.60.16.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0c6fa299b0..5b8d0a5925 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,30 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.16.0] - 2026-09-30
+
+**Long-running brains stop getting stuck waiting on a `git` check that already finished.**
+
+Before GBrain publishes a page to your brain's git repo, it runs two quick `git` commands to confirm the repo is safe to write to. On the Bun versions GBrain runs on today, Bun can miss the signal that one of those commands has finished. GBrain then waited forever. The write queue stalled, and shutting down the owner process hung behind it. In our test suite this hit roughly one run in sixty under load and showed up as whole test files timing out after "killed 1 dangling process".
+
+Now every one of those `git` calls has its own deadline. If the command hasn't reported back in time, GBrain stops it and moves on, with the same "git unavailable" result a slow `git` already produced. The worst case is a 10 to 20 second delay instead of a hang.
+
+| Under load (16 parallel test workers) | Before | After |
+| --- | --- | --- |
+| Runs that hung | 4 of 250 | 0 of 320 |
+| Worst-case wait on a lost `git` exit | forever | 10 s (durability check), 20 s (page publish) |
+
+Nothing to configure and nothing to run after upgrading.
+
+### To take advantage of v0.60.16.0
+
+`gbrain upgrade` is all you need. There is no migration. To confirm, run `gbrain doctor`.
+
+### Itemized changes
+
+- `execFileBounded` in `src/core/brain-repo-durability.ts` settles from its own timer at the deadline or on abort and SIGKILLs the child, so a lost exit or pipe event (Bun 1.3.x, oven-sh/bun#30301) can no longer strand the caller. The durability probe (10 s) and the persistence effect `git` runner (20 s) use it; the staged topology clone's exit wait also returns once its deadline kill fires.
+- New `test/bounded-child-exec.test.ts` reproduces the lost exit event deterministically and pins deadline, abort, exit code and stdout behavior.
+
## [0.60.15.0] - 2026-09-30
**Import retries pick up edited files, contacts recover from expired sync tokens, and published skills work without extra tool annotations.** This release also filters machine-authored transcript entries and makes lock, push, and health checks report the right outcome.
diff --git a/VERSION b/VERSION
index 6f886a4f3d..95046d679b 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.60.15.0
+0.60.16.0
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.md
index 0e23af0447..d09b3e1717 100644
--- a/docs/architecture/key-files/files-and-sync-1.md
+++ b/docs/architecture/key-files/files-and-sync-1.md
@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/audit-week-file.ts` — single source of truth for ISO-week audit JSONL filename math. Exports `isoWeek(d)`, `isoWeekFilename(prefix, now?)`, `resolveAuditDir()` (honors `GBRAIN_AUDIT_DIR`). Year-boundary correctness pinned by tests at 2020-W53 (the 53-week year), 2025-W01 rolling in from 2024-12-30 (Monday), 2026-W01. Four call sites: `src/core/minions/handlers/shell-audit.ts`, `src/core/facts/phantom-audit.ts`, `src/core/audit-slug-fallback.ts`, `src/core/cycle/budget-meter.ts`. Each keeps its `compute<X>AuditFilename` thin wrapper.
-- `src/core/brain-repo-durability.ts` + `src/commands/sources-harden.ts` — brain-repo git durability. `hardenBrainRepo(opts)` makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked `.git/hooks/post-commit` auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active `core.hooksPath` dir and excluded via `.git/info/exclude` when that dir is tracked), a committed `scripts/brain-commit-push.sh` that refuses to exit 0 without a successful push or confirmation that the exact destination branch on origin contains the attempted commit and stages+commits BEFORE any pull so a dirty tree of modified pages (the write-through shape) can still be committed — the push-retry's rebase-on-reject handles a remote that advanced (hook + helper render from ONE bash push-retry template — DRY at the TS source, not by the hook sourcing a repo-controlled script), durability rules patched into the active resolver file (`findResolverFile` → RESOLVER.md > AGENTS.md; taxonomy rendered from the bundled `_brain-filing-rules.json`), a minimal DB-free pull cron (launchd/crontab running `gbrain sources pull --path <dir>` so it never opens the PGLite single-writer lock), and a push-probe verify (no heartbeat commit). Credential is REPO-scoped (`acceptPat` from `--pat-file`/`GBRAIN_GITHUB_PAT`, warns on loose perms; reuses an existing repo-local `credential.helper`, else a `0600` store wired via repo-local config); the token is redacted everywhere via `redactSecretsInText` and never enters the repo, remote URL, logs, or `DurabilityReport`. `unhardenBrainRepo` removes the cron/hook/credential wiring (ownership-fingerprinted); `sources remove` runs it only AFTER the source row's DELETE commits (a refused or raced delete leaves the scaffolding intact; post-commit teardown failure is loud but non-fatal). CLI: `gbrain sources harden <id|--all>` / `pull <id>|--path <dir>` / `unharden <id>`; auto-harden fires on `sources add --url ... --pat-file` for managed clones (`--no-harden` opts out). `sources pull --path` is dispatched in `src/cli.ts` BEFORE `connectEngine` so the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP. `isDurabilityHardened(repoPath)` (the durability hook banner is installed) and `commitWriteThroughFile(repoPath, absPath, slug, action = 'write-through')` are the shared helpers every write-through sink (page write/delete, facts fence, timeline, lint --fix) uses to best-effort commit ONE file path-limited on a hardened repo — never throws, false on any failure; `action` only labels the subject (`gbrain: <action> <slug>`; `'delete write-through'` for removals). Tests: `test/brain-repo-durability.serial.test.ts`, `test/git-remote-durable.serial.test.ts`, `test/brain-durability-hook.serial.test.ts`, `test/durability-cron.test.ts`. `brain_remote_contains_commit` checks the exact `refs/heads/<branch>` at every effective push URL, fetches each advertised tip without writing `FETCH_HEAD`, and proves ancestry of the captured commit; branch existence, a different fetch destination, or a stale tracking ref is not enough. Probe diagnostics are suppressed, ambiguous URL resolution fails closed, and recovery is skipped if local HEAD has moved since the failed push. This check runs after a rejected push and after retry failure, logging `ok-already-on-remote` on confirmation; `getLastPushOutcome` recognizes it as success. Existing unmanaged installations must rerun `gbrain sources harden <source-id>` to refresh both the local hook and committed helper; upgrading the CLI alone does not rewrite those scripts. Managed worktrees retain the persistence outbox as their Git writer; generated legacy helpers refuse to bypass it. `GBRAIN_PUSH_LOCK_WAIT_SECONDS` (default 30, env-only) tunes the `flock -w` wait in the rendered push-retry block that both the committed helper and the local hook share; on lock timeout the synchronous helper returns rc 1 (fail-loud, no push was attempted) while the detached post-commit hook returns rc 0 (another holder is already pushing — the designed coalescing outcome).
+- `src/core/brain-repo-durability.ts` + `src/commands/sources-harden.ts` — brain-repo git durability. `hardenBrainRepo(opts)` makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked `.git/hooks/post-commit` auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active `core.hooksPath` dir and excluded via `.git/info/exclude` when that dir is tracked), a committed `scripts/brain-commit-push.sh` that refuses to exit 0 without a successful push or confirmation that the exact destination branch on origin contains the attempted commit and stages+commits BEFORE any pull so a dirty tree of modified pages (the write-through shape) can still be committed — the push-retry's rebase-on-reject handles a remote that advanced (hook + helper render from ONE bash push-retry template — DRY at the TS source, not by the hook sourcing a repo-controlled script), durability rules patched into the active resolver file (`findResolverFile` → RESOLVER.md > AGENTS.md; taxonomy rendered from the bundled `_brain-filing-rules.json`), a minimal DB-free pull cron (launchd/crontab running `gbrain sources pull --path <dir>` so it never opens the PGLite single-writer lock), and a push-probe verify (no heartbeat commit). Credential is REPO-scoped (`acceptPat` from `--pat-file`/`GBRAIN_GITHUB_PAT`, warns on loose perms; reuses an existing repo-local `credential.helper`, else a `0600` store wired via repo-local config); the token is redacted everywhere via `redactSecretsInText` and never enters the repo, remote URL, logs, or `DurabilityReport`. `unhardenBrainRepo` removes the cron/hook/credential wiring (ownership-fingerprinted); `sources remove` runs it only AFTER the source row's DELETE commits (a refused or raced delete leaves the scaffolding intact; post-commit teardown failure is loud but non-fatal). CLI: `gbrain sources harden <id|--all>` / `pull <id>|--path <dir>` / `unharden <id>`; auto-harden fires on `sources add --url ... --pat-file` for managed clones (`--no-harden` opts out). `sources pull --path` is dispatched in `src/cli.ts` BEFORE `connectEngine` so the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP. `isDurabilityHardened(repoPath)` (the durability hook banner is installed) and `commitWriteThroughFile(repoPath, absPath, slug, action = 'write-through')` are the shared helpers every write-through sink (page write/delete, facts fence, timeline, lint --fix) uses to best-effort commit ONE file path-limited on a hardened repo — never throws, false on any failure; `action` only labels the subject (`gbrain: <action> <slug>`; `'delete write-through'` for removals). `isDurabilityHardenedAsync(repoPath)` is the non-blocking probe long-running persistence owners use; it and the persistence Git runner (`effect-git.ts`) spawn through `execFileBounded`, which settles at its deadline or on abort from its own timer because Bun 1.3.x can drop a child's exit and pipe events when bun:test `expect().resolves/.rejects` re-enters the event loop (oven-sh/bun#30301); an unbounded wait there stranded `disposePersistenceConsumer` and hung every later test in the file (test: `test/bounded-child-exec.test.ts`). Tests: `test/brain-repo-durability.serial.test.ts`, `test/git-remote-durable.serial.test.ts`, `test/brain-durability-hook.serial.test.ts`, `test/durability-cron.test.ts`. `brain_remote_contains_commit` checks the exact `refs/heads/<branch>` at every effective push URL, fetches each advertised tip without writing `FETCH_HEAD`, and proves ancestry of the captured commit; branch existence, a different fetch destination, or a stale tracking ref is not enough. Probe diagnostics are suppressed, ambiguous URL resolution fails closed, and recovery is skipped if local HEAD has moved since the failed push. This check runs after a rejected push and after retry failure, logging `ok-already-on-remote` on confirmation; `getLastPushOutcome` recognizes it as success. Existing unmanaged installations must rerun `gbrain sources harden <source-id>` to refresh both the local hook and committed helper; upgrading the CLI alone does not rewrite those scripts. Managed worktrees retain the persistence outbox as their Git writer; generated legacy helpers refuse to bypass it. `GBRAIN_PUSH_LOCK_WAIT_SECONDS` (default 30, env-only) tunes the `flock -w` wait in the rendered push-retry block that both the committed helper and the local hook share; on lock timeout the synchronous helper returns rc 1 (fail-loud, no push was attempted) while the detached post-commit hook returns rc 0 (another holder is already pushing — the designed coalescing outcome).
- `src/core/content-sanity-literals.ts` — operator literal-substring loader. Reads `~/.gbrain/junk-substrings.txt`, one literal per non-comment non-blank line; optional `# name=<id>` header pairs an identifier with the following literal so audit JSONL groups by site (`linkedin_auth_wall`, `reddit_blocked`, etc.). Fail-soft on ENOENT (missing file = empty array). Loaded on every ingest. Deliberately literal substrings (NOT regex) to defeat ReDoS. Pinned by `test/content-sanity-literals.test.ts`.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 36046f6b43..98855f5e80 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.60.15.0",
+ "version": "0.60.16.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"kind": "context-engine",
diff --git a/package.json b/package.json
index 9b6eb19583..3e459c3f15 100644
--- a/package.json
+++ b/package.json
@@ -204,7 +204,7 @@
"bun": ">=1.3.11"
},
"license": "MIT",
- "version": "0.60.15.0",
+ "version": "0.60.16.0",
"overrides": {
"@ai-sdk/provider-utils": "4.0.33",
"@hono/node-server": "^2.0.5",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index 2116ca6933..5aed54dd96 100644
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.60.15.0",
+ "version": "0.60.16.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index a14603d9c8..62d1e8e5ae 100644
--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.60.15.0",
+ "version": "0.60.16.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index 672e888e3d..50a062d256 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.60.15.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.60.16.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 6d3ad0fec9..d2aac707c4 100644
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.60.15.0",
+ "version": "0.60.16.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index 20f78e9484..7c0bd83cb6 100644
--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.60.15.0",
+ "version": "0.60.16.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index 2fc5ec4cea..3079b91f52 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.60.15.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.60.16.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --git a/plugin/README.md b/plugin/README.md
index 3f4f5c4617..e5eebcb71e 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.60.15.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.60.16.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.ts
index ef5ebe578c..33cd9638d7 100644
--- a/src/core/brain-repo-durability.ts
+++ b/src/core/brain-repo-durability.ts
@@ -33,7 +33,7 @@ import {
existsSync, readFileSync, writeFileSync, mkdirSync, chmodSync, rmSync, statSync, renameSync,
} from 'fs';
import { join, dirname, relative, isAbsolute } from 'path';
-import { execFile, execFileSync, execSync } from 'child_process';
+import { execFile, execFileSync, execSync, type ExecFileException } from 'child_process';
import {
GIT_ENV, GIT_ENV_AUTH, divergenceSafePull, detectDefaultBranch, pushProbe,
type PullOutcome, type PushProbeResult,
@@ -474,14 +474,50 @@ export function isDurabilityHardened(repoPath: string): boolean {
}
}
-/** A git probe that does not block the event loop; a failed probe reads as ''. */
-function gitOutput(repoPath: string, args: string[]): Promise<string> {
+export interface BoundedExecOptions {
+ timeout: number;
+ env?: NodeJS.ProcessEnv;
+ maxBuffer?: number;
+ signal?: AbortSignal;
+}
+
+/**
+ * `execFile` that settles within `timeout` or on abort even when the runtime
+ * never delivers the child's exit or pipe close. Bun through 1.3.x drops
+ * one-shot pidfd and pipe events when a callback re-enters the event loop
+ * (bun:test `expect().resolves/.rejects`, oven-sh/bun#30301): execFile's
+ * callback and its own `timeout` then never fire and the child stays a zombie,
+ * so the deadline and abort are enforced with our own timer.
+ */
+export function execFileBounded(file: string, args: string[], options: BoundedExecOptions): Promise<{ error: ExecFileException | null; stdout: string }> {
+ const { timeout, signal, ...rest } = options;
return new Promise(resolve => {
- execFile('git', ['-C', repoPath, ...args], { encoding: 'utf8', timeout: 10_000, env: { ...process.env, ...GIT_ENV } },
- (error, stdout) => resolve(error ? '' : stdout.trim()));
+ let settled = false;
+ const finish = (error: ExecFileException | null, stdout: string) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ signal?.removeEventListener('abort', onAbort);
+ resolve({ error, stdout });
+ };
+ const child = execFile(file, args, { ...rest, encoding: 'utf8' }, (error, stdout) => finish(error, stdout));
+ const stop = (message: string, code: string) => {
+ child.kill('SIGKILL');
+ finish(Object.assign(new Error(message), { code, killed: true, signal: 'SIGKILL' as const }), '');
+ };
+ const timer = setTimeout(() => stop(`${file} did not finish within ${timeout}ms`, 'ETIMEDOUT'), timeout);
+ const onAbort = () => stop(`${file} was aborted`, 'ABORT_ERR');
+ if (signal?.aborted) onAbort();
+ else signal?.addEventListener('abort', onAbort, { once: true });
});
}
+/** A git probe that does not block the event loop; a failed probe reads as ''. */
+async function gitOutput(repoPath: string, args: string[]): Promise<string> {
+ const { error, stdout } = await execFileBounded('git', ['-C', repoPath, ...args], { timeout: 10_000, env: { ...process.env, ...GIT_ENV } });
+ return error ? '' : stdout.trim();
+}
+
/**
* {@link isDurabilityHardened} for long-running owners: the same two git
* probes, run concurrently as child processes the event loop does not wait on.
diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.ts
index 620bf6907f..ef79cbd5d0 100644
--- a/src/core/persistence/effect-git.ts
+++ b/src/core/persistence/effect-git.ts
@@ -1,22 +1,18 @@
-import { execFile } from 'node:child_process';
import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import { dirname, join, relative, resolve as resolvePath, sep } from 'node:path';
-import { isDurabilityHardenedAsync } from '../brain-repo-durability.ts';
+import { execFileBounded, isDurabilityHardenedAsync } from '../brain-repo-durability.ts';
import { OperationError } from '../ops/contract.ts';
import { persistenceHome } from './identity.ts';
import { nativeFileTarget } from './native-file-target.ts';
-function git(root: string, hooks: string, args: string[], signal?: AbortSignal): Promise<{ stdout: string; code: number }> {
- return new Promise((resolve, reject) => {
- execFile('git', ['--literal-pathspecs', '-C', root, '-c', `core.hooksPath=${hooks}`, '-c', 'commit.gpgsign=false', ...args], {
- encoding: 'utf8', timeout: 20_000, maxBuffer: 1024 * 1024, signal,
- env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never',
- GIT_GLOB_PATHSPECS: '0', GIT_NOGLOB_PATHSPECS: '0', GIT_ICASE_PATHSPECS: '0' },
- }, (error, stdout) => {
- if (error && (error.killed || typeof error.code !== 'number')) reject(new OperationError('git_unavailable', 'Git execution did not finish within its bounded attempt.'));
- else resolve({ stdout, code: error?.code as number ?? 0 });
- });
+async function git(root: string, hooks: string, args: string[], signal?: AbortSignal): Promise<{ stdout: string; code: number }> {
+ const { error, stdout } = await execFileBounded('git', ['--literal-pathspecs', '-C', root, '-c', `core.hooksPath=${hooks}`, '-c', 'commit.gpgsign=false', ...args], {
+ timeout: 20_000, maxBuffer: 1024 * 1024, signal,
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never',
+ GIT_GLOB_PATHSPECS: '0', GIT_NOGLOB_PATHSPECS: '0', GIT_ICASE_PATHSPECS: '0' },
});
+ if (error && (error.killed || typeof error.code !== 'number')) throw new OperationError('git_unavailable', 'Git execution did not finish within its bounded attempt.');
+ return { stdout, code: error?.code as number ?? 0 };
}
type GitOutcome = { git: string; reason?: string; push?: string };
diff --git a/src/core/persistence/topology-filesystem.ts b/src/core/persistence/topology-filesystem.ts
index 96c7c8e45c..aafc891761 100644
--- a/src/core/persistence/topology-filesystem.ts
+++ b/src/core/persistence/topology-filesystem.ts
@@ -54,7 +54,7 @@ export async function cloneTopologyCheckout(url:string,destination:string,maxByt
const hooks=mkdtempSync(join(base,'clone-'));
const child=spawn('git',[...durableSsrfFlags(),'-c',`core.hooksPath=${hooks}`, 'clone',...GIT_SSRF_SUBCOMMAND_FLAGS,'--depth=1','--',url,destination],
{stdio:['ignore','ignore','ignore'],detached:process.platform!=='win32',env:{...process.env,...GIT_ENV}});
- let failure:unknown,check:Promise<void>|undefined,stopping:Promise<void>|undefined;
+ let failure:unknown,check:Promise<void>|undefined,stopping:Promise<void>|undefined,abandon=()=>{};
const stop=(error:unknown)=>{
failure??=error;
if(stopping)return;
@@ -67,13 +67,14 @@ export async function cloneTopologyCheckout(url:string,destination:string,maxByt
killer.once('exit',()=>resolve());killer.once('error',()=>{child.kill('SIGKILL');resolve();});
}else{try{process.kill(-child.pid,'SIGKILL');}catch{}resolve();}
});
+ abandon();
};
const monitor=setInterval(()=>{
if(!check)check=topologyDirectoryBytes(destination,maxBytes).then(()=>{}).catch(stop).finally(()=>{check=undefined;});
},50);
const timer=setTimeout(()=>stop(new OperationError('storage_error','The staged clone exceeded its execution deadline.')),timeoutMs);
try{
- const code=await new Promise<number|null>((resolve,reject)=>{child.once('error',reject);child.once('exit',resolve);});
+ const code=await new Promise<number|null>((resolve,reject)=>{child.once('error',reject);child.once('exit',resolve);abandon=()=>resolve(null);});
await check;await stopping;
if(failure)throw failure;
if(code!==0)throw new OperationError('storage_error','The reserved source clone failed.','Inspect the configured remote and owner Git credentials.');
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index 6fe4651331..f21001ffb1 100644
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@ -1,6 +1,6 @@
# gbrain agent workspace — template
-<!-- gbrain-template-stamp: 0.60.15.0 -->
+<!-- gbrain-template-stamp: 0.60.16.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/bounded-child-exec.test.ts b/test/bounded-child-exec.test.ts
new file mode 100644
index 0000000000..47b5a2f84e
--- /dev/null
+++ b/test/bounded-child-exec.test.ts
@@ -0,0 +1,66 @@
+import { afterAll, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { execFileBounded, isDurabilityHardenedAsync } from '../src/core/brain-repo-durability.ts';
+
+const dir = mkdtempSync(join(tmpdir(), 'gbrain-bounded-exec-'));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+/**
+ * Starts short-lived children whose first exit callback re-enters the event
+ * loop the way bun:test `expect().resolves/.rejects` does. On Bun 1.3.x that
+ * drops the other exit and pipe events of the same poll batch
+ * (oven-sh/bun#30301), which is how managed-maintenance, persistence-reconcile
+ * and google-attachments hung behind a persistence consumer's git probe.
+ */
+function nestedTickDuring<T>(work: () => Promise<T>[]): Promise<T[]> {
+ let nested = false;
+ for (let i = 0; i < 20; i++) {
+ Bun.spawn(['true'], { stdio: ['ignore', 'ignore', 'ignore'], onExit() {
+ if (nested) return;
+ nested = true;
+ void expect(Bun.sleep(1)).resolves.toBeUndefined();
+ } });
+ }
+ return Promise.all(work());
+}
+
+function within<T>(ms: number, promise: Promise<T>): Promise<T | 'unsettled'> {
+ return Promise.race([promise, Bun.sleep(ms).then(() => 'unsettled' as const)]);
+}
+
+test('bounded execution settles by its deadline when the runtime drops child events', async () => {
+ const outcomes = await within(5000, nestedTickDuring(() => Array.from({ length: 20 },
+ () => execFileBounded('git', ['-C', dir, 'rev-parse', '--git-path', 'hooks'], { timeout: 1500 }))));
+ expect(outcomes).not.toBe('unsettled');
+ for (const { error } of outcomes as Awaited<ReturnType<typeof execFileBounded>>[]) {
+ if (error?.killed) expect(error.code).toBe('ETIMEDOUT');
+ }
+});
+
+test('the persistence durability probe settles when the runtime drops child events', async () => {
+ const probes = await within(20_000, nestedTickDuring(() => Array.from({ length: 20 }, () => isDurabilityHardenedAsync(dir))));
+ expect(probes).toEqual(Array(20).fill(false));
+}, 30_000);
+
+test('bounded execution keeps execFile exit codes and stdout', async () => {
+ const { error, stdout } = await execFileBounded('sh', ['-c', 'printf example; exit 3'], { timeout: 10_000 });
+ expect(stdout).toBe('example');
+ expect(error?.code).toBe(3);
+ expect(error?.killed).toBeFalsy();
+ expect(await execFileBounded('sh', ['-c', 'printf ok'], { timeout: 10_000 })).toEqual({ error: null, stdout: 'ok' });
+});
+
+test('bounded execution stops a running child on abort and at its deadline', async () => {
+ const abort = new AbortController();
+ const started = performance.now();
+ const aborted = execFileBounded('sleep', ['30'], { timeout: 60_000, signal: abort.signal });
+ setTimeout(() => abort.abort(), 50);
+ expect((await aborted).error).toMatchObject({ code: 'ABORT_ERR', killed: true });
+ expect((await execFileBounded('sleep', ['30'], { timeout: 100 })).error).toMatchObject({ code: 'ETIMEDOUT', killed: true });
+ expect(performance.now() - started).toBeLessThan(5000);
+ const preAborted = new AbortController();
+ preAborted.abort();
+ expect((await execFileBounded('sleep', ['30'], { timeout: 60_000, signal: preAborted.signal })).error).toMatchObject({ code: 'ABORT_ERR' });
+});