Skip to content

chore(deps): bump goreleaser/goreleaser-action from 6 to 7 - #2

Closed
dependabot[bot] wants to merge 1 commit into
mainfrom
dependabot/github_actions/goreleaser/goreleaser-action-7
Closed

dependabot[bot] wants to merge 1 commit into
mainfrom
dependabot/github_actions/goreleaser/goreleaser-action-7

Conversation

@dependabot

@dependabot dependabot Bot commented on behalf of github Mar 28, 2026

Copy link
Copy Markdown

Bumps goreleaser/goreleaser-action from 6 to 7.

Release notes

Sourced from goreleaser/goreleaser-action's releases.

v7.0.0

What's Changed

Full Changelog: goreleaser/goreleaser-action@v6...v7.0.0

v6.4.0

What's Changed

New Contributors

Full Changelog: goreleaser/goreleaser-action@v6.3.0...v6.4.0

v6.3.0

Full Changelog: goreleaser/goreleaser-action@v6.2.1...v6.3.0

v6.2.1

What's Changed

This version of the actions adds support for GoReleaser Pro v2.7.0 versioning (which dropped the -pro suffix). Older versions should work fine.

[!WARNING] This version is required for GoReleaser Pro v2.7.0+. Read more here.

Full Changelog: goreleaser/goreleaser-action@v6.2.0...v6.2.1

... (truncated)

Commits
  • ec59f47 fix: yargs usage
  • 752dede fix: gitignore
  • 1881ae0 ci: update dependabot settings
  • fdc5e66 chore: gitignore provenance.json
  • 51b5b35 chore(deps): bump semver from 7.7.3 to 7.7.4 in the npm group (#539)
  • 4247c53 ci(deps): bump docker/setup-buildx-action in the actions group (#538)
  • c169bfd chore(deps): bump @​actions/http-client from 3.0.2 to 4.0.0 in the npm group (...
  • 902ab4a chore(deps): bump the npm group across 1 directory with 4 updates (#536)
  • c59a691 chore: gitignore
  • 56cc8b2 ci: add job to automate dependabot pre-checkin/vendor
  • Additional commits viewable in compare view

Dependabot compatibility score

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


Dependabot commands and options

You can trigger Dependabot actions by commenting on this PR:

  • @dependabot rebase will rebase this PR
  • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
  • @dependabot show <dependency name> ignore conditions will show all of the ignore conditions of the specified dependency
  • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
  • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
  • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)

Bumps [goreleaser/goreleaser-action](https://github.com/goreleaser/goreleaser-action) from 6 to 7.
- [Release notes](https://github.com/goreleaser/goreleaser-action/releases)
- [Commits](goreleaser/goreleaser-action@v6...v7)

---
updated-dependencies:
- dependency-name: goreleaser/goreleaser-action
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
@dependabot dependabot Bot added dependencies Pull requests that update a dependency file github_actions Pull requests that update GitHub Actions code labels Mar 28, 2026
@vineethsai7 vineethsai7 closed this Apr 3, 2026
@dependabot @github

dependabot Bot commented on behalf of github Apr 3, 2026

Copy link
Copy Markdown
Author

OK, I won't notify you again about this release, but will get in touch when a new version is available. If you'd rather skip all updates until the next major or minor version, let me know by commenting @dependabot ignore this major version or @dependabot ignore this minor version. You can also ignore all major, minor, or patch releases for a dependency by adding an ignore condition with the desired update_types to your config file.

If you change your mind, just re-open this PR and I'll resolve any conflicts on it.

@dependabot
dependabot Bot deleted the dependabot/github_actions/goreleaser/goreleaser-action-7 branch April 3, 2026 02:36
@vineethsai vineethsai mentioned this pull request Apr 13, 2026
16 tasks done
vineethsai added a commit that referenced this pull request Apr 17, 2026
Adds context-aware `o`-menu to the Plugins panel matching the
Skills / MCPs parity pattern. Every verb in the menu dispatches
through `defenseclaw plugin <verb> <name>` so PolicyEngine,
admission audit, and the gateway RPC for runtime enable/disable
all stay in one place. No plugin state is forked in Go.

Action visibility is driven off verdict + enabled + status:
  - scan / info always available
  - block / unblock / allow driven off verdict
  - disable / enable driven off runtime state
  - quarantine / restore driven off status substring
  - remove always exposed last (destructive, but discoverable)

Tests cover:
  - PluginActions visibility across 4 verdicts × 2 statuses × 2
    enabled states (24 matrix combos), including no-duplicate-key
    invariant
  - `o` opens the menu with the plugin's name (falling back to ID
    when the manifest omits it) and populates info rows
  - every key PluginActions can emit maps to a non-nil CLI
    invocation via executeActionMenuItem (prevents silent no-ops
    when new verbs are added to the menu without dispatch wiring)
  - nil-selection safety on both open and dispatch paths
vineethsai7 pushed a commit that referenced this pull request Apr 21, 2026
…dge-row dedup (#116)

* feat: comprehensive CLI UX audit and remediation

Audit and fix all CLI command surfaces (Python + Go) for information
gaps, broken non-interactive flows, stale messages, credential
visibility, exit codes, and output consistency.

Setup commands:
- Redesign interactive guardrail prompts with value prop, numbered
  choices, and advanced options gate
- Add --accept-defaults alias, sensible defaults, and validation for
  guardrail non-interactive mode
- Change --restart default to True for setup guardrail
- Fix contradictory disable messaging
- Show Splunk Web credentials after setup; add --show-credentials flag
- Add --index/--source/--sourcetype and per-signal toggle flags for
  setup splunk non-interactive
- Validate skill-scanner policy names; show api_key_env consistently
- Add --verify to setup mcp-scanner
- Wire --remote for setup gateway non-interactive

Doctor command:
- Implement --json-output (was declared but never used)
- Check all subsystems from /health JSON (api, telemetry, splunk,
  sandbox)
- Upgrade scanner-missing severity from WARN to FAIL

Init flow:
- Show CLI + gateway versions in Environment section
- Replace bare "Health: ok" with rich /health JSON summary
- Auto-restart sidecar after init --enable-guardrail
- Context-aware "Next steps" based on what was configured

Gateway CLI (Go):
- Show health summary + log path after restart (parity with start)
- Sort status detail keys for stable output
- Return non-zero exit from status when sidecar unreachable
- Fix stale "defenseclaw sidecar" hint
- Add watchdog status subcommand
- Fix printSplunkLocalHint to read splunk-bridge .env
- Use configured APIBind for policy reload
- Sort policy diff output for determinism
- Add mode check to sandbox stop

Skill/MCP commands:
- Show full finding details in MCP scan (parity with skill scan)
- Show DB-only enforcement rows in MCP list
- Return exit code 2 for blocked/allowed scans
- Short-circuit upgrade when target == current version

Tests:
- Update test_guardrail.py for auto-restart default, --accept-defaults
- Update test_cmd_misc.py for Splunk credential display, add
  --show-credentials tests
- Update test_cmd_skill.py/test_cmd_mcp.py for exit code 2
- Add test_cmd_init.py version display tests
- Add test_cmd_doctor.py JSON output and record tests

* fix: resolve CI lint failures and add post-command hints

- Remove unused sortedMapKeys function (Go lint: unused)
- Fix f-string without placeholders and line-length violations (ruff F541/E501)
- Add tty-aware hint() helper for Python CLI and printHint() for Go CLI
- Add contextual "next steps" hints to: aibom scan, codeguard install-skill,
  status, skill scan/block/list, mcp scan/list/set, plugin install/remove/list,
  gateway stop, scan code
- Hints are dim-styled and only shown on interactive terminals (suppressed
  in JSON mode, piped output, and test runners)

* feat(tui): upgrade to Bubbletea v2 with inline detail panes, auto-init, and review fixes

- Migrate TUI to charm.land/bubbletea/v2, bubbles/v2, lipgloss/v2
- Add inline detail panes to Skills, MCPs, Plugins, Audit, Inventory panels
  with enriched data from audit store (findings, enforcement state, history)
- Add Esc key handling to close detail panes in all panel key handlers
- Fix ScrollOffset in Plugins/Audit panels to use dynamic listHeight()
- Fix AuditPanel.listHeight() off-by-one (was -2, now -3)
- Cache GetDetailInfo results per panel to avoid re-querying SQLite on render
- Run auto-init via standalone goroutine to keep executor free for user commands
- Close inventory detail pane on sub-tab switch
- Add explicit 'defenseclaw tui' CLI command
- Add action menu, activity panel, command executor, palette, health panel
- Add unit tests for detail toggle, cache invalidation, layout calculations

* fix: resolve Go and Python lint failures

- Remove unused `sys` import from cmd_tui.py (ruff F401)
- Replace WriteString(fmt.Sprintf(...)) with fmt.Fprintf (QF1012)
- Remove unused struct fields: ActivityPanel.scroll, logPollMsg.lines
- Fix switch type assertion pattern in logs.go (S1034)

* fix(tui): fix inventory table alignment, add clickable filters and data source hints

- Fix column alignment in Skills/Plugins tables using visual-width-aware
  padRight() helper instead of fmt.Sprintf padding (ANSI codes broke alignment)
- Widen SOURCE column to show full values instead of truncating to "opencla..."
- Add clickable sub-tab bar in inventory (Summary, Skills, Plugins, etc.)
- Add clickable filter stats in Skills (eligible/warning/blocked) and
  Plugins (loaded/disabled/blocked) sub-tabs with toggle behavior
- Add keyboard filter shortcuts (1-4) and Esc to clear
- Add italic hint notes explaining data source differences:
  "Inventory lists all items found by AIBOM on disk. The [X] tab only shows
  items with scan/enforcement records."

* fix(tui): fix command input rendering, delete wizard, add setup hint + review fixes

- Fix command input bar: remove lipgloss double-wrapping of textinput.View()
  that made typed text invisible; move background to textinput's own styles
- Delete pre-TUI huh-forms wizard (wizard.go); setup tab covers this now
- Add "First time?" notice in overview when system is unconfigured
- Fix autoInitCmd capturing Model by value (activity updates were lost)
- Fix readInteractiveOutput partial line corruption; split into readLineOutput
  (non-interactive) and readInteractiveOutput (PTY) with EOF flush
- Gate mouse clicks under full-screen overlays (help, detail, action menu)
- Fix setup wizard stuck state when executor rejects command
- Add bounds checks in setup.go to prevent panics
- Open palette on input bar mouse click (match :/ Ctrl+K behavior)
- Fix buildNotices cfg==nil suppressing first-time hint

* fix(tui): handle scanner.Err() in readLineOutput

Surface I/O errors (e.g. token-too-long) instead of silently dropping them.

* fix(guardrail): harden detection strategies, fix data races, and improve judge resilience

- Add RWMutex on allRuleCategories to prevent data race between
  ApplyRulePackOverrides (write at startup) and ScanAllRules (read on
  every request)
- Guard against ReDoS in user-supplied rule pack regexes with compile
  timeout and pattern length cap
- Fix completion-side NEEDS_REVIEW secrets being silently dropped when
  no judge is available — now falls back to MEDIUM/alert verdict
- Improve inspectJudgeFirst fallback documentation and ensure regex
  safety net always runs alongside judge results
- Switch postCallContext from context.Background() to
  context.WithoutCancel(parent) to preserve request-scoped tracing and
  correlation IDs while still detaching from request cancellation
- Apply pre-judge content strips in AdjudicateFindings, consistent with
  other judge code paths
- Add judgeSem rate limiting to inspectToolResult to bound concurrent
  LLM judge calls from tool-result inspection
- Fix broken indentation in proxy.go mid-stream scan block
- Tighten "token:" secret pattern from bare substring to regex requiring
  assignment syntax (token[:=] followed by 8+ chars) to reduce FPs
- Add "exfil" shorthand to triage exfil patterns
- Redact dotenv filesystem path in LLM judge init logging

* feat: production-readiness hardening — no placeholders

P0: HTTP rate limiting (100 req/s, burst 200), log rotation via
lumberjack, os.Exit only in main(), installer checksum verification.

P1: Real E2E tests replacing all t.Skip() stubs (scan rules, prompt
injection, block/allow/quarantine admission gate, audit persistence),
plugin registry Discover()/Register()/Get() with full tests, config
version migration (v0→v2), goreleaser homebrew tap enabled, NOTICE file.

P2: SSRF hardening tests (decimal/hex/IPv6/file/ftp), rate limit
middleware tests, header injection tests, /health/liveness endpoint,
malicious fixture updated with real detectable patterns.

Full test suite: 18/18 packages pass.

* fix: wire-up audit, fix 12 bugs, tighten AMD P2 regexes, remove dead code

Fixes found during deep review-and-ship audit:

Critical/High:
- watcher: takeActionFor now handles InstallPlugin/InstallMCP instead of
  falling through to watch.auto_block, honoring per-type take_action config
- guardrail: regex_only strategy no longer invokes the LLM judge (was adding
  unexpected latency/cost for operators choosing regex-only mode)
- config: EffectiveStrategy() default aligned with viper/defaults (regex_judge)
- configedit: add missing applyConfigField case for stream_buffer_bytes

Medium:
- tui: Tab/Shift+Tab now delegates to Policy panel before global panel switch
- tui: mouse wheel blocked behind open overlays (help, detail, action menu)
- tui: highlightRego guarded against strings.Index returning -1
- tui: Cisco AI Defense wizard fields now pre-filled from config
- tui: overview uses EffectiveStrategy() instead of hardcoded fallback

Security:
- policy: suppressions.yaml written with 0600 permissions (was 0644)

AMD P2:
- token regex tightened to require 20+ alphanumeric value (fixes FP on
  conversational "reply with this token: XYZ")
- bulk access triage pattern added for sensitive tools (users_list top N)

Wire-up:
- default_llm_api_key_env/default_llm_model added to TUI config editor
  and applyConfigField (were only usable via YAML/Python CLI)
- PolicyPanel.executor removed (dead field; commands returned to parent)
- WizardDone removed (dead function; WizardFinished is the active path)

All 18 Go packages pass with -race. go vet clean. Zero linter errors.

* feat: port multi-turn ContextTracker, scanner normalization, and per-scanner policy packs from PR #109

Consolidates PR #109 (feat/unified-rule-pack-arch) into this branch so a
single PR carries all rule-pack work. PR #109 is now obsolete.

Ported net-new features:

  * internal/gateway/context_tracker.go + _test.go
    - Per-session bounded buffer (10 turns / 200 sessions by default)
    - HasRepeatedInjection() raises HIGH alert when 3+ user turns hit
      local injection patterns within a session
    - Adapted HasRepeatedInjection signature to drop the *RulePack param;
      rule pack overrides already apply globally via
      ApplyRulePackOverrides(), so the simpler API is sufficient
    - Wired into EventRouter.handleSessionMessage (Record + multi-turn
      escalation path with telemetry emit)

  * internal/gateway/normalize.go + _test.go
    - NormalizedFinding with canonical ID, source, category, severity
    - Maps scanner-specific IDs (SEC-*, JUDGE-*, LP-*, CISCO-*) to
      stable canonical form for cross-scanner correlation

  * internal/scanner/codeguard.go + plugin.go
    - CodeGuardScanner now loads custom YAML rules from rules dir at
      construction; built-ins + custom rules concatenated per scan
    - PluginScanner gains Policy/Profile fields for per-scanner policy
      pack selection

  * policies/scanners/{codeguard,plugin-scanner,skill-scanner}/*.yaml
    - Per-scanner policy packs (default/strict/permissive/balanced tiers)

All 18 Go packages pass with -race -count=1. go vet clean. Zero lints on
edited files.

* fix: final review pass — heartbeat tests, scanner key fallback, sig cleanup

Close-out of the review-and-ship cycle on PR 111:

* Narrow heartbeat bypass tests — `isHeartbeatMessage` now verified to
  require the specific OpenClaw tokens (HEARTBEAT.MD / HEARTBEAT_OK)
  AND a <=512 byte payload; adding the word "heartbeat" alone or
  wrapping a large prompt in heartbeat tokens cannot bypass guardrails.
* Align Python skill-scan paths with `app.cfg.effective_inspect_llm()`
  so the shared `default_llm_api_key_env` fallback works the same way
  from the CLI as it does from the Go gateway.
* Update `test_guardrail_detection_strategy_defaults` to assert the new
  `regex_judge` default (matches Go + Python `_merge_guardrail`).
* Drop the unused `rp *RulePack` parameter from
  `ContextTracker.HasRepeatedInjection` — patterns are now sourced from
  the globally active rule pack via `ApplyRulePackOverrides`, so the
  per-call pack argument was dead code.

All tests pass locally: `go test -count=1 ./...` (18 packages),
`python -m unittest cli.tests.test_judge` (13/13).

* fix(ci): resolve lint, dep audit, and E2E sidecar health gaps

Go lint (staticcheck):
- Drop embedded-field selectors in provider_bifrost.go (QF1008).
- Replace WriteString(fmt.Sprintf(...)) with Fprintf in policy.go (QF1012).
- Remove dead readOpenAISSE helper and its now-unused imports.

Python dep audit:
- Override python-multipart>=0.0.26 to close CVE-2026-40347 (pulled in
  transitively by mcp and cisco-ai-skill-scanner).

E2E reliability:
- Replace fixed 5s sleep after gateway start with a 30s poll loop on
  'defenseclaw-gateway status' so slow self-hosted runners don't fail.
- On failure, dump the last 200 lines of gateway.log and watchdog.log
  and upload them as artifacts for post-mortem debugging.

* fix(lint): replace remaining WriteString(fmt.Sprintf(...)) with Fprintf

Three additional QF1012 staticcheck findings that only surfaced after the
first batch of fixes:

- internal/gateway/llm_judge.go: triage-signal formatter
- internal/tui/policy.go: two rule-browser helpers

* fix: seed guardrail rule packs, emit canonical finding IDs, drop broad token FP

- cmd_init now seeds bundled guardrail profiles (default/strict/permissive)
  into policy_dir so operators can edit YAML and `policy reload` picks it up
- paths.py gains bundled_guardrail_profiles_dir() resolver
- proxy + api guardrail audit events include canonical=<ids> for
  cross-scanner correlation (wires NormalizeScanVerdict into telemetry)
- legacy policies/default.yaml and policies/strict.yaml drop bare 'token:'
  pattern — gateway secretPatternRegexes already covers tokens with
  20+ char entropy requirement (fixes false positives like "reply with
  this token: XYZ")
- adds unit coverage: TestHandleGuardrailEventEmitsCanonicalIDs,
  TestSeedGuardrailProfiles (seed/preserve/noop paths)

* test(gateway): switch live E2E from Anthropic-direct to Bedrock via Bifrost

The Anthropic-direct account backing TestBifrostE2E_LiveAnthropic* is out of
credits, causing Full Live E2E to fail on every run. Switch both tests to
Bedrock via Bifrost (ABSK bearer key) against
claude-haiku-4-5-20251001-v1:0, gated on BIFROST_API_KEY so they still
skip gracefully when the secret is absent.

- Rename TestBifrostE2E_LiveAnthropic{,Stream} -> TestBifrostE2E_LiveBedrock{,Stream}
- Swap ANTHROPIC_API_KEY -> BIFROST_API_KEY (ABSK auto-detected as Bedrock)
- Use model bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0
- Wire BIFROST_API_KEY into the core and full-live job env blocks

* test(e2e): bump sidecar /health wait from 60s to 180s on self-hosted runners

The Core/Full-Live E2E workflows on the ARM64 self-hosted runner flake on a
60-second wait for SIDECAR_URL/health after defenseclaw-gateway start. The
gateway log shows the WebSocket handshake completing after the 60s window
expires — the sidecar is healthy, just slower to boot under runner load.

Extend both blocking /health waits (Phase 1 startup, Phase 7C recovery) to
180s and dump the tail of gateway.log plus defenseclaw-gateway status on
timeout so any future regression is self-diagnosing in-line.

* test(e2e): self-heal sidecar bring-up in Phase 1 with 3x retry

The previous 180s single-shot /health wait still failed on the ARM64
self-hosted runner because the sidecar daemon can exit during early
init before /health is ever served (observed on main too, not just this
branch — April 15 & 16 scheduled runs on main failed the same way).

Gateway.log dumps show the init-era sidecar is already dead by the time
Phase 1's stop reaches it ("Gateway sidecar is not running" before our
stop call) and the newly-spawned sidecar also exits within 5 seconds of
start. The log contains two overlapping startup sequences, suggesting a
brief lifecycle race.

Rather than keep extending the timeout, wrap the stop→start→health-wait
block in a 3-attempt loop with a 60s wait per attempt (~same wall clock
budget as before: 180s). Each defenseclaw-gateway start internally calls
killStaleProcesses via pgrep, so the retry naturally reaps any stragglers
that caused the previous attempt to fail.

On final failure, also dump watchdog.log, the full defenseclaw/openclaw
process tree, and listeners on 18789/18970 so the next flake is
self-diagnosing without needing an artifact download.

* e2e: add OOM/dmesg diagnostics + per-process memory trace on sidecar failure

Previous retry loop proved the sidecar is being killed externally (reaches
"event loop running" then vanishes within ~60s with no panic, no shutdown
message, watchdog survives). This is the signature of SIGKILL from outside,
almost certainly OOM killer on the shared self-hosted ARM64 runner.

We can't fix the runner from the script. But we can capture definitive
evidence so the root cause is not ambiguous on the next failure:

- free -m before each of the 3 bring-up attempts
- background sampler logs sidecar PID + VmRSS + VmSize every 3s while
  we poll /health; when the process vanishes, the trace timestamps the
  death and the last-known memory usage
- ps at failure now includes rss/vsz columns
- dmesg -T | grep -iE 'out of memory|killed process|oom|defenseclaw-gat'
- journalctl -k fallback (some distros gate dmesg behind CAP_SYSLOG)
- system-wide free -h at failure moment

On the next red run, either we'll see the OOM smoking gun in dmesg (then
the fix is runner memory / workload isolation, not CI patches), or the
memory trace will show steady RSS right up to death (then we'll know it
was an external pkill / signal, not OOM).

Refs PR #111. Bedrock migration itself is green; this is instrumentation
to unblock the pre-existing runner infra flake that also reproduces on
main.

* sidecar(diag): instrument signal handling + heartbeat to pinpoint silent exits

The E2E sidecar flake on the self-hosted ARM64 runner shows the sidecar
reaching "event loop running", writing audit DB entries, then vanishing
within ~3–5 seconds. No panic, no shutdown message, no OOM trace in
dmesg/journalctl, and the watchdog sibling (same binary) survives. This
is consistent with an external termination (SIGKILL) or a signal we're
not currently catching.

This commit adds scoped diagnostic instrumentation to runSidecar:

1. Widen signal.Notify to capture SIGHUP, SIGQUIT, SIGPIPE, SIGUSR1,
   SIGUSR2 in addition to SIGINT/SIGTERM. Each signal is logged with
   its name, number, PID, and RFC3339Nano timestamp before any action
   is taken. SIGPIPE is logged but NOT treated as a shutdown trigger —
   this also suppresses Go runtime's default "exit on SIGPIPE to stderr"
   behaviour that could silently terminate us if the log file descriptor
   transiently misbehaves.

2. 5-second heartbeat goroutine that prints
   "[sidecar][diag][heartbeat] alive at HH:MM:SS.mmm pid=N uptime=Ns"
   so the post-mortem CI log can narrow the kill window to <5s.

3. Defer + explicit log line around sc.Run(ctx) so we capture the
   exact return value, ctx.Err(), and PID at the moment runSidecar
   unwinds. If the process dies BEFORE these lines print, the kill
   is truly silent (SIGKILL or equivalent).

Interpretation guide for next E2E run:
- If "[sidecar][diag] received signal" appears → we know which signal
  and who probably sent it.
- If heartbeats stop mid-stream and NO signal line appears → SIGKILL,
  external source (runner OOM, supervisor, or manual pkill).
- If "sc.Run returned" appears → ctx was cancelled internally and we
  can inspect ctxErr to find the cancellation source.

No production behaviour change; only added log lines. Keeps PR #111
scope tight to diagnostic observability for a pre-existing sidecar
lifecycle bug that also reproduces on main.

* ci(e2e): switch full-live LLM from Anthropic to OpenAI (gpt-4o-mini)

PR #111's Full Live E2E has been failing on:
  "LLM request rejected: Your credit balance is too low to access the
   Anthropic API. Please go to Plans & Billing to upgrade or purchase
   credits."

This is not a regression in PR #111; the shared Anthropic test account
has no balance. OPENAI_API_KEY is already wired into the full-live job
env (line 351) and reportedly has credits, so migrate CI to OpenAI:

1. openclaw.json patch step now writes auth.profiles["openai:default"]
   (provider=openai) and agents.defaults.model.primary = "openai/gpt-4o-mini"
   instead of the anthropic:default / claude-sonnet-4-5 pair.
2. auth-profiles.json keyRef.id switches from ANTHROPIC_API_KEY to
   OPENAI_API_KEY; profile order map now keys on "openai".
3. GUARDRAIL_REQUEST_MODEL is set to openai/gpt-4o-mini in the patch
   step (the subsequent Init step re-derives it from OC_MODEL, which is
   consistent since the primary model is now the OpenAI one).
4. Downstream provider detection (grep "openai\|gpt\|o1\|o3\|o4") at
   line 731 already maps to OPENAI_API_KEY, so API_KEY_ENV resolution
   for the guardrail config (cfg.guardrail.api_key_env) works without
   further changes.
5. "Restore OpenClaw Anthropic model" step renamed to
   "Restore OpenClaw model and auth backups" (behaviour is generic —
   restores whatever the pre-run backup held — so the old name was
   actively misleading).

ANTHROPIC_API_KEY remains plumbed through the env and dotenv files as
defensive pass-through in case any other component consults it; it is
no longer the driver of agent LLM traffic.

Why gpt-4o-mini: cheapest current OpenAI model that supports tool
calling end-to-end (required by block/allow enforcement tests where the
agent must actually attempt tool use); the earlier Anthropic choice was
sonnet-4-5 primarily for consistency with dev, not because the tests
need a premium model.

Guardrail round-trip now takes the native OpenAI chat-completions shape
through the proxy's /v1/chat/completions handler and
resolveConfiguredProvider → Bifrost OpenAI provider path, which is the
simplest routing in the codebase and avoids any Bedrock/SigV4 or
Anthropic->Bedrock translation work.

Core E2E is unaffected (that job doesn't exercise the live LLM path).

* Revert "ci(e2e): switch full-live LLM from Anthropic to OpenAI (gpt-4o-mini)"

This reverts commit 3b7153ce684e6a5437dcd277ad9dcdc4f93674fe.

* ci(e2e): switch full-live LLM to OpenClaw-native amazon-bedrock provider

Previously the full-live E2E job hard-coded OpenClaw to call the Anthropic
API directly (anthropic/claude-sonnet-4-5 + ANTHROPIC_API_KEY), which is
exactly the path that's currently failing because the Anthropic account is
out of credits. That's also unnecessary: OpenClaw supports AWS Bedrock
natively via its stock amazon-bedrock provider
(https://docs.openclaw.ai/providers/bedrock), and our BIFROST_API_KEY
secret is already an AWS Bedrock bearer token (ABSK…) — the exact format
AWS_BEARER_TOKEN_BEDROCK wants. Reusing the key OC-side means we drop the
Anthropic dependency entirely with no new secrets.

Workflow changes (.github/workflows/e2e.yml, full-live only):
  - Add AWS_BEARER_TOKEN_BEDROCK: \${{ secrets.BIFROST_API_KEY }} and
    AWS_REGION: us-east-1 to the job env so OC's AWS SDK default chain
    can authenticate to Bedrock.
  - Patch openclaw.json to register models.providers[\"amazon-bedrock\"]
    with api=bedrock-converse-stream, auth=aws-sdk, and a single model
    entry for us.anthropic.claude-haiku-4-5-20251001-v1:0 (cheapest
    current Claude on Bedrock with tool-calling, matches the model our
    in-process Bifrost e2e test already covers).
  - Point agents.defaults.model.primary at
    amazon-bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0 and
    rewrite auth-profiles.json to use mode=aws_sdk (no keyRef).
  - Propagate BIFROST_API_KEY + AWS_BEARER_TOKEN_BEDROCK + AWS_REGION
    into both ~/.defenseclaw/.env (guardrail sidecar) and the OpenClaw
    systemd user-service drop-in environment file.
  - In the guardrail-detection block, match Bedrock models first (order
    matters because a Bedrock inference profile id contains \"claude\")
    and set API_KEY_ENV=BIFROST_API_KEY so the guardrail proxy can talk
    to Bedrock via the embedded Bifrost SDK. Drop the stale
    \"SigV4 not supported\" comment — Bifrost consumes the ABSK bearer
    token directly, no SigV4 signing needed.

Go changes (required so the guardrail sidecar actually understands the
\"amazon-bedrock/\" prefix OpenClaw writes into openclaw.json):
  - internal/gateway/provider.go: add \"amazon-bedrock\" to
    knownProviders so splitModel() correctly splits
    \"amazon-bedrock/us.anthropic…\" into (amazon-bedrock, us.anthropic…).
  - internal/gateway/provider_bifrost.go: add \"amazon-bedrock\" to
    mapProviderKey() as an alias of \"bedrock\" -> schemas.Bedrock so the
    Bifrost SDK routes it correctly.
  - internal/gateway/provider_bifrost_test.go: new
    amazon_bedrock_openclaw_prefix table case in
    TestBifrostProvider_Creation and \"amazon-bedrock\" added to
    TestMapProviderKey_AllKnownProviders.

All gateway + config tests pass locally, including the live Bedrock
round-trip tests (TestBifrostProvider_LiveBedrock,
TestBifrostProvider_LiveBedrockStream).

* ci/doctor: unblock full-live on amazon-bedrock (fix cascade from bad auth profile)

The previous full-live run hit a single root cause that cascaded into ~8
"FAIL" lines:

  auth.profiles.amazon-bedrock:default.mode: Invalid input
  (allowed: "api_key", "oauth", "token")

OpenClaw's config schema only allows those three values for an auth-profile
mode; our Python patch step wrote `mode: "aws_sdk"`, which OC rejected at
startup, so the gateway never came up and every downstream check (doctor,
block/allow, skill-api disable, etc.) failed with "gateway: not connected".
Per https://docs.openclaw.ai/providers/bedrock, Bedrock auth is driven by
the provider's own `auth: "aws-sdk"` setting, which delegates to the AWS
SDK default credential chain (AWS_BEARER_TOKEN_BEDROCK is already exported
from the BIFROST_API_KEY secret) — no auth-profile entry is needed.

This change:

  * .github/workflows/e2e.yml
    - Stop writing an `auth.profiles.amazon-bedrock:default` entry into
      openclaw.json; scrub any stale entry for good measure.
    - Write auth-profiles.json as an empty profile store so a prior run's
      ANTHROPIC_API_KEY-based profile can't bleed through.
    - Remove ANTHROPIC_API_KEY from the full-live job env entirely. The
      guardrail passthrough / duplicate-header / X-AI-Auth tests in
      scripts/test-e2e-full-stack.sh all skip cleanly with "ANTHROPIC_API_KEY
      not set", which is the correct behavior for a Bedrock-only live run
      (previously these tests called api.anthropic.com directly with a
      depleted key and reported "credit balance too low" as test failures).

  * cli/defenseclaw/commands/cmd_doctor.py
    - Route the "LLM API key" check by *provider prefix* (segment before the
      first "/"), not by substring. The old `"anthropic" in model` check
      wrongly matched Bedrock inference profile ids like
      `amazon-bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0` and sent
      our ABSK bearer token to api.anthropic.com, producing a spurious 401
      FAIL even when the actual Bedrock path was fine.

  * cli/tests/test_cmd_doctor.py
    - Lock the new behavior in with three regression tests: the bedrock
      inference profile case (must NOT call _verify_anthropic), plus the
      `anthropic/…` and `openai/…` happy paths.

* review: address H1-H6 + M1-M10 findings from PR #111 review

High-severity hardening:
- H1/M10: cache policy.Engine per-sidecar via sync.Once; log init
  failure exactly once instead of per-request, preventing repeated
  Rego recompilation and log floods.
- H2: gate raw judge-response logging behind DEFENSECLAW_JUDGE_TRACE=1
  and add redactEntity() for PII-safe logging of detected entities.
- H3: replace process-wide atomic.Bool judgeActive with a context-scoped
  withJudgeActive/isJudgeActive guard; recursive judge invocations are
  now blocked per-request without globally serialising concurrent
  guardrail traffic.
- H4: harden injection/PII/tool judge prompts with <<<SAMPLE>>> delimiters
  and explicit anti-injection instructions; flip parsing to fail-closed
  (errorVerdict instead of allowVerdict) when judge output is malformed.
- H5: narrow IsPlatformID to fail-OPEN for valid NANP phone numbers so
  real US/CA phones are no longer suppressed by default.
- H6: gate verbose sidecar diagnostic logging behind
  DEFENSECLAW_SIDECAR_DIAG=1; SIGPIPE handling stays always-on.

Medium-severity hardening:
- M1: UTF-8-safe extractEvidence/extractEvidenceAt — clamp slice
  boundaries to rune starts so evidence strings written to logs and
  audit records are always valid UTF-8.
- M2: RulePack.Validate() now compiles every regex at load time and
  warns on invalid patterns instead of silently skipping them per
  request.
- M3: bound regexCache via container/list LRU (1024 entries) and cache
  negative results so invalid patterns aren't recompiled hot-path.
- M4: derive Bifrost Key.ID via SHA-256 hash of the API key (helper
  bifrostKeyID) instead of embedding the raw key in upstream structures
  that may reach logs.
- M5: add TTL-based session eviction (default 30m) to ContextTracker
  and refactor pruneOldestLocked from O(n^2) to O(n log n).
- M6: replace hardcoded claude-sonnet-4-20250514 probe model in
  defenseclaw doctor with _anthropic_probe_model() — prefers the
  configured anthropic/<model>, then DEFENSECLAW_ANTHROPIC_PROBE_MODEL,
  then claude-3-5-haiku-latest.
- M7: route doctor LLM API key verification by the *model provider
  prefix* first; env-name prefix (ANTHROPIC_API_KEY etc.) is only a
  last-resort fallback. Prevents Bedrock tokens stored in
  ANTHROPIC_API_KEY from being shipped to the Anthropic API.
- M8: deprecate the --token sidecar flag (still accepted, prints a
  warning, hidden from help) in favour of OPENCLAW_GATEWAY_TOKEN.
- M9: access Bifrost ToolCalls symmetrically via
  bm.ChatAssistantMessage.ToolCalls to guard against upstream schema
  drift.

Tests:
- New: TestRedactEntity (incl. UTF-8 multibyte coverage) and
  TestJudgeLogTraceFlag in llm_judge_logging_test.go.
- New: TestContextTracker_EvictsStaleSessions covering TTL eviction.
- New: doctor routing tests — env-name fallback, model-prefix wins,
  AnthropicProbeModelTests covering all three probe-model branches.
- Updated: TestPIIToVerdict/telegram_id_suppressed now uses a 9-digit
  non-NANP id so it still exercises platform-ID suppression after H5.
- Updated: TestRunToolJudgeIgnoresPromptJudgeReentrancyFlag wired
  through the new context-scoped withJudgeActive helper.

No on-the-wire schema changes; verdict structure and OPA input are
unchanged. Splunk/OTel forwarding and CLI surface are unchanged except
for the deprecated --token flag warning.

* feat(observability): decouple OTel + introduce generic audit_sinks (Phase 0)

Phase 0 of the stacked observability refactor on top of PR #111
(feat/wire-rulepack-runtime). Replaces the single-Splunk audit
forwarder with a declarative, multi-destination audit_sinks list
and removes the Splunk-specific coupling from the OTel provider.

BREAKING: the legacy `splunk:` config block is rejected on startup
with a hard error pointing operators at docs/OBSERVABILITY.md. This
is intentional so nobody silently loses forwarding after upgrading.

What changed:

- internal/audit/sinks/: new package defining Sink interface, Manager
  for fan-out, and per-kind implementations for splunk_hec, otlp_logs,
  and http_jsonl. Each sink owns its own batching/timeouts and is
  independent — one failing sink never blocks the hot path.
- internal/config/sinks.go: new AuditSink schema with per-kind
  configs (SplunkHECSinkConfig, OTLPLogsSinkConfig, HTTPJSONLSinkConfig),
  common batch/timeout/filter fields, and eager Validate() per sink.
- internal/config/config.go: CurrentConfigVersion -> 4. viper.Reset()
  at the start of Load() so tests don't leak state. detectLegacySplunk()
  refuses to start if legacy keys are present.
- internal/audit/logger.go: SetSinks(*sinks.Manager) replaces
  SetSplunkForwarder. forwardToSinks() fans every event out via the
  Manager with a bounded 2s context so sinks can't stall decisions.
- internal/audit/splunk.go + splunk_test.go: deleted — behaviour is
  now owned by internal/audit/sinks/splunk_hec.go.
- internal/audit/export.go: ExportSplunk removed (replay command now
  drives the generic sink pipeline).
- internal/audit/network_egress.go: routes egress alerts through
  forwardToSinks.
- internal/cli/root.go + internal/cli/audit_sinks.go: new init path
  (initAuditSinks -> buildAuditSinks) that translates config.AuditSink
  declarations into concrete sinks.Sink instances and installs them
  on the audit logger at startup.
- internal/gateway/health.go + sidecar.go: Splunk subsystem renamed
  to Sinks; aggregates health + names + kinds across every configured
  sink. /health and defenseclaw-gateway status both show the new shape.
- internal/cli/sidecar.go: prints the generic "Sinks" line instead of
  a Splunk-only banner.
- internal/telemetry/provider.go: expandHeaders is now vendor-neutral
  — no more X-SF-Token auto-injection from SPLUNK_ACCESS_TOKEN. The
  telemetry stack is a plain OTLP client; use otel.headers (or
  OTEL_EXPORTER_OTLP_HEADERS) to send any vendor-specific auth header.
- internal/tui/app.go + overview.go: HealthSnapshot.Splunk -> Sinks.
- internal/tui/configedit.go + setup.go: removed single-key splunk.*
  edits (the new schema is list-based); read-only summary of the
  configured audit_sinks list is shown with a pointer to the
  dedicated editor landing in Phase 3.3.
- docs/OBSERVABILITY.md: new operator guide — concepts, migration
  from v3 splunk: block, full sink reference, OTel examples, event
  shape, health reporting.

Tests are green across the whole tree. Redaction scrubbing at the
sink layer will land in a separate PR so this one stays scoped to
the observability refactor.

* feat(observability): structured gateway events (Phase 1)

Introduce internal/gatewaylog for JSONL verdict/judge/lifecycle
emissions with lumberjack rotation and a stderr pretty-printer.

- New writer wired into sidecar boot/teardown, writing to
  $DATA_DIR/gateway.jsonl alongside a human-readable mirror on
  stderr. Existing defaultLogWriter diagnostics stay intact.
- Central verdict event at GuardrailInspector.Inspect covers every
  strategy (regex, regex+judge, judge-first) so no caller has to
  plumb the writer through each path.
- Judge invocations (injection + PII) now emit a structured Judge
  event with latency, parse state, action, and severity. Raw
  bodies stay gated behind DEFENSECLAW_JUDGE_TRACE so PII-heavy
  payloads don't leak into the JSONL stream by default.
- Lifecycle events for sidecar init/stop give operators a
  timeline anchor in the JSONL feed.

Tests: writer round-trip / pretty / fanout / emit-after-close
coverage plus inspector-level verdict emission assertions.

Remainder of Phase 1.3 (migrating every defaultLogWriter site)
and Phase 2/3 (OTel mapping, metrics, TUI tab) continue in
follow-up commits.

* feat(observability): OTel pipeline, TUI verdicts, JSONL coverage (Phase 2-4)

Completes the structured observability stack on top of the Phase 0/1
sink + gatewaylog foundations:

Phase 2 — OTel pipeline
 - Map gatewaylog.Event to OTel LogRecords with typed attributes
   per event (verdict/judge/lifecycle/error/diagnostic) and fan
   out from the JSONL writer directly to the OTLP logs exporter.
 - Add guardrail pipeline span via SetTracerFunc / StartGuardrailStageSpan;
   proxy injects the tracer closure so the inspector stays decoupled
   from the telemetry package.
 - Record guardrail metrics driven by gatewaylog events:
   defenseclaw.gateway.verdicts, judge.invocations, judge.latency,
   judge.errors, gateway.errors, audit.sink_send_failures.
 - Add guardrail.retain_judge_bodies config flag + atomic to opt in
   to raw judge response retention (default off; DEFENSECLAW_JUDGE_TRACE
   still required for full-fidelity capture).

Phase 3 — TUI
 - New Verdicts source in the logs panel tailing gateway.jsonl with
   block/alert/allow action filter chips ('a' to cycle).
 - Enter on a verdict row opens the detail modal with full event
   (timestamp, severity, action, stage, direction, model, reason,
   raw JSON).
 - Setup panel surfaces OTel knobs (TLS, per-signal endpoints,
   redacted headers) and an audit_sinks summary with an edit hint;
   configedit wires the new OTel keys.

Phase 4 — polish & migration
 - Coverage test asserts every file calling audit.Logger.LogAction
   in internal/gateway also emits at least one structured
   emit*() sibling; add strategic emits in router.go/proxy.go/api.go
   to cover the migration.
 - scripts/assert-gateway-jsonl.py validates JSONL schema for any
   captured file; wired into both e2e workflow jobs and the
   full-stack e2e dump-on-failure tails gateway.jsonl alongside
   gateway.log.
 - test-e2e-cli.py picks up a jsonl_event_contains helper so new
   e2e tests can assert on the structured stream.
 - install/upgrade/sandbox help text points at both gateway.log
   (pretty) and gateway.jsonl (structured).

BREAKING: gateway now emits two files — gateway.log (pretty) and
gateway.jsonl (structured). Operators consuming the text log for
verdict parsing must switch to the JSONL stream; schema is stable
per internal/gatewaylog/events.go and documented in
docs/OBSERVABILITY.md.

* tests(observability): fill coverage gaps + Phase 2.3 SQLite judge retention

Addressed the review challenge on Phase 2-4 completeness.

Fills the missing test coverage identified by the self-audit:
- internal/audit/sinks/*: Manager fan-out, Splunk HEC envelope/auth,
  HTTP JSONL TLS/bearer/env-expansion, OTLP logs severity mapping
- internal/cli/audit_sinks.go: sink builder, error aggregation,
  env-token resolution
- internal/telemetry/gateway_events.go: OTel log-record attributes,
  metric updates for all event types, nil-payload safety
- internal/telemetry/runtime.go: StartGuardrailStageSpan /
  EndGuardrailStageSpan attributes, reason truncation, allow→Ok vs
  block→Error status mapping, nil-provider safety
- internal/gateway/llm_judge.go: judgeRawForEmit / SetRetainJudgeBodies
  env-var + config-flag gating, long-body truncation
- internal/tui/logs.go: parseVerdictRow, loadVerdicts filter gating,
  cycleVerdictAction rotation, SelectedVerdict, renderVerdictLine
- internal/tui/setup.go: fmtOTelHeaders redaction + sort,
  auditSinkSummaryFields per-kind rendering + edit hint

Completes Phase 2.3 (SQLite judge-body persistence) — previously only
the sinks half landed:
- audit.Store migration 3: judge_responses table + indexes
- Store.InsertJudgeResponse / ListJudgeResponses with UUID + RFC3339Nano
- gateway events pipeline gains SetJudgePersistor hook; emitJudge runs
  the persistor BEFORE emitEvent's redaction pass so the operator-
  owned SQLite receives the un-redacted body while fanout sinks still
  get the scrubbed form
- sidecar wires the persistor iff guardrail.retain_judge_bodies is
  true and tears it down on shutdown

Expands coverage_test.go scope to internal/audit + internal/telemetry:
- TestLogActionFreeInAuditAndTelemetry pins those packages as
  LogAction-free so the sink/pipeline substrate can never grow a
  circular routing back into itself
- Factored out scanLogActionCoverage for reuse

All tests pass (full go test ./..., go vet clean).

* docs(observability): add DEFENSECLAW_REVEAL_PII production warning + drop goto

OBSERVABILITY.md now spells out why DEFENSECLAW_REVEAL_PII=1 must never
run in production: any shared transport (journald, tmux, CI logs,
support bundles) that captures stderr becomes an exfiltration channel
for the literal secrets/PII the gateway prints when the flag is set.
The flag is documented as a developer-workstation / incident-triage
tool only.

Also replaces the single `goto done` in redaction.findKVBoundaries
with a labelled `break keyLoop` — same control flow, but keeps the
file goto-free now that it has grown into the primary PII seam.

* fix(observability): review pass — panic safety, bounded backlogs, UTF-8 safety

Addresses the H1–H6, M1/M2/M4, and L1 findings from the post-merge
review of the observability stack.

High:
- Thread gatewaylog.Direction through the judge persistor so SQLite
  rows no longer drop the inbound/outbound tag.
- Wrap fanout callbacks in gatewaylog.Writer.Emit and per-sink
  Forward calls in sinks.Manager with recover(); a panicking
  exporter can no longer unwind into the guardrail hot path.
- Coalesce immediate flushes (guardrail-verdict bursts) behind an
  atomic.Bool single-flight so high-frequency verdict traffic cannot
  explode goroutines.
- Cap the in-memory retry backlog for http_jsonl and splunk_hec at
  100×BatchSize (floor 10k) so a persistently offline endpoint cannot
  OOM the sidecar; oldest events drop with an operator warning.
- Truncate judge raw_response at MaxJudgeRawBytes (64KiB) with UTF-8
  rewind and a [truncated N bytes] marker to bound audit DB growth.

Medium:
- TUI verdict filter now applies to both verdict and judge rows and
  hides actionless events when a filter is active (consistent UX).
- Rewrite truncateVerdictReason to be rune-aware so multi-byte
  strings are never sliced mid-codepoint.
- Cap the OTel defenseclaw.verdict.reason attribute at 200 bytes to
  bound cardinality on backends that index attribute values; the
  full reason still ships in the log body.

Low:
- Emit a one-shot stderr warning when http_jsonl or splunk_hec is
  configured with verify_tls=false against an https:// endpoint, so
  silent TLS downgrades never slip through review.

Regression tests added for every fix. Full go test ./... and
go vet ./... are green.

* fix(ci): migrate E2E workflow from legacy splunk: to audit_sinks:

The observability refactor (this PR) makes config.Load() refuse to
start when a legacy `splunk:` block is present — that's the whole
point of the v3 → v4 migration check in internal/config/config.go.
The E2E workflow was still writing the old shape, so the gateway
daemon exited immediately during "Init DefenseClaw" with:

  Error: start daemon: daemon: process exited immediately
  (check /home/ubuntu/.defenseclaw/gateway.log for errors)

and the two downstream E2E jobs + the required-checks gate all
failed together.

Rewrites both Python-yaml patches (Core E2E and Full Live E2E) to
emit a single audit_sinks entry pointing at the same local Splunk
container the "Start Splunk" step brings up. The token still flows
via DEFENSECLAW_SPLUNK_HEC_TOKEN, so no secret/env changes.

Also extends the on-failure log artifact to include ~/.defenseclaw/
*.jsonl (gateway.jsonl is the new structured sibling of gateway.log)
so the next triage run has the schema-validated trail available in
the uploaded artifact — the ci-watcher pass flagged that only *.log
was being captured.

* fix(config): stop writing legacy splunk: from Python, load .env before config.Load

The first CI retry after migrating the e2e.yml patches to audit_sinks
still red-x'd with the same "daemon: process exited immediately"
error. Root cause, per ci-watcher triage of run 24544271547:

1. defenseclaw init (Python) unconditionally serializes the
   SplunkConfig dataclass — including default hec_endpoint /
   hec_token_env strings — into ~/.defenseclaw/config.yaml. The Go
   gateway's v3→v4 migration check (config.detectLegacySplunk) treats
   any populated splunk.* key as a hard error and refuses to start.
   So defenseclaw init calls sidecar start, the sidecar immediately
   fails config.Load(), and we exit before the workflow's post-init
   Python yaml patch ever runs.

2. Even if init succeeded, SplunkHECSinkConfig.Validate() resolves
   token_env via os.Getenv at config-load time, but loadDotEnvIntoOS
   currently runs *after* config.Load(). In CI the HEC token lives
   only in ~/.defenseclaw/.env, so validation would fail with a
   misleading "token is empty" error during the next restart.

Fixes:

- cli/defenseclaw/config.py: _config_to_dict now drops the `splunk`
  key entirely. v4 routes Splunk forwarding through audit_sinks; the
  in-memory SplunkConfig dataclass stays for backward-compatible
  *reads* of existing config.yaml files, but we never write it again.
  setup splunk --logs becomes a no-op until it's ported to emit
  audit_sinks entries (tracked as a follow-up; out of scope here).

- internal/cli/root.go: loadDotEnvIntoOS(config.DefaultDataPath()/.env)
  now runs *before* config.Load() so token_env references in
  audit_sinks resolve against secrets written by defenseclaw setup
  / defenseclaw init. Added a second deferred load keyed on cfg.DataDir
  so DEFENSECLAW_HOME overrides still pick up .env contents.

Covered by existing internal/config + internal/cli Go test suites
(all green) and the full Python cli test suite (987/987 passing).

* fix(config): python CLI reads audit_sinks[*].splunk_hec as SplunkConfig fallback

Phase 0 removed the legacy \`splunk:\` yaml block and moved Splunk
forwarding under \`audit_sinks:\`. The Go gateway consumes the new
shape, but the Python CLI keeps its own in-process Splunk forwarder
for events it raises locally — \`defenseclaw aibom scan\`,
\`defenseclaw skill quarantine/restore/block/allow\`,
\`defenseclaw mcp block/allow\`, \`defenseclaw plugin *\`, etc.

That Python forwarder still reads \`cfg.splunk.*\`. With the v4
config.yaml containing only \`audit_sinks\`, \`SplunkConfig\` loaded
defaults (\`enabled=False\`), so the Python-side forwarder
short-circuited and all of those events disappeared from Splunk even
though SQLite + the Go sink pipeline were fine. That’s what the CI
run 24544639016 showed: skill-scanner and codeguard scans (logged by
the Go gateway) landed in Splunk, but AIBOM, quarantine/restore,
block/allow, and every plugin action (logged by Python) did not.

Teaches \`config.load()\` to hydrate \`cfg.splunk\` in memory from
the first enabled \`audit_sinks[*]\` entry whose \`kind\` is
\`splunk_hec\`. This is:

- IN MEMORY ONLY. \`_config_to_dict\` still strips the \`splunk\`
  key on save so we never reintroduce the \`detectLegacySplunk\`
  tripwire in the Go gateway.
- STRICTLY FALLBACK. If the user explicitly wrote a legacy
  \`splunk:\` block (for older installs), we keep their values
  untouched.
- SAFE FOR INPUTS. Any non-dict / missing-endpoint / disabled sink
  is skipped without raising.

Manually verified by loading a pure-audit_sinks config.yaml and
confirming \`cfg.splunk.enabled == True\`, endpoint/index/sourcetype
mirror the sink, and \`resolved_hec_token()\` pulls the env token.
All 987 Python tests pass.

* feat(tui): interactive Audit Sinks editor (P0-#1)

Adds an interactive sub-mode to the Setup panel that lists configured
audit sinks and shells out to `defenseclaw setup observability
list|enable|disable|remove|test|migrate-splunk` for every mutation.
The Python CLI remains the single source of truth — the TUI never
edits config.yaml directly — so the gateway's atomic-write invariants
and audit logging stay intact regardless of which front-end the
operator uses.

Entry point: press E while the Config Editor is focused on the Audit
Sinks section. Bindings: j/k nav · e enable · d disable · r remove
(with [y/N] confirm) · t test · a hand off to Observability wizard ·
m migrate legacy splunk: block · Ctrl+R refresh · Esc close.

Also registers `setup observability list|migrate-splunk` palette
entries so the migration is reachable without entering the editor
(P3-#18).

Coverage: 27 tests (unit + SetupPanel integration) stubbing the
list lister to avoid requiring an installed CLI at test time.

* feat(tui): Plugins panel action menu — PluginActions (P0-#2)

Adds context-aware `o`-menu to the Plugins panel matching the
Skills / MCPs parity pattern. Every verb in the menu dispatches
through `defenseclaw plugin <verb> <name>` so PolicyEngine,
admission audit, and the gateway RPC for runtime enable/disable
all stay in one place. No plugin state is forked in Go.

Action visibility is driven off verdict + enabled + status:
  - scan / info always available
  - block / unblock / allow driven off verdict
  - disable / enable driven off runtime state
  - quarantine / restore driven off status substring
  - remove always exposed last (destructive, but discoverable)

Tests cover:
  - PluginActions visibility across 4 verdicts × 2 statuses × 2
    enabled states (24 matrix combos), including no-duplicate-key
    invariant
  - `o` opens the menu with the plugin's name (falling back to ID
    when the manifest omits it) and populates info rows
  - every key PluginActions can emit maps to a non-nil CLI
    invocation via executeActionMenuItem (prevents silent no-ops
    when new verbs are added to the menu without dispatch wiring)
  - nil-selection safety on both open and dispatch paths

* tui(parity P0-#3): add Tools panel + ToolActions

Wires a new Tools panel into the unified TUI so operators can view and
mutate tool block/allow policy without dropping to a shell. All
mutations route through `defenseclaw tool {block,allow,unblock,status}`
so the admission gate, scoped-policy resolution (e.g.
`write_file@filesystem`), and audit emission stay in one authoritative
code path — CLI remains the single source of truth.

Panel is registered at index PanelTools, inserted immediately before
PanelSetup so the existing 1–9/0 numeric keybindings all stay stable;
Tools is reached via the new uppercase 'T' shortcut, the command
palette, or tab navigation. Action menu surfaces Info/Block/Allow/
Unblock keys contextually by current status and deliberately omits
Scan/Enable/Disable/Quarantine (those verbs belong to Skills/MCPs/
Plugins, not Tools) — guarded by TestToolActions_NoScanOrEnable.

Scoped targets preserve the `@scope` suffix through the dispatcher so
operators never accidentally edit the global row when they selected a
scoped one.

Tests cover: ToolActions branches by status, global-scope placeholder
rendering, action-menu dispatch for every key, nil-selection safety,
cursor clamping, BlockedCount, 'T' global shortcut routing, and a
panel-ordering regression guard so future refactors can't silently
shift numeric keybindings.

* feat(tui): route Skills panel mutations through CLI (P0-#4)

Before this change, pressing 'b' in the Skills panel called
SkillsPanel.ToggleBlock() which flipped state directly in the audit
store. That bypassed the admission gate, the gateway RPC
notification, and the formal audit event — so a block from the TUI
looked different in the log than a block from the shell, and could
drift out of policy sync.

Now every mutation (block/allow/unblock/disable/enable/quarantine/
restore/install/scan) dispatches `defenseclaw skill <verb> <name>`
through CommandExecutor. The Python CLI is the single source of
truth. Adds install/enable/restore to the action menu so the TUI
covers the full CLI surface.

SkillActions() now branches by status (blocked/allowed/quarantined/
disabled/default) to match _skill_status_display() in cmd_skill.py,
and skills.Refresh() recognises quarantined + disabled rows.

Tests: TestSkillActions covers every branch (+ dup-key guard),
TestHandleSkillsKey_{B,A}_RoutesToCLI anchors the regression, and
TestExecuteActionMenuItem_SkillDispatch confirms every key surfaced
by any SkillActions branch resolves to a real CLI verb.

* feat(tui): MCPSetForm + route MCP actions through CLI (P0-#5)

Symmetric change to P0-#4 but for MCP servers:

* 'b' and 'a' no longer call MCPsPanel.ToggleBlock() (which
  mutated the audit store directly, skipping admission gate and
  gateway RPC). Both now dispatch through `defenseclaw mcp`.
* 'a' is always "allow" now — the old "only if blocked →
  unblock" short-circuit was a footgun. Pure unblock is still on
  'u' in the action menu.
* Info ('i') is wired through the menu dispatcher so the action
  menu button isn't silently a no-op.
* New MCPSetForm covers the `mcp set` CLI verb (add/update
  server). Triggered from the MCP panel with 'n' (or '+'). Tab /
  Shift+Tab move between fields, Enter advances or submits,
  BackSpace / Ctrl-U edit the focused field, Esc cancels.
  BuildCommand() validates required fields (name + one of
  command/url) and env KEY=VAL shape before dispatching, so the
  operator stays in the form on error rather than bouncing out
  to a raw click traceback.

Tests:
* form navigation wraps cleanly; named keys (f5/home/…) are not
  appended as literal input; UTF-8 backspace trims whole runes.
* BuildCommand argv matches cmd_mcp.py's flag layout;
  skip-scan accepts y/yes/true/1; env without '=' fails.
* handleMCPsKey B/A dispatch via CLI across all status branches;
  'n' opens the form; form owns the keyboard while active so 'j'
  becomes input (not a list cursor-down).
* executeActionMenuItem covers every key MCPActions surfaces.

* feat(tui): actions-matrix editor in Setup panel (P1-#6)

The admission gate's severity → (file, runtime, install) decision
table lives in three parallel configs (skill_actions, mcp_actions,
plugin_actions) of 5 severities × 3 columns each. Previously the
TUI Setup panel ignored them, forcing anyone who wanted to raise
the severity threshold for, say, plugin install-blocking, to open
~/.defenseclaw/config.yaml by hand.

Adds three new sections (Skill Actions / MCP Actions / Plugin
Actions) to the SetupPanel config editor. Each section surfaces
one header row plus 15 choice rows, backed by the existing
configField rendering so operators keep the same keymap
(arrow / enter / toggle / save). The choice option lists are
deliberately per-column (file: none/quarantine; runtime:
enable/disable; install: none/block/allow) so operators cannot
pick semantically invalid pairings.

Save path: applyConfigField gained a dotted-prefix fallback that
routes skill_actions.*/mcp_actions.*/plugin_actions.* through a
new applyActionsField helper. A 45-case switch would have
quadrupled the function length without adding precision.

Tests:
* shape is locked at 1+5×3 rows per section (a future severity
  or column add forces a deliberate review);
* each column keeps its own option set (no accidental merging);
* every (prefix, severity, column) triple round-trips through
  applyConfigField;
* malformed keys silently drop (don't panic Save's hot loop);
* loadSections exposes all three sections (so a missing caller
  fails loudly, not silently).

* feat(tui): admission-policy CRUD + policy test binding (P1-#7/#8)

Policy panel previously exposed only guardrail rule packs / judge
prompts / suppressions / rego — the admission-gate YAML policies
(`defenseclaw policy <verb>`) were invisible. Operators had to
drop out of the TUI to create, activate, show, or delete a policy,
which defeats the "one pane of glass" pitch.

Adds a new "Policies" sub-tab (now the first tab, because admission
policy is the most common reason to open this panel):

* ↑/↓ / j/k — navigate the list
* enter or 'a' — `policy activate <name>`
* 's' — `policy show <name>`
* 'n' / '+' — open PolicyCreateForm overlay (→ `policy create`)
* 'd' — `policy delete <name>` (CLI confirms before irreversible)
* 'v' — `policy validate`
* 'l' — `policy list` (prints full CLI-formatted table)
* 'r' — refresh the local list from disk (no CLI round-trip)

All mutating keys dispatch through CommandExecutor so they route
through the gateway and emit proper audit events — same rationale
as skills / mcps / tools.

PolicyCreateForm is the third wizard overlay in this series (after
SinkEditor and MCPSetForm) and reuses the same sequential-field
layout so the three forms feel like one subsystem. It maps 1:1 to
the `policy create` CLI option surface:
  Name, Description, --from-preset, {critical/high/medium/low}-action

Validation happens client-side (name regex, preset choices, action
choices) so the operator gets an inline status line rather than a
bounce to stderr.

P1-#8 rides along: capital-T on the OPA/Rego tab now runs
`policy test`. Lowercase 't' keeps its existing meaning (toggle
show-tests) so muscle memory is preserved. The help text for both
affected tabs (Policies + OPA) is updated to list the new keys.

Tests (25 new):
  PolicyCreateForm — field navigation, UTF-8 safe backspace, named
  keys don't append, name/preset/action validation, blank-severity
  passthrough, Enter advances then submits, Esc cancels.
  Policies sub-tab — list loads from PolicyDir, active.yaml symlink
  detection, navigation + CLI dispatch for every verb, no-selection
  safety, 'n' opens form and then HandleKey routes to the form.
  OPA tab — 'T' dispatches `policy test`, lowercase 't' still
  toggles (pair of assertions to freeze the case distinction).

* tui(setup): full scanner rows + gateway watcher/watchdog editor (P2-#9)

Fleshes the Setup panel's Scanners section with the full Python-side
surface (policy, lenient, llm_consensus_runs, enable_meta, use_trigger,
VirusTotal/AIDefense toggles, key-env binding, MCP scan_prompts /
scan_resources / scan_instructions). Adds two new sections, Gateway
Watcher and Gateway Watchdog, exposing enabled/take_action/dirs per
stream plus watchdog interval/debounce. applyConfigField grows the
matching cases and a splitCSV helper to round-trip comma-separated
directory lists cleanly (empty input collapses to nil so YAML stays
tidy). Covered by exhaustive per-key round-trip tests plus section-
shape guards to prevent silent row drops.

* tui(setup): full OTel editor — per-signal, batch, resource (P2-#10)

Expands the OTel section from a handful of globals into the full
SDK surface: sampler + sampler_arg, per-signal endpoint/protocol/
url_path overrides (traces/logs/metrics), metrics export interval
and temporality, batch processor tuning (max_export_batch_size /
scheduled_delay_ms / max_queue_size), and a deterministic resource-
attribute summary row. Headers remain redacted read-only because
their values carry bearer tokens — map CRUD stays in the CLI wizard.
applyConfigField gains matching cases so a round-trip save preserves
every new field. Covered by per-key round-trip tests and a shape
guard that pins the list of keys the section must expose.

* tui(setup): interactive Webhooks editor (P2-#11)

Adds a WebhookEditorModel that mirrors the Audit Sinks editor —
list + e/d/r/t/s/a keybindings that shell out to `defenseclaw setup
webhook` so every mutation emits an audit event from the CLI rather
than a duplicated Go path. 'a' hands off to the existing Webhooks
wizard form since per-type prompts (slack room_id, generic HMAC
secret, cooldown tri-state) can't be captured in a flat list-view.
Registers IsEditorActive in SetupPanel so app.go gates hotkeys with
a single check instead of enumerating every sub-mode. Covered by
parser, lifecycle, bounds, and CLI-argv parity tests.

* tui(setup): inspect_llm editable + AI Defense/Firewall read-only (P2-#12)

Adds three new Config Editor sections: Inspect LLM is fully editable
(provider/model/base_url/timeout/max_retries, plus api_key masked as
kind=password and the preferred api_key_env for keychain-backed
rotation); Cisco AI Defense is read-only because enabled_rules comes
from the Cisco console and mutating api_key inline would land a
cleartext bearer in YAML — the row reports three distinct states
(inline redacted, env-resolved, env-unresolved, unset) so operators
know what's actually in effect; Firewall is read-only because its
paths bind to system-owned pf/nft anchors that DefenseClaw never
creates and silently rewriting them would orphan live rules.
applyConfigField routes inspect_llm.* writes and *refuses* to touch
cisco_ai_defense.* / firewall.* — a dedicated test pins this down so
a future refactor can't accidentally introduce an edit path.

* tui(setup): guardrail/openshell parity + config_version row (P2-#13/#14)

Guardrail gains host, model_name, original_model, api_base, and
retain_judge_bodies so the TUI surface matches the CLI/config.yaml
knobs (missing these meant `defenseclaw config show` reported state
the TUI could never produce).

OpenShell exposes sandbox_home plus the two tristate *bool fields
(auto_pair, host_networking) as kind=choice with ["", "true",
"false"] options. The empty-string preserves nil so
ShouldAutoPair/HostNetworkingEnabled defaults still apply — a plain
bool would collapse nil and &false and silently flip defaults.
parseTristateBool trims+lowercases and maps everything else back to
nil so a fat-fingered keystroke never writes a bogus literal.

config_version lands in General as a read-only header row rendered
via fmtConfigVersion: bare number when in sync with
CurrentConfigVersion, "N (binary expects schema vM — migration on
next save)" when drifted, "(unset)" for fresh in-memory configs.
Editing bypasses migrateConfig, so the row is explicitly kind=header
and a test pins down that applyConfigField never writes the field.

Tests cover every new case, the tristate round-trip (including the
"clear to nil" state), and the migration-drift summary.

* tui(inventory): --only scope chips with fast-scan preset (P3-#19)

Surfaces `defenseclaw aibom scan --only` in the TUI so operators can
narrow the scan to the security-review subset (skills+plugins+mcp)
and skip the slow agents/tools/models/memory discovery during
iteration.

- Adds categoryScope state to InventoryPanel + SetCategoryScope,
  ToggleCategory, ToggleFastScan helpers. nil scope = "scan all"
  (CLI default, no --only emitted). SetCategoryScope filters out
  unknown categories so a stale persisted value can't land a bogus
  --only value on the next reload.
- Extracts loadCmdArgs from LoadCmd so tests can assert the exact
  argv without needing the CLI installed in CI.
- New chip row below the sub-tab bar shows current scope as
  "Scope (all)", "Scope (fast)", or a custom subset. Inactive chips
  are dimmed, active ones highlighted.
- Binds 'o' in the inventory panel to ToggleFastScan. Deliberately
  does NOT auto-reload — operators press 'r' next so they can see
  the new scope before paying the 15-30s scan cost.
- Updates inventoryHint and adds an inline "(o toggles fast,
  r reloads)" legend on the chip row.

Tests (internal/tui/inventory_scope_test.go):
- LoadCmdArgs with/without scope.
- SetCategoryScope filters unknown, empty/nil round-trip to nil.
- ToggleCategory add/remove/empty/unknown.
- ToggleFastScan cycle + replaces manual scope.
- Order-independent isFastScan.
- Categories list locked to CLI --only choices (cmd_aibom.py).
- Fast-preset stability guard + --only value format (no spaces).

* tui(alerts): enrich Go panel detail + retire Textual alerts TUI (P3-#20)

- Remove the legacy Textual-based `defenseclaw alerts --tui` app. The
  flag now prints a single deprecation line on stderr and falls back
  to the Rich table output so wrapper scripts keep working while
  operators migrate to `defenseclaw tui` (2 => Alerts).
- Drop the `tui = [textual>=0.50]` extra from pyproject so we stop
  shipping a second TUI frontend; `uv.lock` regenerated.
- Port the Python `_humanize_details` summarizer into Go
  (`humanizeAlertDetails`) and use it in the AlertsPanel detail pane
  to render a "Summary:" line above the raw "Details:" when the two
  differ, keeping raw kv intact for copy/paste.
- Surface TraceID / RequestID on every event and, for findings, show
  the scanner tag and remediation hint inline so the Go panel is at
  parity with (actually, a superset of) the retired Textual view.
- Adds internal/tui/alerts_enrichment_test.go covering humanize
  edge cases (host/port, model slash-tail, noise drop, duplicate
  keys) and the enriched detail rendering.

* tui(overview): cached Doctor status box (P3-#21)

Renders a compact DOCTOR box on the Overview panel backed by an
on-disk cache so operators see "all green" or the top failures
without waiting for doctor's full network-probing run on every
redraw.

CLI side (single source of truth):
- cmd_doctor.py now persists <data_dir>/doctor_cache.json at the
  end of every run (including setup --verify) via a new
  _write_doctor_cache helper. Writes are atomic (tempfile +
  os.replace) so concurrent TUI reads never see partial JSON.
- Timestamps use RFC3339 with the "Z" suffix so Go's time.Time
  parser accepts them without a custom unmarshaler.

Go/TUI side:
- internal/tui/doctor_cache.go: DoctorCache type + Load/Save helpers
  with soft error semantics (NotExist => nil cache, parse errors
  surface as toasts, never panics). Age/IsStale/TopFailures/
  SummaryLine/SortChecksByStatus/FormatAge helpers drive the
  rendering + future detail modal.
- OverviewPanel gains a DOCTOR box showing counts, freshness, and
  top 3 failures/warnings. A top-of-screen notice bubbles up
  failures or staleness. Falls back to "not yet run — press [d]"
  on first launch.
- Model loads the cache on Init and reloads it after any
  `defenseclaw doctor` completion (CommandDoneMsg detected via
  isDoctorCommand prefix match), so running doctor from the palette
  or activity refreshes the box automatically.

Tests:
- internal/tui/doctor_cache_test.go: roundtrip, atomicity, Python-
  timestamp compat, age/staleness, TopFailures ordering,
  SummaryLine, FormatAge, SortChecksByStatus, corrupt-file soft
  fail, no-data-dir no-op.
- internal/tui/overview_doctor_test.g…
vineethsai7 pushed a commit that referenced this pull request Apr 21, 2026
…ed) (#117)

* feat: comprehensive CLI UX audit and remediation

Audit and fix all CLI command surfaces (Python + Go) for information
gaps, broken non-interactive flows, stale messages, credential
visibility, exit codes, and output consistency.

Setup commands:
- Redesign interactive guardrail prompts with value prop, numbered
  choices, and advanced options gate
- Add --accept-defaults alias, sensible defaults, and validation for
  guardrail non-interactive mode
- Change --restart default to True for setup guardrail
- Fix contradictory disable messaging
- Show Splunk Web credentials after setup; add --show-credentials flag
- Add --index/--source/--sourcetype and per-signal toggle flags for
  setup splunk non-interactive
- Validate skill-scanner policy names; show api_key_env consistently
- Add --verify to setup mcp-scanner
- Wire --remote for setup gateway non-interactive

Doctor command:
- Implement --json-output (was declared but never used)
- Check all subsystems from /health JSON (api, telemetry, splunk,
  sandbox)
- Upgrade scanner-missing severity from WARN to FAIL

Init flow:
- Show CLI + gateway versions in Environment section
- Replace bare "Health: ok" with rich /health JSON summary
- Auto-restart sidecar after init --enable-guardrail
- Context-aware "Next steps" based on what was configured

Gateway CLI (Go):
- Show health summary + log path after restart (parity with start)
- Sort status detail keys for stable output
- Return non-zero exit from status when sidecar unreachable
- Fix stale "defenseclaw sidecar" hint
- Add watchdog status subcommand
- Fix printSplunkLocalHint to read splunk-bridge .env
- Use configured APIBind for policy reload
- Sort policy diff output for determinism
- Add mode check to sandbox stop

Skill/MCP commands:
- Show full finding details in MCP scan (parity with skill scan)
- Show DB-only enforcement rows in MCP list
- Return exit code 2 for blocked/allowed scans
- Short-circuit upgrade when target == current version

Tests:
- Update test_guardrail.py for auto-restart default, --accept-defaults
- Update test_cmd_misc.py for Splunk credential display, add
  --show-credentials tests
- Update test_cmd_skill.py/test_cmd_mcp.py for exit code 2
- Add test_cmd_init.py version display tests
- Add test_cmd_doctor.py JSON output and record tests

* fix: resolve CI lint failures and add post-command hints

- Remove unused sortedMapKeys function (Go lint: unused)
- Fix f-string without placeholders and line-length violations (ruff F541/E501)
- Add tty-aware hint() helper for Python CLI and printHint() for Go CLI
- Add contextual "next steps" hints to: aibom scan, codeguard install-skill,
  status, skill scan/block/list, mcp scan/list/set, plugin install/remove/list,
  gateway stop, scan code
- Hints are dim-styled and only shown on interactive terminals (suppressed
  in JSON mode, piped output, and test runners)

* feat(tui): upgrade to Bubbletea v2 with inline detail panes, auto-init, and review fixes

- Migrate TUI to charm.land/bubbletea/v2, bubbles/v2, lipgloss/v2
- Add inline detail panes to Skills, MCPs, Plugins, Audit, Inventory panels
  with enriched data from audit store (findings, enforcement state, history)
- Add Esc key handling to close detail panes in all panel key handlers
- Fix ScrollOffset in Plugins/Audit panels to use dynamic listHeight()
- Fix AuditPanel.listHeight() off-by-one (was -2, now -3)
- Cache GetDetailInfo results per panel to avoid re-querying SQLite on render
- Run auto-init via standalone goroutine to keep executor free for user commands
- Close inventory detail pane on sub-tab switch
- Add explicit 'defenseclaw tui' CLI command
- Add action menu, activity panel, command executor, palette, health panel
- Add unit tests for detail toggle, cache invalidation, layout calculations

* fix: resolve Go and Python lint failures

- Remove unused `sys` import from cmd_tui.py (ruff F401)
- Replace WriteString(fmt.Sprintf(...)) with fmt.Fprintf (QF1012)
- Remove unused struct fields: ActivityPanel.scroll, logPollMsg.lines
- Fix switch type assertion pattern in logs.go (S1034)

* fix(tui): fix inventory table alignment, add clickable filters and data source hints

- Fix column alignment in Skills/Plugins tables using visual-width-aware
  padRight() helper instead of fmt.Sprintf padding (ANSI codes broke alignment)
- Widen SOURCE column to show full values instead of truncating to "opencla..."
- Add clickable sub-tab bar in inventory (Summary, Skills, Plugins, etc.)
- Add clickable filter stats in Skills (eligible/warning/blocked) and
  Plugins (loaded/disabled/blocked) sub-tabs with toggle behavior
- Add keyboard filter shortcuts (1-4) and Esc to clear
- Add italic hint notes explaining data source differences:
  "Inventory lists all items found by AIBOM on disk. The [X] tab only shows
  items with scan/enforcement records."

* fix(tui): fix command input rendering, delete wizard, add setup hint + review fixes

- Fix command input bar: remove lipgloss double-wrapping of textinput.View()
  that made typed text invisible; move background to textinput's own styles
- Delete pre-TUI huh-forms wizard (wizard.go); setup tab covers this now
- Add "First time?" notice in overview when system is unconfigured
- Fix autoInitCmd capturing Model by value (activity updates were lost)
- Fix readInteractiveOutput partial line corruption; split into readLineOutput
  (non-interactive) and readInteractiveOutput (PTY) with EOF flush
- Gate mouse clicks under full-screen overlays (help, detail, action menu)
- Fix setup wizard stuck state when executor rejects command
- Add bounds checks in setup.go to prevent panics
- Open palette on input bar mouse click (match :/ Ctrl+K behavior)
- Fix buildNotices cfg==nil suppressing first-time hint

* fix(tui): handle scanner.Err() in readLineOutput

Surface I/O errors (e.g. token-too-long) instead of silently dropping them.

* fix(guardrail): harden detection strategies, fix data races, and improve judge resilience

- Add RWMutex on allRuleCategories to prevent data race between
  ApplyRulePackOverrides (write at startup) and ScanAllRules (read on
  every request)
- Guard against ReDoS in user-supplied rule pack regexes with compile
  timeout and pattern length cap
- Fix completion-side NEEDS_REVIEW secrets being silently dropped when
  no judge is available — now falls back to MEDIUM/alert verdict
- Improve inspectJudgeFirst fallback documentation and ensure regex
  safety net always runs alongside judge results
- Switch postCallContext from context.Background() to
  context.WithoutCancel(parent) to preserve request-scoped tracing and
  correlation IDs while still detaching from request cancellation
- Apply pre-judge content strips in AdjudicateFindings, consistent with
  other judge code paths
- Add judgeSem rate limiting to inspectToolResult to bound concurrent
  LLM judge calls from tool-result inspection
- Fix broken indentation in proxy.go mid-stream scan block
- Tighten "token:" secret pattern from bare substring to regex requiring
  assignment syntax (token[:=] followed by 8+ chars) to reduce FPs
- Add "exfil" shorthand to triage exfil patterns
- Redact dotenv filesystem path in LLM judge init logging

* feat: production-readiness hardening — no placeholders

P0: HTTP rate limiting (100 req/s, burst 200), log rotation via
lumberjack, os.Exit only in main(), installer checksum verification.

P1: Real E2E tests replacing all t.Skip() stubs (scan rules, prompt
injection, block/allow/quarantine admission gate, audit persistence),
plugin registry Discover()/Register()/Get() with full tests, config
version migration (v0→v2), goreleaser homebrew tap enabled, NOTICE file.

P2: SSRF hardening tests (decimal/hex/IPv6/file/ftp), rate limit
middleware tests, header injection tests, /health/liveness endpoint,
malicious fixture updated with real detectable patterns.

Full test suite: 18/18 packages pass.

* fix: wire-up audit, fix 12 bugs, tighten AMD P2 regexes, remove dead code

Fixes found during deep review-and-ship audit:

Critical/High:
- watcher: takeActionFor now handles InstallPlugin/InstallMCP instead of
  falling through to watch.auto_block, honoring per-type take_action config
- guardrail: regex_only strategy no longer invokes the LLM judge (was adding
  unexpected latency/cost for operators choosing regex-only mode)
- config: EffectiveStrategy() default aligned with viper/defaults (regex_judge)
- configedit: add missing applyConfigField case for stream_buffer_bytes

Medium:
- tui: Tab/Shift+Tab now delegates to Policy panel before global panel switch
- tui: mouse wheel blocked behind open overlays (help, detail, action menu)
- tui: highlightRego guarded against strings.Index returning -1
- tui: Cisco AI Defense wizard fields now pre-filled from config
- tui: overview uses EffectiveStrategy() instead of hardcoded fallback

Security:
- policy: suppressions.yaml written with 0600 permissions (was 0644)

AMD P2:
- token regex tightened to require 20+ alphanumeric value (fixes FP on
  conversational "reply with this token: XYZ")
- bulk access triage pattern added for sensitive tools (users_list top N)

Wire-up:
- default_llm_api_key_env/default_llm_model added to TUI config editor
  and applyConfigField (were only usable via YAML/Python CLI)
- PolicyPanel.executor removed (dead field; commands returned to parent)
- WizardDone removed (dead function; WizardFinished is the active path)

All 18 Go packages pass with -race. go vet clean. Zero linter errors.

* feat: port multi-turn ContextTracker, scanner normalization, and per-scanner policy packs from PR #109

Consolidates PR #109 (feat/unified-rule-pack-arch) into this branch so a
single PR carries all rule-pack work. PR #109 is now obsolete.

Ported net-new features:

  * internal/gateway/context_tracker.go + _test.go
    - Per-session bounded buffer (10 turns / 200 sessions by default)
    - HasRepeatedInjection() raises HIGH alert when 3+ user turns hit
      local injection patterns within a session
    - Adapted HasRepeatedInjection signature to drop the *RulePack param;
      rule pack overrides already apply globally via
      ApplyRulePackOverrides(), so the simpler API is sufficient
    - Wired into EventRouter.handleSessionMessage (Record + multi-turn
      escalation path with telemetry emit)

  * internal/gateway/normalize.go + _test.go
    - NormalizedFinding with canonical ID, source, category, severity
    - Maps scanner-specific IDs (SEC-*, JUDGE-*, LP-*, CISCO-*) to
      stable canonical form for cross-scanner correlation

  * internal/scanner/codeguard.go + plugin.go
    - CodeGuardScanner now loads custom YAML rules from rules dir at
      construction; built-ins + custom rules concatenated per scan
    - PluginScanner gains Policy/Profile fields for per-scanner policy
      pack selection

  * policies/scanners/{codeguard,plugin-scanner,skill-scanner}/*.yaml
    - Per-scanner policy packs (default/strict/permissive/balanced tiers)

All 18 Go packages pass with -race -count=1. go vet clean. Zero lints on
edited files.

* fix: final review pass — heartbeat tests, scanner key fallback, sig cleanup

Close-out of the review-and-ship cycle on PR 111:

* Narrow heartbeat bypass tests — `isHeartbeatMessage` now verified to
  require the specific OpenClaw tokens (HEARTBEAT.MD / HEARTBEAT_OK)
  AND a <=512 byte payload; adding the word "heartbeat" alone or
  wrapping a large prompt in heartbeat tokens cannot bypass guardrails.
* Align Python skill-scan paths with `app.cfg.effective_inspect_llm()`
  so the shared `default_llm_api_key_env` fallback works the same way
  from the CLI as it does from the Go gateway.
* Update `test_guardrail_detection_strategy_defaults` to assert the new
  `regex_judge` default (matches Go + Python `_merge_guardrail`).
* Drop the unused `rp *RulePack` parameter from
  `ContextTracker.HasRepeatedInjection` — patterns are now sourced from
  the globally active rule pack via `ApplyRulePackOverrides`, so the
  per-call pack argument was dead code.

All tests pass locally: `go test -count=1 ./...` (18 packages),
`python -m unittest cli.tests.test_judge` (13/13).

* fix(ci): resolve lint, dep audit, and E2E sidecar health gaps

Go lint (staticcheck):
- Drop embedded-field selectors in provider_bifrost.go (QF1008).
- Replace WriteString(fmt.Sprintf(...)) with Fprintf in policy.go (QF1012).
- Remove dead readOpenAISSE helper and its now-unused imports.

Python dep audit:
- Override python-multipart>=0.0.26 to close CVE-2026-40347 (pulled in
  transitively by mcp and cisco-ai-skill-scanner).

E2E reliability:
- Replace fixed 5s sleep after gateway start with a 30s poll loop on
  'defenseclaw-gateway status' so slow self-hosted runners don't fail.
- On failure, dump the last 200 lines of gateway.log and watchdog.log
  and upload them as artifacts for post-mortem debugging.

* fix(lint): replace remaining WriteString(fmt.Sprintf(...)) with Fprintf

Three additional QF1012 staticcheck findings that only surfaced after the
first batch of fixes:

- internal/gateway/llm_judge.go: triage-signal formatter
- internal/tui/policy.go: two rule-browser helpers

* fix: seed guardrail rule packs, emit canonical finding IDs, drop broad token FP

- cmd_init now seeds bundled guardrail profiles (default/strict/permissive)
  into policy_dir so operators can edit YAML and `policy reload` picks it up
- paths.py gains bundled_guardrail_profiles_dir() resolver
- proxy + api guardrail audit events include canonical=<ids> for
  cross-scanner correlation (wires NormalizeScanVerdict into telemetry)
- legacy policies/default.yaml and policies/strict.yaml drop bare 'token:'
  pattern — gateway secretPatternRegexes already covers tokens with
  20+ char entropy requirement (fixes false positives like "reply with
  this token: XYZ")
- adds unit coverage: TestHandleGuardrailEventEmitsCanonicalIDs,
  TestSeedGuardrailProfiles (seed/preserve/noop paths)

* test(gateway): switch live E2E from Anthropic-direct to Bedrock via Bifrost

The Anthropic-direct account backing TestBifrostE2E_LiveAnthropic* is out of
credits, causing Full Live E2E to fail on every run. Switch both tests to
Bedrock via Bifrost (ABSK bearer key) against
claude-haiku-4-5-20251001-v1:0, gated on BIFROST_API_KEY so they still
skip gracefully when the secret is absent.

- Rename TestBifrostE2E_LiveAnthropic{,Stream} -> TestBifrostE2E_LiveBedrock{,Stream}
- Swap ANTHROPIC_API_KEY -> BIFROST_API_KEY (ABSK auto-detected as Bedrock)
- Use model bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0
- Wire BIFROST_API_KEY into the core and full-live job env blocks

* test(e2e): bump sidecar /health wait from 60s to 180s on self-hosted runners

The Core/Full-Live E2E workflows on the ARM64 self-hosted runner flake on a
60-second wait for SIDECAR_URL/health after defenseclaw-gateway start. The
gateway log shows the WebSocket handshake completing after the 60s window
expires — the sidecar is healthy, just slower to boot under runner load.

Extend both blocking /health waits (Phase 1 startup, Phase 7C recovery) to
180s and dump the tail of gateway.log plus defenseclaw-gateway status on
timeout so any future regression is self-diagnosing in-line.

* test(e2e): self-heal sidecar bring-up in Phase 1 with 3x retry

The previous 180s single-shot /health wait still failed on the ARM64
self-hosted runner because the sidecar daemon can exit during early
init before /health is ever served (observed on main too, not just this
branch — April 15 & 16 scheduled runs on main failed the same way).

Gateway.log dumps show the init-era sidecar is already dead by the time
Phase 1's stop reaches it ("Gateway sidecar is not running" before our
stop call) and the newly-spawned sidecar also exits within 5 seconds of
start. The log contains two overlapping startup sequences, suggesting a
brief lifecycle race.

Rather than keep extending the timeout, wrap the stop→start→health-wait
block in a 3-attempt loop with a 60s wait per attempt (~same wall clock
budget as before: 180s). Each defenseclaw-gateway start internally calls
killStaleProcesses via pgrep, so the retry naturally reaps any stragglers
that caused the previous attempt to fail.

On final failure, also dump watchdog.log, the full defenseclaw/openclaw
process tree, and listeners on 18789/18970 so the next flake is
self-diagnosing without needing an artifact download.

* e2e: add OOM/dmesg diagnostics + per-process memory trace on sidecar failure

Previous retry loop proved the sidecar is being killed externally (reaches
"event loop running" then vanishes within ~60s with no panic, no shutdown
message, watchdog survives). This is the signature of SIGKILL from outside,
almost certainly OOM killer on the shared self-hosted ARM64 runner.

We can't fix the runner from the script. But we can capture definitive
evidence so the root cause is not ambiguous on the next failure:

- free -m before each of the 3 bring-up attempts
- background sampler logs sidecar PID + VmRSS + VmSize every 3s while
  we poll /health; when the process vanishes, the trace timestamps the
  death and the last-known memory usage
- ps at failure now includes rss/vsz columns
- dmesg -T | grep -iE 'out of memory|killed process|oom|defenseclaw-gat'
- journalctl -k fallback (some distros gate dmesg behind CAP_SYSLOG)
- system-wide free -h at failure moment

On the next red run, either we'll see the OOM smoking gun in dmesg (then
the fix is runner memory / workload isolation, not CI patches), or the
memory trace will show steady RSS right up to death (then we'll know it
was an external pkill / signal, not OOM).

Refs PR #111. Bedrock migration itself is green; this is instrumentation
to unblock the pre-existing runner infra flake that also reproduces on
main.

* sidecar(diag): instrument signal handling + heartbeat to pinpoint silent exits

The E2E sidecar flake on the self-hosted ARM64 runner shows the sidecar
reaching "event loop running", writing audit DB entries, then vanishing
within ~3–5 seconds. No panic, no shutdown message, no OOM trace in
dmesg/journalctl, and the watchdog sibling (same binary) survives. This
is consistent with an external termination (SIGKILL) or a signal we're
not currently catching.

This commit adds scoped diagnostic instrumentation to runSidecar:

1. Widen signal.Notify to capture SIGHUP, SIGQUIT, SIGPIPE, SIGUSR1,
   SIGUSR2 in addition to SIGINT/SIGTERM. Each signal is logged with
   its name, number, PID, and RFC3339Nano timestamp before any action
   is taken. SIGPIPE is logged but NOT treated as a shutdown trigger —
   this also suppresses Go runtime's default "exit on SIGPIPE to stderr"
   behaviour that could silently terminate us if the log file descriptor
   transiently misbehaves.

2. 5-second heartbeat goroutine that prints
   "[sidecar][diag][heartbeat] alive at HH:MM:SS.mmm pid=N uptime=Ns"
   so the post-mortem CI log can narrow the kill window to <5s.

3. Defer + explicit log line around sc.Run(ctx) so we capture the
   exact return value, ctx.Err(), and PID at the moment runSidecar
   unwinds. If the process dies BEFORE these lines print, the kill
   is truly silent (SIGKILL or equivalent).

Interpretation guide for next E2E run:
- If "[sidecar][diag] received signal" appears → we know which signal
  and who probably sent it.
- If heartbeats stop mid-stream and NO signal line appears → SIGKILL,
  external source (runner OOM, supervisor, or manual pkill).
- If "sc.Run returned" appears → ctx was cancelled internally and we
  can inspect ctxErr to find the cancellation source.

No production behaviour change; only added log lines. Keeps PR #111
scope tight to diagnostic observability for a pre-existing sidecar
lifecycle bug that also reproduces on main.

* ci(e2e): switch full-live LLM from Anthropic to OpenAI (gpt-4o-mini)

PR #111's Full Live E2E has been failing on:
  "LLM request rejected: Your credit balance is too low to access the
   Anthropic API. Please go to Plans & Billing to upgrade or purchase
   credits."

This is not a regression in PR #111; the shared Anthropic test account
has no balance. OPENAI_API_KEY is already wired into the full-live job
env (line 351) and reportedly has credits, so migrate CI to OpenAI:

1. openclaw.json patch step now writes auth.profiles["openai:default"]
   (provider=openai) and agents.defaults.model.primary = "openai/gpt-4o-mini"
   instead of the anthropic:default / claude-sonnet-4-5 pair.
2. auth-profiles.json keyRef.id switches from ANTHROPIC_API_KEY to
   OPENAI_API_KEY; profile order map now keys on "openai".
3. GUARDRAIL_REQUEST_MODEL is set to openai/gpt-4o-mini in the patch
   step (the subsequent Init step re-derives it from OC_MODEL, which is
   consistent since the primary model is now the OpenAI one).
4. Downstream provider detection (grep "openai\|gpt\|o1\|o3\|o4") at
   line 731 already maps to OPENAI_API_KEY, so API_KEY_ENV resolution
   for the guardrail config (cfg.guardrail.api_key_env) works without
   further changes.
5. "Restore OpenClaw Anthropic model" step renamed to
   "Restore OpenClaw model and auth backups" (behaviour is generic —
   restores whatever the pre-run backup held — so the old name was
   actively misleading).

ANTHROPIC_API_KEY remains plumbed through the env and dotenv files as
defensive pass-through in case any other component consults it; it is
no longer the driver of agent LLM traffic.

Why gpt-4o-mini: cheapest current OpenAI model that supports tool
calling end-to-end (required by block/allow enforcement tests where the
agent must actually attempt tool use); the earlier Anthropic choice was
sonnet-4-5 primarily for consistency with dev, not because the tests
need a premium model.

Guardrail round-trip now takes the native OpenAI chat-completions shape
through the proxy's /v1/chat/completions handler and
resolveConfiguredProvider → Bifrost OpenAI provider path, which is the
simplest routing in the codebase and avoids any Bedrock/SigV4 or
Anthropic->Bedrock translation work.

Core E2E is unaffected (that job doesn't exercise the live LLM path).

* Revert "ci(e2e): switch full-live LLM from Anthropic to OpenAI (gpt-4o-mini)"

This reverts commit 3b7153ce684e6a5437dcd277ad9dcdc4f93674fe.

* ci(e2e): switch full-live LLM to OpenClaw-native amazon-bedrock provider

Previously the full-live E2E job hard-coded OpenClaw to call the Anthropic
API directly (anthropic/claude-sonnet-4-5 + ANTHROPIC_API_KEY), which is
exactly the path that's currently failing because the Anthropic account is
out of credits. That's also unnecessary: OpenClaw supports AWS Bedrock
natively via its stock amazon-bedrock provider
(https://docs.openclaw.ai/providers/bedrock), and our BIFROST_API_KEY
secret is already an AWS Bedrock bearer token (ABSK…) — the exact format
AWS_BEARER_TOKEN_BEDROCK wants. Reusing the key OC-side means we drop the
Anthropic dependency entirely with no new secrets.

Workflow changes (.github/workflows/e2e.yml, full-live only):
  - Add AWS_BEARER_TOKEN_BEDROCK: \${{ secrets.BIFROST_API_KEY }} and
    AWS_REGION: us-east-1 to the job env so OC's AWS SDK default chain
    can authenticate to Bedrock.
  - Patch openclaw.json to register models.providers[\"amazon-bedrock\"]
    with api=bedrock-converse-stream, auth=aws-sdk, and a single model
    entry for us.anthropic.claude-haiku-4-5-20251001-v1:0 (cheapest
    current Claude on Bedrock with tool-calling, matches the model our
    in-process Bifrost e2e test already covers).
  - Point agents.defaults.model.primary at
    amazon-bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0 and
    rewrite auth-profiles.json to use mode=aws_sdk (no keyRef).
  - Propagate BIFROST_API_KEY + AWS_BEARER_TOKEN_BEDROCK + AWS_REGION
    into both ~/.defenseclaw/.env (guardrail sidecar) and the OpenClaw
    systemd user-service drop-in environment file.
  - In the guardrail-detection block, match Bedrock models first (order
    matters because a Bedrock inference profile id contains \"claude\")
    and set API_KEY_ENV=BIFROST_API_KEY so the guardrail proxy can talk
    to Bedrock via the embedded Bifrost SDK. Drop the stale
    \"SigV4 not supported\" comment — Bifrost consumes the ABSK bearer
    token directly, no SigV4 signing needed.

Go changes (required so the guardrail sidecar actually understands the
\"amazon-bedrock/\" prefix OpenClaw writes into openclaw.json):
  - internal/gateway/provider.go: add \"amazon-bedrock\" to
    knownProviders so splitModel() correctly splits
    \"amazon-bedrock/us.anthropic…\" into (amazon-bedrock, us.anthropic…).
  - internal/gateway/provider_bifrost.go: add \"amazon-bedrock\" to
    mapProviderKey() as an alias of \"bedrock\" -> schemas.Bedrock so the
    Bifrost SDK routes it correctly.
  - internal/gateway/provider_bifrost_test.go: new
    amazon_bedrock_openclaw_prefix table case in
    TestBifrostProvider_Creation and \"amazon-bedrock\" added to
    TestMapProviderKey_AllKnownProviders.

All gateway + config tests pass locally, including the live Bedrock
round-trip tests (TestBifrostProvider_LiveBedrock,
TestBifrostProvider_LiveBedrockStream).

* ci/doctor: unblock full-live on amazon-bedrock (fix cascade from bad auth profile)

The previous full-live run hit a single root cause that cascaded into ~8
"FAIL" lines:

  auth.profiles.amazon-bedrock:default.mode: Invalid input
  (allowed: "api_key", "oauth", "token")

OpenClaw's config schema only allows those three values for an auth-profile
mode; our Python patch step wrote `mode: "aws_sdk"`, which OC rejected at
startup, so the gateway never came up and every downstream check (doctor,
block/allow, skill-api disable, etc.) failed with "gateway: not connected".
Per https://docs.openclaw.ai/providers/bedrock, Bedrock auth is driven by
the provider's own `auth: "aws-sdk"` setting, which delegates to the AWS
SDK default credential chain (AWS_BEARER_TOKEN_BEDROCK is already exported
from the BIFROST_API_KEY secret) — no auth-profile entry is needed.

This change:

  * .github/workflows/e2e.yml
    - Stop writing an `auth.profiles.amazon-bedrock:default` entry into
      openclaw.json; scrub any stale entry for good measure.
    - Write auth-profiles.json as an empty profile store so a prior run's
      ANTHROPIC_API_KEY-based profile can't bleed through.
    - Remove ANTHROPIC_API_KEY from the full-live job env entirely. The
      guardrail passthrough / duplicate-header / X-AI-Auth tests in
      scripts/test-e2e-full-stack.sh all skip cleanly with "ANTHROPIC_API_KEY
      not set", which is the correct behavior for a Bedrock-only live run
      (previously these tests called api.anthropic.com directly with a
      depleted key and reported "credit balance too low" as test failures).

  * cli/defenseclaw/commands/cmd_doctor.py
    - Route the "LLM API key" check by *provider prefix* (segment before the
      first "/"), not by substring. The old `"anthropic" in model` check
      wrongly matched Bedrock inference profile ids like
      `amazon-bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0` and sent
      our ABSK bearer token to api.anthropic.com, producing a spurious 401
      FAIL even when the actual Bedrock path was fine.

  * cli/tests/test_cmd_doctor.py
    - Lock the new behavior in with three regression tests: the bedrock
      inference profile case (must NOT call _verify_anthropic), plus the
      `anthropic/…` and `openai/…` happy paths.

* review: address H1-H6 + M1-M10 findings from PR #111 review

High-severity hardening:
- H1/M10: cache policy.Engine per-sidecar via sync.Once; log init
  failure exactly once instead of per-request, preventing repeated
  Rego recompilation and log floods.
- H2: gate raw judge-response logging behind DEFENSECLAW_JUDGE_TRACE=1
  and add redactEntity() for PII-safe logging of detected entities.
- H3: replace process-wide atomic.Bool judgeActive with a context-scoped
  withJudgeActive/isJudgeActive guard; recursive judge invocations are
  now blocked per-request without globally serialising concurrent
  guardrail traffic.
- H4: harden injection/PII/tool judge prompts with <<<SAMPLE>>> delimiters
  and explicit anti-injection instructions; flip parsing to fail-closed
  (errorVerdict instead of allowVerdict) when judge output is malformed.
- H5: narrow IsPlatformID to fail-OPEN for valid NANP phone numbers so
  real US/CA phones are no longer suppressed by default.
- H6: gate verbose sidecar diagnostic logging behind
  DEFENSECLAW_SIDECAR_DIAG=1; SIGPIPE handling stays always-on.

Medium-severity hardening:
- M1: UTF-8-safe extractEvidence/extractEvidenceAt — clamp slice
  boundaries to rune starts so evidence strings written to logs and
  audit records are always valid UTF-8.
- M2: RulePack.Validate() now compiles every regex at load time and
  warns on invalid patterns instead of silently skipping them per
  request.
- M3: bound regexCache via container/list LRU (1024 entries) and cache
  negative results so invalid patterns aren't recompiled hot-path.
- M4: derive Bifrost Key.ID via SHA-256 hash of the API key (helper
  bifrostKeyID) instead of embedding the raw key in upstream structures
  that may reach logs.
- M5: add TTL-based session eviction (default 30m) to ContextTracker
  and refactor pruneOldestLocked from O(n^2) to O(n log n).
- M6: replace hardcoded claude-sonnet-4-20250514 probe model in
  defenseclaw doctor with _anthropic_probe_model() — prefers the
  configured anthropic/<model>, then DEFENSECLAW_ANTHROPIC_PROBE_MODEL,
  then claude-3-5-haiku-latest.
- M7: route doctor LLM API key verification by the *model provider
  prefix* first; env-name prefix (ANTHROPIC_API_KEY etc.) is only a
  last-resort fallback. Prevents Bedrock tokens stored in
  ANTHROPIC_API_KEY from being shipped to the Anthropic API.
- M8: deprecate the --token sidecar flag (still accepted, prints a
  warning, hidden from help) in favour of OPENCLAW_GATEWAY_TOKEN.
- M9: access Bifrost ToolCalls symmetrically via
  bm.ChatAssistantMessage.ToolCalls to guard against upstream schema
  drift.

Tests:
- New: TestRedactEntity (incl. UTF-8 multibyte coverage) and
  TestJudgeLogTraceFlag in llm_judge_logging_test.go.
- New: TestContextTracker_EvictsStaleSessions covering TTL eviction.
- New: doctor routing tests — env-name fallback, model-prefix wins,
  AnthropicProbeModelTests covering all three probe-model branches.
- Updated: TestPIIToVerdict/telegram_id_suppressed now uses a 9-digit
  non-NANP id so it still exercises platform-ID suppression after H5.
- Updated: TestRunToolJudgeIgnoresPromptJudgeReentrancyFlag wired
  through the new context-scoped withJudgeActive helper.

No on-the-wire schema changes; verdict structure and OPA input are
unchanged. Splunk/OTel forwarding and CLI surface are unchanged except
for the deprecated --token flag warning.

* feat(observability): decouple OTel + introduce generic audit_sinks (Phase 0)

Phase 0 of the stacked observability refactor on top of PR #111
(feat/wire-rulepack-runtime). Replaces the single-Splunk audit
forwarder with a declarative, multi-destination audit_sinks list
and removes the Splunk-specific coupling from the OTel provider.

BREAKING: the legacy `splunk:` config block is rejected on startup
with a hard error pointing operators at docs/OBSERVABILITY.md. This
is intentional so nobody silently loses forwarding after upgrading.

What changed:

- internal/audit/sinks/: new package defining Sink interface, Manager
  for fan-out, and per-kind implementations for splunk_hec, otlp_logs,
  and http_jsonl. Each sink owns its own batching/timeouts and is
  independent — one failing sink never blocks the hot path.
- internal/config/sinks.go: new AuditSink schema with per-kind
  configs (SplunkHECSinkConfig, OTLPLogsSinkConfig, HTTPJSONLSinkConfig),
  common batch/timeout/filter fields, and eager Validate() per sink.
- internal/config/config.go: CurrentConfigVersion -> 4. viper.Reset()
  at the start of Load() so tests don't leak state. detectLegacySplunk()
  refuses to start if legacy keys are present.
- internal/audit/logger.go: SetSinks(*sinks.Manager) replaces
  SetSplunkForwarder. forwardToSinks() fans every event out via the
  Manager with a bounded 2s context so sinks can't stall decisions.
- internal/audit/splunk.go + splunk_test.go: deleted — behaviour is
  now owned by internal/audit/sinks/splunk_hec.go.
- internal/audit/export.go: ExportSplunk removed (replay command now
  drives the generic sink pipeline).
- internal/audit/network_egress.go: routes egress alerts through
  forwardToSinks.
- internal/cli/root.go + internal/cli/audit_sinks.go: new init path
  (initAuditSinks -> buildAuditSinks) that translates config.AuditSink
  declarations into concrete sinks.Sink instances and installs them
  on the audit logger at startup.
- internal/gateway/health.go + sidecar.go: Splunk subsystem renamed
  to Sinks; aggregates health + names + kinds across every configured
  sink. /health and defenseclaw-gateway status both show the new shape.
- internal/cli/sidecar.go: prints the generic "Sinks" line instead of
  a Splunk-only banner.
- internal/telemetry/provider.go: expandHeaders is now vendor-neutral
  — no more X-SF-Token auto-injection from SPLUNK_ACCESS_TOKEN. The
  telemetry stack is a plain OTLP client; use otel.headers (or
  OTEL_EXPORTER_OTLP_HEADERS) to send any vendor-specific auth header.
- internal/tui/app.go + overview.go: HealthSnapshot.Splunk -> Sinks.
- internal/tui/configedit.go + setup.go: removed single-key splunk.*
  edits (the new schema is list-based); read-only summary of the
  configured audit_sinks list is shown with a pointer to the
  dedicated editor landing in Phase 3.3.
- docs/OBSERVABILITY.md: new operator guide — concepts, migration
  from v3 splunk: block, full sink reference, OTel examples, event
  shape, health reporting.

Tests are green across the whole tree. Redaction scrubbing at the
sink layer will land in a separate PR so this one stays scoped to
the observability refactor.

* feat(observability): structured gateway events (Phase 1)

Introduce internal/gatewaylog for JSONL verdict/judge/lifecycle
emissions with lumberjack rotation and a stderr pretty-printer.

- New writer wired into sidecar boot/teardown, writing to
  $DATA_DIR/gateway.jsonl alongside a human-readable mirror on
  stderr. Existing defaultLogWriter diagnostics stay intact.
- Central verdict event at GuardrailInspector.Inspect covers every
  strategy (regex, regex+judge, judge-first) so no caller has to
  plumb the writer through each path.
- Judge invocations (injection + PII) now emit a structured Judge
  event with latency, parse state, action, and severity. Raw
  bodies stay gated behind DEFENSECLAW_JUDGE_TRACE so PII-heavy
  payloads don't leak into the JSONL stream by default.
- Lifecycle events for sidecar init/stop give operators a
  timeline anchor in the JSONL feed.

Tests: writer round-trip / pretty / fanout / emit-after-close
coverage plus inspector-level verdict emission assertions.

Remainder of Phase 1.3 (migrating every defaultLogWriter site)
and Phase 2/3 (OTel mapping, metrics, TUI tab) continue in
follow-up commits.

* feat(observability): OTel pipeline, TUI verdicts, JSONL coverage (Phase 2-4)

Completes the structured observability stack on top of the Phase 0/1
sink + gatewaylog foundations:

Phase 2 — OTel pipeline
 - Map gatewaylog.Event to OTel LogRecords with typed attributes
   per event (verdict/judge/lifecycle/error/diagnostic) and fan
   out from the JSONL writer directly to the OTLP logs exporter.
 - Add guardrail pipeline span via SetTracerFunc / StartGuardrailStageSpan;
   proxy injects the tracer closure so the inspector stays decoupled
   from the telemetry package.
 - Record guardrail metrics driven by gatewaylog events:
   defenseclaw.gateway.verdicts, judge.invocations, judge.latency,
   judge.errors, gateway.errors, audit.sink_send_failures.
 - Add guardrail.retain_judge_bodies config flag + atomic to opt in
   to raw judge response retention (default off; DEFENSECLAW_JUDGE_TRACE
   still required for full-fidelity capture).

Phase 3 — TUI
 - New Verdicts source in the logs panel tailing gateway.jsonl with
   block/alert/allow action filter chips ('a' to cycle).
 - Enter on a verdict row opens the detail modal with full event
   (timestamp, severity, action, stage, direction, model, reason,
   raw JSON).
 - Setup panel surfaces OTel knobs (TLS, per-signal endpoints,
   redacted headers) and an audit_sinks summary with an edit hint;
   configedit wires the new OTel keys.

Phase 4 — polish & migration
 - Coverage test asserts every file calling audit.Logger.LogAction
   in internal/gateway also emits at least one structured
   emit*() sibling; add strategic emits in router.go/proxy.go/api.go
   to cover the migration.
 - scripts/assert-gateway-jsonl.py validates JSONL schema for any
   captured file; wired into both e2e workflow jobs and the
   full-stack e2e dump-on-failure tails gateway.jsonl alongside
   gateway.log.
 - test-e2e-cli.py picks up a jsonl_event_contains helper so new
   e2e tests can assert on the structured stream.
 - install/upgrade/sandbox help text points at both gateway.log
   (pretty) and gateway.jsonl (structured).

BREAKING: gateway now emits two files — gateway.log (pretty) and
gateway.jsonl (structured). Operators consuming the text log for
verdict parsing must switch to the JSONL stream; schema is stable
per internal/gatewaylog/events.go and documented in
docs/OBSERVABILITY.md.

* tests(observability): fill coverage gaps + Phase 2.3 SQLite judge retention

Addressed the review challenge on Phase 2-4 completeness.

Fills the missing test coverage identified by the self-audit:
- internal/audit/sinks/*: Manager fan-out, Splunk HEC envelope/auth,
  HTTP JSONL TLS/bearer/env-expansion, OTLP logs severity mapping
- internal/cli/audit_sinks.go: sink builder, error aggregation,
  env-token resolution
- internal/telemetry/gateway_events.go: OTel log-record attributes,
  metric updates for all event types, nil-payload safety
- internal/telemetry/runtime.go: StartGuardrailStageSpan /
  EndGuardrailStageSpan attributes, reason truncation, allow→Ok vs
  block→Error status mapping, nil-provider safety
- internal/gateway/llm_judge.go: judgeRawForEmit / SetRetainJudgeBodies
  env-var + config-flag gating, long-body truncation
- internal/tui/logs.go: parseVerdictRow, loadVerdicts filter gating,
  cycleVerdictAction rotation, SelectedVerdict, renderVerdictLine
- internal/tui/setup.go: fmtOTelHeaders redaction + sort,
  auditSinkSummaryFields per-kind rendering + edit hint

Completes Phase 2.3 (SQLite judge-body persistence) — previously only
the sinks half landed:
- audit.Store migration 3: judge_responses table + indexes
- Store.InsertJudgeResponse / ListJudgeResponses with UUID + RFC3339Nano
- gateway events pipeline gains SetJudgePersistor hook; emitJudge runs
  the persistor BEFORE emitEvent's redaction pass so the operator-
  owned SQLite receives the un-redacted body while fanout sinks still
  get the scrubbed form
- sidecar wires the persistor iff guardrail.retain_judge_bodies is
  true and tears it down on shutdown

Expands coverage_test.go scope to internal/audit + internal/telemetry:
- TestLogActionFreeInAuditAndTelemetry pins those packages as
  LogAction-free so the sink/pipeline substrate can never grow a
  circular routing back into itself
- Factored out scanLogActionCoverage for reuse

All tests pass (full go test ./..., go vet clean).

* docs(observability): add DEFENSECLAW_REVEAL_PII production warning + drop goto

OBSERVABILITY.md now spells out why DEFENSECLAW_REVEAL_PII=1 must never
run in production: any shared transport (journald, tmux, CI logs,
support bundles) that captures stderr becomes an exfiltration channel
for the literal secrets/PII the gateway prints when the flag is set.
The flag is documented as a developer-workstation / incident-triage
tool only.

Also replaces the single `goto done` in redaction.findKVBoundaries
with a labelled `break keyLoop` — same control flow, but keeps the
file goto-free now that it has grown into the primary PII seam.

* fix(observability): review pass — panic safety, bounded backlogs, UTF-8 safety

Addresses the H1–H6, M1/M2/M4, and L1 findings from the post-merge
review of the observability stack.

High:
- Thread gatewaylog.Direction through the judge persistor so SQLite
  rows no longer drop the inbound/outbound tag.
- Wrap fanout callbacks in gatewaylog.Writer.Emit and per-sink
  Forward calls in sinks.Manager with recover(); a panicking
  exporter can no longer unwind into the guardrail hot path.
- Coalesce immediate flushes (guardrail-verdict bursts) behind an
  atomic.Bool single-flight so high-frequency verdict traffic cannot
  explode goroutines.
- Cap the in-memory retry backlog for http_jsonl and splunk_hec at
  100×BatchSize (floor 10k) so a persistently offline endpoint cannot
  OOM the sidecar; oldest events drop with an operator warning.
- Truncate judge raw_response at MaxJudgeRawBytes (64KiB) with UTF-8
  rewind and a [truncated N bytes] marker to bound audit DB growth.

Medium:
- TUI verdict filter now applies to both verdict and judge rows and
  hides actionless events when a filter is active (consistent UX).
- Rewrite truncateVerdictReason to be rune-aware so multi-byte
  strings are never sliced mid-codepoint.
- Cap the OTel defenseclaw.verdict.reason attribute at 200 bytes to
  bound cardinality on backends that index attribute values; the
  full reason still ships in the log body.

Low:
- Emit a one-shot stderr warning when http_jsonl or splunk_hec is
  configured with verify_tls=false against an https:// endpoint, so
  silent TLS downgrades never slip through review.

Regression tests added for every fix. Full go test ./... and
go vet ./... are green.

* fix(ci): migrate E2E workflow from legacy splunk: to audit_sinks:

The observability refactor (this PR) makes config.Load() refuse to
start when a legacy `splunk:` block is present — that's the whole
point of the v3 → v4 migration check in internal/config/config.go.
The E2E workflow was still writing the old shape, so the gateway
daemon exited immediately during "Init DefenseClaw" with:

  Error: start daemon: daemon: process exited immediately
  (check /home/ubuntu/.defenseclaw/gateway.log for errors)

and the two downstream E2E jobs + the required-checks gate all
failed together.

Rewrites both Python-yaml patches (Core E2E and Full Live E2E) to
emit a single audit_sinks entry pointing at the same local Splunk
container the "Start Splunk" step brings up. The token still flows
via DEFENSECLAW_SPLUNK_HEC_TOKEN, so no secret/env changes.

Also extends the on-failure log artifact to include ~/.defenseclaw/
*.jsonl (gateway.jsonl is the new structured sibling of gateway.log)
so the next triage run has the schema-validated trail available in
the uploaded artifact — the ci-watcher pass flagged that only *.log
was being captured.

* fix(config): stop writing legacy splunk: from Python, load .env before config.Load

The first CI retry after migrating the e2e.yml patches to audit_sinks
still red-x'd with the same "daemon: process exited immediately"
error. Root cause, per ci-watcher triage of run 24544271547:

1. defenseclaw init (Python) unconditionally serializes the
   SplunkConfig dataclass — including default hec_endpoint /
   hec_token_env strings — into ~/.defenseclaw/config.yaml. The Go
   gateway's v3→v4 migration check (config.detectLegacySplunk) treats
   any populated splunk.* key as a hard error and refuses to start.
   So defenseclaw init calls sidecar start, the sidecar immediately
   fails config.Load(), and we exit before the workflow's post-init
   Python yaml patch ever runs.

2. Even if init succeeded, SplunkHECSinkConfig.Validate() resolves
   token_env via os.Getenv at config-load time, but loadDotEnvIntoOS
   currently runs *after* config.Load(). In CI the HEC token lives
   only in ~/.defenseclaw/.env, so validation would fail with a
   misleading "token is empty" error during the next restart.

Fixes:

- cli/defenseclaw/config.py: _config_to_dict now drops the `splunk`
  key entirely. v4 routes Splunk forwarding through audit_sinks; the
  in-memory SplunkConfig dataclass stays for backward-compatible
  *reads* of existing config.yaml files, but we never write it again.
  setup splunk --logs becomes a no-op until it's ported to emit
  audit_sinks entries (tracked as a follow-up; out of scope here).

- internal/cli/root.go: loadDotEnvIntoOS(config.DefaultDataPath()/.env)
  now runs *before* config.Load() so token_env references in
  audit_sinks resolve against secrets written by defenseclaw setup
  / defenseclaw init. Added a second deferred load keyed on cfg.DataDir
  so DEFENSECLAW_HOME overrides still pick up .env contents.

Covered by existing internal/config + internal/cli Go test suites
(all green) and the full Python cli test suite (987/987 passing).

* fix(config): python CLI reads audit_sinks[*].splunk_hec as SplunkConfig fallback

Phase 0 removed the legacy \`splunk:\` yaml block and moved Splunk
forwarding under \`audit_sinks:\`. The Go gateway consumes the new
shape, but the Python CLI keeps its own in-process Splunk forwarder
for events it raises locally — \`defenseclaw aibom scan\`,
\`defenseclaw skill quarantine/restore/block/allow\`,
\`defenseclaw mcp block/allow\`, \`defenseclaw plugin *\`, etc.

That Python forwarder still reads \`cfg.splunk.*\`. With the v4
config.yaml containing only \`audit_sinks\`, \`SplunkConfig\` loaded
defaults (\`enabled=False\`), so the Python-side forwarder
short-circuited and all of those events disappeared from Splunk even
though SQLite + the Go sink pipeline were fine. That’s what the CI
run 24544639016 showed: skill-scanner and codeguard scans (logged by
the Go gateway) landed in Splunk, but AIBOM, quarantine/restore,
block/allow, and every plugin action (logged by Python) did not.

Teaches \`config.load()\` to hydrate \`cfg.splunk\` in memory from
the first enabled \`audit_sinks[*]\` entry whose \`kind\` is
\`splunk_hec\`. This is:

- IN MEMORY ONLY. \`_config_to_dict\` still strips the \`splunk\`
  key on save so we never reintroduce the \`detectLegacySplunk\`
  tripwire in the Go gateway.
- STRICTLY FALLBACK. If the user explicitly wrote a legacy
  \`splunk:\` block (for older installs), we keep their values
  untouched.
- SAFE FOR INPUTS. Any non-dict / missing-endpoint / disabled sink
  is skipped without raising.

Manually verified by loading a pure-audit_sinks config.yaml and
confirming \`cfg.splunk.enabled == True\`, endpoint/index/sourcetype
mirror the sink, and \`resolved_hec_token()\` pulls the env token.
All 987 Python tests pass.

* feat(tui): interactive Audit Sinks editor (P0-#1)

Adds an interactive sub-mode to the Setup panel that lists configured
audit sinks and shells out to `defenseclaw setup observability
list|enable|disable|remove|test|migrate-splunk` for every mutation.
The Python CLI remains the single source of truth — the TUI never
edits config.yaml directly — so the gateway's atomic-write invariants
and audit logging stay intact regardless of which front-end the
operator uses.

Entry point: press E while the Config Editor is focused on the Audit
Sinks section. Bindings: j/k nav · e enable · d disable · r remove
(with [y/N] confirm) · t test · a hand off to Observability wizard ·
m migrate legacy splunk: block · Ctrl+R refresh · Esc close.

Also registers `setup observability list|migrate-splunk` palette
entries so the migration is reachable without entering the editor
(P3-#18).

Coverage: 27 tests (unit + SetupPanel integration) stubbing the
list lister to avoid requiring an installed CLI at test time.

* feat(tui): Plugins panel action menu — PluginActions (P0-#2)

Adds context-aware `o`-menu to the Plugins panel matching the
Skills / MCPs parity pattern. Every verb in the menu dispatches
through `defenseclaw plugin <verb> <name>` so PolicyEngine,
admission audit, and the gateway RPC for runtime enable/disable
all stay in one place. No plugin state is forked in Go.

Action visibility is driven off verdict + enabled + status:
  - scan / info always available
  - block / unblock / allow driven off verdict
  - disable / enable driven off runtime state
  - quarantine / restore driven off status substring
  - remove always exposed last (destructive, but discoverable)

Tests cover:
  - PluginActions visibility across 4 verdicts × 2 statuses × 2
    enabled states (24 matrix combos), including no-duplicate-key
    invariant
  - `o` opens the menu with the plugin's name (falling back to ID
    when the manifest omits it) and populates info rows
  - every key PluginActions can emit maps to a non-nil CLI
    invocation via executeActionMenuItem (prevents silent no-ops
    when new verbs are added to the menu without dispatch wiring)
  - nil-selection safety on both open and dispatch paths

* tui(parity P0-#3): add Tools panel + ToolActions

Wires a new Tools panel into the unified TUI so operators can view and
mutate tool block/allow policy without dropping to a shell. All
mutations route through `defenseclaw tool {block,allow,unblock,status}`
so the admission gate, scoped-policy resolution (e.g.
`write_file@filesystem`), and audit emission stay in one authoritative
code path — CLI remains the single source of truth.

Panel is registered at index PanelTools, inserted immediately before
PanelSetup so the existing 1–9/0 numeric keybindings all stay stable;
Tools is reached via the new uppercase 'T' shortcut, the command
palette, or tab navigation. Action menu surfaces Info/Block/Allow/
Unblock keys contextually by current status and deliberately omits
Scan/Enable/Disable/Quarantine (those verbs belong to Skills/MCPs/
Plugins, not Tools) — guarded by TestToolActions_NoScanOrEnable.

Scoped targets preserve the `@scope` suffix through the dispatcher so
operators never accidentally edit the global row when they selected a
scoped one.

Tests cover: ToolActions branches by status, global-scope placeholder
rendering, action-menu dispatch for every key, nil-selection safety,
cursor clamping, BlockedCount, 'T' global shortcut routing, and a
panel-ordering regression guard so future refactors can't silently
shift numeric keybindings.

* feat(tui): route Skills panel mutations through CLI (P0-#4)

Before this change, pressing 'b' in the Skills panel called
SkillsPanel.ToggleBlock() which flipped state directly in the audit
store. That bypassed the admission gate, the gateway RPC
notification, and the formal audit event — so a block from the TUI
looked different in the log than a block from the shell, and could
drift out of policy sync.

Now every mutation (block/allow/unblock/disable/enable/quarantine/
restore/install/scan) dispatches `defenseclaw skill <verb> <name>`
through CommandExecutor. The Python CLI is the single source of
truth. Adds install/enable/restore to the action menu so the TUI
covers the full CLI surface.

SkillActions() now branches by status (blocked/allowed/quarantined/
disabled/default) to match _skill_status_display() in cmd_skill.py,
and skills.Refresh() recognises quarantined + disabled rows.

Tests: TestSkillActions covers every branch (+ dup-key guard),
TestHandleSkillsKey_{B,A}_RoutesToCLI anchors the regression, and
TestExecuteActionMenuItem_SkillDispatch confirms every key surfaced
by any SkillActions branch resolves to a real CLI verb.

* feat(tui): MCPSetForm + route MCP actions through CLI (P0-#5)

Symmetric change to P0-#4 but for MCP servers:

* 'b' and 'a' no longer call MCPsPanel.ToggleBlock() (which
  mutated the audit store directly, skipping admission gate and
  gateway RPC). Both now dispatch through `defenseclaw mcp`.
* 'a' is always "allow" now — the old "only if blocked →
  unblock" short-circuit was a footgun. Pure unblock is still on
  'u' in the action menu.
* Info ('i') is wired through the menu dispatcher so the action
  menu button isn't silently a no-op.
* New MCPSetForm covers the `mcp set` CLI verb (add/update
  server). Triggered from the MCP panel with 'n' (or '+'). Tab /
  Shift+Tab move between fields, Enter advances or submits,
  BackSpace / Ctrl-U edit the focused field, Esc cancels.
  BuildCommand() validates required fields (name + one of
  command/url) and env KEY=VAL shape before dispatching, so the
  operator stays in the form on error rather than bouncing out
  to a raw click traceback.

Tests:
* form navigation wraps cleanly; named keys (f5/home/…) are not
  appended as literal input; UTF-8 backspace trims whole runes.
* BuildCommand argv matches cmd_mcp.py's flag layout;
  skip-scan accepts y/yes/true/1; env without '=' fails.
* handleMCPsKey B/A dispatch via CLI across all status branches;
  'n' opens the form; form owns the keyboard while active so 'j'
  becomes input (not a list cursor-down).
* executeActionMenuItem covers every key MCPActions surfaces.

* feat(tui): actions-matrix editor in Setup panel (P1-#6)

The admission gate's severity → (file, runtime, install) decision
table lives in three parallel configs (skill_actions, mcp_actions,
plugin_actions) of 5 severities × 3 columns each. Previously the
TUI Setup panel ignored them, forcing anyone who wanted to raise
the severity threshold for, say, plugin install-blocking, to open
~/.defenseclaw/config.yaml by hand.

Adds three new sections (Skill Actions / MCP Actions / Plugin
Actions) to the SetupPanel config editor. Each section surfaces
one header row plus 15 choice rows, backed by the existing
configField rendering so operators keep the same keymap
(arrow / enter / toggle / save). The choice option lists are
deliberately per-column (file: none/quarantine; runtime:
enable/disable; install: none/block/allow) so operators cannot
pick semantically invalid pairings.

Save path: applyConfigField gained a dotted-prefix fallback that
routes skill_actions.*/mcp_actions.*/plugin_actions.* through a
new applyActionsField helper. A 45-case switch would have
quadrupled the function length without adding precision.

Tests:
* shape is locked at 1+5×3 rows per section (a future severity
  or column add forces a deliberate review);
* each column keeps its own option set (no accidental merging);
* every (prefix, severity, column) triple round-trips through
  applyConfigField;
* malformed keys silently drop (don't panic Save's hot loop);
* loadSections exposes all three sections (so a missing caller
  fails loudly, not silently).

* feat(tui): admission-policy CRUD + policy test binding (P1-#7/#8)

Policy panel previously exposed only guardrail rule packs / judge
prompts / suppressions / rego — the admission-gate YAML policies
(`defenseclaw policy <verb>`) were invisible. Operators had to
drop out of the TUI to create, activate, show, or delete a policy,
which defeats the "one pane of glass" pitch.

Adds a new "Policies" sub-tab (now the first tab, because admission
policy is the most common reason to open this panel):

* ↑/↓ / j/k — navigate the list
* enter or 'a' — `policy activate <name>`
* 's' — `policy show <name>`
* 'n' / '+' — open PolicyCreateForm overlay (→ `policy create`)
* 'd' — `policy delete <name>` (CLI confirms before irreversible)
* 'v' — `policy validate`
* 'l' — `policy list` (prints full CLI-formatted table)
* 'r' — refresh the local list from disk (no CLI round-trip)

All mutating keys dispatch through CommandExecutor so they route
through the gateway and emit proper audit events — same rationale
as skills / mcps / tools.

PolicyCreateForm is the third wizard overlay in this series (after
SinkEditor and MCPSetForm) and reuses the same sequential-field
layout so the three forms feel like one subsystem. It maps 1:1 to
the `policy create` CLI option surface:
  Name, Description, --from-preset, {critical/high/medium/low}-action

Validation happens client-side (name regex, preset choices, action
choices) so the operator gets an inline status line rather than a
bounce to stderr.

P1-#8 rides along: capital-T on the OPA/Rego tab now runs
`policy test`. Lowercase 't' keeps its existing meaning (toggle
show-tests) so muscle memory is preserved. The help text for both
affected tabs (Policies + OPA) is updated to list the new keys.

Tests (25 new):
  PolicyCreateForm — field navigation, UTF-8 safe backspace, named
  keys don't append, name/preset/action validation, blank-severity
  passthrough, Enter advances then submits, Esc cancels.
  Policies sub-tab — list loads from PolicyDir, active.yaml symlink
  detection, navigation + CLI dispatch for every verb, no-selection
  safety, 'n' opens form and then HandleKey routes to the form.
  OPA tab — 'T' dispatches `policy test`, lowercase 't' still
  toggles (pair of assertions to freeze the case distinction).

* tui(setup): full scanner rows + gateway watcher/watchdog editor (P2-#9)

Fleshes the Setup panel's Scanners section with the full Python-side
surface (policy, lenient, llm_consensus_runs, enable_meta, use_trigger,
VirusTotal/AIDefense toggles, key-env binding, MCP scan_prompts /
scan_resources / scan_instructions). Adds two new sections, Gateway
Watcher and Gateway Watchdog, exposing enabled/take_action/dirs per
stream plus watchdog interval/debounce. applyConfigField grows the
matching cases and a splitCSV helper to round-trip comma-separated
directory lists cleanly (empty input collapses to nil so YAML stays
tidy). Covered by exhaustive per-key round-trip tests plus section-
shape guards to prevent silent row drops.

* tui(setup): full OTel editor — per-signal, batch, resource (P2-#10)

Expands the OTel section from a handful of globals into the full
SDK surface: sampler + sampler_arg, per-signal endpoint/protocol/
url_path overrides (traces/logs/metrics), metrics export interval
and temporality, batch processor tuning (max_export_batch_size /
scheduled_delay_ms / max_queue_size), and a deterministic resource-
attribute summary row. Headers remain redacted read-only because
their values carry bearer tokens — map CRUD stays in the CLI wizard.
applyConfigField gains matching cases so a round-trip save preserves
every new field. Covered by per-key round-trip tests and a shape
guard that pins the list of keys the section must expose.

* tui(setup): interactive Webhooks editor (P2-#11)

Adds a WebhookEditorModel that mirrors the Audit Sinks editor —
list + e/d/r/t/s/a keybindings that shell out to `defenseclaw setup
webhook` so every mutation emits an audit event from the CLI rather
than a duplicated Go path. 'a' hands off to the existing Webhooks
wizard form since per-type prompts (slack room_id, generic HMAC
secret, cooldown tri-state) can't be captured in a flat list-view.
Registers IsEditorActive in SetupPanel so app.go gates hotkeys with
a single check instead of enumerating every sub-mode. Covered by
parser, lifecycle, bounds, and CLI-argv parity tests.

* tui(setup): inspect_llm editable + AI Defense/Firewall read-only (P2-#12)

Adds three new Config Editor sections: Inspect LLM is fully editable
(provider/model/base_url/timeout/max_retries, plus api_key masked as
kind=password and the preferred api_key_env for keychain-backed
rotation); Cisco AI Defense is read-only because enabled_rules comes
from the Cisco console and mutating api_key inline would land a
cleartext bearer in YAML — the row reports three distinct states
(inline redacted, env-resolved, env-unresolved, unset) so operators
know what's actually in effect; Firewall is read-only because its
paths bind to system-owned pf/nft anchors that DefenseClaw never
creates and silently rewriting them would orphan live rules.
applyConfigField routes inspect_llm.* writes and *refuses* to touch
cisco_ai_defense.* / firewall.* — a dedicated test pins this down so
a future refactor can't accidentally introduce an edit path.

* tui(setup): guardrail/openshell parity + config_version row (P2-#13/#14)

Guardrail gains host, model_name, original_model, api_base, and
retain_judge_bodies so the TUI surface matches the CLI/config.yaml
knobs (missing these meant `defenseclaw config show` reported state
the TUI could never produce).

OpenShell exposes sandbox_home plus the two tristate *bool fields
(auto_pair, host_networking) as kind=choice with ["", "true",
"false"] options. The empty-string preserves nil so
ShouldAutoPair/HostNetworkingEnabled defaults still apply — a plain
bool would collapse nil and &false and silently flip defaults.
parseTristateBool trims+lowercases and maps everything else back to
nil so a fat-fingered keystroke never writes a bogus literal.

config_version lands in General as a read-only header row rendered
via fmtConfigVersion: bare number when in sync with
CurrentConfigVersion, "N (binary expects schema vM — migration on
next save)" when drifted, "(unset)" for fresh in-memory configs.
Editing bypasses migrateConfig, so the row is explicitly kind=header
and a test pins down that applyConfigField never writes the field.

Tests cover every new case, the tristate round-trip (including the
"clear to nil" state), and the migration-drift summary.

* tui(inventory): --only scope chips with fast-scan preset (P3-#19)

Surfaces `defenseclaw aibom scan --only` in the TUI so operators can
narrow the scan to the security-review subset (skills+plugins+mcp)
and skip the slow agents/tools/models/memory discovery during
iteration.

- Adds categoryScope state to InventoryPanel + SetCategoryScope,
  ToggleCategory, ToggleFastScan helpers. nil scope = "scan all"
  (CLI default, no --only emitted). SetCategoryScope filters out
  unknown categories so a stale persisted value can't land a bogus
  --only value on the next reload.
- Extracts loadCmdArgs from LoadCmd so tests can assert the exact
  argv without needing the CLI installed in CI.
- New chip row below the sub-tab bar shows current scope as
  "Scope (all)", "Scope (fast)", or a custom subset. Inactive chips
  are dimmed, active ones highlighted.
- Binds 'o' in the inventory panel to ToggleFastScan. Deliberately
  does NOT auto-reload — operators press 'r' next so they can see
  the new scope before paying the 15-30s scan cost.
- Updates inventoryHint and adds an inline "(o toggles fast,
  r reloads)" legend on the chip row.

Tests (internal/tui/inventory_scope_test.go):
- LoadCmdArgs with/without scope.
- SetCategoryScope filters unknown, empty/nil round-trip to nil.
- ToggleCategory add/remove/empty/unknown.
- ToggleFastScan cycle + replaces manual scope.
- Order-independent isFastScan.
- Categories list locked to CLI --only choices (cmd_aibom.py).
- Fast-preset stability guard + --only value format (no spaces).

* tui(alerts): enrich Go panel detail + retire Textual alerts TUI (P3-#20)

- Remove the legacy Textual-based `defenseclaw alerts --tui` app. The
  flag now prints a single deprecation line on stderr and falls back
  to the Rich table output so wrapper scripts keep working while
  operators migrate to `defenseclaw tui` (2 => Alerts).
- Drop the `tui = [textual>=0.50]` extra from pyproject so we stop
  shipping a second TUI frontend; `uv.lock` regenerated.
- Port the Python `_humanize_details` summarizer into Go
  (`humanizeAlertDetails`) and use it in the AlertsPanel detail pane
  to render a "Summary:" line above the raw "Details:" when the two
  differ, keeping raw kv intact for copy/paste.
- Surface TraceID / RequestID on every event and, for findings, show
  the scanner tag and remediation hint inline so the Go panel is at
  parity with (actually, a superset of) the retired Textual view.
- Adds internal/tui/alerts_enrichment_test.go covering humanize
  edge cases (host/port, model slash-tail, noise drop, duplicate
  keys) and the enriched detail rendering.

* tui(overview): cached Doctor status box (P3-#21)

Renders a compact DOCTOR box on the Overview panel backed by an
on-disk cache so operators see "all green" or the top failures
without waiting for doctor's full network-probing run on every
redraw.

CLI side (single source of truth):
- cmd_doctor.py now persists <data_dir>/doctor_cache.json at the
  end of every run (including setup --verify) via a new
  _write_doctor_cache helper. Writes are atomic (tempfile +
  os.replace) so concurrent TUI reads never see partial JSON.
- Timestamps use RFC3339 with the "Z" suffix so Go's time.Time
  parser accepts them without a custom unmarshaler.

Go/TUI side:
- internal/tui/doctor_cache.go: DoctorCache type + Load/Save helpers
  with soft error semantics (NotExist => nil cache, parse errors
  surface as toasts, never panics). Age/IsStale/TopFailures/
  SummaryLine/SortChecksByStatus/FormatAge helpers drive the
  rendering + future detail modal.
- OverviewPanel gains a DOCTOR box showing counts, freshness, and
  top 3 failures/warnings. A top-of-screen notice bubbles up
  failures or staleness. Falls back to "not yet run — press [d]"
  on first launch.
- Model loads the cache on Init and reloads it after any
  `defenseclaw doctor` completion (CommandDoneMsg detected via
  isDoctorCommand prefix match), so running doctor from the palette
  or activity refreshes the box automatically.

Tests:
- internal/tui/doctor_cache_test.go: roundtrip, atomicity, Python-
  timestamp compat, age/staleness, TopFailures ordering,
  SummaryLine, FormatAge, SortChecksByStatus, corrupt-file soft
  fail, no-data-dir no-op.
- internal/tui/overview_doctor_test.go: renders…
vineethsai7 pushed a commit that referenced this pull request Apr 22, 2026
…tack (stacked on #117) (#127)

* feat: comprehensive CLI UX audit and remediation

Audit and fix all CLI command surfaces (Python + Go) for information
gaps, broken non-interactive flows, stale messages, credential
visibility, exit codes, and output consistency.

Setup commands:
- Redesign interactive guardrail prompts with value prop, numbered
  choices, and advanced options gate
- Add --accept-defaults alias, sensible defaults, and validation for
  guardrail non-interactive mode
- Change --restart default to True for setup guardrail
- Fix contradictory disable messaging
- Show Splunk Web credentials after setup; add --show-credentials flag
- Add --index/--source/--sourcetype and per-signal toggle flags for
  setup splunk non-interactive
- Validate skill-scanner policy names; show api_key_env consistently
- Add --verify to setup mcp-scanner
- Wire --remote for setup gateway non-interactive

Doctor command:
- Implement --json-output (was declared but never used)
- Check all subsystems from /health JSON (api, telemetry, splunk,
  sandbox)
- Upgrade scanner-missing severity from WARN to FAIL

Init flow:
- Show CLI + gateway versions in Environment section
- Replace bare "Health: ok" with rich /health JSON summary
- Auto-restart sidecar after init --enable-guardrail
- Context-aware "Next steps" based on what was configured

Gateway CLI (Go):
- Show health summary + log path after restart (parity with start)
- Sort status detail keys for stable output
- Return non-zero exit from status when sidecar unreachable
- Fix stale "defenseclaw sidecar" hint
- Add watchdog status subcommand
- Fix printSplunkLocalHint to read splunk-bridge .env
- Use configured APIBind for policy reload
- Sort policy diff output for determinism
- Add mode check to sandbox stop

Skill/MCP commands:
- Show full finding details in MCP scan (parity with skill scan)
- Show DB-only enforcement rows in MCP list
- Return exit code 2 for blocked/allowed scans
- Short-circuit upgrade when target == current version

Tests:
- Update test_guardrail.py for auto-restart default, --accept-defaults
- Update test_cmd_misc.py for Splunk credential display, add
  --show-credentials tests
- Update test_cmd_skill.py/test_cmd_mcp.py for exit code 2
- Add test_cmd_init.py version display tests
- Add test_cmd_doctor.py JSON output and record tests

* fix: resolve CI lint failures and add post-command hints

- Remove unused sortedMapKeys function (Go lint: unused)
- Fix f-string without placeholders and line-length violations (ruff F541/E501)
- Add tty-aware hint() helper for Python CLI and printHint() for Go CLI
- Add contextual "next steps" hints to: aibom scan, codeguard install-skill,
  status, skill scan/block/list, mcp scan/list/set, plugin install/remove/list,
  gateway stop, scan code
- Hints are dim-styled and only shown on interactive terminals (suppressed
  in JSON mode, piped output, and test runners)

* feat(tui): upgrade to Bubbletea v2 with inline detail panes, auto-init, and review fixes

- Migrate TUI to charm.land/bubbletea/v2, bubbles/v2, lipgloss/v2
- Add inline detail panes to Skills, MCPs, Plugins, Audit, Inventory panels
  with enriched data from audit store (findings, enforcement state, history)
- Add Esc key handling to close detail panes in all panel key handlers
- Fix ScrollOffset in Plugins/Audit panels to use dynamic listHeight()
- Fix AuditPanel.listHeight() off-by-one (was -2, now -3)
- Cache GetDetailInfo results per panel to avoid re-querying SQLite on render
- Run auto-init via standalone goroutine to keep executor free for user commands
- Close inventory detail pane on sub-tab switch
- Add explicit 'defenseclaw tui' CLI command
- Add action menu, activity panel, command executor, palette, health panel
- Add unit tests for detail toggle, cache invalidation, layout calculations

* fix: resolve Go and Python lint failures

- Remove unused `sys` import from cmd_tui.py (ruff F401)
- Replace WriteString(fmt.Sprintf(...)) with fmt.Fprintf (QF1012)
- Remove unused struct fields: ActivityPanel.scroll, logPollMsg.lines
- Fix switch type assertion pattern in logs.go (S1034)

* fix(tui): fix inventory table alignment, add clickable filters and data source hints

- Fix column alignment in Skills/Plugins tables using visual-width-aware
  padRight() helper instead of fmt.Sprintf padding (ANSI codes broke alignment)
- Widen SOURCE column to show full values instead of truncating to "opencla..."
- Add clickable sub-tab bar in inventory (Summary, Skills, Plugins, etc.)
- Add clickable filter stats in Skills (eligible/warning/blocked) and
  Plugins (loaded/disabled/blocked) sub-tabs with toggle behavior
- Add keyboard filter shortcuts (1-4) and Esc to clear
- Add italic hint notes explaining data source differences:
  "Inventory lists all items found by AIBOM on disk. The [X] tab only shows
  items with scan/enforcement records."

* fix(tui): fix command input rendering, delete wizard, add setup hint + review fixes

- Fix command input bar: remove lipgloss double-wrapping of textinput.View()
  that made typed text invisible; move background to textinput's own styles
- Delete pre-TUI huh-forms wizard (wizard.go); setup tab covers this now
- Add "First time?" notice in overview when system is unconfigured
- Fix autoInitCmd capturing Model by value (activity updates were lost)
- Fix readInteractiveOutput partial line corruption; split into readLineOutput
  (non-interactive) and readInteractiveOutput (PTY) with EOF flush
- Gate mouse clicks under full-screen overlays (help, detail, action menu)
- Fix setup wizard stuck state when executor rejects command
- Add bounds checks in setup.go to prevent panics
- Open palette on input bar mouse click (match :/ Ctrl+K behavior)
- Fix buildNotices cfg==nil suppressing first-time hint

* fix(tui): handle scanner.Err() in readLineOutput

Surface I/O errors (e.g. token-too-long) instead of silently dropping them.

* fix(guardrail): harden detection strategies, fix data races, and improve judge resilience

- Add RWMutex on allRuleCategories to prevent data race between
  ApplyRulePackOverrides (write at startup) and ScanAllRules (read on
  every request)
- Guard against ReDoS in user-supplied rule pack regexes with compile
  timeout and pattern length cap
- Fix completion-side NEEDS_REVIEW secrets being silently dropped when
  no judge is available — now falls back to MEDIUM/alert verdict
- Improve inspectJudgeFirst fallback documentation and ensure regex
  safety net always runs alongside judge results
- Switch postCallContext from context.Background() to
  context.WithoutCancel(parent) to preserve request-scoped tracing and
  correlation IDs while still detaching from request cancellation
- Apply pre-judge content strips in AdjudicateFindings, consistent with
  other judge code paths
- Add judgeSem rate limiting to inspectToolResult to bound concurrent
  LLM judge calls from tool-result inspection
- Fix broken indentation in proxy.go mid-stream scan block
- Tighten "token:" secret pattern from bare substring to regex requiring
  assignment syntax (token[:=] followed by 8+ chars) to reduce FPs
- Add "exfil" shorthand to triage exfil patterns
- Redact dotenv filesystem path in LLM judge init logging

* feat: production-readiness hardening — no placeholders

P0: HTTP rate limiting (100 req/s, burst 200), log rotation via
lumberjack, os.Exit only in main(), installer checksum verification.

P1: Real E2E tests replacing all t.Skip() stubs (scan rules, prompt
injection, block/allow/quarantine admission gate, audit persistence),
plugin registry Discover()/Register()/Get() with full tests, config
version migration (v0→v2), goreleaser homebrew tap enabled, NOTICE file.

P2: SSRF hardening tests (decimal/hex/IPv6/file/ftp), rate limit
middleware tests, header injection tests, /health/liveness endpoint,
malicious fixture updated with real detectable patterns.

Full test suite: 18/18 packages pass.

* fix: wire-up audit, fix 12 bugs, tighten AMD P2 regexes, remove dead code

Fixes found during deep review-and-ship audit:

Critical/High:
- watcher: takeActionFor now handles InstallPlugin/InstallMCP instead of
  falling through to watch.auto_block, honoring per-type take_action config
- guardrail: regex_only strategy no longer invokes the LLM judge (was adding
  unexpected latency/cost for operators choosing regex-only mode)
- config: EffectiveStrategy() default aligned with viper/defaults (regex_judge)
- configedit: add missing applyConfigField case for stream_buffer_bytes

Medium:
- tui: Tab/Shift+Tab now delegates to Policy panel before global panel switch
- tui: mouse wheel blocked behind open overlays (help, detail, action menu)
- tui: highlightRego guarded against strings.Index returning -1
- tui: Cisco AI Defense wizard fields now pre-filled from config
- tui: overview uses EffectiveStrategy() instead of hardcoded fallback

Security:
- policy: suppressions.yaml written with 0600 permissions (was 0644)

AMD P2:
- token regex tightened to require 20+ alphanumeric value (fixes FP on
  conversational "reply with this token: XYZ")
- bulk access triage pattern added for sensitive tools (users_list top N)

Wire-up:
- default_llm_api_key_env/default_llm_model added to TUI config editor
  and applyConfigField (were only usable via YAML/Python CLI)
- PolicyPanel.executor removed (dead field; commands returned to parent)
- WizardDone removed (dead function; WizardFinished is the active path)

All 18 Go packages pass with -race. go vet clean. Zero linter errors.

* feat: port multi-turn ContextTracker, scanner normalization, and per-scanner policy packs from PR #109

Consolidates PR #109 (feat/unified-rule-pack-arch) into this branch so a
single PR carries all rule-pack work. PR #109 is now obsolete.

Ported net-new features:

  * internal/gateway/context_tracker.go + _test.go
    - Per-session bounded buffer (10 turns / 200 sessions by default)
    - HasRepeatedInjection() raises HIGH alert when 3+ user turns hit
      local injection patterns within a session
    - Adapted HasRepeatedInjection signature to drop the *RulePack param;
      rule pack overrides already apply globally via
      ApplyRulePackOverrides(), so the simpler API is sufficient
    - Wired into EventRouter.handleSessionMessage (Record + multi-turn
      escalation path with telemetry emit)

  * internal/gateway/normalize.go + _test.go
    - NormalizedFinding with canonical ID, source, category, severity
    - Maps scanner-specific IDs (SEC-*, JUDGE-*, LP-*, CISCO-*) to
      stable canonical form for cross-scanner correlation

  * internal/scanner/codeguard.go + plugin.go
    - CodeGuardScanner now loads custom YAML rules from rules dir at
      construction; built-ins + custom rules concatenated per scan
    - PluginScanner gains Policy/Profile fields for per-scanner policy
      pack selection

  * policies/scanners/{codeguard,plugin-scanner,skill-scanner}/*.yaml
    - Per-scanner policy packs (default/strict/permissive/balanced tiers)

All 18 Go packages pass with -race -count=1. go vet clean. Zero lints on
edited files.

* fix: final review pass — heartbeat tests, scanner key fallback, sig cleanup

Close-out of the review-and-ship cycle on PR 111:

* Narrow heartbeat bypass tests — `isHeartbeatMessage` now verified to
  require the specific OpenClaw tokens (HEARTBEAT.MD / HEARTBEAT_OK)
  AND a <=512 byte payload; adding the word "heartbeat" alone or
  wrapping a large prompt in heartbeat tokens cannot bypass guardrails.
* Align Python skill-scan paths with `app.cfg.effective_inspect_llm()`
  so the shared `default_llm_api_key_env` fallback works the same way
  from the CLI as it does from the Go gateway.
* Update `test_guardrail_detection_strategy_defaults` to assert the new
  `regex_judge` default (matches Go + Python `_merge_guardrail`).
* Drop the unused `rp *RulePack` parameter from
  `ContextTracker.HasRepeatedInjection` — patterns are now sourced from
  the globally active rule pack via `ApplyRulePackOverrides`, so the
  per-call pack argument was dead code.

All tests pass locally: `go test -count=1 ./...` (18 packages),
`python -m unittest cli.tests.test_judge` (13/13).

* fix(ci): resolve lint, dep audit, and E2E sidecar health gaps

Go lint (staticcheck):
- Drop embedded-field selectors in provider_bifrost.go (QF1008).
- Replace WriteString(fmt.Sprintf(...)) with Fprintf in policy.go (QF1012).
- Remove dead readOpenAISSE helper and its now-unused imports.

Python dep audit:
- Override python-multipart>=0.0.26 to close CVE-2026-40347 (pulled in
  transitively by mcp and cisco-ai-skill-scanner).

E2E reliability:
- Replace fixed 5s sleep after gateway start with a 30s poll loop on
  'defenseclaw-gateway status' so slow self-hosted runners don't fail.
- On failure, dump the last 200 lines of gateway.log and watchdog.log
  and upload them as artifacts for post-mortem debugging.

* fix(lint): replace remaining WriteString(fmt.Sprintf(...)) with Fprintf

Three additional QF1012 staticcheck findings that only surfaced after the
first batch of fixes:

- internal/gateway/llm_judge.go: triage-signal formatter
- internal/tui/policy.go: two rule-browser helpers

* fix: seed guardrail rule packs, emit canonical finding IDs, drop broad token FP

- cmd_init now seeds bundled guardrail profiles (default/strict/permissive)
  into policy_dir so operators can edit YAML and `policy reload` picks it up
- paths.py gains bundled_guardrail_profiles_dir() resolver
- proxy + api guardrail audit events include canonical=<ids> for
  cross-scanner correlation (wires NormalizeScanVerdict into telemetry)
- legacy policies/default.yaml and policies/strict.yaml drop bare 'token:'
  pattern — gateway secretPatternRegexes already covers tokens with
  20+ char entropy requirement (fixes false positives like "reply with
  this token: XYZ")
- adds unit coverage: TestHandleGuardrailEventEmitsCanonicalIDs,
  TestSeedGuardrailProfiles (seed/preserve/noop paths)

* test(gateway): switch live E2E from Anthropic-direct to Bedrock via Bifrost

The Anthropic-direct account backing TestBifrostE2E_LiveAnthropic* is out of
credits, causing Full Live E2E to fail on every run. Switch both tests to
Bedrock via Bifrost (ABSK bearer key) against
claude-haiku-4-5-20251001-v1:0, gated on BIFROST_API_KEY so they still
skip gracefully when the secret is absent.

- Rename TestBifrostE2E_LiveAnthropic{,Stream} -> TestBifrostE2E_LiveBedrock{,Stream}
- Swap ANTHROPIC_API_KEY -> BIFROST_API_KEY (ABSK auto-detected as Bedrock)
- Use model bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0
- Wire BIFROST_API_KEY into the core and full-live job env blocks

* test(e2e): bump sidecar /health wait from 60s to 180s on self-hosted runners

The Core/Full-Live E2E workflows on the ARM64 self-hosted runner flake on a
60-second wait for SIDECAR_URL/health after defenseclaw-gateway start. The
gateway log shows the WebSocket handshake completing after the 60s window
expires — the sidecar is healthy, just slower to boot under runner load.

Extend both blocking /health waits (Phase 1 startup, Phase 7C recovery) to
180s and dump the tail of gateway.log plus defenseclaw-gateway status on
timeout so any future regression is self-diagnosing in-line.

* test(e2e): self-heal sidecar bring-up in Phase 1 with 3x retry

The previous 180s single-shot /health wait still failed on the ARM64
self-hosted runner because the sidecar daemon can exit during early
init before /health is ever served (observed on main too, not just this
branch — April 15 & 16 scheduled runs on main failed the same way).

Gateway.log dumps show the init-era sidecar is already dead by the time
Phase 1's stop reaches it ("Gateway sidecar is not running" before our
stop call) and the newly-spawned sidecar also exits within 5 seconds of
start. The log contains two overlapping startup sequences, suggesting a
brief lifecycle race.

Rather than keep extending the timeout, wrap the stop→start→health-wait
block in a 3-attempt loop with a 60s wait per attempt (~same wall clock
budget as before: 180s). Each defenseclaw-gateway start internally calls
killStaleProcesses via pgrep, so the retry naturally reaps any stragglers
that caused the previous attempt to fail.

On final failure, also dump watchdog.log, the full defenseclaw/openclaw
process tree, and listeners on 18789/18970 so the next flake is
self-diagnosing without needing an artifact download.

* e2e: add OOM/dmesg diagnostics + per-process memory trace on sidecar failure

Previous retry loop proved the sidecar is being killed externally (reaches
"event loop running" then vanishes within ~60s with no panic, no shutdown
message, watchdog survives). This is the signature of SIGKILL from outside,
almost certainly OOM killer on the shared self-hosted ARM64 runner.

We can't fix the runner from the script. But we can capture definitive
evidence so the root cause is not ambiguous on the next failure:

- free -m before each of the 3 bring-up attempts
- background sampler logs sidecar PID + VmRSS + VmSize every 3s while
  we poll /health; when the process vanishes, the trace timestamps the
  death and the last-known memory usage
- ps at failure now includes rss/vsz columns
- dmesg -T | grep -iE 'out of memory|killed process|oom|defenseclaw-gat'
- journalctl -k fallback (some distros gate dmesg behind CAP_SYSLOG)
- system-wide free -h at failure moment

On the next red run, either we'll see the OOM smoking gun in dmesg (then
the fix is runner memory / workload isolation, not CI patches), or the
memory trace will show steady RSS right up to death (then we'll know it
was an external pkill / signal, not OOM).

Refs PR #111. Bedrock migration itself is green; this is instrumentation
to unblock the pre-existing runner infra flake that also reproduces on
main.

* sidecar(diag): instrument signal handling + heartbeat to pinpoint silent exits

The E2E sidecar flake on the self-hosted ARM64 runner shows the sidecar
reaching "event loop running", writing audit DB entries, then vanishing
within ~3–5 seconds. No panic, no shutdown message, no OOM trace in
dmesg/journalctl, and the watchdog sibling (same binary) survives. This
is consistent with an external termination (SIGKILL) or a signal we're
not currently catching.

This commit adds scoped diagnostic instrumentation to runSidecar:

1. Widen signal.Notify to capture SIGHUP, SIGQUIT, SIGPIPE, SIGUSR1,
   SIGUSR2 in addition to SIGINT/SIGTERM. Each signal is logged with
   its name, number, PID, and RFC3339Nano timestamp before any action
   is taken. SIGPIPE is logged but NOT treated as a shutdown trigger —
   this also suppresses Go runtime's default "exit on SIGPIPE to stderr"
   behaviour that could silently terminate us if the log file descriptor
   transiently misbehaves.

2. 5-second heartbeat goroutine that prints
   "[sidecar][diag][heartbeat] alive at HH:MM:SS.mmm pid=N uptime=Ns"
   so the post-mortem CI log can narrow the kill window to <5s.

3. Defer + explicit log line around sc.Run(ctx) so we capture the
   exact return value, ctx.Err(), and PID at the moment runSidecar
   unwinds. If the process dies BEFORE these lines print, the kill
   is truly silent (SIGKILL or equivalent).

Interpretation guide for next E2E run:
- If "[sidecar][diag] received signal" appears → we know which signal
  and who probably sent it.
- If heartbeats stop mid-stream and NO signal line appears → SIGKILL,
  external source (runner OOM, supervisor, or manual pkill).
- If "sc.Run returned" appears → ctx was cancelled internally and we
  can inspect ctxErr to find the cancellation source.

No production behaviour change; only added log lines. Keeps PR #111
scope tight to diagnostic observability for a pre-existing sidecar
lifecycle bug that also reproduces on main.

* ci(e2e): switch full-live LLM from Anthropic to OpenAI (gpt-4o-mini)

PR #111's Full Live E2E has been failing on:
  "LLM request rejected: Your credit balance is too low to access the
   Anthropic API. Please go to Plans & Billing to upgrade or purchase
   credits."

This is not a regression in PR #111; the shared Anthropic test account
has no balance. OPENAI_API_KEY is already wired into the full-live job
env (line 351) and reportedly has credits, so migrate CI to OpenAI:

1. openclaw.json patch step now writes auth.profiles["openai:default"]
   (provider=openai) and agents.defaults.model.primary = "openai/gpt-4o-mini"
   instead of the anthropic:default / claude-sonnet-4-5 pair.
2. auth-profiles.json keyRef.id switches from ANTHROPIC_API_KEY to
   OPENAI_API_KEY; profile order map now keys on "openai".
3. GUARDRAIL_REQUEST_MODEL is set to openai/gpt-4o-mini in the patch
   step (the subsequent Init step re-derives it from OC_MODEL, which is
   consistent since the primary model is now the OpenAI one).
4. Downstream provider detection (grep "openai\|gpt\|o1\|o3\|o4") at
   line 731 already maps to OPENAI_API_KEY, so API_KEY_ENV resolution
   for the guardrail config (cfg.guardrail.api_key_env) works without
   further changes.
5. "Restore OpenClaw Anthropic model" step renamed to
   "Restore OpenClaw model and auth backups" (behaviour is generic —
   restores whatever the pre-run backup held — so the old name was
   actively misleading).

ANTHROPIC_API_KEY remains plumbed through the env and dotenv files as
defensive pass-through in case any other component consults it; it is
no longer the driver of agent LLM traffic.

Why gpt-4o-mini: cheapest current OpenAI model that supports tool
calling end-to-end (required by block/allow enforcement tests where the
agent must actually attempt tool use); the earlier Anthropic choice was
sonnet-4-5 primarily for consistency with dev, not because the tests
need a premium model.

Guardrail round-trip now takes the native OpenAI chat-completions shape
through the proxy's /v1/chat/completions handler and
resolveConfiguredProvider → Bifrost OpenAI provider path, which is the
simplest routing in the codebase and avoids any Bedrock/SigV4 or
Anthropic->Bedrock translation work.

Core E2E is unaffected (that job doesn't exercise the live LLM path).

* Revert "ci(e2e): switch full-live LLM from Anthropic to OpenAI (gpt-4o-mini)"

This reverts commit 3b7153ce684e6a5437dcd277ad9dcdc4f93674fe.

* ci(e2e): switch full-live LLM to OpenClaw-native amazon-bedrock provider

Previously the full-live E2E job hard-coded OpenClaw to call the Anthropic
API directly (anthropic/claude-sonnet-4-5 + ANTHROPIC_API_KEY), which is
exactly the path that's currently failing because the Anthropic account is
out of credits. That's also unnecessary: OpenClaw supports AWS Bedrock
natively via its stock amazon-bedrock provider
(https://docs.openclaw.ai/providers/bedrock), and our BIFROST_API_KEY
secret is already an AWS Bedrock bearer token (ABSK…) — the exact format
AWS_BEARER_TOKEN_BEDROCK wants. Reusing the key OC-side means we drop the
Anthropic dependency entirely with no new secrets.

Workflow changes (.github/workflows/e2e.yml, full-live only):
  - Add AWS_BEARER_TOKEN_BEDROCK: \${{ secrets.BIFROST_API_KEY }} and
    AWS_REGION: us-east-1 to the job env so OC's AWS SDK default chain
    can authenticate to Bedrock.
  - Patch openclaw.json to register models.providers[\"amazon-bedrock\"]
    with api=bedrock-converse-stream, auth=aws-sdk, and a single model
    entry for us.anthropic.claude-haiku-4-5-20251001-v1:0 (cheapest
    current Claude on Bedrock with tool-calling, matches the model our
    in-process Bifrost e2e test already covers).
  - Point agents.defaults.model.primary at
    amazon-bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0 and
    rewrite auth-profiles.json to use mode=aws_sdk (no keyRef).
  - Propagate BIFROST_API_KEY + AWS_BEARER_TOKEN_BEDROCK + AWS_REGION
    into both ~/.defenseclaw/.env (guardrail sidecar) and the OpenClaw
    systemd user-service drop-in environment file.
  - In the guardrail-detection block, match Bedrock models first (order
    matters because a Bedrock inference profile id contains \"claude\")
    and set API_KEY_ENV=BIFROST_API_KEY so the guardrail proxy can talk
    to Bedrock via the embedded Bifrost SDK. Drop the stale
    \"SigV4 not supported\" comment — Bifrost consumes the ABSK bearer
    token directly, no SigV4 signing needed.

Go changes (required so the guardrail sidecar actually understands the
\"amazon-bedrock/\" prefix OpenClaw writes into openclaw.json):
  - internal/gateway/provider.go: add \"amazon-bedrock\" to
    knownProviders so splitModel() correctly splits
    \"amazon-bedrock/us.anthropic…\" into (amazon-bedrock, us.anthropic…).
  - internal/gateway/provider_bifrost.go: add \"amazon-bedrock\" to
    mapProviderKey() as an alias of \"bedrock\" -> schemas.Bedrock so the
    Bifrost SDK routes it correctly.
  - internal/gateway/provider_bifrost_test.go: new
    amazon_bedrock_openclaw_prefix table case in
    TestBifrostProvider_Creation and \"amazon-bedrock\" added to
    TestMapProviderKey_AllKnownProviders.

All gateway + config tests pass locally, including the live Bedrock
round-trip tests (TestBifrostProvider_LiveBedrock,
TestBifrostProvider_LiveBedrockStream).

* ci/doctor: unblock full-live on amazon-bedrock (fix cascade from bad auth profile)

The previous full-live run hit a single root cause that cascaded into ~8
"FAIL" lines:

  auth.profiles.amazon-bedrock:default.mode: Invalid input
  (allowed: "api_key", "oauth", "token")

OpenClaw's config schema only allows those three values for an auth-profile
mode; our Python patch step wrote `mode: "aws_sdk"`, which OC rejected at
startup, so the gateway never came up and every downstream check (doctor,
block/allow, skill-api disable, etc.) failed with "gateway: not connected".
Per https://docs.openclaw.ai/providers/bedrock, Bedrock auth is driven by
the provider's own `auth: "aws-sdk"` setting, which delegates to the AWS
SDK default credential chain (AWS_BEARER_TOKEN_BEDROCK is already exported
from the BIFROST_API_KEY secret) — no auth-profile entry is needed.

This change:

  * .github/workflows/e2e.yml
    - Stop writing an `auth.profiles.amazon-bedrock:default` entry into
      openclaw.json; scrub any stale entry for good measure.
    - Write auth-profiles.json as an empty profile store so a prior run's
      ANTHROPIC_API_KEY-based profile can't bleed through.
    - Remove ANTHROPIC_API_KEY from the full-live job env entirely. The
      guardrail passthrough / duplicate-header / X-AI-Auth tests in
      scripts/test-e2e-full-stack.sh all skip cleanly with "ANTHROPIC_API_KEY
      not set", which is the correct behavior for a Bedrock-only live run
      (previously these tests called api.anthropic.com directly with a
      depleted key and reported "credit balance too low" as test failures).

  * cli/defenseclaw/commands/cmd_doctor.py
    - Route the "LLM API key" check by *provider prefix* (segment before the
      first "/"), not by substring. The old `"anthropic" in model` check
      wrongly matched Bedrock inference profile ids like
      `amazon-bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0` and sent
      our ABSK bearer token to api.anthropic.com, producing a spurious 401
      FAIL even when the actual Bedrock path was fine.

  * cli/tests/test_cmd_doctor.py
    - Lock the new behavior in with three regression tests: the bedrock
      inference profile case (must NOT call _verify_anthropic), plus the
      `anthropic/…` and `openai/…` happy paths.

* review: address H1-H6 + M1-M10 findings from PR #111 review

High-severity hardening:
- H1/M10: cache policy.Engine per-sidecar via sync.Once; log init
  failure exactly once instead of per-request, preventing repeated
  Rego recompilation and log floods.
- H2: gate raw judge-response logging behind DEFENSECLAW_JUDGE_TRACE=1
  and add redactEntity() for PII-safe logging of detected entities.
- H3: replace process-wide atomic.Bool judgeActive with a context-scoped
  withJudgeActive/isJudgeActive guard; recursive judge invocations are
  now blocked per-request without globally serialising concurrent
  guardrail traffic.
- H4: harden injection/PII/tool judge prompts with <<<SAMPLE>>> delimiters
  and explicit anti-injection instructions; flip parsing to fail-closed
  (errorVerdict instead of allowVerdict) when judge output is malformed.
- H5: narrow IsPlatformID to fail-OPEN for valid NANP phone numbers so
  real US/CA phones are no longer suppressed by default.
- H6: gate verbose sidecar diagnostic logging behind
  DEFENSECLAW_SIDECAR_DIAG=1; SIGPIPE handling stays always-on.

Medium-severity hardening:
- M1: UTF-8-safe extractEvidence/extractEvidenceAt — clamp slice
  boundaries to rune starts so evidence strings written to logs and
  audit records are always valid UTF-8.
- M2: RulePack.Validate() now compiles every regex at load time and
  warns on invalid patterns instead of silently skipping them per
  request.
- M3: bound regexCache via container/list LRU (1024 entries) and cache
  negative results so invalid patterns aren't recompiled hot-path.
- M4: derive Bifrost Key.ID via SHA-256 hash of the API key (helper
  bifrostKeyID) instead of embedding the raw key in upstream structures
  that may reach logs.
- M5: add TTL-based session eviction (default 30m) to ContextTracker
  and refactor pruneOldestLocked from O(n^2) to O(n log n).
- M6: replace hardcoded claude-sonnet-4-20250514 probe model in
  defenseclaw doctor with _anthropic_probe_model() — prefers the
  configured anthropic/<model>, then DEFENSECLAW_ANTHROPIC_PROBE_MODEL,
  then claude-3-5-haiku-latest.
- M7: route doctor LLM API key verification by the *model provider
  prefix* first; env-name prefix (ANTHROPIC_API_KEY etc.) is only a
  last-resort fallback. Prevents Bedrock tokens stored in
  ANTHROPIC_API_KEY from being shipped to the Anthropic API.
- M8: deprecate the --token sidecar flag (still accepted, prints a
  warning, hidden from help) in favour of OPENCLAW_GATEWAY_TOKEN.
- M9: access Bifrost ToolCalls symmetrically via
  bm.ChatAssistantMessage.ToolCalls to guard against upstream schema
  drift.

Tests:
- New: TestRedactEntity (incl. UTF-8 multibyte coverage) and
  TestJudgeLogTraceFlag in llm_judge_logging_test.go.
- New: TestContextTracker_EvictsStaleSessions covering TTL eviction.
- New: doctor routing tests — env-name fallback, model-prefix wins,
  AnthropicProbeModelTests covering all three probe-model branches.
- Updated: TestPIIToVerdict/telegram_id_suppressed now uses a 9-digit
  non-NANP id so it still exercises platform-ID suppression after H5.
- Updated: TestRunToolJudgeIgnoresPromptJudgeReentrancyFlag wired
  through the new context-scoped withJudgeActive helper.

No on-the-wire schema changes; verdict structure and OPA input are
unchanged. Splunk/OTel forwarding and CLI surface are unchanged except
for the deprecated --token flag warning.

* feat(observability): decouple OTel + introduce generic audit_sinks (Phase 0)

Phase 0 of the stacked observability refactor on top of PR #111
(feat/wire-rulepack-runtime). Replaces the single-Splunk audit
forwarder with a declarative, multi-destination audit_sinks list
and removes the Splunk-specific coupling from the OTel provider.

BREAKING: the legacy `splunk:` config block is rejected on startup
with a hard error pointing operators at docs/OBSERVABILITY.md. This
is intentional so nobody silently loses forwarding after upgrading.

What changed:

- internal/audit/sinks/: new package defining Sink interface, Manager
  for fan-out, and per-kind implementations for splunk_hec, otlp_logs,
  and http_jsonl. Each sink owns its own batching/timeouts and is
  independent — one failing sink never blocks the hot path.
- internal/config/sinks.go: new AuditSink schema with per-kind
  configs (SplunkHECSinkConfig, OTLPLogsSinkConfig, HTTPJSONLSinkConfig),
  common batch/timeout/filter fields, and eager Validate() per sink.
- internal/config/config.go: CurrentConfigVersion -> 4. viper.Reset()
  at the start of Load() so tests don't leak state. detectLegacySplunk()
  refuses to start if legacy keys are present.
- internal/audit/logger.go: SetSinks(*sinks.Manager) replaces
  SetSplunkForwarder. forwardToSinks() fans every event out via the
  Manager with a bounded 2s context so sinks can't stall decisions.
- internal/audit/splunk.go + splunk_test.go: deleted — behaviour is
  now owned by internal/audit/sinks/splunk_hec.go.
- internal/audit/export.go: ExportSplunk removed (replay command now
  drives the generic sink pipeline).
- internal/audit/network_egress.go: routes egress alerts through
  forwardToSinks.
- internal/cli/root.go + internal/cli/audit_sinks.go: new init path
  (initAuditSinks -> buildAuditSinks) that translates config.AuditSink
  declarations into concrete sinks.Sink instances and installs them
  on the audit logger at startup.
- internal/gateway/health.go + sidecar.go: Splunk subsystem renamed
  to Sinks; aggregates health + names + kinds across every configured
  sink. /health and defenseclaw-gateway status both show the new shape.
- internal/cli/sidecar.go: prints the generic "Sinks" line instead of
  a Splunk-only banner.
- internal/telemetry/provider.go: expandHeaders is now vendor-neutral
  — no more X-SF-Token auto-injection from SPLUNK_ACCESS_TOKEN. The
  telemetry stack is a plain OTLP client; use otel.headers (or
  OTEL_EXPORTER_OTLP_HEADERS) to send any vendor-specific auth header.
- internal/tui/app.go + overview.go: HealthSnapshot.Splunk -> Sinks.
- internal/tui/configedit.go + setup.go: removed single-key splunk.*
  edits (the new schema is list-based); read-only summary of the
  configured audit_sinks list is shown with a pointer to the
  dedicated editor landing in Phase 3.3.
- docs/OBSERVABILITY.md: new operator guide — concepts, migration
  from v3 splunk: block, full sink reference, OTel examples, event
  shape, health reporting.

Tests are green across the whole tree. Redaction scrubbing at the
sink layer will land in a separate PR so this one stays scoped to
the observability refactor.

* feat(observability): structured gateway events (Phase 1)

Introduce internal/gatewaylog for JSONL verdict/judge/lifecycle
emissions with lumberjack rotation and a stderr pretty-printer.

- New writer wired into sidecar boot/teardown, writing to
  $DATA_DIR/gateway.jsonl alongside a human-readable mirror on
  stderr. Existing defaultLogWriter diagnostics stay intact.
- Central verdict event at GuardrailInspector.Inspect covers every
  strategy (regex, regex+judge, judge-first) so no caller has to
  plumb the writer through each path.
- Judge invocations (injection + PII) now emit a structured Judge
  event with latency, parse state, action, and severity. Raw
  bodies stay gated behind DEFENSECLAW_JUDGE_TRACE so PII-heavy
  payloads don't leak into the JSONL stream by default.
- Lifecycle events for sidecar init/stop give operators a
  timeline anchor in the JSONL feed.

Tests: writer round-trip / pretty / fanout / emit-after-close
coverage plus inspector-level verdict emission assertions.

Remainder of Phase 1.3 (migrating every defaultLogWriter site)
and Phase 2/3 (OTel mapping, metrics, TUI tab) continue in
follow-up commits.

* feat(observability): OTel pipeline, TUI verdicts, JSONL coverage (Phase 2-4)

Completes the structured observability stack on top of the Phase 0/1
sink + gatewaylog foundations:

Phase 2 — OTel pipeline
 - Map gatewaylog.Event to OTel LogRecords with typed attributes
   per event (verdict/judge/lifecycle/error/diagnostic) and fan
   out from the JSONL writer directly to the OTLP logs exporter.
 - Add guardrail pipeline span via SetTracerFunc / StartGuardrailStageSpan;
   proxy injects the tracer closure so the inspector stays decoupled
   from the telemetry package.
 - Record guardrail metrics driven by gatewaylog events:
   defenseclaw.gateway.verdicts, judge.invocations, judge.latency,
   judge.errors, gateway.errors, audit.sink_send_failures.
 - Add guardrail.retain_judge_bodies config flag + atomic to opt in
   to raw judge response retention (default off; DEFENSECLAW_JUDGE_TRACE
   still required for full-fidelity capture).

Phase 3 — TUI
 - New Verdicts source in the logs panel tailing gateway.jsonl with
   block/alert/allow action filter chips ('a' to cycle).
 - Enter on a verdict row opens the detail modal with full event
   (timestamp, severity, action, stage, direction, model, reason,
   raw JSON).
 - Setup panel surfaces OTel knobs (TLS, per-signal endpoints,
   redacted headers) and an audit_sinks summary with an edit hint;
   configedit wires the new OTel keys.

Phase 4 — polish & migration
 - Coverage test asserts every file calling audit.Logger.LogAction
   in internal/gateway also emits at least one structured
   emit*() sibling; add strategic emits in router.go/proxy.go/api.go
   to cover the migration.
 - scripts/assert-gateway-jsonl.py validates JSONL schema for any
   captured file; wired into both e2e workflow jobs and the
   full-stack e2e dump-on-failure tails gateway.jsonl alongside
   gateway.log.
 - test-e2e-cli.py picks up a jsonl_event_contains helper so new
   e2e tests can assert on the structured stream.
 - install/upgrade/sandbox help text points at both gateway.log
   (pretty) and gateway.jsonl (structured).

BREAKING: gateway now emits two files — gateway.log (pretty) and
gateway.jsonl (structured). Operators consuming the text log for
verdict parsing must switch to the JSONL stream; schema is stable
per internal/gatewaylog/events.go and documented in
docs/OBSERVABILITY.md.

* tests(observability): fill coverage gaps + Phase 2.3 SQLite judge retention

Addressed the review challenge on Phase 2-4 completeness.

Fills the missing test coverage identified by the self-audit:
- internal/audit/sinks/*: Manager fan-out, Splunk HEC envelope/auth,
  HTTP JSONL TLS/bearer/env-expansion, OTLP logs severity mapping
- internal/cli/audit_sinks.go: sink builder, error aggregation,
  env-token resolution
- internal/telemetry/gateway_events.go: OTel log-record attributes,
  metric updates for all event types, nil-payload safety
- internal/telemetry/runtime.go: StartGuardrailStageSpan /
  EndGuardrailStageSpan attributes, reason truncation, allow→Ok vs
  block→Error status mapping, nil-provider safety
- internal/gateway/llm_judge.go: judgeRawForEmit / SetRetainJudgeBodies
  env-var + config-flag gating, long-body truncation
- internal/tui/logs.go: parseVerdictRow, loadVerdicts filter gating,
  cycleVerdictAction rotation, SelectedVerdict, renderVerdictLine
- internal/tui/setup.go: fmtOTelHeaders redaction + sort,
  auditSinkSummaryFields per-kind rendering + edit hint

Completes Phase 2.3 (SQLite judge-body persistence) — previously only
the sinks half landed:
- audit.Store migration 3: judge_responses table + indexes
- Store.InsertJudgeResponse / ListJudgeResponses with UUID + RFC3339Nano
- gateway events pipeline gains SetJudgePersistor hook; emitJudge runs
  the persistor BEFORE emitEvent's redaction pass so the operator-
  owned SQLite receives the un-redacted body while fanout sinks still
  get the scrubbed form
- sidecar wires the persistor iff guardrail.retain_judge_bodies is
  true and tears it down on shutdown

Expands coverage_test.go scope to internal/audit + internal/telemetry:
- TestLogActionFreeInAuditAndTelemetry pins those packages as
  LogAction-free so the sink/pipeline substrate can never grow a
  circular routing back into itself
- Factored out scanLogActionCoverage for reuse

All tests pass (full go test ./..., go vet clean).

* docs(observability): add DEFENSECLAW_REVEAL_PII production warning + drop goto

OBSERVABILITY.md now spells out why DEFENSECLAW_REVEAL_PII=1 must never
run in production: any shared transport (journald, tmux, CI logs,
support bundles) that captures stderr becomes an exfiltration channel
for the literal secrets/PII the gateway prints when the flag is set.
The flag is documented as a developer-workstation / incident-triage
tool only.

Also replaces the single `goto done` in redaction.findKVBoundaries
with a labelled `break keyLoop` — same control flow, but keeps the
file goto-free now that it has grown into the primary PII seam.

* fix(observability): review pass — panic safety, bounded backlogs, UTF-8 safety

Addresses the H1–H6, M1/M2/M4, and L1 findings from the post-merge
review of the observability stack.

High:
- Thread gatewaylog.Direction through the judge persistor so SQLite
  rows no longer drop the inbound/outbound tag.
- Wrap fanout callbacks in gatewaylog.Writer.Emit and per-sink
  Forward calls in sinks.Manager with recover(); a panicking
  exporter can no longer unwind into the guardrail hot path.
- Coalesce immediate flushes (guardrail-verdict bursts) behind an
  atomic.Bool single-flight so high-frequency verdict traffic cannot
  explode goroutines.
- Cap the in-memory retry backlog for http_jsonl and splunk_hec at
  100×BatchSize (floor 10k) so a persistently offline endpoint cannot
  OOM the sidecar; oldest events drop with an operator warning.
- Truncate judge raw_response at MaxJudgeRawBytes (64KiB) with UTF-8
  rewind and a [truncated N bytes] marker to bound audit DB growth.

Medium:
- TUI verdict filter now applies to both verdict and judge rows and
  hides actionless events when a filter is active (consistent UX).
- Rewrite truncateVerdictReason to be rune-aware so multi-byte
  strings are never sliced mid-codepoint.
- Cap the OTel defenseclaw.verdict.reason attribute at 200 bytes to
  bound cardinality on backends that index attribute values; the
  full reason still ships in the log body.

Low:
- Emit a one-shot stderr warning when http_jsonl or splunk_hec is
  configured with verify_tls=false against an https:// endpoint, so
  silent TLS downgrades never slip through review.

Regression tests added for every fix. Full go test ./... and
go vet ./... are green.

* fix(ci): migrate E2E workflow from legacy splunk: to audit_sinks:

The observability refactor (this PR) makes config.Load() refuse to
start when a legacy `splunk:` block is present — that's the whole
point of the v3 → v4 migration check in internal/config/config.go.
The E2E workflow was still writing the old shape, so the gateway
daemon exited immediately during "Init DefenseClaw" with:

  Error: start daemon: daemon: process exited immediately
  (check /home/ubuntu/.defenseclaw/gateway.log for errors)

and the two downstream E2E jobs + the required-checks gate all
failed together.

Rewrites both Python-yaml patches (Core E2E and Full Live E2E) to
emit a single audit_sinks entry pointing at the same local Splunk
container the "Start Splunk" step brings up. The token still flows
via DEFENSECLAW_SPLUNK_HEC_TOKEN, so no secret/env changes.

Also extends the on-failure log artifact to include ~/.defenseclaw/
*.jsonl (gateway.jsonl is the new structured sibling of gateway.log)
so the next triage run has the schema-validated trail available in
the uploaded artifact — the ci-watcher pass flagged that only *.log
was being captured.

* fix(config): stop writing legacy splunk: from Python, load .env before config.Load

The first CI retry after migrating the e2e.yml patches to audit_sinks
still red-x'd with the same "daemon: process exited immediately"
error. Root cause, per ci-watcher triage of run 24544271547:

1. defenseclaw init (Python) unconditionally serializes the
   SplunkConfig dataclass — including default hec_endpoint /
   hec_token_env strings — into ~/.defenseclaw/config.yaml. The Go
   gateway's v3→v4 migration check (config.detectLegacySplunk) treats
   any populated splunk.* key as a hard error and refuses to start.
   So defenseclaw init calls sidecar start, the sidecar immediately
   fails config.Load(), and we exit before the workflow's post-init
   Python yaml patch ever runs.

2. Even if init succeeded, SplunkHECSinkConfig.Validate() resolves
   token_env via os.Getenv at config-load time, but loadDotEnvIntoOS
   currently runs *after* config.Load(). In CI the HEC token lives
   only in ~/.defenseclaw/.env, so validation would fail with a
   misleading "token is empty" error during the next restart.

Fixes:

- cli/defenseclaw/config.py: _config_to_dict now drops the `splunk`
  key entirely. v4 routes Splunk forwarding through audit_sinks; the
  in-memory SplunkConfig dataclass stays for backward-compatible
  *reads* of existing config.yaml files, but we never write it again.
  setup splunk --logs becomes a no-op until it's ported to emit
  audit_sinks entries (tracked as a follow-up; out of scope here).

- internal/cli/root.go: loadDotEnvIntoOS(config.DefaultDataPath()/.env)
  now runs *before* config.Load() so token_env references in
  audit_sinks resolve against secrets written by defenseclaw setup
  / defenseclaw init. Added a second deferred load keyed on cfg.DataDir
  so DEFENSECLAW_HOME overrides still pick up .env contents.

Covered by existing internal/config + internal/cli Go test suites
(all green) and the full Python cli test suite (987/987 passing).

* fix(config): python CLI reads audit_sinks[*].splunk_hec as SplunkConfig fallback

Phase 0 removed the legacy \`splunk:\` yaml block and moved Splunk
forwarding under \`audit_sinks:\`. The Go gateway consumes the new
shape, but the Python CLI keeps its own in-process Splunk forwarder
for events it raises locally — \`defenseclaw aibom scan\`,
\`defenseclaw skill quarantine/restore/block/allow\`,
\`defenseclaw mcp block/allow\`, \`defenseclaw plugin *\`, etc.

That Python forwarder still reads \`cfg.splunk.*\`. With the v4
config.yaml containing only \`audit_sinks\`, \`SplunkConfig\` loaded
defaults (\`enabled=False\`), so the Python-side forwarder
short-circuited and all of those events disappeared from Splunk even
though SQLite + the Go sink pipeline were fine. That’s what the CI
run 24544639016 showed: skill-scanner and codeguard scans (logged by
the Go gateway) landed in Splunk, but AIBOM, quarantine/restore,
block/allow, and every plugin action (logged by Python) did not.

Teaches \`config.load()\` to hydrate \`cfg.splunk\` in memory from
the first enabled \`audit_sinks[*]\` entry whose \`kind\` is
\`splunk_hec\`. This is:

- IN MEMORY ONLY. \`_config_to_dict\` still strips the \`splunk\`
  key on save so we never reintroduce the \`detectLegacySplunk\`
  tripwire in the Go gateway.
- STRICTLY FALLBACK. If the user explicitly wrote a legacy
  \`splunk:\` block (for older installs), we keep their values
  untouched.
- SAFE FOR INPUTS. Any non-dict / missing-endpoint / disabled sink
  is skipped without raising.

Manually verified by loading a pure-audit_sinks config.yaml and
confirming \`cfg.splunk.enabled == True\`, endpoint/index/sourcetype
mirror the sink, and \`resolved_hec_token()\` pulls the env token.
All 987 Python tests pass.

* feat(tui): interactive Audit Sinks editor (P0-#1)

Adds an interactive sub-mode to the Setup panel that lists configured
audit sinks and shells out to `defenseclaw setup observability
list|enable|disable|remove|test|migrate-splunk` for every mutation.
The Python CLI remains the single source of truth — the TUI never
edits config.yaml directly — so the gateway's atomic-write invariants
and audit logging stay intact regardless of which front-end the
operator uses.

Entry point: press E while the Config Editor is focused on the Audit
Sinks section. Bindings: j/k nav · e enable · d disable · r remove
(with [y/N] confirm) · t test · a hand off to Observability wizard ·
m migrate legacy splunk: block · Ctrl+R refresh · Esc close.

Also registers `setup observability list|migrate-splunk` palette
entries so the migration is reachable without entering the editor
(P3-#18).

Coverage: 27 tests (unit + SetupPanel integration) stubbing the
list lister to avoid requiring an installed CLI at test time.

* feat(tui): Plugins panel action menu — PluginActions (P0-#2)

Adds context-aware `o`-menu to the Plugins panel matching the
Skills / MCPs parity pattern. Every verb in the menu dispatches
through `defenseclaw plugin <verb> <name>` so PolicyEngine,
admission audit, and the gateway RPC for runtime enable/disable
all stay in one place. No plugin state is forked in Go.

Action visibility is driven off verdict + enabled + status:
  - scan / info always available
  - block / unblock / allow driven off verdict
  - disable / enable driven off runtime state
  - quarantine / restore driven off status substring
  - remove always exposed last (destructive, but discoverable)

Tests cover:
  - PluginActions visibility across 4 verdicts × 2 statuses × 2
    enabled states (24 matrix combos), including no-duplicate-key
    invariant
  - `o` opens the menu with the plugin's name (falling back to ID
    when the manifest omits it) and populates info rows
  - every key PluginActions can emit maps to a non-nil CLI
    invocation via executeActionMenuItem (prevents silent no-ops
    when new verbs are added to the menu without dispatch wiring)
  - nil-selection safety on both open and dispatch paths

* tui(parity P0-#3): add Tools panel + ToolActions

Wires a new Tools panel into the unified TUI so operators can view and
mutate tool block/allow policy without dropping to a shell. All
mutations route through `defenseclaw tool {block,allow,unblock,status}`
so the admission gate, scoped-policy resolution (e.g.
`write_file@filesystem`), and audit emission stay in one authoritative
code path — CLI remains the single source of truth.

Panel is registered at index PanelTools, inserted immediately before
PanelSetup so the existing 1–9/0 numeric keybindings all stay stable;
Tools is reached via the new uppercase 'T' shortcut, the command
palette, or tab navigation. Action menu surfaces Info/Block/Allow/
Unblock keys contextually by current status and deliberately omits
Scan/Enable/Disable/Quarantine (those verbs belong to Skills/MCPs/
Plugins, not Tools) — guarded by TestToolActions_NoScanOrEnable.

Scoped targets preserve the `@scope` suffix through the dispatcher so
operators never accidentally edit the global row when they selected a
scoped one.

Tests cover: ToolActions branches by status, global-scope placeholder
rendering, action-menu dispatch for every key, nil-selection safety,
cursor clamping, BlockedCount, 'T' global shortcut routing, and a
panel-ordering regression guard so future refactors can't silently
shift numeric keybindings.

* feat(tui): route Skills panel mutations through CLI (P0-#4)

Before this change, pressing 'b' in the Skills panel called
SkillsPanel.ToggleBlock() which flipped state directly in the audit
store. That bypassed the admission gate, the gateway RPC
notification, and the formal audit event — so a block from the TUI
looked different in the log than a block from the shell, and could
drift out of policy sync.

Now every mutation (block/allow/unblock/disable/enable/quarantine/
restore/install/scan) dispatches `defenseclaw skill <verb> <name>`
through CommandExecutor. The Python CLI is the single source of
truth. Adds install/enable/restore to the action menu so the TUI
covers the full CLI surface.

SkillActions() now branches by status (blocked/allowed/quarantined/
disabled/default) to match _skill_status_display() in cmd_skill.py,
and skills.Refresh() recognises quarantined + disabled rows.

Tests: TestSkillActions covers every branch (+ dup-key guard),
TestHandleSkillsKey_{B,A}_RoutesToCLI anchors the regression, and
TestExecuteActionMenuItem_SkillDispatch confirms every key surfaced
by any SkillActions branch resolves to a real CLI verb.

* feat(tui): MCPSetForm + route MCP actions through CLI (P0-#5)

Symmetric change to P0-#4 but for MCP servers:

* 'b' and 'a' no longer call MCPsPanel.ToggleBlock() (which
  mutated the audit store directly, skipping admission gate and
  gateway RPC). Both now dispatch through `defenseclaw mcp`.
* 'a' is always "allow" now — the old "only if blocked →
  unblock" short-circuit was a footgun. Pure unblock is still on
  'u' in the action menu.
* Info ('i') is wired through the menu dispatcher so the action
  menu button isn't silently a no-op.
* New MCPSetForm covers the `mcp set` CLI verb (add/update
  server). Triggered from the MCP panel with 'n' (or '+'). Tab /
  Shift+Tab move between fields, Enter advances or submits,
  BackSpace / Ctrl-U edit the focused field, Esc cancels.
  BuildCommand() validates required fields (name + one of
  command/url) and env KEY=VAL shape before dispatching, so the
  operator stays in the form on error rather than bouncing out
  to a raw click traceback.

Tests:
* form navigation wraps cleanly; named keys (f5/home/…) are not
  appended as literal input; UTF-8 backspace trims whole runes.
* BuildCommand argv matches cmd_mcp.py's flag layout;
  skip-scan accepts y/yes/true/1; env without '=' fails.
* handleMCPsKey B/A dispatch via CLI across all status branches;
  'n' opens the form; form owns the keyboard while active so 'j'
  becomes input (not a list cursor-down).
* executeActionMenuItem covers every key MCPActions surfaces.

* feat(tui): actions-matrix editor in Setup panel (P1-#6)

The admission gate's severity → (file, runtime, install) decision
table lives in three parallel configs (skill_actions, mcp_actions,
plugin_actions) of 5 severities × 3 columns each. Previously the
TUI Setup panel ignored them, forcing anyone who wanted to raise
the severity threshold for, say, plugin install-blocking, to open
~/.defenseclaw/config.yaml by hand.

Adds three new sections (Skill Actions / MCP Actions / Plugin
Actions) to the SetupPanel config editor. Each section surfaces
one header row plus 15 choice rows, backed by the existing
configField rendering so operators keep the same keymap
(arrow / enter / toggle / save). The choice option lists are
deliberately per-column (file: none/quarantine; runtime:
enable/disable; install: none/block/allow) so operators cannot
pick semantically invalid pairings.

Save path: applyConfigField gained a dotted-prefix fallback that
routes skill_actions.*/mcp_actions.*/plugin_actions.* through a
new applyActionsField helper. A 45-case switch would have
quadrupled the function length without adding precision.

Tests:
* shape is locked at 1+5×3 rows per section (a future severity
  or column add forces a deliberate review);
* each column keeps its own option set (no accidental merging);
* every (prefix, severity, column) triple round-trips through
  applyConfigField;
* malformed keys silently drop (don't panic Save's hot loop);
* loadSections exposes all three sections (so a missing caller
  fails loudly, not silently).

* feat(tui): admission-policy CRUD + policy test binding (P1-#7/#8)

Policy panel previously exposed only guardrail rule packs / judge
prompts / suppressions / rego — the admission-gate YAML policies
(`defenseclaw policy <verb>`) were invisible. Operators had to
drop out of the TUI to create, activate, show, or delete a policy,
which defeats the "one pane of glass" pitch.

Adds a new "Policies" sub-tab (now the first tab, because admission
policy is the most common reason to open this panel):

* ↑/↓ / j/k — navigate the list
* enter or 'a' — `policy activate <name>`
* 's' — `policy show <name>`
* 'n' / '+' — open PolicyCreateForm overlay (→ `policy create`)
* 'd' — `policy delete <name>` (CLI confirms before irreversible)
* 'v' — `policy validate`
* 'l' — `policy list` (prints full CLI-formatted table)
* 'r' — refresh the local list from disk (no CLI round-trip)

All mutating keys dispatch through CommandExecutor so they route
through the gateway and emit proper audit events — same rationale
as skills / mcps / tools.

PolicyCreateForm is the third wizard overlay in this series (after
SinkEditor and MCPSetForm) and reuses the same sequential-field
layout so the three forms feel like one subsystem. It maps 1:1 to
the `policy create` CLI option surface:
  Name, Description, --from-preset, {critical/high/medium/low}-action

Validation happens client-side (name regex, preset choices, action
choices) so the operator gets an inline status line rather than a
bounce to stderr.

P1-#8 rides along: capital-T on the OPA/Rego tab now runs
`policy test`. Lowercase 't' keeps its existing meaning (toggle
show-tests) so muscle memory is preserved. The help text for both
affected tabs (Policies + OPA) is updated to list the new keys.

Tests (25 new):
  PolicyCreateForm — field navigation, UTF-8 safe backspace, named
  keys don't append, name/preset/action validation, blank-severity
  passthrough, Enter advances then submits, Esc cancels.
  Policies sub-tab — list loads from PolicyDir, active.yaml symlink
  detection, navigation + CLI dispatch for every verb, no-selection
  safety, 'n' opens form and then HandleKey routes to the form.
  OPA tab — 'T' dispatches `policy test`, lowercase 't' still
  toggles (pair of assertions to freeze the case distinction).

* tui(setup): full scanner rows + gateway watcher/watchdog editor (P2-#9)

Fleshes the Setup panel's Scanners section with the full Python-side
surface (policy, lenient, llm_consensus_runs, enable_meta, use_trigger,
VirusTotal/AIDefense toggles, key-env binding, MCP scan_prompts /
scan_resources / scan_instructions). Adds two new sections, Gateway
Watcher and Gateway Watchdog, exposing enabled/take_action/dirs per
stream plus watchdog interval/debounce. applyConfigField grows the
matching cases and a splitCSV helper to round-trip comma-separated
directory lists cleanly (empty input collapses to nil so YAML stays
tidy). Covered by exhaustive per-key round-trip tests plus section-
shape guards to prevent silent row drops.

* tui(setup): full OTel editor — per-signal, batch, resource (P2-#10)

Expands the OTel section from a handful of globals into the full
SDK surface: sampler + sampler_arg, per-signal endpoint/protocol/
url_path overrides (traces/logs/metrics), metrics export interval
and temporality, batch processor tuning (max_export_batch_size /
scheduled_delay_ms / max_queue_size), and a deterministic resource-
attribute summary row. Headers remain redacted read-only because
their values carry bearer tokens — map CRUD stays in the CLI wizard.
applyConfigField gains matching cases so a round-trip save preserves
every new field. Covered by per-key round-trip tests and a shape
guard that pins the list of keys the section must expose.

* tui(setup): interactive Webhooks editor (P2-#11)

Adds a WebhookEditorModel that mirrors the Audit Sinks editor —
list + e/d/r/t/s/a keybindings that shell out to `defenseclaw setup
webhook` so every mutation emits an audit event from the CLI rather
than a duplicated Go path. 'a' hands off to the existing Webhooks
wizard form since per-type prompts (slack room_id, generic HMAC
secret, cooldown tri-state) can't be captured in a flat list-view.
Registers IsEditorActive in SetupPanel so app.go gates hotkeys with
a single check instead of enumerating every sub-mode. Covered by
parser, lifecycle, bounds, and CLI-argv parity tests.

* tui(setup): inspect_llm editable + AI Defense/Firewall read-only (P2-#12)

Adds three new Config Editor sections: Inspect LLM is fully editable
(provider/model/base_url/timeout/max_retries, plus api_key masked as
kind=password and the preferred api_key_env for keychain-backed
rotation); Cisco AI Defense is read-only because enabled_rules comes
from the Cisco console and mutating api_key inline would land a
cleartext bearer in YAML — the row reports three distinct states
(inline redacted, env-resolved, env-unresolved, unset) so operators
know what's actually in effect; Firewall is read-only because its
paths bind to system-owned pf/nft anchors that DefenseClaw never
creates and silently rewriting them would orphan live rules.
applyConfigField routes inspect_llm.* writes and *refuses* to touch
cisco_ai_defense.* / firewall.* — a dedicated test pins this down so
a future refactor can't accidentally introduce an edit path.

* tui(setup): guardrail/openshell parity + config_version row (P2-#13/#14)

Guardrail gains host, model_name, original_model, api_base, and
retain_judge_bodies so the TUI surface matches the CLI/config.yaml
knobs (missing these meant `defenseclaw config show` reported state
the TUI could never produce).

OpenShell exposes sandbox_home plus the two tristate *bool fields
(auto_pair, host_networking) as kind=choice with ["", "true",
"false"] options. The empty-string preserves nil so
ShouldAutoPair/HostNetworkingEnabled defaults still apply — a plain
bool would collapse nil and &false and silently flip defaults.
parseTristateBool trims+lowercases and maps everything else back to
nil so a fat-fingered keystroke never writes a bogus literal.

config_version lands in General as a read-only header row rendered
via fmtConfigVersion: bare number when in sync with
CurrentConfigVersion, "N (binary expects schema vM — migration on
next save)" when drifted, "(unset)" for fresh in-memory configs.
Editing bypasses migrateConfig, so the row is explicitly kind=header
and a test pins down that applyConfigField never writes the field.

Tests cover every new case, the tristate round-trip (including the
"clear to nil" state), and the migration-drift summary.

* tui(inventory): --only scope chips with fast-scan preset (P3-#19)

Surfaces `defenseclaw aibom scan --only` in the TUI so operators can
narrow the scan to the security-review subset (skills+plugins+mcp)
and skip the slow agents/tools/models/memory discovery during
iteration.

- Adds categoryScope state to InventoryPanel + SetCategoryScope,
  ToggleCategory, ToggleFastScan helpers. nil scope = "scan all"
  (CLI default, no --only emitted). SetCategoryScope filters out
  unknown categories so a stale persisted value can't land a bogus
  --only value on the next reload.
- Extracts loadCmdArgs from LoadCmd so tests can assert the exact
  argv without needing the CLI installed in CI.
- New chip row below the sub-tab bar shows current scope as
  "Scope (all)", "Scope (fast)", or a custom subset. Inactive chips
  are dimmed, active ones highlighted.
- Binds 'o' in the inventory panel to ToggleFastScan. Deliberately
  does NOT auto-reload — operators press 'r' next so they can see
  the new scope before paying the 15-30s scan cost.
- Updates inventoryHint and adds an inline "(o toggles fast,
  r reloads)" legend on the chip row.

Tests (internal/tui/inventory_scope_test.go):
- LoadCmdArgs with/without scope.
- SetCategoryScope filters unknown, empty/nil round-trip to nil.
- ToggleCategory add/remove/empty/unknown.
- ToggleFastScan cycle + replaces manual scope.
- Order-independent isFastScan.
- Categories list locked to CLI --only choices (cmd_aibom.py).
- Fast-preset stability guard + --only value format (no spaces).

* tui(alerts): enrich Go panel detail + retire Textual alerts TUI (P3-#20)

- Remove the legacy Textual-based `defenseclaw alerts --tui` app. The
  flag now prints a single deprecation line on stderr and falls back
  to the Rich table output so wrapper scripts keep working while
  operators migrate to `defenseclaw tui` (2 => Alerts).
- Drop the `tui = [textual>=0.50]` extra from pyproject so we stop
  shipping a second TUI frontend; `uv.lock` regenerated.
- Port the Python `_humanize_details` summarizer into Go
  (`humanizeAlertDetails`) and use it in the AlertsPanel detail pane
  to render a "Summary:" line above the raw "Details:" when the two
  differ, keeping raw kv intact for copy/paste.
- Surface TraceID / RequestID on every event and, for findings, show
  the scanner tag and remediation hint inline so the Go panel is at
  parity with (actually, a superset of) the retired Textual view.
- Adds internal/tui/alerts_enrichment_test.go covering humanize
  edge cases (host/port, model slash-tail, noise drop, duplicate
  keys) and the enriched detail rendering.

* tui(overview): cached Doctor status box (P3-#21)

Renders a compact DOCTOR box on the Overview panel backed by an
on-disk cache so operators see "all green" or the top failures
without waiting for doctor's full network-probing run on every
redraw.

CLI side (single source of truth):
- cmd_doctor.py now persists <data_dir>/doctor_cache.json at the
  end of every run (including setup --verify) via a new
  _write_doctor_cache helper. Writes are atomic (tempfile +
  os.replace) so concurrent TUI reads never see partial JSON.
- Timestamps use RFC3339 with the "Z" suffix so Go's time.Time
  parser accepts them without a custom unmarshaler.

Go/TUI side:
- internal/tui/doctor_cache.go: DoctorCache type + Load/Save helpers
  with soft error semantics (NotExist => nil cache, parse errors
  surface as toasts, never panics). Age/IsStale/TopFailures/
  SummaryLine/SortChecksByStatus/FormatAge helpers drive the
  rendering + future detail modal.
- OverviewPanel gains a DOCTOR box showing counts, freshness, and
  top 3 failures/warnings. A top-of-screen notice bubbles up
  failures or staleness. Falls back to "not yet run — press [d]"
  on first launch.
- Model loads the cache on Init and reloads it after any
  `defenseclaw doctor` completion (CommandDoneMsg detected via
  isDoctorCommand prefix match), so running doctor from the palette
  or activity refreshes the box automatically.

Tests:
- internal/tui/doctor_cache_test.go: roundtrip, atomicity, Python-
  timestamp compat, age/staleness, TopFailures ordering,
  SummaryLine, FormatAge, SortChecksByStatus, corrupt-file soft
  fail, no-data-dir no-op.
- internal/tui/overview_do…
cjsanjay pushed a commit to cjsanjay/defenseclaw that referenced this pull request Aug 13, 2026
…dary

Vineet's review [P1] on internal/inventory/ai_discovery.go:1794 flagged
that the walker treats Codex's `.system` container as an ordinary skill
entry, that the v8 projection drops bundled provenance completely, and
that neither Go nor Python mutation paths hard-refuse block / disable /
quarantine of `.system` or its descendants. Managed remediation can
therefore act on a vendor-shipped bundled skill the operator cannot
restore — the safety issue Vineet flagged for this PR's acceptance.

Fixes:

  - internal/enforce/bundled_skill.go: new IsBundledSkillPath /
    IsBundledSkillContainerName helpers + ErrBundledSkill sentinel.
    Component-wise `.system` segment check on a Cleaned path so a
    file whose basename happens to contain the substring (e.g.
    `hello.system.md`) does not falsely match. Symlink resolution is
    the caller's responsibility — every mutation surface must
    realpath before calling.

  - internal/inventory/ai_discovery.go:
      * AIEvidence gains explicit Origin ("user" | "bundled") and
        Bundled fields (kept in sync). Missing Origin is treated as
        non-actionable by all mutation paths — fail-safe.
      * signalFromDirectoryChildren, when detector="skill", never
        emits the `.system` container as a skill_entry. It recurses
        one level and emits each `.system/<child>` with
        origin=bundled. Same-named user sibling (`hello` vs
        `.system/hello`) continues to emit with origin=user;
        downstream mutation surfaces can enforce the user copy while
        refusing the bundled one.
      * Non-skill detectors (rule / plugin) treat `.system`
        literally — the reserved-container contract is skill-specific.

  - internal/enforce/plugin_enforcer.go: Quarantine refuses
    ErrBundledSkill before any stat / copy touches the source tree.
    No partial move can land in the quarantine store.

  - internal/enforce/quarantine_asset.go: NewAssetQuarantinePlan
    (skill target) refuses ErrBundledSkill after pathWithinRoots
    normalises the source path, so an unnormalised input cannot
    bypass the guard.

  - cli/defenseclaw/enforce/skill_enforcer.py: SkillEnforcer.quarantine
    resolves symlinks then raises BundledSkillRefused. The check runs
    before any hash or copy work so a bundled skill's content is
    never staged, even transiently. Mirrors the Go
    BundledSkillContainer constant.

Tests:

  - internal/enforce/bundled_skill_test.go: table-driven path check
    (positive + negative cases including substring-only false-positive
    guard); PluginEnforcer.Quarantine refuses ErrBundledSkill + source
    tree preserved + quarantine store not partially populated;
    positive baseline where a plain user skill still moves.
  - internal/inventory/bundled_skill_walker_test.go: walker expands
    `.system` for skill detector (2 bundled + 2 user siblings, all
    stamped with correct origin/bundled); non-skill detectors
    (plugin) treat `.system` literally.

Not in this commit (follow-ups from the plan):

  - PolicyEngine.{Block,Quarantine,Disable} guard by source_path
    lookup — needs the audit store's GetSourcePath surface, which
    lands with the scope-aware-identity work in commit cisco-ai-defense#2 of the plan.
  - REST/watcher endpoint refusal contract (HTTP 409 +
    bundled_skill_refused code). Endpoints don't exist yet; landing
    them here would pre-empt the REST design.
  - v8 telemetry vocabulary for inventory.item.origin. Documented in
    schemas/telemetry/v8/operations.yaml in commit cisco-ai-defense#5 of the plan.

Two pre-existing internal/enforce tests
(TestAssetQuarantineAndRestorePreserveHashAndOwnership /
TestAssetRestoreCompletesCrashWithBothVerifiedCopies) fail locally on
macOS due to /var being a symlink in the fixture — reproduces
identically with all changes stashed, not introduced here.

Refs: Vineet review comments on PR cisco-ai-defense#674 (issue cisco-ai-defense#2 in
PR674_VINEET_REVIEW_PLAN.md).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
sanjayab23 added a commit that referenced this pull request Aug 17, 2026
…e MCP coverage (#674)

* fix(inventory): enumerate skill/mcp child basenames in discovery signals

For Skill/Plugin/Rule discovery, signalFromPath stamped
filepath.Base(<parent directory>) so basenames shipped as constants
like ["skills"] / ["plugins"] / ["rules"] rather than the actual
skill/plugin/rule names. For MCP discovery the config-file basename
was the only thing surfaced (["mcp.json"], ["settings.json"], ...)
with no clue which MCP servers were declared inside.

Extend the detectors to enumerate:
  * detectSkills/detectRules/detectPlugins - direct children of the
    parent directory become one AIEvidence row each so Basenames
    carries the actual entry names (child dirs / rule files).
  * detectMCPPaths - parse the matched MCP config file with the
    right format-specific reader (JSON .mcp.json, Claude settings,
    Codex TOML, YAML) and emit one mcp_server-typed evidence row
    per declared server name.

The parent-directory / config-file evidence row is preserved as
evidence[0] so PathHashes still identifies the surface and lifecycle
stability across scans is retained.

New sanitizer sanitizeBasenameValue mirrors ValidateSanitizedAIDiscoveryReport
so OS-metadata dotfiles (.DS_Store, Thumbs.db, desktop.ini) and
separator-bearing names never pollute the wire payload.

Config-package exports (ReadMCPFromDotMCPJSON, ReadMCPFromClaudeSettings,
ReadMCPFromCodexConfigTOML, ReadMCPFromYAMLPath) let inventory reuse
the existing MCP parsers without duplicating logic.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(installer): populate ai_discovery.home_dirs from eligible-user enumeration

The managed_enterprise sidecar runs as root under launchd. macOS launchd
does not export HOME to daemons, so Go's os.UserHomeDir() falls through
to getpwuid(0) which is /var/root — a directory that never contains
operator-owned AI-agent state (~/.claude, ~/.codex, ...). Per-user AI
Discovery detectors (skills, plugins, rules, MCP configs) consequently
found nothing on freshly installed hosts.

Fix at the boundary that already knows every eligible local user: the
installer's enumerate_local_users pass (same filter that renders
targets.yaml). Feed those homes to render_config as an explicit
home_dirs list so ai_discovery.home_dirs is written into the managed
config alongside every other setting. The sidecar's existing
homesToScan() / ~-expansion path picks them up unchanged.

Schema: add home_dirs (bounded pathString array, matches scan_roots
shape) under the aiDiscovery block so the v8 config validator accepts
the field.

render_config: back-compatible signature. Numeric 6th arg triggers the
new "count + N homes + connectors" form; a non-numeric 6th arg leaves
home_dirs empty and treats every arg as a connector, keeping all
existing test callers working.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(observability): ship per-item skill/plugin/MCP inventory to managed AID

The v8 managed-enterprise pipeline previously shipped only three aggregate
inventories (agent / connector / MCP) into the Cisco AI Defense sink, each
projected through the v7 gateway compatibility envelope. For MCP that
envelope carries only a rollup count, so downstream inventory processing
had no way to enumerate the actual MCP servers, skills, or plugins on the
host, nor to correlate any of them with their parent agent connector.

This change adds a per-item shipping path:

  * Two new release-owned actions -- managed_skill_inventory and
    managed_plugin_inventory -- reserved on the generated managed plan so
    the sidecar can emit one ai_component.observed record per skill or
    plugin entry.

  * A per-connector MCP fanout in the endpoint inventory emitter that
    enumerates every configured connector's native MCP config (codex
    config.toml, claudecode ~/.claude/settings.json + ~/.claude.json,
    cursor ~/.cursor/mcp.json, ...) and ships one record per (connector,
    server) pair. Coverage unions cfg.ActiveConnectors() with the
    built-in connector registry so managed installs (which pin a single
    guardrail connector) still scan every registered client.

  * Threading of the latest AI-Discovery report snapshot into the
    endpoint inventory emitter so skills / plugins / MCP evidence rows
    discovered by the scan can be flattened into per-entry records as
    well as the aggregate roll-up.

  * defenseclaw.agent.discovery.connector on every per-item record so
    downstream analytics can pivot MCP / skill / plugin enumeration by
    parent agent (codex, claudecode, cursor, ...).

  * defenseclaw.inventory.item.name on every per-item record with the
    actual entry name; component.id uses a hyphen-only prefix
    (endpoint-mcp-entry-<sha256>) to stay inside the family constraint
    ^[A-Za-z0-9][A-Za-z0-9._:/-]*$.

Routing changes to prevent per-item detail from being dropped:

  * The managed destination's drop-managed-inventory-components route now
    only covers agent and connector inventories -- the two that DO have
    a v7 wrapper. MCP is removed because its v7 wrapper carries only a
    count, so the per-item detail is only preserved on the raw v8 send
    path. Skill and plugin were never in the drop route.

  * managedaid/compatibility.go accepts both "ok" (the emitter's
    canonical clean-scan value) and "completed" for
    defenseclaw.ai.discovery.result on inventory summaries.

  * The compatibility projector's default switch case lets recognized v8
    discovery / inventory actions without a v7 wrapper (managed_skill_
    inventory, managed_plugin_inventory, ai_discovery scan summaries)
    flow through unprojected. Unknown / diagnostic actions remain
    fail-closed so an unrecognized record shape cannot silently pass.

Corresponding managed-plan validator update in factory.go and router.go
now expects two actions in the components drop route instead of three.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(config): read Claude Code MCP servers from ~/.claude.json (user + local)

readMCPServersClaudeCode previously only walked ~/.claude/settings.json.
The Claude Code CLI actually stores user-scope MCP servers in
~/.claude.json (top-level mcpServers), and per-project local-scope servers
under projects.<path>.mcpServers in the same file. Servers registered via
the Claude Desktop UI landed in one of those two blocks, invisible to the
inventory scanner.

Extend the reader to walk both files:

  * ~/.claude/settings.json (unchanged): top-level mcpServers
  * ~/.claude.json (new user-scope): top-level mcpServers
  * ~/.claude.json (new local-scope): projects.<path>.mcpServers flattened
  * <workspace>/.mcp.json (unchanged): top-level

readMCPFromClaudeSettings now also parses url and type fields so
HTTP/SSE/streamable-http transports (e.g. cisco-platform-sdk) are
preserved with their URL and transport instead of being silently discarded
because command is empty.

An exported ReadMCPFromClaudeJSONProjects wrapper lets the endpoint
inventory fanout (managed_enterprise per-connector path) reach the
local-scope block directly under an operator user home without mutating
the daemon's HOME environment.

Skip the ~/.claude.json walk when CLAUDE_CONFIG_DIR is explicitly set --
that override reroutes the whole Claude Code state directory and the
adjacent .claude.json file is not authoritative.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(observability): bound authentication circuit-open to a few minutes

FailureClassAuthentication currently trips the shared immediate-open
duration (maxCircuitOpenDuration = 24h), which is the same trap used for
FailureClassUnsafeEndpoint. That is far too aggressive on the very first
auth failure -- a single expired token mint, a transient identity-service
hiccup, or a clock skew during CMID rotation silently suppresses the
destination for a full day.

Split the two classes at the point where the open duration is chosen:

  * FailureClassUnsafeEndpoint keeps the 24-hour trap. A broken endpoint
    is not expected to self-heal within a session, so parking the circuit
    for a day gives the operator a bounded surface for triage instead of
    letting the exporter loop against a permanently-rejecting target.

  * FailureClassAuthentication now uses a bounded five-minute cool-down
    (authenticationCircuitOpenDuration). Long enough for the upstream
    identity service / token rotation to recover, short enough that a
    recoverable auth error clears within the same operator session.

Both Circuit.RecordFailure and Dispatcher.recordCircuitFailure funnel
their duration choice through immediateCircuitOpenDurationFor(class) so
the two paths stay in sync.

Tests updated:
  * circuit_test.go asserts the auth cool-down uses the new bound and
    that a probe is granted after it.
  * dispatcher_internal_test.go: the auth row of the failure-class
    table now expects authenticationCircuitOpenDuration.
    TestCircuitCooldownHalfOpenRecoveryAndGenerationReset switches its
    initial failure to FailureClassUnsafeEndpoint so its 24-hour bound
    assertion stays meaningful.
  * otlp/metrics_circuit_test.go asserts per-class open-until bands
    instead of a shared 24-hour equality.
  * runtime/health_test.go asserts the auth-class open-until falls in
    a bounded few-minute band on the aggregated destination health
    snapshot.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore(review): address CodeRabbit feedback + gofmt

- gofmt: reformat metrics_circuit_test.go struct tags (unblocks Go Lint).
- health/metrics tests: enforce the exact 5-minute authentication cooldown
  band instead of the broad `1min <= x <= 1h` range so a regression to the
  legacy 24h trap is caught.
- sidecar.go: capture aiDiscoverySnapshot() once at both binding sites so
  the snapshot function and the emit hook cannot end up bound to different
  discovery-service instances across a concurrent swap.
- ai_discovery_basenames_test.go: cover the containsUnicodeControl branch
  in sanitizeBasenameValue (newline / NUL / ESC).
- ai_discovery.go: parseMCPConfigForNames now routes .claude.json through
  ReadMCPFromClaudeJSONBothScopes so basenames covers per-project
  local-scope servers, not just user scope.
- installer_lib.sh: guard the home-dir shift loop against a caller-declared
  count that exceeds the number of positional args and against empty
  entries (schema requires minLength: 1).
- config/claw.go: new ReadMCPFromClaudeJSONBothScopes that unmarshals
  ~/.claude.json once and returns both user- and local-scope entries;
  discovery + inventory flows now use it so the (multi-MB) conversation-
  state file is decoded once per pass instead of twice.
- inventory_events.go: openhands connector reads .openhands/mcp.json via
  ReadMCPFromDotMCPJSON (the actual on-disk format) instead of the wrong
  .openhands/mcp.yaml.
- inventory_events.go: Pass 1 gates on hasNativeMCPReader so unrecognized
  connector slugs cannot fall through to the OpenClaw registry default
  and duplicate its servers under a foreign agent label.
- observability_v8_managed_destination.go: extend the operator-destination
  drop route to also cover ManagedSkillInventoryAction and
  ManagedPluginInventoryAction — per-item skill/plugin records carry
  endpoint identity and must only reach the release-owned Cisco AI Defense
  destination. Test updated to match.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore(review): honor CLAUDE_CONFIG_DIR in per-home managed inventory

readMCPServersUnderHome iterates every configured user home and read
the default `~/.claude/settings.json` and `~/.claude.json` paths
unconditionally. If the operator has redirected the Claude Code CLI to a
custom directory via CLAUDE_CONFIG_DIR, those default files may be stale
or entirely ignored by the CLI — managed inventory would then emit MCP
servers the CLI itself never sees.

Mirror the CLAUDE_CONFIG_DIR guard already applied in
readMCPServersClaudeCode: when the env var is set, skip both default
Claude paths for every configured home. `.mcp.json` (project-scope) is
left in place because it's the workspace-scope file the CLI reads
regardless of the override.

Adds TestReadMCPServersUnderHomeHonorsClaudeConfigDirOverride which
proves both default files are ignored under an explicit override and
picked back up when the override is cleared.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore(deps): npm audit fix — bump js-yaml 4.3.0 → 4.3.1

Closes CI failure on npm Dependency Audit for
GHSA-5p4m-2wfm-xmqj (JS-YAML quadratic CPU consumption in !!omap
resolution). Patch-level bumps only:

- js-yaml 4.3.0 → 4.3.1 (production dep of the plugin)
- nanoid 3.3.12 → 3.3.17 (transitive under postcss, dev-only)
- postcss 8.5.15 → 8.5.26 (dev-only)

`npm audit --omit=dev --audit-level=high` now returns 0 vulnerabilities;
`npm run build` still clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(gateway): update inventory expectations for per-connector MCP fanout

Two tests were pinned to the pre-fanout carrier shape and started failing
after the per-item skill/plugin/MCP inventory work landed:

- TestEmitEndpointInventoryManagedUsesCanonicalV8Snapshots
  expected connector_count + 2 records (one summary per family). With
  the per-connector MCP fanout in place a third
  ai.discovery.completed summary can ship under
  ObservabilityV8ManagedMCPInventoryAction, plus one
  ai_component.observed per (home, connector, server). Rewrite the
  record-count check to accept the baseline shape *or* the fanout shape,
  and split the ai_component.observed counter into connector vs.
  mcp_server so the mcp_server rows don't trip the
  "unexpected event family" fatal.

- TestManagedEndpointInventorySurvivesSourceDisabledAIDiscoveryLogs
  drained exactly 2 deliveries and asserted 2 persisted summaries. With
  the per-connector fanout the openclaw.json fixture surfaces an
  additional summary + one per-item ai_component.observed. Switch the
  drain loop to tally summaries by (action, source) until every expected
  summary has landed (letting per-item rows pass through the same
  channel), and update the persisted-count assertions to 3 summaries and
  8 total inventory rows (3 summary carriers + 1 connector item + 1 MCP
  item, each written raw *and* via the managed-AID projection).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore: gofmt inventory_events_test.go

Trailing-comma tab alignment left by the previous test refactor tripped Go Lint.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(gateway): relax inventory row floor for empty-HOME CI runners

Local dev machines with populated ~/.codex/config.toml et al. surface
extra per-item ai_component.observed rows via Pass 1 of
perConnectorMCPEntries, so the exact ==8 assertion introduced last commit
tripped on CI Linux runners which have no such files. Relax to a >=6
floor: 3 summary carriers × 2 (raw + managed-AID projection) is the
guaranteed minimum any environment must produce.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore(review): address CodeRabbit round-4 nitpicks

Three follow-up findings on ec83c11 / bd11bf1 were still open. All
three are correctness tightenings on prior work.

- circuit_test.go: TestCircuitAuthenticationFailureOpensImmediately
  only checked the first post-cooldown Admit returned Probe. A
  regression that double-admits (or forgets to move to half-open)
  would pass. Add a second Admit at the same timestamp and require
  CircuitAdmissionBlocked.

- installer_lib.sh: the home_dirs YAML serializer interpolated `h`
  directly inside a double-quoted scalar, so a legitimate home path
  containing `\` or `"` could produce invalid YAML or a subtly
  different path. Route each entry through the existing
  yaml_double_quoted_scalar helper (used by the same file for every
  other user-supplied string), and propagate its validation failure.

- inventory_events_test.go: the drain in
  TestManagedEndpointInventorySurvivesSourceDisabledAIDiscoveryLogs
  counted total deliveries and would silently pass if the same summary
  landed three times while another one was dropped. Track distinct
  (action, source) pairs instead so the aggregate MCP, connector, and
  per-connector MCP summaries must all arrive before the drain ends,
  and reject any unexpected (action, source) pair up front.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(uninstall): wait for daemon child PID before scrubbing hooks

stop_daemon relied on `launchctl print` returning "not loaded" as its
signal that a daemon was gone, but that only confirms launchd released
the label — the child process is often still alive for a moment after
bootout. During that window the still-running hook-guardian's fsnotify
handler observes the scrub's Write events on the user's agent-config
files (~/.claude/settings.json etc.) and re-heals every DefenseClaw
entry within its ~750 ms debounce, silently undoing the scrub.

Capture the child PID from `launchctl print` BEFORE bootout, then poll
`kill -0` for up to 10 s. Escalate to SIGKILL if the process ignores
SIGTERM, with a 3 s grace after. Also reorder the stop calls so the
hook-guardian goes first — it's the reconciler; killing it before the
gateway/enumerator ensures no reconcile pass can race the scrub even
if the SIGKILL fallback ever fails.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(bundle): ship guardrail rule packs so cold-start LoadRulePack succeeds

The gateway's sidecar init resolves guardrail.rule_pack_dir to
<DataDir>/policies/guardrail/default (config.go:3573 default). On
managed installs that path is /opt/cisco/secureclient/defenseclaw/
runtime/policies/guardrail/default. The rule pack YAMLs live in the
repo at policies/guardrail/{default,strict,permissive}/ (296K, 39
files total across three profiles), but neither the bundle builder
nor install.sh copied them, so the gateway died on cold start with:

  Error: sidecar: init: sidecar: global rule pack "<path>": rule pack
  directory_not_found at .: rule-pack directory does not exist

scripts/build-macos-bundle.sh now stages policies/guardrail/ into
${BUNDLE_DIR}/policies/guardrail/ (mkdir parent explicitly, 0755/0644
so tar -x from any user works). install.sh resolves a POLICIES_SRC
from ${SCRIPT_DIR}/policies (bundle) or ${REPO_ROOT}/policies (dev),
dies if neither exists, and cp -R's the tree into
${RUNTIME_DIR}/policies/guardrail/ with root:wheel 0750 dirs / 0640
files matching the surrounding RUNTIME_DIR perms.

All three profiles (default / strict / permissive) are shipped so an
operator can retarget rule_pack_dir at a stricter profile without a
reinstall.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(config): apply env_config overlay before injecting managed AID destination

ConfigManager.Reload was calling applySidecarObservabilityV8ManagedDestination
inside loadStableCandidate, where next.CiscoAIDefense.Endpoint still held
the raw config.yaml value (US-prod default in most managed installs). The
AVC env_config.json overlay ran AFTER loadStableCandidate returned, so
source.compiledV8.Plan ended up carrying a managed destination pinned to the
config.yaml endpoint. Downstream the Sidecar apply boundary recomputed the
same destination with the newly overlaid endpoint (e.g. preview.api.…),
WithObservabilityV8ManagedAIDDestination's idempotency check
(observability_v8_managed_destination.go:102) saw two different Transport
endpoints, and the reload failed with:

  [config] reload failed: config reload observability v8 managed destination:
  observability: generated managed-enterprise destination rejected

Symptom appeared any time env_config.json set a Cisco AI Defense endpoint
different from what the installer wrote into config.yaml — i.e. every
region-override delivered by AVC after install.

Move the applySidecarObservabilityV8ManagedDestination call out of
loadStableCandidate and into Reload, right after preserveManagedGateway
RuntimeFields (so the overlay + oldCfg carry-forward have both settled).
Both sides of the equivalence comparison now see the same endpoint the
Sidecar boundary will compute. On failure record a load-error metric and
signal StateError health so the reject reason still surfaces in
sidecar status output.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(cli): skip audit.db open for enterprise hooks subcommands

The enterprise hooks command tree chained rootPersistentPreRunE, which
unconditionally opens audit.db in RW mode (root.go:113). That works for
one-shot admin invocations, but the hook-guardian runs as a long-lived
LaunchDaemon beside the main defenseclaw-gateway daemon — and the main
daemon has already claimed audit.db exclusively. SQLite can't accept a
second RW owner on the same file, so every hook-guardian start after
the gateway boots dies with:

  Error: failed to open audit store: audit: verify database open
  /opt/cisco/secureclient/defenseclaw/runtime/audit.db: database is
  locked (5) (SQLITE_BUSY)

With plist KeepAlive=true, launchd relaunches the guardian in a loop
and every restart fails the same way — so the fsnotify heal loop
never actually runs and per-user hooks stop getting reconciled after
tamper. The audit-open code has an explicit "never open audit.db from
a co-resident short-lived process" comment attached to
loadGatewayCommandConfigOnly (root.go:154-158); it just wasn't wired
in for the long-lived guardian.

None of the enterprise hooks subcommands (watch / install / uninstall
/ reconcile) reference auditStore or auditLog anywhere — grep of
internal/cli/enterprise_hooks*.go and internal/enterprisehooks/ hits
only the lifecycle test's save/restore for other tests' isolation.
The audit-open was dead work.

Add rootPersistentPreRunNoAuditE in root.go that runs the same
platform preflight + Windows daemon.RegisterCurrentProcess + config
load, minus the audit-store block. Flip the enterpriseHooks test
seam's default to point at the new variant; lifecycle tests that
already override the seam keep working unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore: gofmt enterprise_hooks.go

Re-align the enterpriseHooksRuntimeGOOS / enterpriseHooksPlatformPreflight
declarations after the previous commit's added comment block. `make go-lint`
runs gofmt in check mode and rejected the misaligned column.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(inventory): add cursor skill_paths + plugin_paths to signature catalog

Cursor's signature was missing both skill_paths and plugin_paths
entirely. The four skill-shaped paths on the entry
(.cursor/skills, ~/.cursor/skills, .agents/skills, ~/.agents/skills)
sat under config_paths — used by detectConfigPaths as a boolean
presence check, not by detectSkills which iterates skill_paths and
enumerates directory children. Same shape for plugins: Cursor's entry
had no plugin_paths at all, so per-item plugin records never emitted
for cursor even when ~/.cursor/plugins was populated.

Two independent gaps surfaced when validating a real Mac's inventory
POST against ~/.cursor/ on disk:
- Zero cursor skills appeared in per-item managed_skill_inventory
  events despite ~/.cursor/skills-cursor/ holding 26 skills (automate,
  autopilot, canvas, create-hook, create-rule, create-skill, review,
  review-security, sdk, shell, statusline, update-cli-config, and
  more).
- Zero cursor plugins appeared in managed_plugin_inventory despite
  ~/.cursor/plugins/local/ being present.

The observed skill directory name is `skills-cursor` (Cursor's current
convention), not `skills` — even the paths that would have been added
if we merely moved them from config_paths to skill_paths would not
have picked up the real dir on this host. skill_paths now covers
BOTH conventions (skills-cursor + skills), user-scope and repo-scope,
plus the neutral .agents/skills fallbacks. plugin_paths mirrors the
structure.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(inventory): protect .system bundled skills at every mutation boundary

Vineet's review [P1] on internal/inventory/ai_discovery.go:1794 flagged
that the walker treats Codex's `.system` container as an ordinary skill
entry, that the v8 projection drops bundled provenance completely, and
that neither Go nor Python mutation paths hard-refuse block / disable /
quarantine of `.system` or its descendants. Managed remediation can
therefore act on a vendor-shipped bundled skill the operator cannot
restore — the safety issue Vineet flagged for this PR's acceptance.

Fixes:

  - internal/enforce/bundled_skill.go: new IsBundledSkillPath /
    IsBundledSkillContainerName helpers + ErrBundledSkill sentinel.
    Component-wise `.system` segment check on a Cleaned path so a
    file whose basename happens to contain the substring (e.g.
    `hello.system.md`) does not falsely match. Symlink resolution is
    the caller's responsibility — every mutation surface must
    realpath before calling.

  - internal/inventory/ai_discovery.go:
      * AIEvidence gains explicit Origin ("user" | "bundled") and
        Bundled fields (kept in sync). Missing Origin is treated as
        non-actionable by all mutation paths — fail-safe.
      * signalFromDirectoryChildren, when detector="skill", never
        emits the `.system` container as a skill_entry. It recurses
        one level and emits each `.system/<child>` with
        origin=bundled. Same-named user sibling (`hello` vs
        `.system/hello`) continues to emit with origin=user;
        downstream mutation surfaces can enforce the user copy while
        refusing the bundled one.
      * Non-skill detectors (rule / plugin) treat `.system`
        literally — the reserved-container contract is skill-specific.

  - internal/enforce/plugin_enforcer.go: Quarantine refuses
    ErrBundledSkill before any stat / copy touches the source tree.
    No partial move can land in the quarantine store.

  - internal/enforce/quarantine_asset.go: NewAssetQuarantinePlan
    (skill target) refuses ErrBundledSkill after pathWithinRoots
    normalises the source path, so an unnormalised input cannot
    bypass the guard.

  - cli/defenseclaw/enforce/skill_enforcer.py: SkillEnforcer.quarantine
    resolves symlinks then raises BundledSkillRefused. The check runs
    before any hash or copy work so a bundled skill's content is
    never staged, even transiently. Mirrors the Go
    BundledSkillContainer constant.

Tests:

  - internal/enforce/bundled_skill_test.go: table-driven path check
    (positive + negative cases including substring-only false-positive
    guard); PluginEnforcer.Quarantine refuses ErrBundledSkill + source
    tree preserved + quarantine store not partially populated;
    positive baseline where a plain user skill still moves.
  - internal/inventory/bundled_skill_walker_test.go: walker expands
    `.system` for skill detector (2 bundled + 2 user siblings, all
    stamped with correct origin/bundled); non-skill detectors
    (plugin) treat `.system` literally.

Not in this commit (follow-ups from the plan):

  - PolicyEngine.{Block,Quarantine,Disable} guard by source_path
    lookup — needs the audit store's GetSourcePath surface, which
    lands with the scope-aware-identity work in commit #2 of the plan.
  - REST/watcher endpoint refusal contract (HTTP 409 +
    bundled_skill_refused code). Endpoints don't exist yet; landing
    them here would pre-empt the REST design.
  - v8 telemetry vocabulary for inventory.item.origin. Documented in
    schemas/telemetry/v8/operations.yaml in commit #5 of the plan.

Two pre-existing internal/enforce tests
(TestAssetQuarantineAndRestorePreserveHashAndOwnership /
TestAssetRestoreCompletesCrashWithBothVerifiedCopies) fail locally on
macOS due to /var being a symlink in the fixture — reproduces
identically with all changes stashed, not introduced here.

Refs: Vineet review comments on PR #674 (issue #2 in
PR674_VINEET_REVIEW_PLAN.md).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(inventory): coverage/truncation flags on AISignal + MCP cap fix

Vineet's [P1] on internal/inventory/ai_discovery.go:1620: MCP inventory
silently caps at 31 servers (parent evidence row consumes one slot of
the 32-entry evidence limit), and no signal flags "we stopped early."
More generally, Vineet's issue #4: read errors, permission errors,
parse failures, and cap hits all silently emit partial=false snapshots,
which downstream consumers (managed remediation, dashboards) then
treat as authoritative.

Fix:

  - AISignal gains two additive JSON fields (omitempty, no wire break):
      * Partial (bool): true when the emitted evidence rows do not
        cover everything the detector saw. Any consumer that promises
        "authoritative snapshot" must fail-close on Partial=true.
      * CoverageReason (string): enumerated over four reasons —
        cap_exceeded, read_error, permission_denied, parse_error —
        so consumers can route diagnostics without pattern-matching.
        Constants exported alongside the field.

  - signalFromDirectoryChildren (skill / plugin / rule walker) sets
    Partial + CoverageReason on:
      * Stat / ReadDir permission-denied → permission_denied
      * Stat / ReadDir generic read error → read_error
      * Per-signal cap hit before exhausting children → cap_exceeded

  - appendBundledSkillChildren (bundled `.system` expansion from the
    prior commit) now returns (partial, reason) so a permission or
    read error inside .system propagates up to the outer signal.
    Bundled read errors are just as bad for the operator's view as
    user-skill ones.

  - signalFromMCPConfigPath (Vineet's inline anchor): explicit
    maxMCPServerRowsPerSignal = maxEvidencePerSignal - 1 constant so
    the intent is grep-able. The 32nd real server no longer falls off
    silently — Partial=true, CoverageReason=cap_exceeded. Added a
    readMCPServerNamesWithErr shim so the parse-error branch can
    stamp CoverageReason=parse_error while preserving the parent
    "mcp" evidence row (the operator still sees "endpoint has MCP
    configured" even when the parser can't enumerate).

Tests (5 new cases across two files):

  - coverage_test.go:
    - Cap exceeded → Partial=true, reason=cap_exceeded, exactly
      maxEvidencePerSignal rows.
    - Healthy dir → Partial=false, CoverageReason="", omitempty round-
      trip keeps both fields off the wire.
    - Permission denied (unix-only, skips root) → Partial=true,
      reason=permission_denied|read_error.

  - mcp_cap_test.go:
    - Cap exceeded on MCP config with 36 servers → Partial=true,
      reason=cap_exceeded, exactly maxEvidencePerSignal-1 mcp_server
      rows (parent reserved).
    - Malformed JSON → Partial=true, reason=parse_error, parent row
      preserved, zero mcp_server rows.
    - Healthy 3-server config → Partial=false, CoverageReason="".

Deferred within issue #4 (follow-up commit):

  - Scope-aware component identity: currently
    endpointInventoryComponentID(kind, sigID + "/" + name) collapses
    same-named skills/MCP servers across user homes. Fix requires
    threading a home hash into every walker signal — worth its own
    focused commit so the identity change is auditable in isolation.
  - MCP `disabled` disagreement between discoveredMCPEntriesFromReport
    and perConnectorMCPEntries. Requires agreeing on the normalised
    shape both readers should produce.

Refs: Vineet review comments on PR #674 (issue #4 in
PR674_VINEET_REVIEW_PLAN.md); inline anchor at
internal/inventory/ai_discovery.go:1620.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(inventory): scope-aware component identity across user homes

Vineet's [P1] identity finding: same-named MCP servers / skills /
plugins in different user homes collapse to a single
defenseclaw.ai.component.id because the identity input omits the
home / parent-surface scope. Two users each with codex/webex configured
in ~/.codex/config.toml previously produced ONE component row at the
SAM, silently dropping the second. Same shape for
~/.codex/skills/hello vs a colleague's identical skill on a shared
host, and for the report-derived-vs-direct MCP readers whose ids can
now diverge or collide on the same server.

Add two helpers to internal/gateway/inventory_events.go:

  * endpointInventoryScopeKey(path) — 16-hex-char sha256 truncation of
    the absolutised path. Used by the direct-home MCP reader
    (perConnectorMCPEntries Pass 2) to scope each user home to its
    own bucket. Disambiguation-only; not a security boundary.

  * endpointInventoryScopeFromEvidence(evidence) — extracts the scope
    from a walker-produced signal by taking the parent surface row's
    PathHash and truncating to 16 hex chars (prefix stripped). The
    walker already hashes the home-prefixed path into evidence[0], so
    this reuses that computation and keeps report-derived scope keys
    stable across walker HMAC-key rotations.

Wire the scope into the three emit sites:

  * discoveredEntriesFromReport (skills / plugins) —
    signalID + "/" + scope + "/" + name.
  * discoveredMCPEntriesFromReport (report-derived MCP) —
    signalID + "/" + scope + "/" + name.
  * perConnectorMCPEntries (direct home reader) —
    connectorName + "/" + homeScope + "/" + serverName. Pass 1
    (daemon's own HOME) keeps homeScope="" so single-home hosts see
    stable ids across the rollout. Pass 2 (per configured HomeDirs)
    uses endpointInventoryScopeKey(home) so same-name servers across
    homes stay distinct AND both survive the seenComponent dedup
    (previous dedup key was identity-scoped-out-of-home, silently
    swallowing the second home's row).

Tests (3 new cases):

  * Two different home paths produce distinct scope keys; empty
    input produces empty scope (not a hash of "").
  * Distinct parent PathHashes on evidence[0] produce distinct
    16-char scope tokens; sha256:/hmac-sha256: prefix stripped.
  * Same-name skill across two scopes produces distinct component
    ids; same scope + same name is stable.

Not in this commit — Vineet's disabled-disagreement flag between
discoveredMCPEntriesFromReport and perConnectorMCPEntries. Requires
agreeing on a normalised MCPServerEntry.Disabled representation both
readers should emit; belongs with the connector-parity refactor
(issue #3 in PR674_VINEET_REVIEW_PLAN.md).

Refs: Vineet review comments on PR #674 (issue #4 in the plan).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(inventory): connector-surface parity + Python catalog sync

Vineet's [P1] on internal/gateway/inventory_events.go:373: the
direct-home MCP switch is not an all-connector implementation. It
omits OpenClaw, Antigravity, OpenCode, Amp; uses incomplete parsers
for Hermes (native YAML — the JSON fallback silently returns nothing);
and the signature catalog leaves 6+ supported_connectors with no
skill_paths / plugin_paths declared at all. Vineet also flagged that
the Cursor plugin_paths I added earlier conflict with the canonical
Cursor connector (Cursor has no user-plugin surface; the earlier
addition was speculative), and that OpenClaw's catalog plugin path
is wrong (points at ~/.openclaw/plugins but OpenClaw actually
installs the fetch-interceptor extension at ~/.openclaw/extensions/).

Catalog (internal/inventory/ai_signatures.json):

  - openclaw: plugin_paths ~/.openclaw/plugins → ~/.openclaw/extensions
  - cursor: REMOVE speculative plugin_paths (canonical conflict)
  - windsurf: skill_paths added
  - geminicli: skill_paths added
  - copilot: skill_paths added
  - antigravity: skill_paths + plugin_paths added
  - openhands: skill_paths added
  - opencode: plugin_paths added
  - amp: skill_paths + plugin_paths added

Direct-home MCP reader (readMCPServersUnderHome):

  - Add openclaw, antigravity, opencode, amp branches.
  - hermes: switch native config.yaml to ReadMCPFromYAMLPath so the
    YAML shape actually decodes (fixes the "incorrect parsers" flag).
  - zeptoclaw: native .zeptoclaw/config.json alongside legacy path.
  - amp: use ReadMCPFromClaudeSettings — Amp settings match the
    Claude top-level mcpServers shape.
  - hasNativeMCPReader: openclaw duplicate removed; every supported
    connector now returns true.

Parity tests (new file: internal/inventory/connector_parity_test.go):

  - TestSupportedConnectorParityMatrix: every supported_connector
    declares at least one of mcp/skill/plugin paths. omnigent is
    exempt (custom policy bridge, no user-facing surfaces).
  - TestSupportedConnectorMCPOnEveryConnector: mcp_paths required
    on every supported_connector except explicit exempt set.
  - TestSupportedConnectorCountMatchesRegistry: pins count at 14 so
    silent additions trip the test.

Packaged Python catalog byte-parity sync
(cli/defenseclaw/inventory/ai_signatures.json):

  - Byte-copied from the Go authority so
    test_packaged_catalog_is_byte_identical_to_go_authority passes.
    That WAS Vineet's [P1] CI blocker on ai_signatures.json:285. All
    8 Python tests in tests/test_ai_signatures.py green locally.

Not in this commit (deferred per plan):

  - Full InventoryReader interface refactor deleting the
    readMCPServersUnderHome switch. The catalog IS now the single
    source of truth for path declarations; the switch remains as the
    parser dispatch since each path shape has a specific parser.
  - Dynamically-loaded connectors hard-refusing to register without
    an inventory-reader interface — requires the interface refactor.
  - MCP `disabled` normaliser between the two MCP readers — belongs
    with the interface refactor.

Refs: Vineet review on PR #674 (issues #3 and #0). Inline anchors:
internal/gateway/inventory_events.go:373 and
internal/inventory/ai_signatures.json:285.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore: gofmt parity test + Python lint N818

- internal/inventory/connector_parity_test.go: align coverage struct
  fields to two spaces per gofmt after `make go-lint` complained.
- cli/defenseclaw/enforce/skill_enforcer.py: rename
  BundledSkillRefused -> BundledSkillRefusedError to satisfy ruff
  N818 (exception class must have an Error suffix). Docstring reference
  updated in the quarantine method.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(managed): v8-only inventory route, drop legacy v7 projection

Vineet's [P1] on managedaid/compatibility.go: the managed adapter was
running a mixed v7/v8 contract. Agent, connector, and MCP inventory
records were being projected into legacy schema-v7 gatewaylog.Event
envelopes while skill/plugin per-item records passed through as v8.
Vineet asked for a v8-only wire: "remove the AI-discovery inventory
cases from projectManagedCompatibility, remove
drop-managed-inventory-components, and send the original generated
v8 summary/item records through routing, redaction, and managed
egress. Rewrite the managed adapter tests so they assert the
canonical v8 wire body instead of deserializing gatewaylog.Event."

Code changes:

- internal/observability/destinations/managedaid/compatibility.go:
    * projectManagedCompatibility no longer routes any ai.discovery
      action through the v7 projection. Only guardrail.evaluation.
      completed retains its legacy flat envelope; every other
      ai.discovery record — agent, connector, MCP, skill, plugin,
      and the ai_discovery scan summary — is v8 passthrough.
    * isV8PassThroughAction widens to cover all five managed
      inventory actions plus the scan summary.
    * The three legacy projectors
      (projectManagedConnectorInventory / projectManagedMCPInventory /
      projectManagedAgentInventory) still live in this file so a
      rollback commit could restore them, but they are no longer
      wired to the compatibility projector.

- internal/config/observability_v8_managed_destination.go:
    * The managed destination now carries TWO generated routes
      instead of three. The middle
      "drop-managed-inventory-components" route existed only to
      suppress raw v8 records while the compat projector emitted v7
      wrappers on the same destination; without it, dropping v8
      records here would silently strip the managed AID destination
      of its inventory content.

- internal/observability/destinations/factory.go: validManagedAIDRoutes
  now expects len(routes) == 2, and the sensitive-profile check
  targets Routes[1] (the send-all fallback, formerly at Routes[2]).

- internal/observability/router/router.go:
  validManagedFallbackDestination expects len(source.Routes) == 2 and
  len(destination.routes) == 2; the diagnostic-drop and send-all
  routes are asserted directly with no middle route in between.

Test rewrites:

- internal/observability/destinations/managedaid/adapter_test.go:
    * TestAdapterManagedCompatibilityGoldenWire: input payloads now
      represent already-redacted state (raw_path / command_path /
      url-with-token / raw_binary_path / operator authorization
      stripped) — under Vineet's design, redaction runs BEFORE the
      adapter, so those fields never reach here. Assertion split:
      verdict record keeps the v7 gatewaylog.Event flat-attribute
      shape; the three inventory records assert v8 passthrough
      (defenseclaw.bucket=ai.discovery / defenseclaw.event.name /
      defenseclaw.connector.instance.id attributes) with the wire
      body carrying the canonical v8 JSON shape (bucket / action /
      body / correlation / provenance).
    * TestManagedCompatibilityInventoryIsAtomicAndFailClosed →
      renamed to TestManagedCompatibilityInventoryIsV8Passthrough.
      The old test enforced v7 carrier validity at the compat layer
      (atomicity checks on parallel arrays / partial flag / overflow
      / unknown fields); under v8-only these move to redaction and
      the OTLP canonical projector. New test asserts every managed
      inventory action + body combination returns
      useProjection=false, valid=true so the record flows through
      unmodified. Diagnostic action remains fail-closed at the
      compat layer.
    * TestAdapterRejectsInvalidManagedCarrierBeforeCredentialsOrNetwork →
      renamed to TestAdapterV8InventoryPassthroughReachesNetwork.
      Old test asserted that invalid carriers were rejected before
      network egress; under v8-only, invalid-shape carriers are now
      v8 passthrough. Test now asserts: mismatched-parallel-array
      inventory reaches the endpoint, the credential resolver is
      called, dispatcher records delivered=1, and the wire body
      contains ai.discovery + connector-inventory identity strings.

- internal/config/observability_v8_managed_destination_test.go:
  TestManagedAIDDestinationIsReleaseOwnedAndSensitive: len==2 and
  send-all is at Routes[1].
- internal/config/observability_v8_managed_inventory_test.go:
  TestManagedAgentInventoryIsForceCollectedAndReservedToManagedDestination:
  len==2 with drop@0 and send@1.
- internal/observability/router/managed_collection_fallback_test.go:
  fallback identity test cases target Routes[1] (send-all) for
  identity-mutation coverage; new "send-all route removed" case
  replaces the old "component drop broadened" mutation which no
  longer has a route to broaden.

Refs: Vineet review comments on PR #674 (issue #1). Inline anchor:
internal/observability/destinations/managedaid/compatibility.go:288
(now line ~272 after the switch simplification).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* spec(telemetry): document v8 inventory vocabulary and regenerate registry

Vineet's [P1] issue #5: schemas/telemetry/v8/operations.yaml documented
the endpoint inventory as connector/MCP/coding-agent data only; it had
no bundled/origin field, no partial/coverage-reason vocabulary, and no
declaration for the skill/plugin per-item shapes that this branch's
walker now emits. Coupled with the .system-protection commit
(commit 7969ed7) and the coverage/truncation commit (commit
15ed824), the registry now formally names the wire-visible fields
those emit paths produce.

New attributes in schemas/telemetry/v8/operations.yaml
(introduced_in: telemetry-registry-v2):

- defenseclaw.inventory.item.origin (enum user | bundled)
    Stamped by the discovery walker on every skill / plugin item row
    so downstream mutation surfaces (block / disable / quarantine)
    can hard-refuse action on vendor-managed bundled entries. Missing
    origin MUST be treated as non-actionable — the fail-safe rule
    from the .system-protection commit's mutation guards.

- defenseclaw.inventory.item.bundled (boolean)
    Convenience derivative of origin so consumers that only want a
    yes/no gate don't have to string-match. Kept in sync with
    origin at emit time.

- defenseclaw.inventory.partial (boolean)
    The inventory snapshot is not complete. Consumers that promise
    "authoritative" MUST fail-close on partial=true. Wire-format
    surface of AISignal.Partial from the coverage/truncation commit.

- defenseclaw.inventory.coverage_reason (enum cap_exceeded |
    permission_denied | read_error | parse_error)
    Names WHY partial=true so consumers can route diagnostics per
    reason. Empty when partial=false. Wire-format surface of
    AISignal.CoverageReason.

Also updated inventory.item.name's normalization notes to document
the scope-aware identity rule from commit cb420ec: basename-only
here, with scope disambiguation carried by defenseclaw.ai.component.id
(which folds in the parent-surface hash so two users' identically-named
items get distinct IDs).

schemas/telemetry/v8/registry.yaml: registry_version 1 -> 2 so the
new attributes' introduced_in: telemetry-registry-v2 fingerprint
matches. Kept schema_version at 1 (per Vineet's clarification —
schema_version is the wire envelope, distinct from the registry
version, and no envelope-shape break is intended here).

Regenerated artifacts from `make telemetry-generate`:
- internal/observability/zz_generated_telemetry_builder_fixtures_test.go
- internal/observability/zz_generated_telemetry_builders_genai.go
- internal/observability/zz_generated_telemetry_builders_operations.go
- internal/observability/zz_generated_telemetry_builders_security.go
- internal/observability/zz_generated_telemetry_catalog.go
- internal/observability/zz_generated_telemetry_ids.go
- internal/observability/zz_generated_telemetry_producers.go
- schemas/telemetry/runtime/catalog.json.gz
- schemas/telemetry/runtime/compatibility/*.json.gz
- schemas/telemetry/runtime/telemetry.schema.json.gz

`make telemetry-check` green; full observability suite green.

Not in this commit (per plan): removal of
defenseclaw.agent.discovery.installed from per-item MCP/skill/plugin
rows, and replacement of the hardcoded
defenseclaw.ai.discovery.privacy_mode: "enhanced" with the actual
runtime privacy mode. Both require emit-side wiring changes and
would benefit from being landed alongside the actual emit-code
edits — deferred as a small follow-up.

Refs: Vineet review comments on PR #674 (issue #5 in
PR674_VINEET_REVIEW_PLAN.md).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test: update assertions for registry_version=2 and 2-route managed dest

Fallout from the two spec commits landed earlier this branch:

- registry_version bumped 1 -> 2 in schemas/telemetry/v8/registry.yaml
  (spec commit b283da9, needed so the four new v8 inventory attributes
  could declare `introduced_in: telemetry-registry-v2`).
- managed AID destination reduced from 3 to 2 generated routes (v8-only
  refactor commit 5f56794, removed the middle
  `drop-managed-inventory-components` route with the v7 compat
  projector for ai.discovery records).

Tests updated:

- cli/tests/test_telemetry_registry_candidate_renderer.py:
  test_every_artifact_carries_candidate_authority_and_view_digest
  now asserts registry_version=2 in every rendered artifact's
  x-defenseclaw-generated marker.

- cli/tests/test_telemetry_schema_resources.py:
  test_packaged_telemetry_resource_matches_generated_source
  (parametrised over 6 resources) now asserts registry_version=2 on
  every packaged runtime resource.

- internal/gateway/sidecar_observability_v8_bootstrap_test.go:
  TestSidecarBootstrapAndReloadOwnManagedAIDDestinationWithoutCredentials
  now expects the two-route shape (drop-local-inventory-diagnostics
  at index 0, all-collected-logs at index 1) with the sensitive-
  profile check retargeted to Routes[1].

Local run — all 48 affected Python tests plus the Go bootstrap test
green.

Not touched — remaining occurrences of `registry_version: 1` in
test fixtures where 1 is scenario data (not a claim about current
state):
- cli/tests/test_telemetry_registry_generator.py:1219 (writes a v1
  fixture registry.yaml for a self-contained generator test).
- cli/tests/test_observability_v8_compatibility.py:60 (`_artifact()`
  helper uses 1 as one side of a "mixed epoch rejection" scenario,
  matched with 2 in the parametrised test cases).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(llm-catalog): drop deprecated Groq llama-4 ids, add gpt-oss-20b + qwen3.6-27b

LiteLLM's registry marked groq/meta-llama/llama-4-maverick-17b-128e-instruct
(deprecated 2026-03-09) and llama-4-scout-17b-16e-instruct (deprecated 2026-07-17),
so `check_llm_catalog` and `test_shipped_catalog_has_no_stale_ids` were failing on
every CI shard. Replace them with two current chat models on Groq.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* ci: retrigger Windows Native CI (2100s wrapper timeout was marginal, non-code)

* fix(inventory): enforce 5-min process-scan floor in managed_enterprise

Every scan tick (full or process-only) fans out through
managedInventoryEmit, so the default 60s process interval currently
publishes a full connector/MCP snapshot to AI Defense every minute on
managed installs. Push volume dominates the operational cost of process
detection there; align the process cadence with the 5-min full-scan
cadence by floor-clamping ProcessInterval to 5 min when
ManagedEnterprise is set. Unmanaged/dev installs still get 60s live
process detection. Operators can configure a longer interval in managed
mode; the floor only lifts sub-5-min values.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: cjsanjay <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
sanjayab23 added a commit that referenced this pull request Aug 24, 2026
…+ tests

Addresses 25 CodeRabbit comments from PR #777 review. Each item is a
minimum surgical change; no functional refactors beyond what the review
asked for. All fixes cross-compile clean for windows/amd64 and the
native darwin test run is green.

  #1 Workflow: hoist payload filename list to env variable
  #2 Workflow: distinguish SKIP from FAIL for restricted-token test
  #3 Python test: anchored C# slice extraction with readable failures
  #4 Docs: add CMID broker row to token-contract table
  #5 Docs: broker fixture name aligned with DefenseClawCert prefix guard
  #6 Test: restore pin-branch coverage of auditDBWindowsTrustedPrincipal
  #7 Test: cover gateway-owned + 3-ACE installer DACL matrix cell
  #8 Refactor: hoist duplicated access masks to package constants
  #9 Correctness: sidecar hardening decide + verify use the same predicate
 #10 Log clarity: distinguish sd.Owner()/sd.DACL() errors from trust verdicts
 #11 Log clarity: enterprise-hook set-comparison now takes a role label
     ("authorization"/"activation"/"guardian state") so activation drift
     no longer reads as an authorization problem
 #12 Correctness: schema-3 legacy journal upgrade synthesizes the three
     absent runtime-selector snapshots before shared validation
 #13 Correctness: --output/--request/--claims/--manifest error strings
     reference real flag names instead of the pre-rename labels
 #14 Refactor: windowsCursorManagedPaths returns a windowsCursorPaths
     struct; every positional-return call site migrated to named fields
 #15 Correctness: after ERROR_ALREADY_EXISTS, use the stricter
     validateWindowsManagedPolicyDirectoryProtection instead of the
     lax windowsManagedPolicyDirTrustCheck (Claude policy + selector too)
 #16 Test doc: comment explaining the intentionally-empty DataDir in
     the deleted-profile removal identity-check case
 #17 Correctness: rollback of a first-time selector selection uses
     nilForSID(receipt.targetSID) sentinel to clear the entry, matching
     the pattern in restoreWindowsManagedRuntimeSelectorTargetCASPlatform
     instead of silently re-publishing receipt.publishedTarget
 #18 Correctness: Claude managed-hook resolver now rejects when the
     target's gatewayAddr/gatewayServiceName disagrees with the resolved
     generation, ending the "trust one of two identity sources" ambiguity
 #21 Test: assertion that windowsCodexMachineReport propagates
     CursorTargetEnabled
 #22 Correctness: patchCursorHooks emits hooks.json timeout in SECONDS
     via the shared windowsCursorEnterpriseHookTimeoutSeconds constant
     (was emitting the millisecond value)
 #23 Test: two new cases cover RunCodexNotify snapshot branch
 #24 Log clarity: informational "[managed-cloud] CMID provider using
     <lane> credential lane" line on both successful build paths so
     operators can tell broker vs native selection from logs alone
 #20 Correctness: "Request body is not in base64: <err>" was already
     addressed in commit 2a8baea — prefix match, tests included
 OD-1 Test: restore on-disk assertion that adapter does not leave
     .cursor-input-*.json in hookDir (removed by an earlier refactor;
     helpers.go:152-156 promises payloads never touch disk)
 OD-2 Refactor: resolveWindowsCodexManifestApplicability returns
     windowsCodexManifestApplicability struct so positional-boolean
     destructuring in the caller is gone

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
sanjayab23 added a commit that referenced this pull request Aug 24, 2026
* feat(windows): isolate managed credentials behind broker

* fix(ci): align broker payload contracts

* fix(docs): render Windows env values literally

* fix(windows): accept empty service contracts

* fix(ci): align uninstall smoke with broker service

* fix(windows): restore managed readiness

* fix(windows): adopt retained uninstall state

* feat(windows): add managed Cursor enterprise hooks

* test(windows): align enterprise lifecycle fixtures

* test(windows): canonicalize managed IPC ACL fixture

* test(tui): stabilize persisted stats generation

* fix(windows): repair native Cursor contracts

* fix(windows): close enterprise certification gaps

* fix(windows): repair managed hook installation

* fix(windows): canonicalize managed runtime creation

* fix(windows): secure managed lock ownership

* fix(windows): publish final runtime directory ACL

* fix(windows): detect official WinGet Codex

* fix(windows): reopen hardened audit databases

* fix(windows): preserve redaction key across repair

* fix(windows): publish hardened redaction key by handle

* fix(windows): use native redaction key rename contract

* fix(windows): retire stale shared IPC grants

* fix(windows): canonicalize guardian manifest ACL

* fix(gateway): report safe Cisco inspect diagnostics

* test(windows): stabilize enterprise lifecycle smokes

* fix(windows): harden fresh install rollback

* fix(windows): repair target runtime native gates

* fix(windows): canonicalize runtime quarantine gates

* fix(windows): persist target runtime claims safely

* test(windows): bind directory ACL flag explicitly

* fix(windows): bind rollback ACL directory flag

* test(windows): isolate uninstall smoke report

* fix(windows): harden manifest before target planning

* fix(windows): complete fresh install recovery

* test(windows): fix rollback ACL fixture

* fix(windows): secure repair manifest and rollback

* fix(windows): normalize empty runtime root claims

* fix(windows): atomically publish managed hook runtime

* fix(windows): recover retired uninstall shell

* fix(windows): model teardown journal in purge smoke

* test(windows): finalize purge fixture journal

* test(windows): preserve legacy guardian recovery lane

* test(windows): align recovery smoke fixtures

* test(windows): certify credential broker lifecycle

* fix(windows): bind service SID before target enumeration

* fix(windows): harden managed hook lifecycle recovery

* test(windows): align uninstall metadata fixture

* fix(cisco-inspect): include verbatim non-200 body under managed_enterprise

Support engineers only ever see captured logs from managed_enterprise
customer endpoints. INVALID_RESPONSE diagnostics previously carried
only a redacted length/hash placeholder for the upstream response body,
which is untriage-able. Under managed.IsManagedEnterprise(cfg.DeploymentMode)
— gated by the existing ManagedEnterpriseActive() accessor set at sidecar
boot via setManagedEnterpriseRedactionPosture — the failure diagnostic
now appends a response_body= field carrying the actual response bytes
(bounded to 512, control chars sanitized to keep single-record framing)
alongside the existing response_summary= redacted field. Applies only
to stage=response_status; body-read and JSON-decode failures keep the
redacted-only path.

Non-managed_enterprise deployments (Reveal()-capable local operator)
are unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(codex-detect): accept Administrators-owned files for admin targets

WinGet installs run under the admin user's elevated token, which
Windows defaults to stamping files with owner BUILTIN\Administrators
(SID S-1-5-32-544) rather than the user's own SID. The Codex WinGet
detector's Test-DefenseClawConnectorMetadataOwnerIdentity required a
strict target-SID-owner match, so Codex installed by the built-in
Administrator (RID -500) or any admin-group member was invisible to
DefenseClaw — the manifest rendered "codex: enabled: false", the
machine policy (%ProgramData%\OpenAI\Codex\requirements.toml) was
never written, and Codex prompts flowed uninspected.

Accept BUILTIN\Administrators as a valid owner iff the target SID is
a local-admin group member (RID -500 fast-path + CIM Win32_GroupUser
walk of local Administrators — direct membership only, nested groups
deliberately not expanded, query failure returns false so we never
widen acceptance on incomplete data). Regular non-admin targets keep
the strict target-SID-only check. Matches the runtime-side elevated-
target relaxation in the guardian.

Smoke tests: RID -500 target accepts Administrators-owned file,
non-admin synthetic target still rejects it, foreign-owner (LocalSystem)
case unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(cisco-inspect): match variable-suffix "Request body is not in base64:"

Cisco AI Defense documents the request-body-encoding 400 as
"Request body is not in base64: <base64-decode-err>" — the exact-match
switch case at classifyOfficialCiscoInspectError never fired on real
responses, so the entire family silently fell through to
upstream_bad_request. Convert to a prefix check ahead of the exact
switch so the family classifies as request_body_encoding_invalid while
the closed classification token still keeps the variable suffix out
of the log line.

Two new test cases pin the prefix behavior (with-suffix and empty-suffix).

Addresses CodeRabbit review comment #20 on PR #777.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(pr-777): address CodeRabbit review comments — correctness + docs + tests

Addresses 25 CodeRabbit comments from PR #777 review. Each item is a
minimum surgical change; no functional refactors beyond what the review
asked for. All fixes cross-compile clean for windows/amd64 and the
native darwin test run is green.

  #1 Workflow: hoist payload filename list to env variable
  #2 Workflow: distinguish SKIP from FAIL for restricted-token test
  #3 Python test: anchored C# slice extraction with readable failures
  #4 Docs: add CMID broker row to token-contract table
  #5 Docs: broker fixture name aligned with DefenseClawCert prefix guard
  #6 Test: restore pin-branch coverage of auditDBWindowsTrustedPrincipal
  #7 Test: cover gateway-owned + 3-ACE installer DACL matrix cell
  #8 Refactor: hoist duplicated access masks to package constants
  #9 Correctness: sidecar hardening decide + verify use the same predicate
 #10 Log clarity: distinguish sd.Owner()/sd.DACL() errors from trust verdicts
 #11 Log clarity: enterprise-hook set-comparison now takes a role label
     ("authorization"/"activation"/"guardian state") so activation drift
     no longer reads as an authorization problem
 #12 Correctness: schema-3 legacy journal upgrade synthesizes the three
     absent runtime-selector snapshots before shared validation
 #13 Correctness: --output/--request/--claims/--manifest error strings
     reference real flag names instead of the pre-rename labels
 #14 Refactor: windowsCursorManagedPaths returns a windowsCursorPaths
     struct; every positional-return call site migrated to named fields
 #15 Correctness: after ERROR_ALREADY_EXISTS, use the stricter
     validateWindowsManagedPolicyDirectoryProtection instead of the
     lax windowsManagedPolicyDirTrustCheck (Claude policy + selector too)
 #16 Test doc: comment explaining the intentionally-empty DataDir in
     the deleted-profile removal identity-check case
 #17 Correctness: rollback of a first-time selector selection uses
     nilForSID(receipt.targetSID) sentinel to clear the entry, matching
     the pattern in restoreWindowsManagedRuntimeSelectorTargetCASPlatform
     instead of silently re-publishing receipt.publishedTarget
 #18 Correctness: Claude managed-hook resolver now rejects when the
     target's gatewayAddr/gatewayServiceName disagrees with the resolved
     generation, ending the "trust one of two identity sources" ambiguity
 #21 Test: assertion that windowsCodexMachineReport propagates
     CursorTargetEnabled
 #22 Correctness: patchCursorHooks emits hooks.json timeout in SECONDS
     via the shared windowsCursorEnterpriseHookTimeoutSeconds constant
     (was emitting the millisecond value)
 #23 Test: two new cases cover RunCodexNotify snapshot branch
 #24 Log clarity: informational "[managed-cloud] CMID provider using
     <lane> credential lane" line on both successful build paths so
     operators can tell broker vs native selection from logs alone
 #20 Correctness: "Request body is not in base64: <err>" was already
     addressed in commit 2a8baea — prefix match, tests included
 OD-1 Test: restore on-disk assertion that adapter does not leave
     .cursor-input-*.json in hookDir (removed by an earlier refactor;
     helpers.go:152-156 promises payloads never touch disk)
 OD-2 Refactor: resolveWindowsCodexManifestApplicability returns
     windowsCodexManifestApplicability struct so positional-boolean
     destructuring in the caller is gone

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(pr-777): address CodeRabbit review comments — security + serialization

Addresses the three security-sensitive CodeRabbit comments from PR #777.
Each is a defense-in-depth change with clear failure mode analysis in
the code comments.

  #19 Machine-wide serialization for enterprise-hook mutations.
      Per-SID sync.Mutex only serialized goroutines inside one process.
      Add a Windows named mutex at Global\Cisco.DefenseClaw.EnterpriseHooks.<SID>
      acquired by lockWindowsUserRuntimeTransaction, so separate
      processes (install-time, guardian reconcile, uninstall) cannot
      interleave transactions for the same target. In-process mutex
      still held first (blocks) so intra-process callers don't fight
      the fail-fast named-mutex CreateMutex/ERROR_ALREADY_EXISTS path.
      platformRemoveManagedPolicy now also participates.

  #25 CMID broker: FlushFileBuffers before DisconnectNamedPipe,
      bounded by OperationTimeout. A slow client that never drains its
      side of the pipe cannot hold a broker slot indefinitely; the
      response reaches the client before the disconnect races an
      in-transit write.

  #26 CMID broker pipe auth by TOKEN SID, not PID.
      authenticatePipeClient impersonates the connected pipe endpoint
      via ImpersonateNamedPipeClient, reads the token user SID, and
      compares it against the gateway's virtual service SID resolved
      from `NT SERVICE\<gatewayServiceName>` via managed.WindowsServiceAccountSID.
      PID-based auth is retained as defense-in-depth (a non-Running
      gateway still fails), but PID reuse in the window between the
      gateway exiting and SCM refreshing status can no longer let a
      non-gateway process pass. Failure to RevertToSelf retires the
      OS thread rather than releasing a leaked impersonation into the
      goroutine pool — same pattern as
      runWindowsEnterpriseImpersonatedCallback.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(windows): stabilize managed verify and service diagnostics

* fix(pr-777): address CodeRabbit round-2 review comments + gofmt

Addresses six new CodeRabbit review comments that landed after the
round-1 batch, plus the gofmt lint failure the round-1 batch left
behind.

  gofmt Restore gofmt formatting on hook_only.go and
        service_identity_windows.go (Go Lint job failure).

  NEW-26 cmd/defenseclaw/service_windows_test.go: synchronize on
         client.Inspect completion before sending svc.Stop. An
         inspectDone channel signals from the executor callback; the
         SCM mock waits on it before requesting Stop, bounded so a
         broken executor still fails rather than deadlocks. Without
         this, cancellation from Stop could preempt the 403 diagnostic
         the test asserts on.

  NEW-27 internal/enterprisehooks/install_windows.go: lock
         platformRemoveManagedPolicy when only UserHome is supplied
         for Claude Code. Resolve the target SID from either
         OwnerSID or UserHome BEFORE lockWindowsUserRuntimeTransaction,
         then lock on the canonical SID string. UserHome-only requests
         no longer bypass the per-SID machine-wide named mutex.

  NEW-28 internal/managed/cmidbroker/server_windows.go: eliminate the
         flush/close race in flushPipeBounded. On timeout, cancel the
         pending FlushFileBuffers via CancelIoEx and wait for the
         goroutine to observe the cancellation before returning, so
         the pipe handle stays valid at every point the goroutine
         still references it (subsequent deferred DisconnectNamedPipe
         / CloseHandle can no longer race with an in-flight flush).

  NEW-29 internal/managed/cmidbroker/service_identity_windows.go:
         switch modAdvapi32 to windows.NewLazySystemDLL. The loader
         is now restricted to %SystemRoot%\System32\, closing a
         residual DLL search-hijack gap even when KnownDLLs already
         covers most cases. Removes now-unused syscall import.

  NEW-30 same file: replace the "capture and silently discard"
         threadToken close pattern with a deferred close that
         surfaces the error on the success path. A Close failure
         indicates handle-leak / kernel-state corruption — visible
         in the broker log rail rather than swallowed.

  NEW-31 packaging/windows/install-enterprise.ps1: anchor the RID
         -500 pattern in Test-DefenseClawConnectorMetadataTargetIsLocalAdmin
         to require exactly three non-empty numeric sub-authorities
         between S-1-5-21 and -500. The prior `[0-9-]+` sub-pattern
         would match `S-1-5-21---500` and `S-1-5-21-1-500` (only one
         sub-authority) — neither is a real built-in Administrator SID.

Native tests on affected packages pass on darwin. Cross-compile clean
for windows/amd64.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(pr-777): cancel synchronous FlushFileBuffers, not overlapped I/O

CodeRabbit round-3 flagged that CancelIoEx cannot interrupt the
synchronous FlushFileBuffers used by flushPipeBounded: CancelIoEx
targets *pending* overlapped operations, but FlushFileBuffers is a
synchronous kernel call. On a client that stopped reading, the timeout
path would call CancelIoEx (no effect), then block indefinitely on
<-done — holding the active-client semaphore past OperationTimeout and
letting waitForActiveClients return while the flush goroutine remained
in kernel wait.

Use CancelSynchronousIo, which targets a specific thread and aborts
whatever synchronous kernel call is currently blocked on it with
ERROR_OPERATION_ABORTED. Bound to kernel32 via NewLazySystemDLL so a
same-directory kernel32.dll cannot hijack the resolution (same defense
in depth pattern as advapi32 in service_identity_windows.go).

Flush goroutine: LockOSThread + DuplicateHandle(CurrentThread) so the
parent has a shareable real thread handle. On timeout the parent
CancelSynchronousIo's that handle, then reads <-done bounded. The
goroutine deliberately does NOT UnlockOSThread on exit — the Go
runtime retires the still-being-cancelled OS thread rather than
recycling one whose kernel-mode unwind hasn't finished. Same pattern
as runWindowsEnterpriseImpersonatedCallback.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: cjsanjay <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
sanjayab23 added a commit that referenced this pull request Aug 24, 2026
Addresses two audit items from Vineeth's PR #767 review that concern
initial-boot / config-wait behavior.

  #2  Documented recomputeConfigurationLocked's waiting_for_config
      branch as intentionally reserved for a future hot-reload path.
      The audit confirmed it is currently unreachable in production
      (SetDaemonConfigLoaded(true) runs after loadGatewayConfigV8
      already succeeded, and the deferred-config wait happens before
      SidecarHealth is even constructed) — leaving the branch + proto
      value in place because (a) removing
      CONFIGURATION_STATE_WAITING_FOR_CONFIG is a proto wire-compat
      change to AVC UI clients that already receive it, and (b) a
      future hot-reload flow can call SetDaemonConfigLoaded(false) at
      the reload's start and back to true when the new config lands
      without any additional plumbing. Comment names the wiring point.

  #7  waitForConfigV8Managed no longer aborts when fsw.Add on the
      parent directory returns ENOENT / permission errors. UCB drops
      that create "dir + config.yaml" atomically hit ENOENT and turned
      the intended 24-hour bounded wait into a crash-restart loop.
      Log the miss and fall through to the poll ticker — poll is
      strictly slower for spotting the file, but functionally
      equivalent, and never fatal at daemon start.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
nghodkicisco added a commit that referenced this pull request Oct 14, 2026
…tation retry

#2: Remove duplicate Connect() from sidecar.go — bridge.Start() now
owns the single MQTT connection lifecycle. autopaho handles reconnect.

#3: Replace stack-reused char topic[128] with three static buffers
(topic_verdict, topic_policy, topic_emergency) so Paho's stored
pointers remain valid across subscriptions.

#4: Rewrite dclaw_paho_read to loop with monotonic deadline instead
of breaking on EAGAIN. TCP fragments arriving across poll cycles are
now reassembled within the original timeout.

#5: Remove requireClientID feature — MQTT PUBLISH does not carry the
sender's ClientID, so the check always failed. Broker ACLs are the
correct publisher identity mechanism.

Also: remove P1-fix-tracking comments from CLI files.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
nghodkicisco added a commit that referenced this pull request Oct 15, 2026
* feat(fleet): DefenseClaw Lite Phase 1 — Edge Connector fleet management

Complete Phase 1 implementation of DefenseClaw Lite for IoT/edge device
fleet management:

C Edge Connector (edge-connector/):
- 17 C source files, 11 test binaries, all passing
- 8-stage policy evaluation pipeline with content scanning
- MQTT client with Paho Embedded, CBOR codec, verdict protocol
- OTA policy receiver with signature verification and A/B partitions
- Canary health-check window with auto-rollback
- Emergency broadcast handler with sequence anti-replay
- Audit ring with HMAC chain integrity on flash storage
- HAL abstraction for Linux (Raspberry Pi, SBCs)

Go Fleet Manager (internal/fleet/):
- Fleet REST API (13 endpoints) with tenant isolation
- MQTT bridge for heartbeat/verdict/registration processing
- Verdict cache with tenant-scoped keys (identity isolation)
- Policy compiler integration, signing, and MQTT distribution
- Emergency command distribution with sequence persistence
- SQLite device store with per-device HMAC key management
- Prometheus metrics and Grafana dashboard

Source of Truth Conformance:
- FleetConfig struct in config.yaml with Resolved* methods
- Config.yaml integration via locked writer (managed host checks)
- Env var fallback for backward compatibility
- JSON schema with fleet section definition
- CLI setup commands write fleet section to config.yaml

Python Tools (edge-connector/tools/):
- Policy compiler (YAML → C header + signed binary)
- Generic hook, MCP proxy, HTTP middleware, LangChain hook
- PicoClaw hook for microcontroller integration

Integration Hooks:
- Bubbaloop camera, ESP-Claw MCU, Home Assistant adapters
- MQTT broker setup with Mosquitto Docker/native

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(fleet): resolve 8 MUST requirement gaps from skill checklist audit

Fixes found by auditing against defenseclaw-develop skill checklist:

M-CFG-1: Add fleet section to canonical schema (schemas/config/v8/),
not just the packaged copy. Without this, config.yaml with fleet: keys
is rejected by the closed-schema validator.

M-CFG-2: Add Python FleetConfig dataclass with _merge_fleet() loader
in cli/defenseclaw/config.py. Add viper.SetDefault for 8 fleet keys
in Go so both sides agree on defaults.

M-CFG-7: Classify fleet keys as restart-required (mqtt_broker_url,
signing keys, enabled) or hot-reloadable (auto_register, allow flags)
in both Go restartKeys and Python RESTART_KEYS.

M-CFG-9: Add SetCredentials(user, pass) to PahoClient so MQTT creds
flow from FleetConfig.ResolvedMQTTUser/Pass() instead of raw os.Getenv.

M-CFG-10: Register 13 DCLAW_* env vars in both registry copies with
managed_policy (allow/ignore/tighten_only) and security_impact fields.

M-DEP-14: Gate fleet initialization on fleetEnabled check — fleet
subsystem only starts when fleet.enabled=true, a broker URL is
present, or an API token is configured.

M-OBS-1: Add 3 missing audit action constants (reregistered,
token.rotated, key_rotated) to Go + Python registries. Replace all 9
raw string emitAudit calls with typed constants.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* chore: remove fix-tracking comments that mislead independent reviewers

Strip MF-*, HIGH-*, BLK-* fix IDs, BUG: labels, TODO markers, and
Phase 2/3 deferred-work references from production code. These cause
reviewers to flag the code as incomplete or buggy when the behavior
is intentional.

- MF-3 ID removed from verdict_protocol.c and defenseclaw.h
- HIGH-10 fix labels removed from 3 integration adapters
- BUG: label on tenant=0/fleet=0 broadcast rewritten as known limitation
- TODO on manager locking rewritten as architectural description
- Phase 2/3 references in manager.go, policy.go, ota_receiver.c
  rewritten as factual descriptions of the current design

REQ-* architecture spec references (34 occurrences) kept — they are
legitimate traceability to the design proposal, not fix-tracking.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* style: gofmt fleet and gateway files to fix CI lint

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(observability): restore compatibility aliases to fix generated code mismatch

The generated zz_generated_telemetry_builders_operations.go expects
NewTelemetryCustomResourceAttributes(map, bool) and references
compatibilityAliases on TraceResourceInput. Restore the original
call signature and struct fields to match. Also resolve merge
conflicts in deleted training/GRPO files.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* docs: remove PR-only review artifacts and demo drafts

* fix(fleet,edge,cli): resolve security and correctness findings from release review

Go fleet API:
- Default listDevices to maxPageSize instead of unbounded (G-1 DoS fix)
- Re-verify device existence after shard lock in ProcessHeartbeat (G-2 race)
- Return partial_timeout status when decommission batch hits deadline (G-4)

C edge-connector:
- Add monotonic counter to lockdown release HMAC to prevent replay (C-1)
- Preserve backward compat with legacy single-HMAC format

Python CLI:
- Pre-create service env file with mode 600 before writing secrets (P-2 TOCTOU)
- Use Path.is_relative_to() instead of str.startswith() for validation (P-1)
- Handle ValueError on malformed tenant_id/fleet_id in YAML metadata (P-3)

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(ci): remove stale compatibility_aliases and enable dev mode for edge tests

- Remove compatibility_aliases from operations.yaml (replaced by
  secure_client_resource_aliases.go on main)
- Enable DCLAW_DEV_MODE=ON in edge-connector CI so tests can use
  dev-mode flash paths and HMAC fallbacks

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(telemetry): restore fleet event builders lost during main merge

Three-way merge of the generated telemetry files: main's base (with
secureClientAliases refactor) + fleet commit's additions (9 fleet event
types, builders, producers, and catalog entries). Manually removed the
compatibility_aliases remnants that the ancestor carried.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(telemetry): restore redaction attribute constants lost in 3-way merge

Re-add ClientAddress, SessionKerberosPrincipal, UserPrincipal, and
UserTenantID to the generated telemetry IDs — needed by the redaction
profile and lost when the generated files were re-merged.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(telemetry): correct 3-way merge of generated files (fleet + bundle + aliases)

- Re-merge generated files keeping main's base (no compatibilityAliases)
  with fleet commit's additions and main's policy bundle additions
- Fix producer group array size (236 → 239 for fleet entries)
- Renumber duplicate context_set_31 → context_set_35 for config.bundle.receipt
- Restore redaction attribute constants (ClientAddress, SessionKerberosPrincipal,
  UserPrincipal, UserTenantID)

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(telemetry): use main's generated files + redaction constants

Reset generated telemetry files to main's authoritative output and add
the 4 redaction attribute constants needed by the redaction package.
Fleet telemetry builders require a full generator run against the updated
operations.yaml — tracked separately.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(telemetry): regenerate from operations.yaml with fleet families and main's signed-bundle additions

Properly merge operations.yaml from main (signed policy bundles, sandbox
events, 20+ new attributes) with fleet additions (9 families, 9 identity
sets, 9 producer mappings). Run the telemetry registry generator to
produce consistent Go sources, binary catalogs, and compatibility schemas.

Key fixes:
- Remove stale compatibility_aliases (replaced by secure_client_resource_aliases.go)
- Add fleet reserved_keys (device.id, deployment.environment, deployment.mode)
- Remove duplicate defenseclaw.config.digest attribute
- Place fleet producer mappings after tool-unblock to match actions.go declaration order

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(ci): add missing audit actions to schema, fix Python lint

- Add fleet.device.key_rotated, fleet.device.reregistered,
  fleet.token.rotated to schemas/audit-event.json (check_audit_actions
  parity gate)
- Fix ruff E402 (module-level imports not at top) in cmd_edge_install,
  cmd_setup_edge_connector, cmd_setup_mqtt
- Fix ruff E501 (line too long) in cmd_edge_connector_cli via ruff format
- Fix ruff I001 and F541 in cmd_setup_mqtt

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(ci): resolve Python lint (UP038/N806) and v8 hard-cut gate

- Fix UP038 (isinstance tuple → union syntax) in 5 changed Python files
- Rename VALID_SEVERITIES → valid_severities in cmd_audit.py (N806)
- Remove retired DEFENSECLAW_DISABLE_REDACTION reference from
  config.go comment (v8 hard-cut gate violation)

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(ci): add 3 missing fleet producer mappings, fix test counts and status crash

- Add producer mappings for fleet.device.reregistered, fleet.token.rotated,
  fleet.device.key_rotated to operations.yaml and v7-compatibility-inputs.yaml
- Regenerate telemetry registry (248 producer groups, 232 audit actions)
- Update classification_generated_test.go counts (236→248, 220→232)
- Update event_registry_test.go snapshot hash for new fleet event names
- Add "fleet" to config schema allowedTopLevel in embed_test.go
- Fix UnboundLocalError on client in cmd_status.py when config is invalid
- Add fleet restart-required keys to source-of-truth.mdx

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(fleet): address reviewer findings — off switch, auth, TLS, DB perms

Functional fixes from PR review comment #6176250659:

- Item 2: Fleet starts only when config fleet.enabled=true (removed
  fallback to env var presence that bypassed the off switch)
- Item 3: Exclude fleet defaults from config digest when fleet is off
  (dropFleetDefaults mirrors dropTetragonDefaults pattern)
- Item 4: Fleet API auth rejects empty tokens, skips tenant-0 scoped
  entries, and returns tenantDenied (65535) for unmatched tokens instead
  of granting admin (0)
- Item 5: Pass fleet.mqtt_require_tls config to MQTT client so the
  config key is actually enforced (was only checking env var)
- Item 7: Create fleet SQLite DBs with mode 0600 (pre-create before
  sql.Open to avoid umask-dependent 0644)
- Item 15: Add Eclipse Paho Go and Embedded C to NOTICE

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(fleet,legal): sync Python config defaults with Go, add SPDX headers

Item 8: Set Python FleetConfig env-var-name defaults to match Go viper
defaults (api_token_env, mqtt_user_env, mqtt_pass_env, ota_key_env,
emergency_key_env, device_key_env). Update _merge_fleet() fallbacks to
use the dataclass defaults rather than empty strings.

Item 14: Add Apache 2.0 + SPDX-License-Identifier headers to 107 newly
added source files (.c, .h, .go, .py, .sh) that were missing them.
Third-party and generated files are excluded.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(ci): revert SPDX headers on testdata/example fixtures, expand restart keys

- Remove SPDX headers from testdata/rulepack_artifact_parity/skill/
  scripts/{comment,docstring}.py — these are scan-test fixtures with
  secrets at known line offsets; the headers shifted the lines and broke
  TestArtifactScanAgreesWithSkillScanOnPythonComments
- Remove SPDX header from packaging/mdm/linux/examples/tetragon/
  fleet-readiness.sh — the docs page embeds this file verbatim; the
  header broke test_tetragon_examples parity check
- Expand fleet restart-required keys in source-of-truth.mdx to list
  each key individually (fleet.ota_key_env, fleet.emergency_key_env,
  fleet.device_key_env, fleet.mqtt_user_env, fleet.mqtt_pass_env)

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(test): accept both phase orderings in sandbox lifecycle test

TestManagedSandboxTelemetryAfterAGatewayRevocation sends stopping and
stopped in the same HTTP batch. The audit store may record them in
either order depending on timing, causing a flaky failure on macOS CI.
Accept both stopping,stopped and stopped,stopping orderings.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(fleet): P0 admin escalation, tenant sentinel collision, DB perms, CI

P0 #1: Token rotation now requires admin (tid=0) authorization. Tenant-
scoped bearers receive 403 instead of minting a new admin token.

P1 #23: Replace uint16 sentinel (65535) with (uint16, bool) return from
tenantFromRequest. Real tenant 65535 is no longer treated as denied.

P2 #24: Tighten permissions on pre-existing fleet SQLite databases — if
an older 0644 DB exists, chmod it to 0600 on open.

CI #25: Skip TestBundleGenerationReloadAuditCarriesPrincipal on Windows
(UID-based actor is not available); device key rotation uses proper
two-return auth check.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* style: gofmt internal/fleet/api.go

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(mqtt): single connection owner, persistent topic buffers, fragmentation retry

#2: Remove duplicate Connect() from sidecar.go — bridge.Start() now
owns the single MQTT connection lifecycle. autopaho handles reconnect.

#3: Replace stack-reused char topic[128] with three static buffers
(topic_verdict, topic_policy, topic_emergency) so Paho's stored
pointers remain valid across subscriptions.

#4: Rewrite dclaw_paho_read to loop with monotonic deadline instead
of breaking on EAGAIN. TCP fragments arriving across poll cycles are
now reassembled within the original timeout.

#5: Remove requireClientID feature — MQTT PUBLISH does not carry the
sender's ClientID, so the check always failed. Broker ACLs are the
correct publisher identity mechanism.

Also: remove P1-fix-tracking comments from CLI files.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(edge): OTA HMAC auto-enable, TLS 1.3, flash safety, replay persistence

#6: Auto-enable DCLAW_ALLOW_HMAC_OTA when TweetNaCl is not found so
the Go HMAC signer and C production verifier agree out of the box.

#7: Add TLS 1.3 cipher suites (AES-256-GCM, AES-128-GCM, ChaCha20)
conditional on MBEDTLS_SSL_PROTO_TLS1_3 so modern brokers negotiate
TLS 1.3 instead of falling back to 1.2.

#8: Gate legacy 4-byte flash format migration behind DCLAW_DEV_MODE.
Production builds reject unprotected legacy partition records.

#9: Fail BLOCK audit write when the preceding buffer flush fails
(flush_buffer_to_flash return value was ignored).

#14: Persist lockdown_release_seq to flash so the anti-replay counter
survives daemon restarts. Loaded lazily on first release attempt.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(fleet): decommission key-first ordering, policy compiler path, install docs

#10: Delete device key BEFORE decommissioning in manager. If key
deletion fails after 3 retries, skip the decommission entirely rather
than leaving an orphaned key.

#11: Pass fleet.policy_compiler_path from config.yaml through the
sidecar to the policy service. Resolves the nil-config bug where the
compiler always used the relative source-tree path.

#13: Add Production Deployment section to INSTALL.md documenting
required env vars (DCLAW_AUDIT_KEY, DCLAW_OTA_KEY, DCLAW_MQTT_BROKER_URL,
DCLAW_DEVICE_KEY) and systemd RuntimeDirectory=defenseclaw directive.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(cli): broker UID resolution, defensive health check

#12: Use mosquitto:mosquitto user name instead of hardcoded UID 1883
in Docker chown command. Lets the container resolve the actual UID.

#15: Add defensive all_ok recalculation before output in the
edge-connector test command. Iterates all result sections and sets
all_ok=False if any status is not ok/skipped/not_configured.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(hygiene): fleet env registry, dead code removal, DCLAW_ prefix support

#17: Remove unimplemented DCLAW_FAIL_OPEN from --help text. Mark
NewTCPClient as deprecated (retained for test fixtures only).

#18: Move 13 DCLAW_* entries from registry.json top level into the
entries array with proper schema fields (category, consumers,
security_impact). Add DCLAW_ as allowed prefix in the Go validator
and test. Add "fleet" category to the registry schema.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(ci): add fleet category to Python envvars ALLOWED_CATEGORIES

The Go registry and JSON both gained a "fleet" category but the Python
envvars loader and gen_envvars_docs.py still had the old category set.
This broke make _bundle-data which cascaded to 14 CI jobs.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(ci): TLS build, flash layout collision, envvar docs and tests

P0 #26: Move LOCKDOWN_RELEASE_SEQ_OFFSET from CONFIG+16 (collides with
partition record B) to CONFIG+32 (after both partition records).

P1 #7: Replace nonexistent mbedtls_ssl_conf_tls13_ciphersuites with a
single combined cipher list using mbedtls_ssl_conf_ciphersuites. TLS 1.3
suite IDs are prepended when MBEDTLS_SSL_PROTO_TLS1_3 is defined.

P1 #18: Add CATEGORY_FLEET and _CATEGORY_TITLES['fleet'] to
gen_envvars_docs.py. Update Python test to accept DCLAW_ prefix.
Regenerate env-vars.mdx. Remove BLK-1 fix-tracking comments from
CMakeLists.txt.

Verified: make _bundle-data, gen_envvars_docs --check, Go envvar+fleet
tests, C 11/11 CTests all pass.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(ci): resolve pre-existing test failures in envvar coverage

- Fix macOS /private/var symlink mismatch in
  test_installed_package_below_checkout by resolving both paths
- Add 11 DEFENSECLAW_TRAINING_* env vars to registry.json (referenced
  by cmd_training.py but undeclared)
- Add DEFENSECLAW_H (C header guard) to _NON_ENVVAR_TOKENS so the
  coverage scanner doesn't treat it as an env var
- Regenerate env-vars.mdx with new training entries

All 40 envvar tests + 13 subtests pass, docs --check passes.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(fleet): policy push, bridge retry, DEFENSECLAW_HOME compiler path

#11: Fix policy push HTTP 500:
- Use relative paths for compiler --input/--output-binary/--output-header
  (Python compiler rejects absolute paths as a security measure)
- Set cmd.Dir to tmpDir so compiler runs in the right working directory
- Read output blob from tmpDir instead of the original outputPath
- Add DEFENSECLAW_HOME to allowed compiler directories so installs
  with custom home directories work

#27: Add exponential-backoff retry loop to Bridge.Start() so a broker
outage at gateway startup doesn't permanently lose MQTT subscriptions.
Update TestBridgeConnectError to use a context timeout.

Verified: policy push returns {"status":"distributed"} with version=1,
79-byte signed blob sent to MQTT. Fleet tests 5/5 pass.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* Harden Fleet edge integration, release packaging, and observability

Fix production TLS and MQTT reconnect behavior, signed OTA and emergency replay durability, Fleet authorization and audit boundaries, managed compiler delivery, gateway discovery, and CLI/docs parity. Add C, Go, Python, packaging, and observability regression coverage.

* Make Fleet opt-in and harden edge connector release paths

* Fix Edge getting started flow and expose native CI test failures

* Harden optional Fleet setup and expose CI failures

* Fix truncated edge evaluations and optional install lifecycle

* Expose bounded Windows Setup CI failure codes

* Honor authenticated Fleet verdict TTLs and retire dead cache writers

* Reject malformed MCP frames and redact proxy diagnostics

* Keep MCP upstream command secrets out of diagnostics

* Update standalone rollback smoke for Fleet compiler leaf

* Keep Fleet compiler out of Windows Fleet-off ensure drift

* Remove one-off PR comment cleanup script

* Require Setup for Windows Fleet compiler state changes

* Describe bundle refusal without overstating side effects

* Check Fleet compiler invariant before confirmed bundle no-op

* Preserve installed state on bundle compiler refusal

* Document Windows Fleet changes through signed Setup

* Preserve Fleet compiler digest on Windows checkout and fix profile fixture

* fix(fleet): secure SQLite journals with Windows ACLs

* fix(fleet): initialize private Windows SQLite ownership

* ci(edge): scope Fleet integration job to Fleet compiler tests

* fix(fleet): make verdict cache LRU stable across clock ties

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: Vineeth Sai Narajala <[email protected]>
Co-authored-by: Codex <[email protected]>
vineethsai7 added a commit that referenced this pull request Oct 22, 2026
…ist (GAP-0611)

"Check it worked" listed with --connector claudecode but ran --show 2
without it, so the number indexed the global alert list; a newer Codex or
gateway alert printed a different alert. The fixed #2 also only fit a
deny-then-approve run. The page now runs
`defenseclaw alerts --connector claudecode --show N`, tells the reader to
pick the newest PreToolUse/confirm row from the list, and gives #2 as the
approve-run example.

The contract test runs the page's commands for approve, deny and
deny-then-approve runs, each with a newer Codex alert, and requires --show
to use the list's --connector.
vineethsai7 added a commit that referenced this pull request Oct 27, 2026
…d to restart, authorized_keys blocks only in action mode, a policy stop of an unsynced MicroVM contains it (GAP-0831, GAP-0454, GAP-1461, GAP-0044)

GAP-0831/GAP-0454 (owner decision 2026-10-27, documented OpenShell 0.1.3 limits): support-matrix Legacy MicroVM guests states that withdrawing the rules does not contain the old broker (NVIDIA/OpenShell#4494) and to restart the sandbox once the rules are withdrawn; sandboxes/guide gets a troubleshooting entry; the raw-start sentences are pinned. GAP-1461: policies/defaults says authorized_keys writes block in action mode and raise a CRITICAL would-block alert in observe (owner decision 2026-10-24 #2), with a source check that the rule is CRITICAL in every pack. GAP-0044: guide and sandbox-cli no longer say a policy stop of an unsynced MicroVM goes ahead; it is contained, as lifecycle.go does (source-tied check). Removes the stale sentences rather than keeping them.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dependencies Pull requests that update a dependency file github_actions Pull requests that update GitHub Actions code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant