Skip to content

feat(audit): daily retention prune for audit_log entries past 365d (#552) - #576

Merged
vybe merged 1 commit into
devfrom
feature/552-audit-retention-prune
Apr 29, 2026
Merged

vybe merged 1 commit into
devfrom
feature/552-audit-retention-prune

Conversation

@dolho

@dolho dolho commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes the gap left by SEC-001 Phase 4: the append-only audit log was protected by SQLite triggers but never pruned, so audit_log grew unbounded. Adds a daily APScheduler job that DELETEs entries older than AUDIT_LOG_RETENTION_DAYS (default 365, floored at 365 to respect the audit_log_no_delete trigger floor).

  • New service: src/backend/services/audit_retention_service.py — mirrors log_archive_service shape, runs at 04:15 UTC daily.
  • New DB op: PlatformAuditOperations.prune_audit_log() + db.prune_audit_log() facade.
  • Wired into main.py lifespan start/stop.
  • Architecture note added to the Background Services table.

Why the SQL deliberately uses datetime('now', ?)

Architectural invariant #16 prefers iso_cutoff() for rolling-window filters on ISO-Z TEXT columns. Here the audit_log_no_delete trigger's WHEN clause already uses datetime('now', '-365 days') — using the same form in our WHERE clause keeps the prune set and the trigger's protected set in sync, avoiding IntegrityError on day-of-cutoff boundary rows. The trigger has the underlying ISO-Z mismatch noted in invariant #16; fixing that is tracked separately to keep this PR scope-bounded.

Hash chain note

Pruning DELETEs rows, which breaks the previous_hash/entry_hash chain across the cutoff. Hash-chain verification ranges should stay inside the retention window by design. Documented in the service docstring; if hash chain is enabled and prune removes >0 rows, a structured warning is logged.

Configuration

Env var Default Notes
AUDIT_LOG_RETENTION_DAYS 365 Floored at 365 (trigger-bounded).
AUDIT_RETENTION_ENABLED true Set false to disable the scheduler.
AUDIT_RETENTION_HOUR 4 UTC hour to run; runs at :15 past.

Closes #552.

Test plan

  • Unit: `pytest unit/test_audit_retention_prune.py` — 4/4 pass
    • removes only old rows
    • empty-table returns 0
    • retention_days < 365 raises before touching DB
    • boundary-row stress (mix of 1d/100d/200d/360d/366d/380d/400d/720d) — proves WHERE + trigger don't drift
  • Manual: insert a synthetic 400d-old row, restart backend, wait for 04:15 UTC (or call `audit_retention_service.prune()` from a Python REPL inside the backend container), verify the row is gone and the structured log line appears.

🤖 Generated with Claude Code

)

Closes the gap left by SEC-001 Phase 4: the append-only contract was
enforced by SQLite triggers but nothing pruned aged-out rows, so
audit_log grew unbounded.

Adds a daily APScheduler job (`audit_retention_service.py`) that
DELETEs `audit_log` rows older than `AUDIT_LOG_RETENTION_DAYS`
(default 365). Floored at 365 because the `audit_log_no_delete`
trigger refuses younger rows. Disable with
`AUDIT_RETENTION_ENABLED=false`; runs at `AUDIT_RETENTION_HOUR:15`
(default 04:15 UTC, one hour after log archival to spread DB writes).

The prune SQL deliberately uses the same `datetime('now', ?)` form as
the trigger's WHEN clause — this trades architectural invariant #16
(prefer `iso_cutoff()`) for trigger consistency, avoiding
IntegrityError on day-of-cutoff boundary rows. Fixing the trigger to
use ISO-Z form is tracked separately.

Hash chain note: pruning DELETEs entries, breaking the SHA-256 chain
across the cutoff. Verification ranges should stay within retention
by design — documented in the service docstring.

Tests cover: old-only removal, empty-table return, sub-365 floor
rejection, and a boundary-row stress case that fails loudly if the
WHERE clause and trigger ever drift.

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

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — well-patterned background service, invariant #16 deviation correctly justified, boundary-stress test covers the trigger/WHERE alignment. Approved.

@vybe
vybe merged commit 2d4589e into dev Apr 29, 2026
vybe pushed a commit that referenced this pull request Sep 13, 2026
… once (Abilityai/trinity-enterprise#551, #576) (#2735)

* feat(voice): a long task runs in the background and the agent says it once (ent#551, ent#576)

In a Workspace voice call `run_task` now answers the model at once with an
accepted task id (t1, t2, ...) and runs the turn as the agent in the bound
thread in the background. The person keeps the floor; when the task lands its
outcome re-enters the live call as a system notice at a natural boundary (model
not mid-turn, person quiet 1.2 s, no tool call pending; held at most 20 s), or
as a failure with its reason. If the model says nothing within 4 s of dispatch
the platform nudges it, so the acknowledgement is structural. At most 3 tasks
run per call; at the cap the tool refuses in words. Ending the call cancels
nothing: background turns are not in `_pending_tool_tasks`, and a task that
lands later writes its rows into the thread, attributed to the call by
`voice_call_id` (typed rows, so the #2694 delta logic is untouched). A `task`
WebSocket frame drives a persistent "N tasks running" badge distinct from the
amber working badge and refetches the canvas when a task lands. The container
(VoIP) path keeps its synchronous 30 s bound as the documented fallback.

One spoken-etiquette block for the whole tool cycle replaces the filler-only
`_TOOL_ETIQUETTE_INSTRUCTION`: announce a wait, not an action (none for a canvas
write); say it once; never read the canvas aloud; one narration per sequence;
report a failure once with its reason; background tasks. Built from the manifest
(ent#535 AC 6) and worded for the session's dispatch shape; the `run_task`
description and the panel instructions agree with it.

Model: the pin stays `models/gemini-3.1-flash-live-preview`, verified against
Google's Live model list as the newest general-purpose Live model; the
`gemini-3.5-*-live` ids are transcribe-only and translate-only.

Fixes Abilityai/trinity-enterprise#551
Fixes Abilityai/trinity-enterprise#576

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ApbFsEqLtAWVdedXAUqV9p

* fix(voice): the call's own task passes the live-call guard, and the model does not invent a result (ent#551)

Found in the first live run on the branch. Every `run_task` failed at once
with "A voice call is on in this chat — end it, then send": #2694's live-call
guard (56fd9e3) landed on dev after ent#535's run-as-the-agent path
(23a2b59) and refused the call's own turns along with the typed turns it was
written for, so a Workspace call could not run a single task. The guard now
lets a turn carrying `voice_call_id` through — only the voice dispatcher writes
it, no request can — and the #2694 delta cursor skips a reply carrying it, so a
task landing mid-call cannot erase the call's earlier spoken rows from the next
typed turn.

Also from the transcript: right after the accepted result the model said
"there are sixty four files in there right now" — an invented count, seconds
before the real one. The acceptance and the etiquette block now say it holds
no result yet and must not guess one.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ApbFsEqLtAWVdedXAUqV9p

* fix(voice): say it once, name the task, keep the thread read, and never transcribe a platform notice (ent#551, ent#576)

From the second live run on the branch:

- The person heard "let me check… / I've started counting… / it's done" back to
  back with no room to speak. The acceptance asked for "one short line about
  what you started" from a model that had already said its filler; it now asks
  only if nothing was said, and says the model holds no result yet. The
  completion notice waits for 2.5 s of quiet from BOTH sides (the model's own
  speech counted for nothing before), so a fast result no longer lands on the
  heels of the acknowledgement.
- The orb badge and the header line say WHAT is running — the task's one-line
  label, or the count then the labels — instead of "1 task running".
- The sidebar's unread badge counted up during the call: every spoken turn and
  task reply landed as an unread agent row in a thread the person was in. The
  conversation now advances the read cursor while the call is on.
- The model read a platform notice aloud verbatim as the call ended and it was
  recorded as the agent's line. Every platform text now opens "never read this
  aloud", and `_record_turn` scrubs an assistant row that echoes one.
- The task's ask row sat above the spoken request that caused it. The
  dispatcher flushes the turn in progress first; the receive loop accumulates
  on the session's partial-turn fields rather than in locals so that flush is
  the one writer.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ApbFsEqLtAWVdedXAUqV9p

* fix(voice): a call started from a new chat survives its own thread being adopted, and the mic worklet loads from self (ent#551)

Found in the ent#551 QA run: every first call started from a brand-new chat
ended itself at exactly 5 s with an empty transcript. `startVoiceCall` creates
the thread and adopts it before the call starts; the shell's route replace then
changes the `sessionId` prop from null to that id a moment later, and the
thread-change watcher — right for browser back and deep links — stopped the
call it had just started. The 5 s was the `saved`-frame timeout inside that
stop, after which the socket was closed. `threadChangeEndsCall` is the rule
now: an agent change or a switch to a DIFFERENT thread ends the call; the
call's own thread arriving does not.

Also from the console: the AudioWorklet processor was inlined into a `blob:`
URL, which `script-src 'self'` (dev and production CSP alike) blocks, so every
call logged a CSP violation and silently fell back to the deprecated
ScriptProcessor. The processor is a static file under `public/`, loaded from
the page's own origin; no CSP loosening.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ApbFsEqLtAWVdedXAUqV9p

* fix(voice): the acceptance is context, not a turn — non-blocking run_task with a SILENT acceptance; shorter lines; no invented canvas (ent#551, ent#576)

Third live run. The model still spoke twice around every task — "Let me count
the files for you." then, on receiving the accepted result, "I'm checking on
that now. Anything else you're curious about while we wait?" — no matter how
the acceptance was worded, because a blocking call's result IS a turn and the
model answers it. The Live API has the shape for this: on a Workspace call
`run_task` is declared NON_BLOCKING and the accepted dispatch is returned with
SILENT scheduling, so it enters context without a turn to answer. Verified on
gemini-3.1-flash-live-preview: one line before the call, nothing after.
Refusals and the container path stay blocking and spoken; both are
getattr-guarded for an SDK without the enums (the unit stub, now extended).

The etiquette caps an acknowledgement at one short sentence and a report at
one or two. And the model said "the canvas shows the breakdown of your files"
and "I've put the weather up there" without one canvas call — the canvas row
was untouched since 2026-09-07. A canvas session is now told never to claim a
canvas it did not draw, and the completion notice states the result is in the
chat only and invites drawing it with show_markdown before speaking.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ApbFsEqLtAWVdedXAUqV9p

* fix(voice): the panel prompt teaches the fence shapes the canvas draws; tools are called, never spoken (ent#576)

Fourth live run. The canvas DID update (three show_markdown calls in the audit
log) but the chart showed as raw JSON: the model wrote a Chart.js-shaped fence
(`data.labels` / `datasets`) because the panel prompt said ```chart fences
exist and never gave their shape. It now carries the chart/kpi/table payloads
in the platform prompt's own words, pinned to the renderer's keys and
CHART_TYPES the ent#536 way, with the Chart.js shape named as the wrong one.

Same run: the model said `show_markdown('Canvas update test') updated now`
aloud, and narrated "the task failed because of a syntax error" for a call the
backend never received. The etiquette now says tools are called, never spoken,
and a failure is reported only when it actually came back as a result. The
block's size cap moves 2200 -> 2600 for the three QA-driven rules (measured
2,259), on purpose.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ApbFsEqLtAWVdedXAUqV9p

* fix(voice): the status line never sits on the call buttons, M mutes the mic, and the voice model draws the canvas itself (ent#551, ent#576)

The orb's status text and its two buttons were separately absolute-positioned
(4 rem and 1.25 rem up, with 48px buttons), so on a short stage LISTENING sat on
top of the mute and end-call buttons. They are one bottom-anchored column now.

M toggles the mic during a call: a shared rule (`isMuteHotkey` — plain M only,
not in a field, not a key an overlay already claimed, no modifier so ⌘M stays
the window's) dispatched from the same keydown handler as Escape, after the
end-call rule and before the turn-cancel rule. The mute button's title says so.

Fifth live run, on the canvas: asked to update a chart, the model dispatched a
task for the numbers AND cleared the panel, the agent replied "canvas tools
aren't available in this environment", and the model told the person it
"can't generate the live chart" — 90 s over a blank canvas, for a chart it could
have drawn itself. The panel prompt now says: you draw, never ask a task to
update the canvas, a task's "no canvas tools" is about the agent not you, and
never clear before you have what replaces it; the completion notice repeats the
first point where it lands.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ApbFsEqLtAWVdedXAUqV9p

* fix(voice): leaving the stage mid-call asks first, the model knows what is on the canvas, and doing means calling (ent#551, ent#576)

Sixth live run, three findings.

A click on the very agent being talked to, in the left rail, ended the call
with no warning: `openAgentPage` pushed a route with no guard, the conversation
remounted, and its unmount hook stopped the call. Rooms had the same gap, and
the other exits refused silently. Every exit from the stage other than the End
button — the agent row, a thread, a room, New chat, ⌘J — now routes through one
guard that holds the action and asks ("End the call? … Stay on the call / End
call and leave"); confirming ends the call through the conversation's own
`endVoiceCall` and then navigates. End call itself never asks.

The model said "I don't have a current table on the canvas" while the table was
on screen: it had never been told what the person was looking at. A Workspace
call now starts with a text rendering of the canvas (one line per block — kind,
title, slot, a short extract), bounded and best-effort, and a task that changed
the canvas while it ran says so in its notice and what the canvas shows now.

Three requests, three spoken promises ("searching for recent news about OpenAI
now"), zero tool calls. A blocking-vs-non-blocking probe on the live model put
both at 4–5 of 6, so the declaration is not the cause; the prompt is. The first
etiquette rule for a task-capable session is now "Doing means calling": the
model has no files, web or skills of its own, and saying it will do something is
not doing it. The run_task description says the same.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ApbFsEqLtAWVdedXAUqV9p

* fix(voice): tasks run one at a time per call and show as separate items; a promise without a tool call is nudged (ent#551)

Seventh live run.

Two tasks dispatched together: the second failed at once with "This
conversation is already handling a message" — the portal admits ONE turn per
thread. Background turns now take a per-call lock: the cap still bounds what is
in flight, but each task waits for the thread and then runs. The `task` frame
carries a `status` (queued | running) and a `running` event marks the moment a
queued task takes its turn; the orb shows one pill per task — the label, and
"· queued" while another holds the thread — never one bunched line.

"creating that bar chart now", "looking into OpenAI's marketing strategy now",
"let me start that search now": three promises, no tool call, until the person
asked "are you sure you ran the task?". The prompt rule did not hold, so the
platform watches: an assistant turn that reads as a promise to act, with no
tool call in the turn or within 3 s after it, gets a notice naming what was
said, stating that nothing has started, and telling the model to call the tool
now or say plainly that it has not. Rate-limited to one nudge per 15 s; a call
that lands just before the promise (the filler-then-call order) counts as kept.

The run_task description also says it is never for the canvas — the model kept
asking the agent (which has no canvas tools) to draw a chart it could draw
itself.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ApbFsEqLtAWVdedXAUqV9p

* fix(voice): the promise watch stays quiet over running work, the same request twice is one task, and Escape cools down after a call (ent#551)

Eighth live run. The promise watch did its job once (a promise with no call
became a real dispatch) and then misfired: with two tasks in flight the model
said "both … are running now", the watch saw a promise-shaped line with no
fresh call, nudged, and the model — told "nothing has started" — said "I
misspoke, they weren't running before" and started a duplicate of t1 with the
identical prompt. Three changes: no nudge while any task is in flight (the pill
already tells the person the truth); status lines ("already", "still working",
"are running") are not promises; the nudge states only what the platform knows
(no call arrived), conditions the action on "not already running", and forbids
commenting on the notice. And a `run_task` whose prompt equals a running task's
is refused as a duplicate — one task, its result once.

Also in both calls, a running task was cancelled ~3 s after the call ended,
with "You stopped this message before the agent finished." The thread had just
reattached to that task's turn, where Escape means "stop the turn", and the key
that ended the call landing again cancels it. Escape is not a cancel for 5 s
after a call ends (the Stop button stays live — a click is deliberate). Because
access logging is off and nothing named the requester, `terminate_execution`
now logs who asked on every arm and the portal route logs the client's email.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ApbFsEqLtAWVdedXAUqV9p

* revert(voice): drop the Escape cooldown after a call — the cancelled tasks were the operator's own Stop (ent#551)

The two tasks that failed 3 s after End in the eighth QA run were cancelled
on purpose by the person testing, not by a stray second Escape. A guard with
no defect behind it is a rule nobody can explain later, so it goes. The
terminate-caller logging stays: it is what would have answered this in one
line.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ApbFsEqLtAWVdedXAUqV9p

* test(portal): the chat-titles ordering guard reads the persist call with its voice_call_id argument (ent#551)

`_persist_user_turn` gained `voice_call_id=` for the call's own background
turns; the ent#473 source guard located the call by its old exact text and
raised instead of asserting order. Same three-point ordering, new spelling.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ApbFsEqLtAWVdedXAUqV9p

---------

Co-authored-by: sim <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants