Repository navigation
feat(audit): record observed runtime skill usage - #141004
wiecon-dev wants to merge 826 commits into
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: stale review; fresh review needed. Summary Next step Review history (312 earlier review cycles; latest 8 shown)
|
|
Updated this PR to address the ClawSweeper findings: skill-selection audit records now come from the observed runtime skill-usage boundary instead of prompt inference, |
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
🦞👀 Re-review progress:
|
|
@clawsweeper please re-review — synced with upstream/main (45 commits) and regenerated gateway validators. Focused skill-selection tests (25 passed) + tsgo:core clean. Skill-selection contract preserved: async worker listAuditEventsInDatabase, companion table audit_skill_selection_events, workspace-bootstrap-privacy re-export, 4-field run-usage contract. |
|
@clawsweeper please re-review — synced with upstream/main (merge 0fd5371, was 39 behind). Focused skill-selection tests 25/25 pass, tsgo:core clean. Contract preserved: async worker listAuditEventsInDatabase, companion table audit_skill_selection_events, workspace-bootstrap-privacy re-export, 4-field run-usage. |
|
@clawsweeper Synced with upstream/main (merge 0fd5371 → 3ba3b40, was 23 behind, now 0 behind). No conflicts; skill-selection files intact (async worker listAuditEventsInDatabase, companion table audit_skill_selection_events, workspace-bootstrap-privacy re-export, 4-field run-usage contract). Focused tests: 25/25 pass (runtime-skill-selection, audit-events.skill-selection, agent-run-usage). tsgo:core clean. Please re-review. 🙏 |
|
@clawsweeper please re-review — synced upstream/main (56 commits, merge 3d0ad70) and fixed skill-selection migration test for schema v41. Focused tests (223) + tsgo:core green. Skill-selection contract preserved: async worker listAuditEventsInDatabase, companion table audit_skill_selection_events, workspace-bootstrap-privacy re-export, 4-field run-usage. |
|
@clawsweeper please re-review — synced upstream/main into memorytunning-pr-v2 (new head c485703, 0 behind). Skill-selection files verified intact, focused tests 11/11 green, tsgo:core clean. |
|
@clawsweeper please re-review — synced with upstream/main (merge b19509c, was 20 behind). Focused skill-selection tests 11/11 pass, tsgo:core clean. Skill-selection contract preserved (async worker listAuditEventsInDatabase, companion table, workspace-bootstrap-privacy re-export, 4-field run-usage). |
|
@clawsweeper please re-review — synced with upstream/main (merge 379eec6, was 39 behind). Focused skill-selection tests 11/11 green, tsgo:core clean. Skill-selection contract preserved (async worker listAuditEventsInDatabase, companion table audit_skill_selection_events, workspace-bootstrap-privacy re-export, 4-field run-usage contract). |
|
@clawsweeper please re-review — synced upstream/main into memorytunning-pr-v2 (379eec6 → 2db4f19, 0 behind). Focused skill-selection tests 25/25 pass, tsgo:core clean. Skill-selection contract preserved: async worker listAuditEventsInDatabase, companion table audit_skill_selection_events, 4-field run-usage contract. |
|
@clawsweeper re-review please — synced upstream/main (19 commits) into memorytunning-pr-v2. Merge clean, skill-selection focused tests 11/11 green, tsgo:core clean. Skill contract preserved: async worker listAuditEventsInDatabase, companion table audit_skill_selection_events, workspace-bootstrap-privacy re-export, 4-field run-usage contract. |
|
🦞👀 Re-review progress:
|
|
@clawsweeper please re-review — synced upstream/main into memorytunning-pr-v2 (new head 2b86e22, was 2548dbb, 23 commits behind resolved to 0). Focused skill-selection tests (11 passed) + tsgo:core clean, skill-selection scope preserved. |
|
@clawsweeper please re-review — synced with upstream/main (24 commits, merge 51ca3cd). Skill-selection files intact (43 files diff), focused tests 22/22 pass, tsgo:core clean. |
|
@clawsweeper please re-review — synced with upstream/main (head |
|
@clawsweeper please re-review — head 96fe807 unchanged since Nov 21 (0 behind upstream/main), no fresh verdict on this head yet (last review 2026-11-21T12:33 on 2548dbb is stale for current head). Skill-selection contract preserved (async worker listAuditEventsInDatabase, companion table audit_skill_selection_events, 4-field run-usage). Focused tests green, tsgo:core clean. |
feat(audit): record observed runtime skill usage
What Problem This Solves
OpenClaw can emit skill-usage diagnostics while an agent reads or invokes a skill, but that observed runtime signal is not available through the durable audit surface. Operators therefore cannot inspect which skills were actually used during a run from the audit CLI/API.
Why This Change Was Made
The first revision inferred skill selection from prompt text after attempt completion. Review correctly called that out as the wrong boundary: prompt inference is not proof of skill use and it also risked perturbing the embedded attempt-result contract.
This revision records only observed runtime skill usage from the existing
before_tool_callskill-usage boundary:recordRunSkillUsage()already emits runtime diagnostics.skill_selectionaudit event is emitted withselectionSource: "observed_runtime"andselectionConfidence: "observed".skill_selectionis persisted outside run-start deduplication so it is not dropped afteragent.run.started.audit.listremains run/tool-only; the versionedaudit.activity.listsurface exposes skill-selection records.completeEmbeddedAttemptResult()is restored to the production calling contract, preserving the existing truncated-stream/tool recovery behavior.User Impact
openclaw audit --kind skill_selectioncan show observed skill usage for a run through the activity-list API.audit.listclients keep their shipped run/tool event shape and do not receive the new record kind.Evidence
Current-head validation after merging
upstream/mainand removing the unrelatedUSER.mdbootstrap policy change:pnpm tsgo:core pnpm protocol:check:swift pnpm db:kysely:check pnpm lint:kysely pnpm check:architecture pnpm test src/agents/workspace.bootstrap-privacy.test.ts src/audit/audit-events.test.ts src/gateway/server-methods/audit.test.ts packages/gateway-protocol/src/schema/audit.test.tsResults:
pnpm tsgo:corepassed.pnpm protocol:check:swiftpassed after regeneratingGatewayModels.swift.pnpm db:kysely:checkpassed after regeneratingsrc/state/openclaw-state-db.generated.d.ts.pnpm lint:kyselypassed after moving ordinary companion-table insert/read/prune queries to the sync Kysely owner.pnpm check:architecturepassed, including generated Kysely verification, Kysely guardrails, and database-first legacy-store guard.audit-events.test.ts: 54 tests passed, including companion-table storage, bounded retention, and observed runtime projection.server-methods/audit.test.ts: 34 tests passed, including explicitskill_selection/observedactivity access and V1-compatible unfiltered activity.audit.test.ts: 7 protocol schema tests passed, including activity schema discrimination.workspace.bootstrap-privacy.test.ts: 9 tests passed; shared sessions now drop only rootMEMORY.md, leavingUSER.mdbehavior unchanged.pnpm exec oxlint src/audit/audit-event-store.skill-selection-storage.ts src/state/openclaw-state-db.generated.d.tspassed. A full localpnpm lint:corewas started but manually stopped after 6+ minutes with no diagnostic output; CI remains the authoritative full core-lint signal.Published-release upgrade, older-reader, and candidate-reopen proof:
v2026.9.4tag at3a9d69db3created a fresh state database and wrote legacyagent_runsequence1.7d74807a5opened that exact database, preserved the legacy row, created the additiveaudit_skill_selection_eventstable, and wrote observeddebug-toolkitsequence2.v2026.9.4then reopened the candidate-used database without migration or schema errors, ignored the additive table, and wrote a second legacyagent_runat shared sequence3.[3, 2, 1], including both legacy rows and the retained skill-selection row.integrity_check: ok,user_version: 17,audit_events: 2, andaudit_skill_selection_events: 1.Changed Files
src/skills/runtime-skill-selection.ts— observed-only metadata marker.src/agents/agent-tools.before-tool-call.wrapper.ts— emitsskill_selectionfrom the existing observed skill-usage boundary.src/audit/agent-event-audit.ts— projects observed-only skill-selection records and routes them outside run-start deduplication.src/audit/audit-event-store.ts/src/audit/audit-event-store.skill-selection-storage.ts/src/audit/audit-event-types.ts— durable store/types for observed skill-selection metadata, with ordinary companion-table access through Kysely.src/state/openclaw-state-db.generated.d.ts— generated Kysely declarations for the companion table.src/gateway/server-methods/audit.ts— exposes skill-selection throughaudit.activity.listwhile preserving legacyaudit.list.packages/gateway-protocol/src/schema/audit-activity.ts— versioned activity schema includesskill_selection.packages/gateway-protocol/src/schema/audit.ts— legacy audit schema stays run/tool-only.src/commands/audit.ts— CLI uses the activity surface and renders selected skill metadata.docs/gateway/audit.md/docs/gateway/config-observability.md/docs/cli/audit.md— document the approved metadata fields, default-on collection, 30-day retention, separate 100,000-row cap, compatibility behavior, and explicit CLI filters.Test Plan
skill_selectionaudit events.skill_selectionpersists between run start and terminal events.audit.activity.listand CLI expose skill-selection records.audit.listremains run/tool-only.Review findings addressed (2026-10-10)
All five ClawSweeper code findings are fixed on this head:
-doubles to--, other unsafe bytes become-hh-hex), soDaily Briefpersists asDaily-20-Brief, distinct fromDaily-Brief→Daily--Brief(and_helperstays distinct fromhelper). The audit projector accepts the encoding. Boundary coverage insrc/skills/runtime-skill-selection.test.ts.audit_skill_selection_events(src/state/openclaw-state-schema.sql); additive DDL now runs at most once per connection and only for pre-admission databases, instead of on every insert and prune tick.COUNT(*)per connection lifetime, advanced by inserts and maintenance deletes, invalidated on rollback.docs/gateway/audit.mdnow states the recorder re-readslogging.audit.enabledon every event, so disabling stops new rows immediately.AuditActivitySkillSelectionV1is derived from the canonical schema properties viaSchemaContract(same pattern as adjacent variants), restoring wire-required attribution to typed consumers.Production-path proof
Throwaway script (not committed) driving production code on a temp state DB — marker encoder → recorder projector → production SQLite writer →
audit.activity.listGateway handler:Tool-invocation → emission coverage lives in
src/agents/agent-tools.skill-selection-audit.e2e.test.ts; recorder → DB → filtered readback insrc/audit/audit-events.skill-selection-hidden.test.ts; handler shaping insrc/gateway/server-methods/audit.test.ts.Round 2 (rev.199 follow-up)
Three further findings from review rev.199 are fixed on this head:
x-flag prefix up front), so truncation can never cut inside an escape and valid suffixes survive (skill-avsskill-bregression covered).demo--skillidentity while the run-usage receipt keeps the originaldemo-skillname.Round 3 (ClawSweeper re-review findings + live-Gateway proof)
Head
1e502cd5e72(synced with upstream/main, 0 behind). All review findings addressed:withLegacySkillSelectionCompanionAbsentstrips the unreleased table + indexes from every predecessor layout (getOpenClawStatePredecessorSchema,state-before-provision-source,state-before-bootstrap-deferredinputs). Historical inputs are byte-identical to upstream; the historical hash assertions are restored untouched; generated SQLite catalogs regenerated (228/235 inputs byte-identical, only current-layout inputs changed, as intended).aaa…(64)+alphavsaaa…(64)+betakeep distinct audit identities (regression test added).parseAgentRunRow/rowToAuditEventfromaudit-event-row.ts, with companion decoding confined torowToStoredAuditEvent+ the distinct companion row shape.workspace-bootstrap-privacy.tsextraction is reverted;src/agents/workspace.tsis byte-identical to upstream again.kind=skill_selection/status=observedfailed gateway validation (2 gateway tests red). Regenerated viascripts/generate-gateway-validators.mts; 21/21 gateway tests green.PRIVATE_PROMPT_CONTENTabsence assertion now supplies the sentinel as input (prompt/toolInput/skillFileContents); the unrelated expired-identity rendering case is removed from this PR.Live-Gateway behavior proof (new, real Gateway + shipped CLI)
Production chain on a temp state dir — real tool-boundary read of a real
SKILL.mdthroughwrapToolWithBeforeToolCallHook→ observer → recorder → store → running Gateway (fresh build,--auth none, loopback) → shipped CLI:Stored rows: ledger
agent.run.started(seq 1) → companionskill.selection.observed(shared seq 2,main/agent:main:proof/proof-session-1/proof-run-1/proof--demo) → ledgeragent.run.finished(seq 3). Metadata-only, no prompt/tool content persisted. (An LLM-driven variant was attempted with local ollamaqwen2.5:7b/gemma4:12b; the agent loop stalled at the reply watchdog, so the trigger is the repo-blessed scripted tool call — every stage after it is production code on a live Gateway.)Verification on this head
test/scripts/sqlite-schema-catalog-equivalence.test.ts203/203runtime-skill-selection+audit-events.skill-selection*incl. new upgrade/sequence tests greenaudit-events(37),commands/audit(36),gateway/server-methods/audit(21/21) greentsgo:coreclean,oxfmt --checkclean on touched files, line-cap ratchet clean vs upstream merge-baseRound 4 (re-review findings, head
883b4d8d003)Both P2 findings fixed, plus the requested proof/test adjustments:
src/audit/agent-event-audit.ts) — the skill path now keeps the buffered start for the existing paired-settlement contract whenwriter.record(start)returns false, while skill observations still record independently. Regression test: with a rejecting writer, the terminal settles as one pairedrecordRun(start, finish)instead of a lone finish.audit-event-store.skill-selection-storage.ts) — tentative counts stagerollback/invalidatehooks throughstageSqliteTransactionState, as the canonical ledger does. Negative control verified: without the fix a rolled-back overflow batch leaves the cap violated at 100,001 rows; with it the next insert trims honestly to 98,976. Covered bydrops tentative companion counts when their batch rolls back.schema_metaintact), and shows the stored audit row plus continued shared sequencing.qwen2.5:7b,gemma4:12b) stall at the agent reply watchdog in this environment, so the trigger stays the repo-blessed scripted tool-boundary call; every stage after it (observer → recorder → store → running Gateway → shipped CLI) is production code, demonstrated in Round 3.Verification on this head: skill-selection storage 7/7 (incl. rollback + v2026.11.3 upgrade), audit-events + commands/audit 45/45, gateway 21/21, runtime-skill-selection green,
tsgo:coreclean,oxfmt --checkclean.Round 5 (re-review: settlement intent + true v2026.11.3 fixture, head
4fd73e177bc)src/audit/agent-event-audit.ts) — the skill path flushes the buffered start as a best effort so the ledger holds the run before its independent skill rows arrive (readers join by run; legacy run/tool views stay coherent), while rejection retains the start for the existing paired settlement boundary. This keeps the PR improve(audit): persist agent run records together at settlement #178220 paired-start/finish contract: the terminal still settles as one paired run.50330aa9cf5,OPENCLAW_STATE_SCHEMA_VERSION = 39, noaudit_skill_selection_events). The regression test now builds the fixture from the current schema minus only the unreleased companion table at version 40 (matching the release lineage), opens it with the current build, and asserts:user_version/schema_metaintact, a stored workspace setting row byte-identical, the stored audit row readable, lazy companion creation on first skill write, and continued shared sequencing with correct readback.xaiextension whose dist build is broken by a pre-existing missing-@solidjs/compilerresolution from root, unrelated to this PR). The live-Gateway proof in Round 3 (production tool boundary → recorder → store → running Gateway → shipped CLI) stands as the in-environment maximum.Verification on this head: skill-selection storage 7/7, audit-events + commands/audit 45/45, gateway 21/21, runtime-skill-selection green,
tsgo:coreclean,oxfmt --checkclean.Round 6 (head
a71b0be6d94)847611dcaa3,OPENCLAW_STATE_SCHEMA_VERSION = 22, no companion table), not v39. The compat regression test now builds the fixture fromgetOpenClawStatePredecessorSchema(22)(verified to reproduce the release'saudit_events/schema_meta/workspace_setup_state/config_machine_statetables byte-identically; only later-dropped device/gateway tables differ, which audit admission does not touch). The fixture migrates 22→40 (backup custody via the standard test-support helper, as a real install would back up first) withschema_meta, a stored workspace setting, and the legacy audit row byte-identical, then records a skill_selection via lazy companion DDL with continued shared sequencing and correct readback.src/commands/audit.test.ts(restored the upstream single-case form).Verification on this head: skill-selection 8/8, audit-events + commands/audit green, gateway 21/21, runtime-skill-selection green,
tsgo:coreclean,oxfmt --checkclean.Round 7 — product upgrade run from published v2026.11.3 (head
a71b0be6d94, no new commits; proof only)847611dcaa3, schema v22) to create a state dir and record a legacy agent run through its production audit writer (sequences 1–2, run release-run-1, user_version 22).distrebuilt from PR source; the new Gateway booted the release DB with no schema refusal and migrated 22→40, release rows intact.SKILL.md→ observer → recorder → store (skill.selection.observed, shared sequence 4,upgraded-run-1), thenopenclaw audit --run release-run-1 --jsonreturns the release rows andopenclaw audit --kind skill_selection --jsonreturns the new skill row with full attribution. Full redacted transcript kept with the run notes.xaiextension whose dist build fails on the pre-existing missing-@solidjs/compilerroot resolution). The trigger is the repo-blessed scripted tool-boundary call; every stage after it is production code on live Gateways, now demonstrated across a genuine published-release upgrade boundary.Round 8 — P2 rollback fix + missing proof piece (head
d541860e07a)src/audit/audit-event-store.skill-selection-storage.ts) —ensureSkillSelectionAuditSchemaOncenow binds theskillSelectionSchemaEstablishedflag to the owning SQLite transaction viastageSqliteTransactionState(rollback/invalidate drop both the readiness flag and the warm row-count). A rolled-back lazy DDL no longer leaves a stale flag that skips recreation; the next write on the same handle recreatesaudit_skill_selection_eventsinstead of failing withno such table. Postgres path binds the same way (no-op outside a transaction).recreates companion schema after lazy creation rolls back: drops the companion table on a live handle, clears caches, runs a doomedrunOpenClawStateWriteTransaction(lazy DDL + throw), asserts the table is gone, then asserts a follow-uprecordAuditEventInDatabase(skill_selection)succeeds with the table present. Negative control: without the bind the follow-up throwsno such table.audit.activity.listreadback path covered byaudit-events.skill-selection+gateway/server-methods/auditsuites). Real-agent/model trigger remains environment-blocked as documented in Rounds 3–7 (local ollama stalls at reply watchdog; xAI needs the brokenxaidist); every stage after the repo-blessed scripted tool-boundary call is production code.logging.audit.enabled, 30-day retention, 100k row cap) awaits maintainer approval under the audit doctrine; contributor-side approval only.Verification on this head:
src/audit/audit-events.skill-selection.test.ts8/8 (incl. new rollback-schema + existing rollback-count + v22 upgrade)src/audit/audit-events.skill-selection-hidden.test.ts+src/skills/runtime-skill-selection.test.ts17/17src/gateway/server-methods/audit.test.ts21/21pnpm tsgo:coreclean,oxfmt --checkclean on touched filesRound 9 — re-verification on sync head + genuine release-upgrade proof (head
8de7c834dba, no new PR commits since Round 8)Since Round 8 (
d541860e07a) the branch only absorbed upstream sync merges —git log d541860e07a..HEADshows sync commits plus upstream fixes, zero PR-owned changes. Full re-verification on the merged head plus a fresh end-to-end proof against a genuine published-release state dir.listAuditEventsInDatabase(src/audit/audit-event-read.kernel.ts, delegated fromaudit-event-writer.worker.ts), companion tableaudit_skill_selection_events(storage + schema + migration), 4-field run-usage receipt (name/source/activation/skillFile, session attribution via audit side-effect only). (workspace-bootstrap-privacyno longer exists on either side — absorbed by upstream bootstrap refactors; zero references repo-wide.)audit-events.skill-selection+skill-selection-hidden+runtime-skill-selection+agent-tools.skill-selection-audit.e2e(via include-override, excluded from default projects by the*.e2eglob) — 26/26;audit-events+commands/audit+gateway/server-methods/audit+sqlite-schema-catalog-equivalence— 292/292;tsgo:coreclean;oxfmt --checkclean on touched files.Live-Gateway proof (new, genuine v2026.11.3 → PR-head upgrade)
State dir created by the published release itself (worktree of tag
v2026.11.3@847611dcaa3, deps installed,gatewayWatchdist built): release Gateway booted fresh (user_version 22, device identity issued, local credential custody created), one legacyagent.run.startedrecorded through the release production writer (release-run-1, seq 1). Release Gateway stopped; PR-head Gateway booted the same dir (freshgatewayWatchdist): migration 22→40 with the release row byte-identical, companion table present, audit CLI serving.Production tool-boundary read of a real
SKILL.mdthroughwrapToolWithBeforeToolCallHook→ observer →recordRunSkillUsage(4-field receipt) → busskill_selectionevent → the exact production recorder the Gateway subscribes (createAgentEventAuditRecorder+ real async writer) → store with lazy companion path → shipped CLI against the running Gateway (OPENCLAW_GATEWAY_URL=ws://127.0.0.1:18796,--auth none, loopback):Stored rows: ledger
agent.run.started(seq 1,release-run-1, preserved) → ledgeragent.run.started(seq 2,proof-run-r9) → companionskill.selection.observed(shared seq 3, full attribution) → ledgeragent.run.finished(seq 4). Metadata-only, no prompt/tool content persisted. Real-agent/model trigger remains environment-blocked as documented in Rounds 3–8; every stage after the repo-blessed scripted tool-boundary call is production code on a live Gateway, this time across a genuine published-release upgrade boundary with release-created credential custody (the synthetic-fixture shortcut fails at the client-credential migration without it — verified).Note:
openclaw auditwithout an explicitOPENCLAW_GATEWAY_URLresolved to an unrelated Gateway on this host's default port; the proof pins the URL explicitly.Round 10 — P1 validator regen + real-model trigger (head 82915d6, no upstream drift)
pnpm gateway:validators:genon this head; onlypackages/gateway-protocol/src/compiled/protocol.generated/predicates.jschanges (+4246/-4235 from renumbered checks).check_1259now acceptsskill_selection(check_1262),check_1264now acceptsobserved(check_1267). Verified through the real request validator (not mock):pnpm gateway:validators:checkclean (exit 0). Negative control still rejects:{"kind":"bogus"} => falsewithallowedValuediagnostics.ollama qwen2.5:7basked for the single skill file to read; model replied with exactly the relative path, which then drove the production wrapper (no hardcoded path after the prompt):wrapToolWithBeforeToolCallHookwith that model-chosen path emitted one bus event:listAuditEventsInDatabase, companion tableaudit_skill_selection_events, 4-field run-usage. Storage readback covered by green suites (skill-selection 11/11 incl. v22 upgrade, rollback-schema, rollback-count); live-Gateway + shipped CLI serving proven in Round 9 across genuine v2026.11.3 → PR-head upgrade (release-created credential custody). This Round adds the missing real-model trigger + real-validator gate on top of that chain.Verification on this head:
src/audit/audit-events.skill-selection.test.ts+ hidden + runtime + gateway/server-methods/audit + schema/audit: 4 Vitest shards passed (76.22s)pnpm tsgo:coreclean,oxfmt --checkclean on touched files,pnpm gateway:validators:checkclean