Skip to content

feat(approvals): update approval queue with approve, reject and defer - #960

Merged
scttbnsn merged 18 commits into
dev/v1.8from
feat/v1.8-approval-queue
Sep 3, 2026
Merged

scttbnsn merged 18 commits into
dev/v1.8from
feat/v1.8-approval-queue

Conversation

@scttbnsn

@scttbnsn scttbnsn commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Adds the update approval queue (CA-2). Updates that need a person now collect in a queue instead of only firing a notification, and a person can approve, reject, or defer each one from the API.

What's in it, in landing order:

  • Classification. classifyApprovalCandidate sorts every update candidate into no-candidate, blocked, auto-dispatch, or queue, using the same policy the watcher already applies. Hard-blocked candidates never queue; soft-blocked ones queue with their hold reasons.
  • Store and reconciler. A LokiJS collection for approval rows and a reconciler that runs on every watcher report: it supersedes a row when the candidate moves, resolves it when the container disappears or the update applies, and re-queues an expired deferral. Agent sync writes nothing.
  • Read API. GET /api/v1/approvals, /summary, /:id, with dd:approval-created and dd:approval-resolved SSE frames.
  • Decisions. POST /api/v1/approvals/:id/approve|reject|defer. Approve reserves the row with a compare-and-swap, then runs the exact code path POST /containers/:id/update runs (extracted into container-update-dispatch.ts, so parity is structural and a test pins it). Any blocker rolls the row back to its pre-reservation state. Reject is the existing Skip policy and defer is the existing snooze, both through one shared writer, so the queue and the container panel can't drift. A decision is refused with 409 if the row's candidate no longer matches the container's current candidate, if the row is already decided, or if the system is in notify mode (approve only). Three audit actions (update-approved, update-rejected, update-deferred) and a dd:approval-decided SSE frame.
  • Request validation matches the OpenAPI schema: days is an integer 1 to 365, until is a full RFC 3339 instant in the future and at most 365 days out, note is a string, unknown keys are rejected.

Not in this PR: the bulk endpoint, the UI (route, sidebar badge, dashboard tile), and the docs pages. Those are the next slices.

Two things worth knowing. The queue's defer validates more strictly than the container panel's snooze, which still accepts date-only and past values; aligning them means changing the panel's behavior and is left for a follow-up. And a row that is both already decided and whose candidate has moved answers "candidate superseded" rather than "already decided", because the candidate check runs first so a refusal never writes.

Full app suite: 13772 tests, 100% coverage. An adversarial review found five issues in the decision slice (candidate binding, stale fields on re-decision, rollback snapshot, request validation, SSE string bounds); all five are fixed in the last commits with mutation checks proving the tests bite.

Changelog

  • ✨ Added approval model, LokiJS store, reconciliation, API routes, OpenAPI schemas, audit actions, and SSE lifecycle events.
  • ✨ Added approve, reject, and defer decisions with candidate binding, compare-and-set reservation, live revalidation, rollback, and retention handling.
  • 🔧 Shared manual update dispatch and update-policy writers between existing container actions and approval decisions.
  • 🔧 Added controller-only reconciler startup and authenticated /api/v1/approvals routes.
  • 🐛 Added validation for notes, defer schedules, timestamps, unknown properties, superseded candidates, and bounded SSE strings.
  • 🐛 Added tests for store behavior, reconciliation, API decisions, parity, events, startup, and OpenAPI conformance.

Concerns

  • Verify the app/index.ts import path. The summary reports ./approotions/reconcile.js, which appears to be a typo for ./approvals/reconcile.js.
  • Confirm that approval store initialization and retention timers do not run in agent-only or migration startup modes.
  • Confirm that SSE payload truncation preserves valid UTF-16 or Unicode boundaries.
  • Confirm that rollback restores the exact prior approval row, including decision, resolution, timestamps, and operation fields.

Adds the LokiJS `approvals` collection and the pure model behind it. Flat
records with no `data` envelope, `schemaVersion` from row one, every field a
scalar, so the collection maps 1:1 onto a SQLite table at the v1.8 store
migration.

`shouldQueueForApproval` reads `hasRawUpdate`, not `container.updateAvailable`.
Soft gates (snooze, threshold, maturity, skip-tag/digest, maintenance window)
suppress the public getter while the raw candidate stays in `image`/`result`,
and that soft-gated set is exactly what an operator wants to review. Soft
blockers become hold reasons; only a hard blocker, or an auto-dispatchable
resolution under `updateMode: auto`, keeps a candidate out of the queue.

Deferral is a query predicate on `deferredUntil`, so there is no sweep job, no
clock skew and no restart-recovery path. Retention prunes decided and resolved
rows after 30 days measured from when the row left the queue, never from
creation, and never touches a pending row or a live deferral.

Nothing calls any of this yet.

Part of spec-ca-2-approval-queue.md, slice 1.
Registers the reconciler on the container-report, container-removed and
update-applied/failed listeners, so a row appears for every candidate the manual
Update button would accept and leaves when it stops being one. The ledger is
derived state: every cycle re-answers the predicate and makes the stored rows
agree with the answer, which is what makes it idempotent rather than a
changed-flag heuristic.

`shouldQueueForApproval` now derives from a `classifyApprovalCandidate` verdict,
because the reconciler needs the reason as well as the answer. No candidate
withdraws a row, a hard blocker leaves it alone, an auto resolution retires it.
One pass also settles a case the boolean could not express: a container that is
both hard-blocked and auto-resolved reads as blocked, because the auto path
cannot apply it either, and calling it auto-dispatchable would resolve a live row
as `auto-applied` for an update that never runs.

A newer candidate supersedes the row it replaces whatever the new candidate's own
fate is, so an operator is never asked to approve a version that is no longer on
offer. Decided rows are never touched: an approved row points at a running
operation and a rejected row is a recorded answer.

Controller-owned by construction. `init()` runs only in the controller branch of
the entrypoint and nothing under `app/agent` touches the approval store. An
agent's own containers do reach these listeners, which is the point, but only
through `processAuthoritativeContainers`, which drops a container the agent does
not own before it emits anything, so an agent can never mint a row for someone
else's container and can never decide or resolve any row. Every listener is
failure-isolated, because the update lifecycle awaits the same emit chain.

Part of spec-ca-2-approval-queue.md, slice 2.
Three read-only routes under `/api/v1/approvals`: a filtered list with the house
envelope, a `/summary` counts endpoint for the badge, and `/:id` for one row.
`/summary` is registered before `/:id` so Express does not read it as an id.

`/:id` recomputes eligibility from the live container rather than replaying what
was stored at sight time, and returns the soft blockers as the row's hold
reasons. Recomputing is the point: the row is a pointer at a candidate, and a
stored snapshot would let the queue tell an operator something the container
panel contradicts. That means `buildEligibilityContext` had to come out of
`sse-container-enrichment.ts` as an export, so both surfaces answer from the same
context instead of two that drift. When the container is gone the eligibility
block is omitted rather than faked, and the row stays readable.

The two SSE events go out on a new ordered-bus event carrying five scalars, not a
container projection. `app/approvals` stays out of `app/api`: the reconciler
emits `emitApprovalEvent`, and `sse.ts` translates the kind into the wire name.
That indirection is worth a hop because the DR-4 disconnect came from a fat
payload, and a projection is the thing that grows a vulnerability array later
without anyone noticing. Slice 4 adds `decided` to the kind union and nothing
else moves.

No decision routes, no audit actions yet. The three audit actions in the spec
describe decisions, and a locale sweep plus new Prometheus label values for
actions nothing emits would be dead weight until slice 4 has something to record.

`reconcileContainer`, `APPROVAL_RETENTION_DAYS` and `ApprovalUpdateKind` lose
their `export` here: knip is right that nothing outside their own file reads
them, and slice 4 can export what it actually needs.

Part of spec-ca-2-approval-queue.md, slice 3.
Adds the compare-and-set the decision API needs. `decideApprovalIfPending` writes a
patch only while the row is semantically pending — `pending`, or `deferred` with an
absent, unparseable or expired `deferredUntil` — and reports which of the three it
found, so a caller can tell a missing row from one somebody already decided.

A read-then-await-then-write handler would let two operators both pass the read and
have the second update fail later on the active-operation gate, with a message about
queued operations rather than about the queue. Reserving before anything is awaited
means the loser is told the truth.

`resetApprovalToPending` is the other half: a patch copies only the fields a caller
names and has no way to spell "unset", which is right for a decision and useless for
a reservation whose work was refused. It clears the five decision fields outright, so
a rolled-back approve leaves a row indistinguishable from one nobody touched.

Part of spec-ca-2-approval-queue.md, slice 4.
Pulls `POST /containers/:id/update`'s body out into a module both it and the approval
queue can call, because approving a queued row has to answer exactly what the Update
button answers for the same container in the same state.

Written as a second copy in the approvals router it would agree on the day it was
written and drift the first time one of them gained a case — a new hard blocker, a
different status for an existing one. Sharing the admission call, the
`UpdateRequestError` translation and the response shape makes that parity structural
instead of asserted, and leaves the paired tests to prove the two endpoints agree
rather than to hold them together.

The dispatcher returns its outcome rather than writing the response, because the queue
has a row to stamp with the operation id and an audit entry to record before anything
goes out, and reconstructing the status codes at that call site is the drift this
exists to prevent. No behaviour moves: the feature gate, the 404, the accepted body and
every rejection are the same values in the same order.

Part of spec-ca-2-approval-queue.md, slice 4.
… request

Rejecting a queued update writes the container's existing skip policy and deferring one
writes its existing snooze — decision 7 of the spec, and the reason the queue adds no
new suppression field and no new precedence rule against `skipTags`. Both of those
already exist behind `PATCH /containers/:id/update-policy`, wrapped in request and
response handling the approval router has no use for.

The action application splits out of the PATCH handler unchanged: same layered-override
branch, same normalization, same override audit entries, same client-safe error
classification. The handler is now the HTTP shell around it. `resolveSnoozeUntilFromPayload`
comes out too, because defer has to know the expiry before it reserves the row and the
row's `deferredUntil` has to be the value the container's `snoozeUntil` ends up holding.

The wiring moves to `update-policy-writer.ts` so there is one instance rather than two
sets of collaborators that agree by coincidence. That is what makes "rejecting an update
is the same operation as the Skip button" a fact about the code instead of a claim in a
doc.

Part of spec-ca-2-approval-queue.md, slice 4.
…ctions

`dd:approval-decided` is its own wire name rather than a reuse of
`dd:approval-resolved`, because the two mean different things to a queue view: decided
is an operator answering, resolved is a row leaving without one. Same five scalars, same
256 KB argument.

The announce call moves out of the reconciler into `approvals/events.ts`, because the
decision API is now the ledger's second writer and both have to read the badge count
after their own store write. Two announce sites would be two chances to send a stale
count, or to send a payload with a container on it.

`update-approved`, `update-rejected` and `update-deferred` join the audit action union.
The union is wider than it looks — the AuditView filter, its labels in 17 locales and
the Prometheus label set all consume it — but the label set is dynamic and the view's
filter list has never been exhaustive, so the locale sweep lands with the view in slice 5
rather than adding filter entries for actions no view can yet reach.

Part of spec-ca-2-approval-queue.md, slice 4.
Three decisions, each a wrapper over a primitive that already exists. Approve dispatches
through the same admission call `POST /containers/:id/update` makes, so it inherits every
rejection that endpoint has and invents none: under `updateMode: notify` it returns the
existing 409 and dispatches nothing, and a container whose last attempt rolled back
returns that blocker's own message rather than a generic error. Admission is re-evaluated
at decision time, so the row is a pointer at a candidate and never a capability — there is
no window between sighting and approval. Reject writes the container's existing skip
policy, which is the same operation as the detail panel's Skip button. Defer writes its
existing snooze and mirrors the expiry onto the row, so the queue and the `snoozed` soft
blocker cannot disagree about when the hold ends.

Every decision reserves the row first, with a compare-and-set taken before anything is
awaited. That is what makes two concurrent approves produce one operation and one 409
instead of two accepted requests whose second update fails later on the active-operation
gate, talking about queued operations rather than about the queue. A reservation whose
work is then refused is rolled back whole, so a decision that did not take effect leaves
no trace and the row's time-in-queue still reads true.

One audit entry per decision that stood, carrying the actor, the approval and container
ids, the decision, the note, and the operation id when there is one. The audit entry is
the permanent record — rows are pruned 30 days after they leave the queue — so a
reservation that was rolled back records nothing, because it decided nothing.

The parity test is the release gate. It drives both handlers in one file against one
admission double and compares the two responses to each other rather than to a literal,
because a test pinning each side to its own expected string would keep passing the day one
of them gained a case the other did not.

Bulk decisions (`POST /approvals/bulk`) are not here.

Part of spec-ca-2-approval-queue.md, slice 4.
Extends the queue's Unreleased entry to describe approve, reject and defer, the
compare-and-set behind a double approve, and the audit entry each decision leaves.

Part of spec-ca-2-approval-queue.md, slice 4.
Knip is right: the accepted-update message and the policy write result type are read
only inside the modules that declare them.
A row names one candidate, but the container it points at is rewritten by every
watch cycle. Between the sighting that minted the row and the click that decides
it the watcher can have stored a newer candidate, and the decision handlers read
the container rather than the row: approve dispatched the new version while the
row and the audit entry named the old one, reject skipped the wrong version, and
defer snoozed the wrong one. Reserving first made it worse, because a reserved
row is no longer open and the reconciler will not supersede it.

Compare the row's candidateRef against the container's live candidate, through
the same getApprovalCandidateRef the row was minted with, and refuse a mismatch
with 409 rather than reserving. The row is left open on purpose: the reconciler
owns resolution and supersedes it on the same report that minted its
replacement.

The reservation now happens after the row, container and candidate checks, so a
refused decision writes nothing at all and has nothing to roll back. Nothing
between the first read and the compare-and-set yields, so it is still the last
thing that happens before an approve awaits the admission path.

The parity test now inspects the candidate each path handed to
requestContainerUpdate, not just the status code and body it answered with.
Two bugs with one cause: a patch only carries the fields its caller named, and
both the decision write and the rollback treated that as the whole row.

decideApprovalIfPending overlaid the patch, so re-deciding an expired deferral
kept the lapsed decision's note and deferredUntil. The approve that followed a
defer carried 'after the freeze' into its audit entry, a reason that operator
never typed. Clear every decision field before applying the patch.

resetApprovalToPending blanked the row to pending, which is only correct when
the reservation replaced a pending row. An expired deferral is semantically
pending and can be reserved, so a rolled-back approve over one destroyed who
deferred it, when, why and until when. Replaced with restoreApproval, which puts
back the snapshot the reservation replaced; the API captures that snapshot when
it reads the row, which it now does before reserving anyway.
The handlers took what the primitives underneath happened to take, which was a
long way from what the OpenAPI document publishes. days: 0.5 became a twelve-hour
hold, days: '7' was coerced, until: '2026-09-09' meant midnight in whatever zone
the process runs in, until in the past wrote a deferral that had already expired,
note: null passed as no note, a scalar body was read as an empty object, and any
property the route does not read was ignored in silence. POST /defer with
snoozeUntil answered 200 and deferred by the default seven days.

Validate the shape in the handler: an object, no properties the route does not
read, a string note, a day count that is an integer in 1..365, an until that is a
full RFC 3339 instant in the future and inside the same one-year ceiling the day
count has. The expiry is normalized to UTC before it is written, so the row's
deferredUntil and the container's snoozeUntil compare equal as strings rather
than merely meaning the same instant.

Defer no longer routes its parsing through resolveSnoozeUntilFromPayload, which
was added for it on this branch and now has no caller, so it goes.
The approval payload names its five fields instead of stripping a container, which
keeps a vulnerability array off the wire but does nothing about the two fields it
does keep. Neither container id nor container name carries a maximum length in
the schema and an agent supplies both, so a long enough value pushes the frame
past the 256 KB pending-byte cap, disconnects a backpressured client, and does it
again when the replay ring hands the same frame back.

Truncate both at 256 characters, past any Docker id or human-typed name. The
row's own id stays whole: it is a generated UUID and the key a client uses to
fetch the row.
@vercel

vercel Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
drydock-website Ready Ready Preview Sep 3, 2026 5:03am UTC
drydockdemo-website Ready Ready Preview Sep 3, 2026 5:03am UTC

@scttbnsn

scttbnsn commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

Review Change Stack

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • CHANGELOG.md is excluded by !CHANGELOG.md

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Team

Run ID: cdeb122d-adb9-4d5a-9f37-adaa68dd5995

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Team

Run ID: d78b1d0e-2412-40f8-878f-080e0a4deeb0

📥 Commits

Reviewing files that changed from the base of the PR and between 88999f6 and b4dc80f.

⛔ Files ignored due to path filters (1)
  • CHANGELOG.md is excluded by !CHANGELOG.md
📒 Files selected for processing (31)
  • app/api/api.test.ts
  • app/api/api.ts
  • app/api/approvals.test.ts
  • app/api/approvals.ts
  • app/api/approvals.update-parity.test.ts
  • app/api/container-actions.ts
  • app/api/container-update-dispatch.ts
  • app/api/container.ts
  • app/api/container/update-policy-writer.ts
  • app/api/container/update-policy.ts
  • app/api/openapi/paths/approvals.ts
  • app/api/openapi/paths/index.ts
  • app/api/openapi/schemas.ts
  • app/api/sse-container-enrichment.ts
  • app/api/sse.lifecycle-events.test.ts
  • app/api/sse.test.ts
  • app/api/sse.ts
  • app/approvals/events.ts
  • app/approvals/reconcile.test.ts
  • app/approvals/reconcile.ts
  • app/event/index.test.ts
  • app/event/index.ts
  • app/index.test.ts
  • app/index.ts
  • app/model/approval.test.ts
  • app/model/approval.ts
  • app/model/audit.d.ts
  • app/store/approval.test.ts
  • app/store/approval.ts
  • app/store/index.test.ts
  • app/store/index.ts

Included review availability: Your plan provides up to 2 included reviews per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

Adds a controller-owned approval queue with derived candidate classification, a LokiJS ledger, reconciliation, retention, and lifecycle events. Adds authenticated list, summary, detail, approve, reject, and defer API routes with validation and OpenAPI contracts. Reuses shared manual update dispatch and policy-writing paths. Adds bounded SSE broadcasts for approval transitions and initializes reconciliation only in controller mode.

Suggested labels: second-opinion

Merge Risk: ⚪ Minimal · up to b4dc8

The approval queue is mergeable with no demonstrated material defect remaining.

🚥 Pre-merge checks | ✅ 2
✅ Passed checks (2 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/v1.8-approval-queue

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai

coderabbitai Bot commented Sep 3, 2026

Copy link
Copy Markdown

Rate Limit Exceeded

@scttbnsn have exceeded the limit for the number of chat messages per hour. Please wait 15 minutes and 11 seconds before sending another message.

@github-actions

github-actions Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

@greptileai Review exact head b4dc80fae63be0d101eca2a391bb9e0f37416064. Review for correctness, security issues, and cross-file regressions.

@codecov

codecov Bot commented Sep 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@biggest-littlest biggest-littlest left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed the diff and the CI run, approving.

@ALARGECOMPANY ALARGECOMPANY left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed the diff and the CI run, approving.

@scttbnsn
scttbnsn merged commit 15718e0 into dev/v1.8 Sep 3, 2026
54 of 56 checks passed
@scttbnsn
scttbnsn deleted the feat/v1.8-approval-queue branch September 3, 2026 05:37

This branch was successfully deployed

2 active deployments
Preview – drydockdemo-website — 11c491f4 Deployed Sep 3, 2026 by vercel[bot]
Preview – drydock-website — 11c491f4 Deployed Sep 3, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

second-opinion Summon Greptile for a second-opinion review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants