Repository navigation
feat: add an opt-in usage-ranked tool index - #197128
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis PR adds opt-in usage ranking for bounded tool indexes, persistent usage counters, and administrative inspection, import, and reset commands. Example: An oversized Code Mode catalog omits sessions_list despite repeated successful use.
Review scores
ProductKind: Feature · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this maintainer-approved feature remains absent from main, and this re-review found no actionable defect; the required CI gate still reports inherited failures. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe built-in agent runtime records successful native tool calls in agent storage; the existing session prompt owner freezes their ranking for Code Mode and Tool Search renderers, while administrative CLI commands use authenticated Gateway RPCs. flowchart LR
A[Successful native tool calls] --> B[Run usage recorder]
B --> C[Transcript actor and settlement writer]
C --> D[Agent usage storage]
D --> E[Session prompt checkpoint]
E --> F[Bounded tool indexes]
G[Administrative CLI] --> H[Admin Gateway RPCs]
H --> D
Technical reviewBest possible solution: Retain the opt-in implementation using the existing transcript, prompt-checkpoint, and worker owners, with the documented upgrade and rollback behavior. Do we have a high-confidence way to reproduce the issue? This is a feature request; source and supplied Gateway output establish the overflowing-index scenario without a reviewer-run reproduction. Is this the best way to solve the issue? The implementation places recording, persistence, and frozen ranking with their existing owners, and the re-review did not establish a smaller complete alternative or an introduced defect. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 2035b0730f82. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
PR surfacePR surface statistics unavailable: the file list is incomplete. Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (3 earlier review cycles)
Reviewed November 12, 2026, 7:25 PM ET / November 13, 2026, 00:25 UTC (Revision 4). |
0ce49ec to
05fd27e
Compare
|
6710d30 to
0710ddc
Compare
0710ddc to
01679c3
Compare
|
Current head CLI note: Remaining CI reds: @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
73448cf to
6aa74a2
Compare
|
@clawsweeper re-review Since
The remaining red CI is inherited (Codex |
|
🦞👀 Re-review progress:
|
|
Merged via explicitly authorized admin squash with attributed pre-existing CI failures.
|
* feat: add an opt-in usage-ranked tool index * fix: preserve tool ranking across admitted runs * fix: co-commit tool usage with transcript writes * fix: classify tool usage SQL as worker-owned * fix: complete tool usage cutovers for CLI, prompt finalization, and CI inventories * test: keep tool usage retention out of the telemetry maintenance fixture
Absorb jump onto openclaw#129388 head 51ff02d (🌊 GO msg 1572279218795188426). Lane checkpoint for review; not a presentation move, not Mode-B accepted. Parents (first-parent ancestry preserved; no rebase, no squash): 1st: 51ff02d openclaw#129388 head (codeagent/85651-upstream-1ba243c8-gates) 2nd: 9122a49 openclaw/openclaw main (dispatch pin) merge-base: 401a1de (single; upstream +2284) Mechanics: diff3, 76 conflicted paths resolved per hunk (74 content, 2 modify/delete). Generated artifacts seeded from upstream, then regenerated from the merged sources (postgres schema/catalogs, gateway validators, config doc baseline, worker-access inventory). Per-file table in the lane output.md. Schema renumber (follows the 2026-11-09 ruling pattern of e4a5562): - upstream 8a328bf (openclaw#197128) takes agent schema 42 (agent_tool_usage) - session_recipient_authority moves to agent schema 43 (OPENCLAW_AGENT_SCHEMA_VERSION 43) in the SQLite owner, PostgreSQL ladder (41 -> 42 tool usage -> 43 authority), backup scopes, witness, port descriptor pin and package schemaVersions - the fleet bridge classifies 38-42 by markers (authority, creation receipts, active event facts, tool usage, payload CHECK); jump 14's 42 (upstream 41 + authority, no tool usage) runs upstream 42 + the idempotent authority step; other 42 shapes are refused before any write - Doctor keeps a full image for the below-marker jump-14 42 - a PostgreSQL jump-14 42 store fails closed (fleet runs SQLite) Semantic repairs needed by the composition (tsgo/test-graph): - fork's session-delivery codec admits upstream's mediaCandidate kind and agentTurn.reviewedTaskId; produced-delivery checks name agentTurn and mediaCandidate instead of "not systemEvent" (fork postCompactionDelegate) - worker readSessionDelivery rebuilt on the fork's load-result reader - fork-moved owner modules carry upstream's in-place edits (removalReason run_rekeyed/retention, requester_waiting outcome, async usage cost, continuation freeze inside the preparation IIFE) - continuation reset retention runs upstream's stopSessionResetWork (subagents then exec processes); retained-send stop cause derives from the cleanup reason - consumedContinuationTraceparent reads freshEntry (upstream removed entryForPatch with cron-continuation restore) - one requester-origin projector (upstream projectUserTurnRequesterOrigin) - fork commands enter the domain-command census and classifier - fork tests adapted to upstream's prepareSessionMaintenanceRequest and the fork's registerRun ownership contract Co-Authored-By: Claude Opus 5.5 <[email protected]>
…'s 42 and 43 The 41bdde2 merge moved continuation's recipient-authority step from 42 to 44: upstream owns 42 (tool usage, openclaw#197128) and 43 (pending-input endings, openclaw#200533) and is at 43. The pins follow, in the pure tree's own shape (no bridge): - owner suite: fresh, v18, v24, derived upstream 32-38, current-schema and double-apply rows read 44; the derived upstream schemas also drop 42's tool usage and 43's endings; captured upstream rows now 39-43 (new fixtures openclaw-agent-schema-v42.sql = blob 43b1886 at 6691aca, the last schema-42 commit, and v43.sql = blob 2a6bb45 at 703c82d, unchanged through 41bdde2); the double-apply row starts from captured 43; a new refusal row: a 43 holding upstream's 42 is refused by upstream's own check (session_pending_inputs) before any write. - Doctor suite: upstream 37-43 -> 44 inside the declared scope, re-run no-op, exact restore; stores below 43 are staged before pending-input first use (upstream's 43 scope names that AUTOINCREMENT table, so a present one takes a full image instead). Revert-proofs (temporary edits, restored byte-exact): - authority step removed: 15/22 owner rows and 7/7 Doctor rows red ("missing table session_recipient_authority"); fresh, current-44, PG-separator and the three refusal rows stay green; - AGENT_RECIPIENT_AUTHORITY_SCHEMA_VERSION left at 42: exactly the captured upstream 42 and 43 rows and the 43-based double-apply row go red, with the same missing-table refusal. Upstream's real 42/43 stores need 44. Owner 22/22, Doctor 7/7. Refs openclaw#129388 Co-Authored-By: Claude Opus 5.5 <[email protected]>
) * fix(plugins): portable plugin-state keys for PostgreSQL Use an exclusive SQL lower bound for Doctor pagination instead of a NUL-suffixed cursor. Reject new NUL keys in test-only plugin-state fixtures while retaining legacy SQLite adoption reads. Add real PostgreSQL Doctor regression coverage and register it in conformance and database-worker lanes. Refs openclaw#184862 openclaw#188642. * test: account for rebased plugin-state coverage * test(clickclack): import legacy revocations before adoption (cherry picked from commit 395cac7) Release adaptation: Only exclusive SQL lower bound in kernel and Doctor pagination; preserve legacy SQLite keys and public validation. Regression exercises real Doctor paging and inspected executed SQL bindings; no NUL-key fixture policy, schema or unrelated tests. Follow-up dispositions: 8253356 fix: preserve child results after source lifecycle changes (openclaw#202708); f3f89c7 fix: show saved child results when completion delivery fails (openclaw#202664); c45faa8 fix: align CI tests with admitted tool calls (openclaw#202655); 5c9389a fix: make channels add report required plugin install failures (openclaw#202091); 52b9188 fix: show hosted model details in `models list` without a Gateway (openclaw#202490); d248a76 fix: show an outcome when kept child chats return no answer (openclaw#202423); 5148804 fix(discord): check a queued message's access again when its turn starts (openclaw#202330); 2470d62 fix: let setup use account models with a fresh catalog (openclaw#202019); 9fa0b92 fix: let PostgreSQL Gateways start with plugin-backed secrets (openclaw#201063); c180824 fix(plugins): Talk and plugin-loading requests fail on PostgreSQL Gateways (openclaw#201976); cb5cfb2 fix: keep a doubtful killed-update recovery on the repair path (openclaw#201361); 17c5fb0 fix(state): PostgreSQL state created before Template bootstrap deferral is refused as schema drift (openclaw#197425); b5c1277 fix: let resumed parents collect children stopped by restart (openclaw#201460); f920a7e chore(postgres): qualify cron completion during graceful shutdown (openclaw#201246); 1680f54 fix(openai): new ChatGPT subscription models missing until an OpenClaw release (openclaw#201130); 0d8820a fix(media): image descriptions use the ChatGPT OAuth route when OpenAI has no API key (openclaw#199299); ee3e16e test(agents): trim and fold low-value regression suites (openclaw#198916); b8029b4 test(agents): qualify PostgreSQL simple-completion acquisition (openclaw#200956); 703c82d fix(sessions): record queued input end causes and recover them across crashes (openclaw#200533); 23fca1a fix: let the next update continue after a killed update when nothing is left to repair (openclaw#200680); d565e17 fix(ci): retire deleted session fork test from inventory (openclaw#200611); 4cf12c6 chore(postgres): qualify prompt refresh and rebalance CI (openclaw#200488); d460273 fix(templates): release earlier Template-managed agents (openclaw#200303); ff75829 fix(update): --no-restart update fails when the Gateway restarts itself during Doctor's stop (openclaw#200181); 0b2ad60 chore(postgres): cover compaction watched-session prompts (openclaw#200117); b90c573 test: consolidate redundant coverage (198795 recut) (openclaw#198943); a042363 test: consolidate redundant coverage (198793, part 2) (openclaw#198936); 9bfad2b test: consolidate suites while retaining recovery owners (openclaw#198933); 4e9812c test: consolidate redundant coverage (198789, part 2) (openclaw#198932); 90814f5 fix(subagents): stops a finished sub-agent's chat being deleted before its parent reads the result; 799bc0b fix(ci): stabilize hourly fixtures and retire unused exports (openclaw#199851); e4a3093 perf(update): replace the candidate canary with a runtime contract check (openclaw#198268); a4cc2ad fix: undo cold-session compaction CPU and latency regressions (openclaw#199561); 55fec79 fix(agents): stop divergent mid-turn overflow recovery (openclaw#199636); 2c4413a fix: reduce Gateway stalls under filesystem pressure (openclaw#197510); 37d977f fix: output reducers are skipped in headless and Code Mode runs (openclaw#199434); c9ee264 fix(compaction): concurrent sessions wait for each other's summaries during compaction (openclaw#196550); 2471ddc feat: let agents review generated images before delivery (openclaw#198227); 21f7dc6 fix(github): publication fails with PostgreSQL session or state stores (openclaw#193749); 63d9e57 fix(ci): new PostgreSQL suites are omitted from conformance (openclaw#198390); 466a4b6 fix(telegram): steered answers quote the wrong input (openclaw#178124); 87b6f52 fix(delivery): resend routed Telegram finals after an ambiguous network failure (openclaw#192779); 68a839b fix: isolate held agent databases until explicit restoration (openclaw#198180); cff99b2 fix(agents): keep provider history append-only across runs (openclaw#197874); 8a328bf feat: add an opt-in usage-ranked tool index (openclaw#197128); 097e648 fix(ci): plan only executable infra tests (openclaw#197911); 76385fd fix(models): discovered models become "Unknown model" after restart or an ended sign-in (openclaw#197784); 89d4177 fix(plugin-state): guarded calls fail until Gateway restart after an unknown write outcome (openclaw#197790); baca36e fix(sessions): commit selected invitations with original messages (openclaw#184512); 699e538 fix(sessions): drain passive notices on sessions_send resumes; d6ded18 chore(ci): drop retired test-lines allocation records (2/3) (openclaw#197656); e0dd020 fix(agents): collect process results at suspended-run capacity; 4897740 feat(auth): preserve delegated OCE user profiles and permissions (openclaw#196856); 7197ce1 feat(templates): install bundled plugins through native management (openclaw#196349); 9c6ee9b feat: let Template automations start paused for onboarding (openclaw#196323); 79a6214 fix(message): retain local final replies in conversation history (openclaw#187795); caa978c feat(templates): open durable chat before verified setup (openclaw#196392); 78e73aa fix(sessions): cold PostgreSQL conversations fail after idle readers close (openclaw#189991); b6ed907 perf(sessions): persist active transcript facts for hydration (openclaw#193682); 1595dd2 feat(plugins): reauthorize accepted session work (openclaw#176886); b43ad0a fix(models): avoid reloading plugins on catalog refresh (openclaw#193903); 0947d02 fix(ci): avoid unrelated PostgreSQL runs and admit owned tests (openclaw#193870); 428ca7d feat(openclaw-id): add Gateway membership authority and publication behind the Labs flag (openclaw#192335); c718583 fix(update): repair refuses forever after a verified update fails a later step (openclaw#193132); 3f64174 fix: deliver background replies after a reload retires the turn registry (openclaw#193130); 982f3b1 fix(imessage): report Automation failures after Gateway updates (openclaw#186117); 31b28e9 fix(agents): wait for a peer OAuth refresh before failing request auth (openclaw#192906); cf50d4a feat(storage): support read-only PostgreSQL standby inspection (openclaw#192645); 82fd4e6 fix(agents): retain stale session target refusal reasons (openclaw#192681); 8ac4e19 fix(worktrees): reserve capacity on PostgreSQL (openclaw#192537); 718b349 fix: reduce session startup stalls under storage contention; 08f4a19 refactor(skills): move Skill Workshop into its bundled plugin (openclaw#192471); 837402a fix(clawrouter): keep upstream credit failures off the shared key (openclaw#192575); f38495f fix(plugins): reject late routing from canceled runs (openclaw#192492); dc5d61a improve(sessions): reduce unnecessary maintenance query rows (openclaw#192023); c4bf0dc fix(sessions): avoid extra maintenance scans for embedded archives (openclaw#184507); e44b3d6 fix(team-reports): recover after database connection loss (openclaw#192020); 991fb33 fix(logbook): recover after database connection loss (openclaw#192011); e6d0d2e fix(test): include omitted PostgreSQL conformance suites (openclaw#191962); da5ff0f fix(codex): reject native hooks from a previous run (openclaw#191788); 09f0b0b feat(plugins): add skill usage runtime for plugins (openclaw#191661); 00b2ff4 fix: parent sessions miss child approvals with a custom session store (openclaw#189827); be44b10 fix: stop completed session writes retaining request data (openclaw#191197); d40aa7c fix(sessions): replay creation requests across Gateway restarts (openclaw#190862); d894035 fix: await Doctor shared-state repair preparation (openclaw#190875); b515cc7 feat: fork threaded conversations with Telegram support (openclaw#190783); def6349 feat(plugins): plugins can run a hidden forked turn of a session with their own tools (openclaw#190950); d983e34 feat(plugins): plugin commands can continue the agent with a replacement prompt, on every channel (openclaw#190908); ea3f0b8 fix(ci): provision Node test prerequisites and retain Baseten routing (openclaw#191050); 29503e1 fix(update): Gateway stays stopped after the updater process dies mid-update (openclaw#188497); fc8c2d0 fix(update): preserve unfinished handoff artifacts (openclaw#190571); 7c26e8c fix(ci): cover PostgreSQL managed update handoffs (openclaw#190336); 4913d41 fix(ci): prevent truncated PostgreSQL target listings (openclaw#189509); 8925f62 fix(gateway): start restored PostgreSQL homes on the first attempt (openclaw#190291); 177fe32 feat(models): preserve inference capabilities in opt-in catalog v3 (openclaw#189678); 7faf32d feat: retain repository disk authority through recovery (openclaw#189106); a658df3 feat(database): capture externally quiesced SQLite migrations; 0f9e7f7 feat(database): capture exact SQLite migration capsules; 4fb684e feat(backup): add PostgreSQL local companion checkpoints; c89a101 fix(doctor): migrate auth profiles on PostgreSQL stores (openclaw#189639); 799de09 fix(ci): split oversized workspace and setup files (openclaw#189356); 21ee847 fix(acp): keep completed run conversations resumable (openclaw#189273); fce0e56 perf(sessions): open cold history without restoring archives (schema 39) (openclaw#188397) Validation: Baseline1 NUL-binding assertion failure/21passing; candidate22/22passes (188693-green.log). Real SQLite Doctor path and generated SQL proved; no native PostgreSQL server execution claimed. Co-authored-by: RomneyDa <[email protected]> (cherry picked from commit 0895146d8c1493146f5c6461eee0b10c329bdd1e) (cherry picked from commit f8ccaa70bc9773d6bbb569bc0e275eee0c544ead)
What Problem This Solves
Large tool catalogs can crowd frequently used tools out of the bounded Code Mode index and Tool Search directory.
User Impact
Adds an off-by-default Labs option,
agents.defaults.experimental.usageRankedToolIndex, that gives frequently and recently used OpenClaw tools priority in those indexes. Protected core tools remain included, selected entries retain canonical rendering order, and ranking never grants tool access. Empty/off cold starts preserve the existing output.Operators can inspect, bootstrap, or clear learned usage with
openclaw tools usage status|import|reset. The matching Gateway methods requireoperator.admin. This is limited to the built-in harness; the MCP directory and Codex harness are unchanged.Why This Change Was Made
Config inventory: the core count increases by exactly one (2,645→2,646) for the explicitly approved Labs setting; channel/plugin counts and hashes are unchanged. The inventory was regenerated, not hand-edited.
Storage/update behavior: agent schema 41→42 adds an initially empty STRICT
agent_tool_usagetable, with SQLite backup/rollback coverage and a PostgreSQL migration. Usage rows contain IDs, scores, and timestamps—not arguments, results, or per-call records. Existing metadata holds bounded import windows and 90-day run-participation receipts. Expired usage is excluded from reads and physically pruned on writes and hourly maintenance, even with the lab disabled. Retention skips closed Gateway admission and drains with its lifecycle owner. Reset fences pending writes without rewriting frozen prompts or transcripts. Crashes/failed flushes can lose unflushed counts; import does not replay live-managed runs.Evidence
All execution proof ran in isolated workspaces and state, on the Mac Studio or on AWS Crabbox. No live Gateway or operator database was modified.
Upgrade compatibility from v2026.11.3 (Mac Studio, Crabbox)
Build of
039a1f3fac69(rebased ontoorigin/maine3502d33aa08). Run on the Mac Studio through Crabbox (CRABBOX_CONFIG=~/.config/crabbox/studio.yaml, leasestudio-usage-ranked-tool-index, runrun_56d0c35d8d2eceb904d0c3020b794513). The test used one isolated state directory (OPENCLAW_STATE_DIR,HOMEandOPENCLAW_CONFIG_PATHunder~/crabbox-work/urti-proof/up-state), Gateway port 18941 bound to loopback, and a synthetic OpenAI Responses provider on 127.0.0.1:18942 that scripts Code Mode tool calls. No live Gateway, credentials or operator data were involved. I used the synthetic provider rather than a real model, because the ranking checks need deterministic tool calls.Before the upgrade, on v2026.11.3 (
npm install [email protected],OpenClaw 2026.11.3 (847611d)):openaiprovider with modelsgpt-a/gpt-b,agents.defaults.model.primary,tools.codeMode.enabled, the Responses endpoint, plusopenclaw config set agents.defaults.timeoutSeconds 900.config validatepassed.hist-a(sessions_list×3 andsession_status×1 through Code Mode, then a follow-up turn; 16 history messages),hist-b(sessions_list×1) andhist-c(plain chat).openclaw cron add --name urti-nightly --cron "0 3 * * *" --message "synthetic nightly automation", alongside the built-inheartbeat-mainjob.openclaw-agent.sqliteatuser_version=27, stateopenclaw.sqliteat 22.openclaw backup create --verifyproduced a verified archive (2026-11-12T13-26-26.862-08-00-openclaw-backup.tar.gz, 24.5 MB).Upgrade.
openclaw doctor --fix --non-interactiveran with the PR build, as candidate Doctor does inopenclaw update. It exited 0, saved pre-migration SQLite backups for both databases (*.pre-startup-migration-ff67a46b-….bak), and migrated the agent database 27→42 (agent_tool_usagepresent) and the state database 22→39. The PR Gateway then started on the same directory with no errors.Everything loads intact. Results were captured through the running Gateway (
config get,sessions.list,chat.history,cron list --all) and compared with the v2026.11.3 capture:timeoutSeconds, primary model, Code Mode, Responses endpoint)hist-b,hist-chistoryhist-ahistoryurti-nightlyautomationheartbeat-main's payload is rewritten by main's existing heartbeat migration (Doctor's "heartbeat migration backups" step). The cron capture from maine3502d33aa08on the same snapshot is byte-identical to the PR's.Lab off: no recording, prompt unchanged. I restored the v2026.11.3 snapshot and ran the same Doctor and the same first turn in upgraded session
hist-a, once with maine3502d33aa08and once with the PR. Instructions, the full tool schemas (10,697 B) and the Code Mode index (21 rows, 38 omitted) were byte-identical. The 50 KB input differed only in theDocs:checkout path and the minute in the turn timestamp. A further lab-off turn callingsessions_listtwice lefttools usage statusatenabled: false, rowCount: 0.Lab on: ranking from pre-existing history. After
openclaw config set agents.defaults.experimental.usageRankedToolIndex trueand a Gateway restart:openclaw tools usage import --agent main --since 90 --dry-run --jsonreportedapplied: falsewith 2 candidate rows:sessions_list6.0 (3 + 1 from v2026.11.3 history, plus 2 from the lab-off turn) andsession_status1.0.statusstill reportedrowCount: 0.tools usage import --agent main --since 90applied the same 2 rows, andstatusthen showed them.sessions_listandsession_status, which the cold 21-row index omitted. Rows keep canonical order.status --sessionshows the frozen snapshotorderedToolIds: [sessions_list, session_status].hist-cgot the same ranked index and the same frozen snapshot on its first turn with the lab on.Downgrade.
e3502d33aa08(agent schema 41) on a copy: startup is refused with "agent database for agent main … uses schema 42; this build supports 41".Logs observed in the upgraded Gateway, not caused by this PR: the
skill-workshopagent_endwarning "Plugin invocation scope is closed" appeared 3/3 tool-call turns on both main and the PR on the same upgraded state, plus macOS-only config watcher and scratch-root notices.Rebased head
73448cf482e9The current head is
73448cf482e9, onorigin/main4efd662cc2c6. Two generated-only rebases followed the039a1f3fac69gate run:2a1914519f65: the config baseline and Gateway predicates were regenerated.4efd662cc2c6:package.jsonschemaVersionsnow keeps main's newstate: 40alongside the PR'sagent: 42. Main's agent schema is still 41.On
73448cf482e9, local checks passed:pnpm tsgo:all,config:docs:check,gateway:validators:check,db:kysely:check,db:postgres:checkandsqlite:sessions-schema:check.src/statemigration test.The upgrade proof above ran on the
039a1f3fac69build. Neither later rebase touched PR runtime code.The first rebase, onto
origin/maine3502d33aa08(136 commits ahead of544e5c37f780), produced the head that the AWS gates and Studio proofs below ran on. Its conflicts:docs/.generated/config-baseline.sha256: regenerated (pnpm config:docs:gen). Core count is main's +1, for the Labs setting.src/agents/tool-search-directory.ts: kept main's run-granted exclusion (fix: narrow unconfigured GitHub tools in the built-in harness #197594's run-granted tool directory) and the PR's ranked native rows. BothisCoreCodingSurfaceToolNameandisRunGrantedCoreToolIdare imported, and main's newbuildRunGrantedToolDirectorynow filters with the PR'sNativeToolDirectoryRowtype.tsgocaught a predicate mismatch here that Vitest did not, and it is fixed in the same commit.src/agents/embedded-agent-runner/run/attempt-system-prompt-prepare.ts: kept main'sbuildRunGrantedToolDirectoryimport and runtime-context listing alongside the PR'sToolUsageRankingSnapshotinput toprepareToolPrompt.openclaw-schema-versions.ts), so the PR's 42 still follows main's latest. No renumbering was needed.Gates on AWS Crabbox lease
cbx_e47e618961fa(real git checkout at the exact head):pnpm check:madge-import-cycles,pnpm tsgo:all,pnpm config:docs:check,pnpm gateway:validators:checkandpnpm protocol:check.attempt-system-prompt,attempt-tool-search-prompt,attempt-session-runtime-prepare,attempt-prompt-phase), Tool Search directory/MCP/discovery,tool-usage-ranking, Code Mode, tool-search executor, the tool-usage Gateway/session tests, the CLI policy tests, the wrapper-inventory tests and everysrc/statemigration test.pnpm check:changed --base e3502d33aa08(runrun_f9115a2a559fe176dd0cca7c7d7d3946): typecheck, lint (848 s) and 37 lanes passed, including the dead-export scan, which main has fixed since the previous head. Only the Plugin SDK surface budget failed (entrypoints 163 > 162, exports 3888 > 3867, callable 2243 > 2236, wildcard reexports 1 > 0).pnpm plugin-sdk:surface:checkon a cleane3502d33aa08worktree on the same box fails with identical numbers, and this PR does not touch the Plugin SDK.CI follow-ups
Head
6aa74a2f8959(rebased ontoorigin/maind30e45c3f48e; generatedpredicates.jsregenerated). Its CI failures on73448cf482e9and this head:server-maintenance.telemetry.test.ts, PR-caused, fixed intest: keep tool usage retention out of the telemetry maintenance fixture. The PR schedules atool-usage-retentionmaintenance job, and in the worker-free telemetry fixture it tried to launch the registry-listing worker ("tool usage retention failed: Worker-free Gateway fixture attempted to launch a worker"). The fixture now stubspruneRegisteredAgentToolUsage, as it already does for the other storage sweeps; retention keeps its own scheduler test inserver-maintenance.test.ts. The CI red was timing-dependent and did not reproduce locally before the fix. After it, both maintenance test files pass under Node and the pinned Bun fork on the Mac Studio, and locally.help-exit.process.test.ts(precomputed root help): fixed on main. fix(cli): restore lightweight help and cleanup test startup #197936 (d30e45c3f48e) replaced the staticnode:tlsimport insrc/cli/one-shot-exit.ts. On this rebased head the file passes on the Mac Studio under Node and Bun.extensions/codex/src/node-app-server.runtime.test.ts("gates native resource readiness…"), inherited on Linux. The command proof returnsexitCode: 1, stdout: ""instead ofworker-command-proof. It fails identically on clean4efd662cc2c6andd30e45c3f48eworktrees on Linux, while the PR head passes it on the Mac Studio (Node and Bun). This PR touches no Codex files; the shard is selected by changed-core dependency.test/scripts/eager-import-closure.test.ts(PR wrapper inventory), inherited. It reports six missingpackages/openclaw-id-protocol/src/*imports reached throughsrc/gateway/openclaw-id/tunnel-principal.ts(main's OpenClaw ID work, feat(openclaw-id): link your OpenClaw ID so your owner devices connect as you #197628/feat(openclaw-id): member roles are opaque names in the protocol #197697). The same test fails identically on a cleanorigin/main02f29597c107worktree; none of those files are touched here.Full CI on
6aa74a2f8959: 208 checks passed (including all PostgreSQL conformance shards) and 43 were skipped. Two test jobs failed, both inherited (above), which also fails theopenclaw/ci-gateaggregate:checks-node-changed-extensions-bundle-1-3(the Codex runtime test) andchecks-node-compact-small-8(the PR wrapper inventory). The telemetry and help-exit failures from earlier heads did not recur. CI was not rerun.native-hook-relay.test.ts120 s timeout: not reproduced. Run on the Mac Studio (darwin-arm64), whole file, interleaved maine3502d33aa08/ PR head, 25 runs per cell:openclaw-v1.4.4-20261026-191755ec11The CI failure was on a Linux x64 Bun shard. The Bun runs here used the same pinned fork tag (confirmed from the running process path), but on darwin-arm64. That's 0/100 failures in total, with no difference between main and the PR, so I recorded it as a non-reproducing CI timeout, not a PR defect.
Latency acceptance. On 2026-11-11 Josh reviewed the Studio latency benchmark and judged the overhead not meaningful (about +2 ms paired median, in his words), which settles the no-meaningful-overhead acceptance criterion. The instrumented 300-pair table below is kept as recorded.
Earlier rebased-head behavior proof (AWS Crabbox)
Proof build
9eac6b2e24a1(runtime tree identical to01679c308c1d; the later CI fixes change prompt finalization only for settled-tool runs and thetoolsCLI root), rebased ontoorigin/main544e5c37f780. Both trees were built withpnpm buildon AWS Crabbox leasecbx_43da335fa37d(c7a.8xlarge, eu-west-1). The run used one isolated Gateway (--port 18931 --bind loopback, its ownOPENCLAW_STATE_DIR/HOME) and a synthetic OpenAI Responses mock on127.0.0.1:18932that scripts Code Modeexeccalls. Turns went throughPOST /v1/responses. Status came fromopenclaw tools usage status --json [--session <key>]. No live Gateway, credentials or operator data were involved. The surface is Code Mode, whose 8,000-character index omits 37–38 of the 58–59 catalog tools on this config.Feature off: same as main. The same config and state path ran against both builds, and the first provider request was compared byte for byte.
toolswas identical (16,830 B), and so was the Code Mode index (21 rows, 38 omitted). The rest of the 45,060 B input differed only in two checkout-path lines (Docs:/Source:pointing at the two worktrees). With the lab off on the head build,sessions_listwas used three times and then a fresh session was opened. The index was unchanged, andtools usage statusreportedenabled:false, rowCount:0.Feature on. The Gateway clock was shifted 20 days back (
libfaketime,FAKETIME=-20d, for the Gateway and its CLI), andupdate_goalwas denied:sessions_list×3 +session_status×1 in one turn (5 requests)6c8dba94…). Neither tool listed. SnapshotorderedToolIds: []sessions_list3.00,session_status1.00sessions_listandsession_status. SnapshotorderedToolIds: [sessions_list, session_status]sessions.patchmodel gpt-a→gpt-b (prefix break)rowCount: 2, scores 2.99997 / 0.99999 before and after (only decay over ~10 s)Real clock,
update_goalallowed again (newly added tool):atstill 20 days ago). The catalog refresh admittedupdate_goalas first-seen now, without rereading scoresupdate_goal(unused, now the only tool inside the 14-day newcomer window) entered the reserved newcomer slot.progress_card(unused, earlier id, first seen 20 days ago) left. Ranked tools stayedThe proof scripts (mock, config writer, driver) and raw logs are kept off-repo as task artifacts. Ports, state dirs and the lease were cleaned up after the run.
Rebase and gates. After the first rebase, check:changed found four PR-owned failures, and commit
fix: classify tool usage SQL as worker-ownedfixes them:tool-usage.kernel.ts, plus 3 inherited insession-cold-storage-chunks.ts. Fix: reviewed worker/purge classifications, andtool-usage-read.worker.tsregistered as worker-only.The second rebase, onto
544e5c37f780, resolved a conflict inattempt-session-runtime-prepare.tswith #197594: the GitHub publication tool-listing pin now refreshes the lazily prepared, ranking-aware prompt. That PR's new test was adapted toprepareSystemPrompt. Generated config baseline and Gateway predicates were regenerated (main's committedpredicates.jslackedinheritedDefault). Agent schema 42 still follows main's 41; no renumbering was needed.On AWS Crabbox (real git checkout at the exact head):
pnpm check:changed --base 544e5c37f780lanes including typecheck-all and lint (914 s),pnpm tsgo:core:testafter the test-type fix,pnpm protocol:check,pnpm gateway:validators:check,pnpm check:no-conflict-markers, the database-worker and mock-export ratchets, and targeted Vitest for the conflicted and ranking-owner files. The earlier Studio run passed all 33 PR test files.scripts/lib/mac-runtime-portability.mjs: auditMacAppPortability(from fix: bundle macOS native dependencies before signing #197383), anddb:worker-inventory:check(stale on main; not a CI gate).First full CI run (head
01679c308c1d). Six PR-caused failures were fixed ind627ff5e0f54(fix: complete tool usage cutovers for CLI, prompt finalization, and CI inventories):attempt-prompt-phase.test.ts(settled-turn finalization): the PR had switched the prompt-commit choice toinHistorySystemUpdates, so settled finalization, which has no active prompt series, committed a pending prompt. The commit now also requires the active series updater, restoring main's contract while ranking-only runs still persist the tool surface. Red under Node before, green after.root-command-descriptions.test.ts:toolswas a reserved, unregistered root and a root-help alias, but this PR registers it as a built-in command.toolsis now a normal built-in root (it keeps its fast, plugin-free startup policy); only the legacytoolstays reserved.openclaw tools --helpnow shows the tools help instead of root help.check:madge-import-cycles: the movedcreateHeldModelRunhelper created a cycle between two spawn test-support files. It now lives in the leafsubagent-spawn.held-model-run.test-support.ts.openclaw-agent-memory-revision-migration.test.ts: the v30→current migration now createsagent_tool_usage, so it joins the declared scope (as earlier version steps did).eager-import-closure.test.tsandpr-worktree-provision.test.ts:src/state/openclaw-agent-tool-usage-schema.tswas missing fromscripts/pr-lib/wrapper-components.txt.Inherited from main, not caused by this PR:
help-exit.process.test.ts > exits naturally after precomputed root helpfails identically on clean544e5c37f780(src/entry.ts→src/cli/one-shot-exit.ts→ staticnode:tls, from #197382; neither file is touched here). On AWS Crabbox leasecbx_8ed4d01ea875(runrun_ebde532cef8556f10fef50b0f986c57b), the fixed head passedcheck:madge-import-cycles, 42 focused test files (including every non-PostgreSQL migration test insrc/state, both wrapper-inventory tests and the production spawn boundary), andcheck:changed --base 544e5c37f780typecheck, lint (851 s) and ratchets. Only the main-inherited Plugin SDK budget and dead-export lanes remain red.Full CI on
d627ff5e0f54: complete. 215 checks passed (including all PostgreSQL conformance shards) and 49 were skipped. Two test jobs failed, which also fails theopenclaw/ci-gateaggregate:checks-node-compact-small-8: only the main-inheritedhelp-exit.process.test.ts > exits naturally after precomputed root helpfailure described above.checks-node-changed-compact-large-8: one 120 s timeout insrc/agents/harness/native-hook-relay.test.ts > keeps replacement pending PermissionRequest approvals when stale approvals settle, while awaiting a session-entry write. It does not reproduce: the whole file passes locally at this head (97 tests in 49.5 s, Node andOPENCLAW_VITEST_RUNTIME=bun), and the PR does not touch that test or its entry-write path. CI was not rerun.Transaction co-commit repair and current limitations
Publication status: the PR left draft so full CI could run. The measurements in this subsection were taken on pre-rebase head
6710d304b90a. Josh accepted the latency result on 2026-11-11 (about +2 ms paired median, not meaningful); see "Latency acceptance" above.pnpm test <file> --maxWorkers=1. Hosted CI seconds remain pending.Whole-turn latency (accepted by Josh on 2026-11-11 as not meaningful). The unchanged copied localization controls ran two isolated Gateways against a shared local mock provider, randomized order with seed
0x197128, ten turns per session, 320 pairs with the first 20 discarded. Controls were verified byte-for-byte and the original workspace restored. This is actual Gateway RPC/agent execution, not external-provider latency.Both arms produced 320 canonical successful tool calls and 32 checkpoints; the off arm had no usage rows and the on arm had the expected decayed count. The measured interval had:
toolUsage.*requestsThe one-request total writer difference is audit work; the 30 additional nonwriter requests are boundary ranking reads. Co-commit removed the separate per-turn usage writer requests, but this does not prove latency neutrality. The trace shows host reply-handling/scheduling stalls, but it does not identify their cause. This is an instrumented run: synchronous trace flushing and separate persistent Gateway processes prevent attributing the residual solely to the feature. Existing traces do not establish a Gateway GC, authority-handshake, or SQLite-commit cause. A discriminating follow-up would use an uninstrumented exact-candidate build, external timing, and reversed feature/process assignments with fresh state. Final performance acceptance remains outstanding.
Retained earlier repair proof
26a4a89b304f: config count/hash and Gateway predicates regenerated; config docs check 7.05 s, validators check 4.70 s, core types 3.85 s. No current mergeability assertion from that historical check.Retained initial feature proof
The following evidence covers the initial feature implementation; unchanged contracts were not rerun solely because the branch was rebased.
The latency overhead was accepted by Josh on 2026-11-11; the upgrade-compatibility proof above covers v2026.11.3 state. Hosted CI results are recorded in the rebased-head section above.
Changed-test wall times and test-cost allocation
Commands were
pnpm test <file> --maxWorkers=1; PostgreSQL files used the native conformance runner. Times include existing compiler/module/worker setup. The slower cold invocations are setup-dominated; the new database fixtures need the actual migration/worker boundary, rather than a mocked SQL helper. CI seconds: not yet available.extensions/copilot/src/tool-bridge.test.tssrc/agents/code-mode.bridge.lifecycle.test.tssrc/agents/code-mode.test.tssrc/agents/embedded-agent-runner/run/attempt-nested-tool-activity.test.tssrc/agents/embedded-agent-runner/run/attempt-plan-completion.test.tssrc/agents/embedded-agent-runner/run/attempt-session-runtime-prepare.test.tssrc/agents/embedded-agent-runner/run/attempt-stream-prepare.test.tssrc/agents/embedded-agent-runner/run/attempt-tool-search-executor.commit.test.tssrc/agents/embedded-agent-runner/run/attempt-tool-search-executor.test.tssrc/agents/embedded-agent-runner/session-prompt-state.tool-usage.test.tssrc/agents/embedded-agent-runner/session-prompt-state.tool-usage.worker.test.tssrc/agents/embedded-agent-subscribe.tool-usage.test.tssrc/agents/tool-search-directory.test.tssrc/agents/tool-usage-ranking.test.tssrc/agents/tool-usage-recorder.test.tssrc/agents/tool-usage.test.tssrc/cli/tools-cli.test.tssrc/config/sessions/tool-usage-import.test.tssrc/config/sessions/tool-usage.test.tssrc/config/zod-schema.agent-defaults.test.tssrc/gateway/server-maintenance.test.tssrc/gateway/server-methods-list.test.tssrc/gateway/server-methods/tool-usage.test.tssrc/infra/database-engine/agent-port-descriptor.test.tssrc/state/openclaw-agent-active-event-facts-migration.test.tssrc/state/openclaw-agent-active-event-facts-migration.postgres.test.tssrc/state/openclaw-agent-tool-usage-migration.test.tssrc/state/openclaw-agent-tool-usage-migration.postgres.test.tsui/src/pages/labs/labs-registry.test.tsThe original 2,067-line allocation, the separate 335-line inheritance repair allocation, and the exact 400-line co-commit allocation cover this change's exact net test/fixture growth: storage and cross-backend migrations, provenance and recording, frozen prompt boundaries and rendering, and operator controls. The shared scalar is unchanged.
Labs screenshots
Before:
After, default off: