Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(bootstrap): OpenClaw host resolution in render-host.ts; dispatcher back under its line ceiling, ratchet unchanged (#7470)
garrytan822af3b5f040
diff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.mdindex b42ea76754..0c0dd7ada3 100644--- a/docs/architecture/key-files/agent-bootstrap.md+++ b/docs/architecture/key-files/agent-bootstrap.md@@ -13,7 +13,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche- `src/core/bootstrap/assets.ts` — every template + the question bank embedded via Bun `with { type: 'file' }` imports (the chunkers/code.ts pattern) so the compiled binary renders with no repo checkout; `DERIVED_TOKENS` (GITHUB_REPO_URL, CORPUS_RETENTION_DAYS) is the non-bank half of the template token set the CI bijection guard checks.- `templates/bootstrap/` — the ten `{{TOKEN}}` identity templates (AGENTS/CLAUDE/SOUL/USER/MEMORY/HEARTBEAT/ACCESS_POLICY/GITHUB/memory-README/gitignore), `questions.json` (12 asked / 6 required; consent keys; `persist:false` sink keys), and `template-repo/` — the VENDORED deterministic render the release job diffs against before publishing the public template repo. Generic placeholder content only (privacy iron rule; CI-asserted).- `src/core/bootstrap/interview.ts` — interview state at `<ws>/state/interview.json` (committed; multi-device re-render source). Read-back confirm hash: `--confirm` must present the hash of the exact answer set shown to the human, and ANY later answer change clears the confirmation — the single-batch self-confirm attack is structurally impossible. Set-time enforcement: length caps, reject-lists, allowed-lists, control-char strip, `{{` escaping. Conflict-markered files return agent-readable errors, not stack traces.-- `src/core/bootstrap/render.ts` — token substitution with interview values treated as data (line-leading `#`/`<!--`/fence escaping), hard-fail on unresolved tokens, never-clobber + timestamped backups on `--force`, blank-line collapse, byte floors scaled to answered count. `--minimal` is the deterministic placeholder mode the template-repo generator uses (byte-identical across runs; leaves required tokens as literal fill-me markers; writes `initialized:false`). `--only` never writes agent.json. On OpenClaw, HEARTBEAT.md renders as SCHEDULES.md (#7470).+- `src/core/bootstrap/render.ts` — token substitution with interview values treated as data (line-leading `#`/`<!--`/fence escaping), hard-fail on unresolved tokens, never-clobber + timestamped backups on `--force`, blank-line collapse, byte floors scaled to answered count. `--minimal` is the deterministic placeholder mode the template-repo generator uses (byte-identical across runs; leaves required tokens as literal fill-me markers; writes `initialized:false`). `--only` never writes agent.json. OpenClaw renders HEARTBEAT.md as SCHEDULES.md (`render-host.ts`, #7470).- `src/core/bootstrap/lock.ts` — the bootstrap-run mutex (atomic mkdir + pid liveness + age guard + ownership token; steal requires dead pid AND stale age) and the family's shared typed `BootstrapError` (GH_MISSING/GH_AUTH carry exit 2 = human action needed).- `src/core/bootstrap/repo.ts` / `attach.ts` / `uninstall.ts` — private-repo lifecycle. `createPrivateRepo`: gh gates, slugified name probe, `gh repo create --private --source --push`, privacy verified via `gh api .private` (rate-limit/5xx is VERIFY_UNAVAILABLE, distinct from not-private) before any push, idempotency keyed off the remote URL. A pre-existing origin is adopted (disposition 'adopted') when the authed gh user owns it, there's no recorded `repo_url`, and it is SAFE — empty or already carrying our history (`assertAdoptableOrigin`; a foreign-content repo is refused `ORIGIN_NOT_EMPTY`, never a silent no-op); this is the create-repo-first path. Org-owned origins and anything else are refused and pointed at attach. Repo-local git identity is set in both create and adopt paths before commit; `repo_url` is recorded only after a successful push. `attachWorkspace` (machine two): requires an `initialized` manifest, writes this machine's receipt, returns structured wiring steps. `uninstallWorkspace`: receipt-keyed, refuses under a live serve (read-only lock probe — never opens the engine), removes exactly receipt-recorded paths + marker-keyed host entries, keeps the brain unless `--delete-brain` AND bootstrap created it; never wholesale-deletes the gbrain home. All gh/git through an injectable ExecRunner seam.- `src/core/bootstrap/hooks.ts` + `host-specs.ts` — host wiring. `host-specs.ts` is the ONE module owning host-format assumptions (dated spec targets with verifiedAt + doc references: claude-code hooks/settings shapes incl. the 10,000-char hook-output cap and the five hook events; codex mcp-add argv, the streamable-HTTP `url` + `http_headers = { Authorization = "Bearer <t>" }` config shape (loads on codex-cli 0.147.x and 0.149.x; inline `bearer_token` is rejected at config load by >=0.149), `codexConfigPath()` honoring CODEX_HOME, `claudeUserSettingsPath()` honoring CLAUDE_CONFIG_DIR/$HOME explicitly — Bun's homedir() ignores a remapped HOME, which would point sandboxed writers at the operator's real settings; the shared resolution lives in the private `claudeConfigBase()` (CLAUDE_CONFIG_DIR-else-$HOME-else-homedir(), the directory playing the role of `~/.claude` — NOT for `claudeUserMcpConfigPath`, whose default lives at the HOME level as `~/.claude.json`), which also feeds `claudeUserSkillsDir()`/`claudeProjectSkillsDir()` (native SKILL.md discovery, the harness-bridge install targets; user scope attested, project scope provisional-from-docs) — and the opencode shapes: `opencodeConfigDir`/`opencodeGlobalConfigPath` (XDG-only resolution; the `.jsonc` name preferred for parity with `opencode mcp add`; OPENCODE_CONFIG/_CONFIG_DIR/_CONFIG_CONTENT deliberately NOT honored — observed INERT in opencode 1.18.18, honoring them would write registrations into a file opencode never reads), `opencodeProjectConfigPath`, `opencodeGlobalSiblingPath` (the OTHER member of the global filename pair — writers reconcile `mcp.<name>` across it because opencode merges both), and `OPENCODE_HAS_HOOKS=false` — 'gbrain does not wire opencode's plugin/event system yet', not 'opencode has no hooks'). The settings writers are path+marker parameterized: `writeClaudeHooksAt`/`removeClaudeHooksAt` take an explicit settings file and a marker VALUE (workspace installs stamp `bootstrap-v1` in `.claude/settings.local.json`; harness installs stamp `bootstrap-harness-v1` in user-scope settings or a --project dir — the two coexist and each removal strips only its own; `refuseOnForeignGbrainMarker` blocks same-file double-wiring), fail-closed on broken JSON (a settings file that doesn't parse THROWS with the path — a writer must never relocate or overwrite a config it can't read), mode-preserving realpath-resolved atomic writes (dotfile symlinks survive), and fixed-or-timestamped backups. `addPermissionsAllowEntry`/`removePermissionsAllowEntry` manage the harness lane's `mcp__<name>` headless pre-approval with set semantics and NO marker (ownership rides the harness receipt; foreign entries always survive); the add path fails CLOSED when an existing `permissions` key or `permissions.allow` carries a shape it doesn't understand (host security policy is never rewritten on a guess), while removal leaves shapes it can't read untouched and reports nothing-to-remove. `registerClaudeMcp`/`registerCodexMcp` build argv only (Claude Code takes `--scope`, project default; Codex has no scope flag — `codex mcp add` is always user-global; `-e`/`--env GBRAIN_SOURCE` so MCP writes land in the workspace source, and the serve argv from `stdioServeArgv` in `src/core/mcp-registration.ts`: `--surface starter` by default so a pre-existing `mcp_surface: verbs` config row can't narrow the registration, or the `surface` the caller passes — `bootstrap hooks --surface`, or an existing entry's form carried over on replacement, `null` meaning a bare `serve`). `bootstrap hooks` never narrows: a matching registration is kept, `verifyMcpTargetsWorkspace` returns the existing entry's surface (`registeredSurface`) and the mismatch re-add keeps it, and the opencode writer keeps the existing command's form unless `--surface` is given. The opencode workspace lane execs NOTHING — registration is the direct `opencode-json.ts` write with an INVERTED scope default (user-global; opencode spawns project-config servers with no trust prompt, so `MCP_SCOPE=project` is an explicit opt-in that writes the committed-candidate `opencode.json` with a PATH-resolved command and prints the sharing warning), verification is config parse-back + a best-effort `opencode mcp list --pure` probe — the probe spawns via a held Bun.spawn handle from a fresh EMPTY temp-dir cwd (never the invoking cwd: opencode merges a project opencode.json from cwd and spawns its servers with no trust prompt), is SKIPPED entirely for project scope (printed note; parse-back is authoritative) and on plugin-bearing configs (`mcp list` is a code-execution surface), and on timeout actually kills the child (SIGTERM → SIGKILL, bounded pipe drain, code 124 into the could-not-confirm branch; `probeSpawn` is the injectable seam). User-scope writes also reconcile the SIBLING global filename first (ours → removed with a note; foreign → refuse naming both files) so a merge-shadow registration can never survive. `detectHarness` probes `OPENCODE`/`OPENCODE_PID` (set in opencode's bash-tool children, observed 1.18.18). `ClaudeHookEnv.GBRAIN_SEAT` (#4618) renders `GBRAIN_SEAT=<label>` into local-carrier hook commands (never the committed carrier); `writeClaudeHooksAt` keeps the seat a prior install of the same marker rendered when the caller passes none, and `''` clears it. `parseSeatFlags` validates `--seat <label>` / `--no-seat` for `bootstrap hooks` and `bootstrap harness` and returns a `note` where a seat cannot be rendered (codex, opencode, the cloud committed carrier). Pinned by `test/bootstrap-seat.serial.test.ts`. Harness-lane hook ownership does not rest on the marker alone: Claude Code can drop unknown keys when it rewrites settings.json, so `parseClaudeHookCommand` (the inverse of `buildClaudeHookCommand`: shellQuote-aware word split, env keys limited to the four the builder writes, each at most once, an absolute launcher, nothing after `hook <sub>`, and a re-render that must equal the input) feeds `classifyHarnessHook(entry, event, identity)` → `marked` / `command` (unmarked, exactly the harness hook for THAT event, launcher/source/seat inside a `HarnessHookIdentity`, no GBRAIN_HOME) / `unowned` (harness-looking under a wired event but edited or another install's; never deleted) / null. `harnessHookIdentity(receipt, target, current)` merges the running install with the receipt's recorded `launcher`/`seat` and source binding (seats constrain only when recorded). `writeClaudeHooksAt({identity})` replaces owned unmarked entries like marked ones (one entry per event on re-run, seat carried from marked then owned entries) and notes `harness_hook_unowned` lookalikes; `removeClaudeHooksAt(path, marker, {identity, dryRun})` returns `unmarked` (event + why, never command text) and `unowned` events; `scanHarnessHookCarrier` is the read-only per-event census (doctor, `--status`, the cross-HOME guard with identity `'any'`); `groupsCarryGbrainHook` feeds `hook_carrier_overlap`. The workspace lane (bootstrap-v1) keys on the marker alone. Pinned by `test/bootstrap-harness-hook-ownership.test.ts`. `hookEntryHash` (sha256 over `type`, `command`, `timeout`; the marker excluded, so a dropped marker keeps the hash) backs the opt-in `ownedEntryHashes` option on both writers: with it a marker match alone never replaces or removes an entry, edited marked entries come back in `preserved`, and unmarked entries with an owned hash are still ours (`gbrain setup`); without it every existing caller keeps marker-keyed ownership.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex b3f7ad8b63..4a4fcc1648 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -28,7 +28,7 @@ src/core/minions/queue.ts 2547 ratchet grown #4078 + megawave probe-liveness unlsrc/commands/init.ts 1884 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts); +2 D8 funnel: a fresh init counts one clean_install when the opt-in funnel is on (core/funnel.ts)src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)-src/commands/bootstrap.ts 2152 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts); +5 #7470: render --host flag parse, refusal and note line, plus one help line (host resolution and note text live in core/bootstrap/render.ts resolveRenderHost)+src/commands/bootstrap.ts 2147 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)src/core/minions/worker.ts 1795 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts); +1 GBRA-158 #7239: refusal.ts import (a deterministic refusal ends the job at once; classification in minions/refusal.ts); +3 #7242 lane reservation: lanes import and the longJobNames/shortJobReservedSlots defaults (the claim passes claimExclusions; policy in minions/lanes.ts); +2 #7242 terminal hook: onJobSettled default and the settle call (logic in terminal-hook.ts); #7252 x #7249 merge: both sides grew the file, re-summed (1794 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (1795 measured)src/commands/sources.ts 2077 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts)src/core/link-extraction.ts 2421 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1)diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 1c92c8c03f..a6495782c4 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -38,7 +38,7 @@ test/book-mirror.test.ts gbrain book-mirror — source file invariants 2 readFiltest/bootstrap-codex-door.test.ts Codex door — rendered AGENTS.md pull protocol (Gate 3) 2 readFileSynctest/bootstrap-contract.test.ts bootstrap same-turn write-back contract 6 readFileSynctest/bootstrap-opencode-door.serial.test.ts opencode door — rendered AGENTS.md pull protocol 1 readFileSync-test/bootstrap-render.test.ts renderWorkspace — OpenClaw host keeps its schedule list out of HEARTBEAT.md (#7470) 5 readFileSync+test/bootstrap-render.test.ts renderWorkspace — OpenClaw host keeps its schedule list out of HEARTBEAT.md (#7470) 6 readFileSynctest/bootstrap-shared-skills.test.ts (file-level) 19 readFileSynctest/brain-durability-hook.serial.test.ts #4682 — push-lock timeout is fail-loud for the helper only 1 readFileSynctest/brain-durability-hook.serial.test.ts brain-commit-push.sh (D13 guarantee) 4 readFileSyncdiff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.tsindex b2ba37ee0e..71b9ae4d94 100644--- a/src/commands/bootstrap.ts+++ b/src/commands/bootstrap.ts@@ -50,7 +50,7 @@ import {readInterviewState,routeProviderKeyToConfig,} from '../core/bootstrap/interview.ts';-import { renderWorkspace, BootstrapRenderError, resolveRenderHost, OPENCLAW_RENDER_NOTE } from '../core/bootstrap/render.ts';+import { renderWorkspace, BootstrapRenderError } from '../core/bootstrap/render.ts';import { acquireBootstrapLock, BootstrapError } from '../core/bootstrap/lock.ts';import { createPrivateRepo, defaultRunner, type ExecRunner, type RepoReceipt } from '../core/bootstrap/repo.ts';import { attachWorkspace } from '../core/bootstrap/attach.ts';@@ -123,10 +123,9 @@ Subcommands (run \`gbrain bootstrap status\` first — it is the resume entrypoi--status Gate: exits nonzero until required answers exist.--show Read-back payload (all answers + confirm hash).--confirm <hash> Record the human's confirmation of the read-back.- render [--force] [--only F] [--minimal] [--host openclaw|generic]+ render [--force] [--only F] [--minimal] [--host openclaw|generic|auto]Render identity files from the confirmed answers.- Never clobbers; --force backs up first. OpenClaw- (detected or --host): HEARTBEAT.md → SCHEDULES.md.+ Never clobbers; --force backs up first. OpenClaw: SCHEDULES.md.contract [--repair] Audit the same-turn GBrain write-back contract.--repair appends it additively and backs up AGENTS.md.hooks [--harness claude-code|codex|opencode] [--repair] [--no-hooks] [--gbrain-bin <path>]@@ -889,8 +888,6 @@ async function runRender(ws: string, rest: string[], home: string): Promise<numbconst force = rest.includes('--force');const minimal = rest.includes('--minimal');const only = flagValues(rest, '--only');- const host = resolveRenderHost(ws, flagValue(rest, '--host'), minimal);- if (host === null) { console.error('unknown --host: pass --host openclaw or --host generic'); return 2; }// Public-origin gate [FIX6]: identity files (SOUL.md/USER.md/…) must NEVER// land in a public repo. `bootstrap status` enforces this for the template@@ -954,27 +951,25 @@ async function runRender(ws: string, rest: string[], home: string): Promise<numb/* canonical fallback applies */}- // source_id seam [source-id collision]: render is ENGINE-FREE (D5/ENG-2)- // and the sources registry lives only in the DB, so render cannot detect a- // 'workspace' id already claimed by another checkout. It therefore passes- // NO sourceId: render.ts preserves an existing manifest source_id and- // defaults new manifests to 'workspace'; verify (which holds the engine)- // detects the collision and persists a derived 'workspace-<hash>' id that- // every consumer reads back from the manifest.+ // source_id seam [source-id collision]: render is ENGINE-FREE (D5/ENG-2) and the sources+ // registry lives only in the DB, so render cannot detect a 'workspace' id already claimed+ // by another checkout. It therefore passes NO sourceId: render.ts preserves an existing+ // manifest source_id and defaults new manifests to 'workspace'; verify (which holds the+ // engine) detects the collision and persists a derived 'workspace-<hash>' id that every+ // consumer reads back from the manifest.const res = renderWorkspace(ws, {force,...(only.length > 0 ? { only } : {}),minimal,derived,createdBy: `gbrain@${VERSION}`,- ...(host ? { host } : {}),+ host: flagValue(rest, '--host'),});if (only.length === 0 && !minimal) writeRenderReceipt(home, ws);abortIfInjected('render');- if (host) console.log(OPENCLAW_RENDER_NOTE);- console.log(`rendered: ${res.written.join(', ') || '(nothing new)'}`);+ console.log(`${res.note ? `${res.note}\n` : ''}rendered: ${res.written.join(', ') || '(nothing new)'}`);if (res.skipped.length > 0) console.log(`kept (already present — use --force to overwrite): ${res.skipped.join(', ')}`);if (res.backups.length > 0) console.log(`backups: ${res.backups.join(', ')}`);return 0;diff --git a/src/core/bootstrap/render-host.ts b/src/core/bootstrap/render-host.tsnew file mode 100644index 0000000000..1e8c6a5097--- /dev/null+++ b/src/core/bootstrap/render-host.ts@@ -0,0 +1,49 @@+/**+ * Which harness a bootstrap render targets (#7470). OpenClaw 2026.10.6+ retired+ * its own HEARTBEAT.md: `openclaw doctor --fix` imports a workspace file by that+ * name into its heartbeat monitor and removes it, so an OpenClaw render writes+ * gbrain's due-job list under another name (assets.ts `openclawDest`).+ */++import { homedir } from 'node:os';+import { join, relative, resolve, sep } from 'node:path';++/**+ * Whether a workspace belongs to OpenClaw, from OpenClaw's own layout: the+ * configured workspace (OPENCLAW_WORKSPACE_DIR, or gbrain's OPENCLAW_WORKSPACE),+ * or a `workspace` tree under the state directory (OPENCLAW_STATE_DIR,+ * ~/.openclaw, or a profile's ~/.openclaw-<profile>). A workspace elsewhere+ * that OpenClaw was pointed at by config alone needs `render --host openclaw`.+ */+export function detectOpenClawWorkspace(+ workspaceDir: string,+ env: Record<string, string | undefined> = process.env,+ home: string = homedir(),+): boolean {+ const ws = resolve(workspaceDir);+ for (const configured of [env.OPENCLAW_WORKSPACE_DIR, env.OPENCLAW_WORKSPACE]) {+ if (configured && resolve(configured) === ws) return true;+ }+ const underWorkspaceOf = (stateDir: string): boolean => {+ const rel = relative(resolve(stateDir), ws);+ const first = rel.split(sep)[0] ?? '';+ return rel !== '' && !rel.startsWith('..') && /^workspace(-.+)?$/.test(first);+ };+ if (env.OPENCLAW_STATE_DIR && underWorkspaceOf(env.OPENCLAW_STATE_DIR)) return true;+ const profile = relative(resolve(home), ws).split(sep)[0] ?? '';+ return /^\.openclaw(-.+)?$/.test(profile) && underWorkspaceOf(join(home, profile));+}++/** `bootstrap render --host`: 'openclaw' forces OpenClaw, 'generic' declines+ * it, 'auto' detects it (never in minimal mode). Any other value is null. */+export function resolveRenderHost(workspaceDir: string, flag: string, minimal: boolean): 'openclaw' | undefined | null {+ if (flag === 'openclaw') return 'openclaw';+ if (flag === 'generic') return undefined;+ if (flag !== 'auto') return null;+ return !minimal && detectOpenClawWorkspace(workspaceDir) ? 'openclaw' : undefined;+}++export const OPENCLAW_RENDER_NOTE =+ 'OpenClaw workspace: the due-job list renders as SCHEDULES.md, and AGENTS.md points there. OpenClaw 2026.10.6+ ' ++ 'retired HEARTBEAT.md, and its doctor migration imports and removes any workspace file by that name. ' ++ 'Pass --host generic to keep HEARTBEAT.md.';diff --git a/src/core/bootstrap/render.ts b/src/core/bootstrap/render.tsindex 5e37715b4c..8d85936d41 100644--- a/src/core/bootstrap/render.ts+++ b/src/core/bootstrap/render.ts@@ -39,8 +39,7 @@*/import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';-import { homedir } from 'node:os';-import { dirname, join, relative, resolve, sep } from 'node:path';+import { dirname, join } from 'node:path';import { BOOTSTRAP_TEMPLATES, DERIVED_TOKENS, GITHUB_URL_PLACEHOLDER, loadQuestionBank, readTemplate } from './assets.ts';import {@@ -51,6 +50,7 @@ import {type AgentManifest,} from './format.ts';import { readInterviewState, type InterviewState } from './interview.ts';+import { OPENCLAW_RENDER_NOTE, resolveRenderHost } from './render-host.ts';// ---------------------------------------------------------------------------// Errors@@ -102,13 +102,16 @@ export interface RenderOptions {/** Recorded as agent.json `source_id`. When unset, an existing initialized* manifest's source_id is preserved; otherwise defaults to 'workspace'. */sourceId?: string;- /** The harness the workspace belongs to. 'openclaw' writes each template's- * `openclawDest` instead of its dest (HEARTBEAT.md → SCHEDULES.md, #7470).- * Ignored in minimal mode (determinism). */- host?: 'openclaw';+ /** The harness the workspace belongs to (render-host.ts): 'openclaw' writes+ * each template's `openclawDest` instead of its dest (HEARTBEAT.md →+ * SCHEDULES.md, #7470), 'generic' never does, 'auto' (the default) detects.+ * Ignored in minimal mode (determinism). An unknown value throws. */+ host?: string;}export interface RenderResult {+ /** Why the render used host-specific names, when it did. */+ note?: string;written: string[];skipped: string[];backups: string[];@@ -134,47 +137,6 @@ export function isBootstrapRenderDest(relPath: string): boolean {return BOOTSTRAP_TEMPLATES.some((t) => t.dest === relPath || t.openclawDest === relPath);}-/**- * Whether a workspace belongs to OpenClaw, from OpenClaw's own layout: the- * configured workspace (OPENCLAW_WORKSPACE_DIR, or gbrain's OPENCLAW_WORKSPACE),- * or a `workspace` tree under the state directory (OPENCLAW_STATE_DIR,- * ~/.openclaw, or a profile's ~/.openclaw-<profile>). A workspace elsewhere- * that OpenClaw was pointed at by config alone needs `render --host openclaw`.- */-export function detectOpenClawWorkspace(- workspaceDir: string,- env: Record<string, string | undefined> = process.env,- home: string = homedir(),-): boolean {- const ws = resolve(workspaceDir);- for (const configured of [env.OPENCLAW_WORKSPACE_DIR, env.OPENCLAW_WORKSPACE]) {- if (configured && resolve(configured) === ws) return true;- }- const underWorkspaceOf = (stateDir: string): boolean => {- const rel = relative(resolve(stateDir), ws);- const first = rel.split(sep)[0] ?? '';- return rel !== '' && !rel.startsWith('..') && /^workspace(-.+)?$/.test(first);- };- if (env.OPENCLAW_STATE_DIR && underWorkspaceOf(env.OPENCLAW_STATE_DIR)) return true;- const profile = relative(resolve(home), ws).split(sep)[0] ?? '';- return /^\.openclaw(-.+)?$/.test(profile) && underWorkspaceOf(join(home, profile));-}--/** The render host for `bootstrap render --host`: 'openclaw' forces it,- * 'generic' declines it, no flag detects it (never in minimal mode). An- * unknown value returns null for the dispatcher to refuse. */-export function resolveRenderHost(workspaceDir: string, flag: string | undefined, minimal: boolean): 'openclaw' | undefined | null {- if (flag === 'openclaw') return 'openclaw';- if (flag === 'generic') return undefined;- if (flag !== undefined) return null;- return !minimal && detectOpenClawWorkspace(workspaceDir) ? 'openclaw' : undefined;-}--export const OPENCLAW_RENDER_NOTE =- 'OpenClaw workspace: the due-job list renders as SCHEDULES.md, and AGENTS.md points there. OpenClaw 2026.10.6+ ' +- 'retired HEARTBEAT.md, and its doctor migration imports and removes any workspace file by that name. ' +- 'Pass --host generic to keep HEARTBEAT.md.';-/*** [S3#3] Structural-marker escape for interview-sourced values (see module* doc). Applied at render time, per line, to answer values only — bank@@ -224,7 +186,7 @@ type Resolution =| { kind: 'placeholder' }| { kind: 'unresolved' };-function buildResolver(opts: RenderOptions, state: InterviewState | null): (token: string) => Resolution {+function buildResolver(opts: RenderOptions, state: InterviewState | null, host: 'openclaw' | undefined): (token: string) => Resolution {const bank = loadQuestionBank();const minimal = opts.minimal === true;const derivedSet = new Set<string>(DERIVED_TOKENS);@@ -235,7 +197,7 @@ function buildResolver(opts: RenderOptions, state: InterviewState | null): (tokeif (minimal) return { kind: 'value', value: canonical };const supplied = opts.derived?.[token];if (supplied !== undefined) return { kind: 'value', value: supplied };- if (token === 'SCHEDULES_FILE' && opts.host === 'openclaw') {+ if (token === 'SCHEDULES_FILE' && host === 'openclaw') {return { kind: 'value', value: BOOTSTRAP_TEMPLATES.find((t) => t.dest === canonical)!.openclawDest! };}return { kind: 'value', value: canonical };@@ -277,9 +239,14 @@ export function renderWorkspace(workspaceDir: string, opts: RenderOptions = {}):}}+ const host = resolveRenderHost(workspaceDir, opts.host ?? 'auto', minimal);+ if (host === null) {+ throw new BootstrapRenderError('unknown_host', `unknown render host '${opts.host}': pass --host openclaw, generic or auto.`);+ }+// Validate --only against the known dest list (typo protection).const destFor = (t: (typeof BOOTSTRAP_TEMPLATES)[number]): string =>- !minimal && opts.host === 'openclaw' && t.openclawDest ? t.openclawDest : t.dest;+ !minimal && host === 'openclaw' && t.openclawDest ? t.openclawDest : t.dest;const selected = BOOTSTRAP_TEMPLATES.filter((t) => !opts.only || opts.only.includes(t.dest) || (t.openclawDest !== undefined && opts.only.includes(t.openclawDest)),);@@ -304,7 +271,7 @@ export function renderWorkspace(workspaceDir: string, opts: RenderOptions = {}):state = read.state;}- const resolve = buildResolver(opts, state);+ const resolve = buildResolver(opts, state, minimal ? undefined : host);// Phase 1 — render everything in memory. Nothing is written until every// selected file resolves cleanly (hard-fail lists ALL unresolved tokens).@@ -348,7 +315,7 @@ export function renderWorkspace(workspaceDir: string, opts: RenderOptions = {}):// backup write with EEXIST. Claim the stamp dir ATOMICALLY (non-recursive// mkdir; EEXIST → bump a numeric suffix) lazily on the first backup, so// every render call owns a distinct backup dir.- const result: RenderResult = { written: [], skipped: [], backups: [] };+ const result: RenderResult = { ...(host && !minimal ? { note: OPENCLAW_RENDER_NOTE } : {}), written: [], skipped: [], backups: [] };let backupStamp: string | null = null;const claimBackupStamp = (): string => {if (backupStamp) return backupStamp;diff --git a/test/bootstrap-render.test.ts b/test/bootstrap-render.test.tsindex 1e2b7e7710..5683d57f62 100644--- a/test/bootstrap-render.test.ts+++ b/test/bootstrap-render.test.ts@@ -28,8 +28,8 @@ import {UnresolvedTokenError,BootstrapRenderError,DERIVED_DEFAULTS,- detectOpenClawWorkspace,} from '../src/core/bootstrap/render.ts';+import { detectOpenClawWorkspace } from '../src/core/bootstrap/render-host.ts';import { BOOTSTRAP_TEMPLATES } from '../src/core/bootstrap/assets.ts';import { readManifest, writeManifest, TEMPLATE_PLACEHOLDER_MANIFEST } from '../src/core/bootstrap/format.ts';import { setAnswer, skipAnswer, interviewStatePath } from '../src/core/bootstrap/interview.ts';@@ -473,6 +473,7 @@ describe('renderWorkspace — OpenClaw host keeps its schedule list out of HEARTtest('host openclaw renders the due-job list as SCHEDULES.md and AGENTS.md points only there', () => {const ws = answeredWs();const result = renderWorkspace(ws, { host: 'openclaw' });+ expect(result.note).toContain('SCHEDULES.md');expect(result.written).toContain('SCHEDULES.md');expect(result.written).not.toContain('HEARTBEAT.md');expect(existsSync(join(ws, 'HEARTBEAT.md'))).toBe(false);@@ -486,9 +487,16 @@ describe('renderWorkspace — OpenClaw host keeps its schedule list out of HEARTexpect(agents).toContain('| Schedules | SCHEDULES.md |');});+ test('an unknown host refuses before writing anything', () => {+ const ws = answeredWs();+ expect(() => renderWorkspace(ws, { host: 'bogus' })).toThrow(/unknown render host 'bogus'/);+ expect(existsSync(join(ws, 'AGENTS.md'))).toBe(false);+ });+test('every other harness keeps HEARTBEAT.md', () => {const ws = answeredWs();const result = renderWorkspace(ws);+ expect(result.note).toBeUndefined();expect(result.written).toContain('HEARTBEAT.md');expect(existsSync(join(ws, 'SCHEDULES.md'))).toBe(false);expect(readFileSync(join(ws, 'HEARTBEAT.md'), 'utf8').startsWith('# HEARTBEAT.md\n')).toBe(true);