* v0.50.2.0 fix(security): critical+high advisory wave — DCR scope ceiling, cwd .env quarantine, format-based transcript redaction, consent pins Closes the critical- and high-severity items from six privately reported advisories (GHSA-548g-mhxp-p66h, GHSA-42r8-3jfh-82vr, GHSA-62gp-q5hj-r9mv, GHSA-q374-hhfh-f79x, GHSA-ghfq-gqmq-7fm4, GHSA-q5p9-qr3g-6v38). Squashed to a single commit so no intermediate revision carries a test-fixture credential shape through the gitleaks range gate. Cluster A — OAuth consent gate (GHSA-548g / -42r8 / -62gp). The v0.50.0.0 owner-approval flow is pinned end to end against a real `serve --http --enable-dcr` process and in-process: anonymous /authorize mints no code, a forged code is rejected at /token, revoked clients are refused at grants.begin, and OAuthGrants.begin() now caps awaiting-decision requests per client_id. Cluster B — DCR scope ceiling (GHSA-q374 defect B, GHSA-548g fix #2). registerClient rejects admin/sources_admin/users_admin/agent with HTTP 400 via scope.ts:dcrScopeViolation; client_credentials DCR clients are read-only. Remote sources_remove is source-fenced like sources_status. doctor's oauth_client_scope_health flags privileged self-registered clients. Cluster C — format-based secret detection (GHSA-ghfq). secret-scan.ts gains jwt/aws(AKIA|ASIA)/google/stripe/sendgrid/twilio/supabase/gitlab/npm/hf plus bearer and db_url_credentials catch-alls; the transcripts lane opts into the digit-gated high-entropy rule; getRawData follows the page soft-delete on both engines; delete_page --purge (local-CLI only) hard-removes a leaked page. Cluster D — cwd .env quarantine (GHSA-q5p9). New env-trust.ts + cli-preflight.ts drop a fixed list of code-loading / exec-target / posture-widening GBRAIN_* variables when a working-directory .env assigns them (key-presence, since Bun expands ${VAR}); the guardrails loader refuses cwd-relative and cwd-.env specs. Release artifacts: VERSION/package.json/three plugin manifests bumped to 0.50.2.0; CHANGELOG entry (reporters credited); SECURITY.md, README, DEPLOY.md, CHATGPT.md, guardrails.md, ENGINES.md and KEY_FILES updated; template + plugin trees, skills.lock, flag registry and llms bundle regenerated; module-size ceilings adjusted with per-row reasons; TODOS follow-ups filed. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix: pre-landing review fixes (v0.50.2.0 security wave) Review cycle 1 of the ship: 6 specialists + red team + coverage audit. Security / red team: - env-trust: parse .env with Bun's line grammar (bare CR terminates a line; BOM/U+2028 cannot hide an assignment); protect the loader / git / node / proxy / AI-CLI variable families a checkout could plant for the programs gbrain spawns; cli-preflight re-execs gbrain once with the sanitized environment so git, the agent CLI and workers inherit the clean view; cwd == ~/.gbrain no longer quarantines the operator's own .env. - guardrails: GBRAIN_GUARDRAILS_MODULE accepts only absolute or ~/ paths (a package name resolves from the cwd's node_modules). - secret-scan: bounded db_url_credentials quantifiers + per-pattern prechecks (linear on long lines), windowed previews that redact every sibling span, single-pass longest-first replacement. - TODOS: follow-up entries reworded to the functional level. API contract / maintainability: - delete_page purge: remote callers get permission_denied; a purged response always carries write_through; get_raw_data description states the soft-delete follow; includeDeleted narrowed to the getRawData signature; client_credentials gate evaluated before the DCR ceiling; doctor privileged set derived from the scope registry; sources_remove / sources_status share assertSourceInCallerScope; shell-job opt-in reaches --job-isolation process children as --allow-shell-jobs; stale help copy. - transcripts ingest: raw-metadata compare uses canonical JSON (JSONB key order made every healthy re-run rewrite unchanged rows). Coverage audit: 5 new test files + 4 extended (25 cases), plus RED-verified pins for every fix above. Docs/KEY_FILES/CHANGELOG/SECURITY updated; llms bundle, flag registry, tool catalog, structural suites regenerated; module-size rows adjusted with reasons. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix: pre-landing review fixes, cycle 2 (v0.50.2.0 security wave) Re-exec redesign (security + red team + adversarial findings): - cli-preflight re-runs gbrain from an empty temporary directory so the sanitized child never reloads the hostile .env: dropped keys are absent, never carried as '' (git and the dynamic loader presence-check GIT_SSL_NO_VERIFY / LD_TRACE_LOADED_OBJECTS; '' broke git ident). - The re-run marker is JSON {cwd, neutral} honoured only when the process provably started in that empty directory — a marker planted via a cwd .env is ignored (the ppid-keyed marker was forgeable under systemd/docker). - SIGINT is delivered by the tty once (wrapper no longer forwards it); SIGTERM/SIGHUP forwarded; execArgv preserved under the dev runtime. - Protected families widened: XDG config roots (git reads $XDG_CONFIG_HOME/git/config as global config), GNUPGHOME, TLS trust stores, EDITOR/VISUAL/PAGER, every provider endpoint variable, the GBRAIN_REMOTE_* / GBRAIN_DIRECT_DATABASE_URL redirects, and the marker. - cwd dotenv parsed once per start; jobs start uses the same '1' literal. secret-scan (cycle-2 findings): - db_url_credentials password class only stops at whitespace, '@' and string delimiters again (unescaped / { } < > | ^ ` \ passwords redact); BEARER uppercase recognized; jwt / high_entropy_assignment / PEM body bounded (adversarial '-eyJ' / '_token' runs and header-only PEM texts were quadratic); incremental PEM line cursor; redactFindings rebuilds the text by span-splice in one pass (was O(unique values x text)). Contract / docs: - delete_page purge responses carry a residuals hint (git history, exports, compiled context, slug-keyed derived rows); CHANGELOG states a single truth for GBRAIN_GUARDRAILS_MODULE (absolute or ~/ only, listed under Changed with a migration note); SECURITY.md / KEY_FILES / docs guides / minion-orchestrator skill describe the new mechanism and the --allow-shell-jobs opt-in; TODOS follow-ups filed; test-reads-source marker on the hook spawn-shape test; new PEM fixtures fragmented. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix: pre-landing review fixes, cycle 3 (v0.50.2.0 security wave) - Compiled binaries: every `bun build --compile` invocation passes `--no-compile-autoload-bunfig`; new `scripts/check-compile-autoload.sh` guard (self-tested, in verify CHECKS) keeps it that way. - cwd `.env` quarantine: `GBRAIN_DATABASE_URL`, `GBRAIN_OAUTH_RELAY_URL`, OpenSSL config/engine/module loaders, temp roots and HOME/USERPROFILE join the protected set; the neutral hop dir is realpath'd; signal handlers are installed before the spawn; non-tty wrappers forward SIGINT once; guardrails fail closed when a dropped GBRAIN_GUARDRAILS_MODULE had a value. - secret-scan: PEM header-line cursor is O(text) on newline-free tails; bounded bearer echo pass redacts bare re-occurrences of claimed tokens. - transcripts ingest: raw-metadata probe reads active rows only. - Tests: afterAll cleanup, execArgv/SIGHUP/chdir-back pins, pty SIGINT, perf pins; docs/CHANGELOG/TODOS/KEY_FILES/SECURITY updated; llms + skills.lock + plugin trees regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix: pre-landing review fixes, cycle 4 (v0.50.2.0 security wave) Cross-model adversarial pass (Codex) + Claude verifier findings: - env-trust: shell-startup / interpreter-home family (BASH_ENV, SHELLOPTS, PS4, BASHOPTS, PROMPT_COMMAND, ZDOTDIR, PYTHONHOME, PERLLIB, GCONV_PATH, BASH_FUNC_* prefix) protected; sh `ENV` deliberately excluded. - cli-preflight: config-dir exemption refused when the cwd .env assigns GBRAIN_HOME/HOME/USERPROFILE; wrapper removes pre-existing signal listeners so its exit is always the child's; SIGINT forwarded only without a controlling terminal (/dev/tty probe); a dropped planted HOME is restored from the passwd home; script-mode runs warn once when the cwd bunfig.toml declares a top-level preload. - secret-scan: overlapping matches redact the UNION of matched spans; echo pass covers bearer + high-entropy values (64 unique, <=512 chars) via per-value sweeps over unclaimed gaps only; planRedaction/ applyRedaction share a session-wide echo dictionary in transcripts render. - sources_remove keys on write authority (assertSourceInCallerWriteScope); federated read grants confer no removal right. - delete_page --purge retries the tombstone's file removal and fails closed (storage_error) while the file remains. - Docs: SECURITY.md quarantine example no longer uses the one key that refuses instead of re-running; KEY_FILES/CHANGELOG/TODOS updated; llms. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * v0.50.3.0 chore: re-bump the security wave to 0.50.3.0 (master claimed 0.50.2.0 in #5122) Five-file lockstep + BOOTSTRAP stamp + CHANGELOG header/date + TODOS follow-up refs + bun.lock, template repo and plugin trees regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix: pre-landing review fixes, cycle 5 — Codex structured-review gate (v0.50.3.0 security wave) - cli-preflight: hop marker carries the wrapper pid; a verified re-run arms an unref'd 1 s watchdog and exits 137 (removing its neutral dir) when the wrapper is force-killed, so supervisor restarts never orphan a worker; relative path-bearing runtime flags (--preload/-r/--require/--import, --config/-c, --env-file, --tsconfig-override) are resolved against the original cwd before the hop. - secret-scan: echo pass is a streaming leftmost-longest merge with O(values) retained state (Codex repro: 64 short claims + 2 MiB repetitive tail went from +233 MiB RSS / 1.4 s to +16 MiB / 140 ms); repetitive tails are now covered wall-to-wall. - Docs: KEY_FILES, SECURITY.md, CHANGELOG; llms regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs: update project documentation for v0.50.3.0 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(ci): green the three failing checks on the v0.50.3.0 wave - semgrep: six `nosemgrep` suppressions with justifications for the path-join/resolve and non-literal-RegExp taint heuristics on operator- controlled cwd/flag paths and compile-time pattern sources (no behaviour change). - test (2): the two pty Ctrl-C pins ran the wrapper through `script -c`'s intermediate /bin/sh; on ubuntu-latest that is dash, which re-raises the pty's SIGINT on itself after the child exits (130) instead of relaying the child's 42. The pty command now `exec`s the wrapper so no shell stays in the foreground group; documented in a `ptyCommand` helper. - Selected E2E: with --enable-dcr, OAuth discovery now advertises exactly the self-registration ceiling (`read write`) via `scopesSupportedForDiscovery`, so a connector that copies `scopes_supported` into /register succeeds (master's #5122 pin); without DCR the full operator list minus `agent` is unchanged. Sibling e2e assertions that expected privileged scopes on the DCR-enabled server updated; unit + PGLite e2e pins added; docs/TODOS/CHANGELOG/KEY_FILES updated; llms regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * v0.50.5.0 chore: re-bump the security wave to 0.50.5.0 (master claimed 0.50.4.0 in #5131) Five-file lockstep + BOOTSTRAP stamp + CHANGELOG header + TODOS follow-up refs + bun.lock, template repo and plugin trees regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
11 KiB
The Manifest Pattern — Durable State for Mass Ingestion
The state substrate for bulk-ingestion. Read this before Phase 2 (ACCESS) of any pipeline build, and at the start of ANY session that touches a large in-flight ingest.
Battle-tested corpus shapes this pattern has carried (anonymized): an audio lecture library (~650 files, transcribe → curate pipeline), an email takeout (~400K messages, high-parallelism worker fan-out), a personal file archive (~2,700 documents), and a messaging-history export (~6,500 threads).
When to use
Any job where you process a large, enumerable set of source items in stages and need to know — at any moment, after any crash, across any number of subagents/workers — exactly what's done, what's in flight, and what's left.
If the set is >~20 items OR the job spans multiple sessions OR multiple workers/subagents touch it: build the manifest FIRST, before processing anything.
The two-file model (non-negotiable)
projects/<pipeline-name>/manifest.json <- SOURCE OF TRUTH. Machine-updatable. Idempotent.
projects/<pipeline-name>/MANIFEST.md <- RENDERED human view. Generated FROM json. Never hand-edited.
Why split: the JSON is what workers read/write programmatically (status updates, checkpoints) — editing markdown by hand would corrupt state and lose idempotency. The MD exists so the user (and you, at a glance) can see progress, per-group rollups, and per-item status without parsing JSON. Regenerate the MD from JSON on every state change, or on demand. They must never disagree.
manifest.json schema
Top-level: separate the item list, the rollup, and the run history.
{
"version": 1,
"project": "lecture-library-curation",
"source": "object-store:archive-bucket/lectures/",
"updated": "2026-08-11T17:35:59Z",
"pipeline": ["pending", "transcribed", "curated"],
"summary": {
"total": 650, "curated": 51, "transcribed": 2, "pending": 597,
"total_pages": 212, "total_gb": 5.1
},
"by_group": {
"collection-01": {"total": 7, "curated": 7, "transcribed": 0, "pending": 0, "pages": 36}
},
"items": [
{
"id": "collection-01/lecture-01-01.mp3",
"group": "collection-01",
"basename": "lecture-01-01.mp3",
"size_mb": 10.1,
"status": "curated",
"outputs": {
"transcript": "media/audio/lectures/transcripts/collection-01/lecture-01-01.md",
"pages": 3
},
"checksum": null,
"notes": null
}
],
"runs": [
{"timestamp": "2026-08-11T14:00Z", "stage": "transcribe", "items_processed": 15, "worker": "chunkA", "outcome": "ok"}
]
}
Field rules:
id— stable, unique, derived from the source path/key (NOT a row index; indexes shift). For files: the source-relative path. For emails: a thread hash. For posts: the post id. This is the same key as the pipeline's dedup key (SKILL.md Phase 1d).status— one value frompipeline. The pipeline array defines the legal stage order so tools can compute "next stage" generically.outputs— where the produced artifact(s) live + counts. Presence of an output is how status is VERIFIED, not asserted.group— the natural partition (collection / folder / era / tier) for rollups and worker chunking.runs— append-only history; each worker/stage execution logs what it did. This is your audit trail and your "did the subagent actually do it" check.
Build the manifest from GROUND TRUTH (never from memory)
The #1 failure mode: declaring an archive "done" by looking at the OUTPUT folder instead of re-scanning the SOURCE. (One production run called a corpus "exhausted" at 8% complete because only the transcript folder was checked, not the 650-file source.)
Build/refresh procedure:
- Enumerate the source authoritatively. Object-store recursive listing,
mbox stream count, archive API walk,
findon a corpus dir. Get the FULL set. - Match outputs back to source by identity, not by guessing. For each
source item, look for its artifact: grep output frontmatter for the
source_path(or equivalent stored backlink) that points back to this item. Match by the stored backlink, never by re-deriving slugs — slugification is lossy and drifts. - Derive status from artifact existence, not assertion:
pending(no output) → mid-pipeline stages (partial outputs) → final stage (all outputs present). - Recompute
summary+by_groupby aggregating items. Never maintain counters by hand — they drift. Always recompute fromitems. - Write JSON, then render MD from it. Commit both.
A refresh is idempotent: re-running it on a half-done job produces the correct current state. Run it at the start of every session that touches the job.
MANIFEST.md rendering
Generated from JSON, never hand-edited. Structure:
- Frontmatter:
type: manifest, the summary numbers,updated. - Overall progress table: status | items | %.
- Progress by group: group | total | per-status counts — sorted so in-progress groups float to the top.
- Item-level manifest: grouped by
group, one line per item with a status icon, size, and output counts.
Icons map to pipeline position generically: last stage = ✅, any middle stage = 📝, first stage = ⬜.
Worker / subagent contract (idempotency + verification)
No atomic claim — partition the work-list UP FRONT. The manifest is a JSON
file, not a database: there is no compare-and-swap, no row lock, no atomic
"claim this item." Workers that race a shared status field to decide what to
process WILL collide — two workers read pending, both process the same item,
and you pay twice for the same expensive extraction; worse, two workers writing
the same manifest.json concurrently can interleave and corrupt the JSON,
losing the whole run's state. git pull --rebase is NOT synchronization — it
resolves text conflicts, it does not prevent two workers from having already
done the same paid work. So the claim is made by PARTITIONING before fan-out:
split the item list into DISJOINT shards (by group, or by an offset/limit
range) and hand each worker its own shard. No two workers ever look at the same
id. Idempotent restart (below) then covers only the crash-and-rerun case
within a shard, not cross-worker contention.
When fanning out processing across chunks/workers/subagents:
- Workers own a disjoint shard, write by
id. Each worker takes its pre-assigned slice (a group, or an offset/limit range) and processes only those items, updating status + outputs in the JSON (or writing a per-worker progress file that's merged — see below). It never scans the whole manifest for "any pending item" — that is the racing pattern the partition exists to prevent. - Idempotent restart. Before processing an item, check its current status. If already at/past the target stage, skip. A killed worker re-run does no double work.
- Checkpoint frequently. Update state every item (small jobs) or every N items (large). Commit/flush so a crash loses at most N items, never the run. For expensive per-item outputs, write one artifact per item and commit per group, so a single provider-side failure costs one item, not the whole chunk.
- NEVER trust a subagent's "completed successfully." Runtimes can
mislabel provider-blocked or crashed runs as success. VERIFY on disk:
re-run the ground-truth refresh and confirm the item's outputs actually
exist + counts match before advancing its status. The manifest refresh
IS the verification. (This is the same discipline
skills/minion-orchestrator/SKILL.mdapplies to job results — inspect outputs, not exit claims.) - Concurrency ceiling. As a rule of thumb: max ~3 heavy subagents or ~20 light workers, and keep CPU below ~75% so lock heartbeats and checkpoints keep firing.
Per-worker progress files (for high parallelism)
When many workers run concurrently, having them all write one JSON races.
Instead each writes worker-<id>-progress.json with
{"processed_ids": [], "stats": {}}; a merge step folds them into the
master manifest. (Proven at 20 workers on an email-takeout ingest.) For low
parallelism (<=4 chunks), direct per-item JSON updates with a
git pull --rebase before each commit is simpler and fine.
Periodic commit during long runs
Long ingests need a heartbeat commit so work survives a crashed session.
Schedule it via skills/cron-scheduler/SKILL.md, executed through Minions
per conventions/cron-via-minions.md —
a recurring shell job shaped like:
gbrain jobs submit shell --params '{"cmd": "cd <brain-repo> && git add projects/<pipeline-name> <output-dirs> && git commit -m \"<pipeline-name> ingest checkpoint\" && git push"}'
Shell jobs require the WORKER to be started with gbrain jobs work --allow-shell-jobs
(or GBRAIN_ALLOW_SHELL_JOBS=1 exported on the worker) — see
minion-orchestrator Preconditions. Do not set it yourself: it is an RCE-class
authorization that belongs to the operator running the daemon, and a submit-side
env prefix (GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs submit ...) is a no-op in
the daemon lane anyway (the worker's environment decides, not the submitter's).
Pre-commit hooks (privacy/durability) intentionally run on checkpoint
commits — a checkpoint that bypasses them can bank unlintable content.
Stage explicit paths, never git add -A (sweeps unrelated churn). Remove
the schedule when the job completes.
Hard rules
- JSON is truth; MD is a view. Regenerate MD from JSON; never hand-edit MD.
- Rebuild state from GROUND TRUTH (re-scan source + verify outputs on disk). Never trust memory, a counter, or a subagent's success claim.
idis a stable source-derived key, never a row index.- Status is DERIVED from artifact existence, not asserted.
- Recompute summary/by_group from items on every write — never maintain by hand.
- Match outputs to source by stored backlink (
source_path-style frontmatter), never by re-deriving slugs. - Idempotent workers: check status before processing; safe to restart.
No atomic claim exists — partition the work-list into disjoint shards up
front; never race a shared
statusfield (double-processes paid work, corrupts the JSON). - Checkpoint + commit frequently; a crash loses at most one batch.
- Never declare a corpus "done" by looking at the output folder — re-scan the source and diff. (The 8%-called-100% bug.)
- Stage explicit paths on commit; the manifest + outputs should be reviewable from the repo history.
Boundaries
- Native
gbrain synccheckpoints cover resumable file sync for brain repo sources only. The manifest covers arbitrary external corpora and multi-stage pipelines (transcription, extraction, curation) that sync knows nothing about. - Minion job progress (
gbrain jobs) is per-job and DB-backed; the manifest is per-CORPUS and survives across any number of jobs, sessions, and workers. Use both: jobs report liveness, the manifest holds truth. skills/archive-crawler/SKILL.mdrenders human-readable status tables for triage projects — that's the human-view half only. Any archive-crawler follow-up that processes items in stages should adopt this JSON-truth model underneath.