Repository navigation
feat(approvals): update approval queue with approve, reject and defer - #960
Conversation
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.
…l-queue # Conflicts: # CHANGELOG.md
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
@coderabbitai review |
|
Important Review skippedReview was skipped due to path filters ⛔ Files ignored due to path filters (1)
CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Team Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Team Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (31)
Included review availability: Your plan provides up to 2 included reviews per hour; 0 remain after this review. 📝 WalkthroughWalkthroughAdds 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: Merge Risk: ⚪ Minimal · up to The approval queue is mergeable with no demonstrated material defect remaining. 🚥 Pre-merge checks | ✅ 2✅ Passed checks (2 passed)
✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
Rate Limit Exceeded
|
|
@greptileai Review exact head |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
biggest-littlest
left a comment
There was a problem hiding this comment.
Reviewed the diff and the CI run, approving.
ALARGECOMPANY
left a comment
There was a problem hiding this comment.
Reviewed the diff and the CI run, approving.
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:
classifyApprovalCandidatesorts 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.GET /api/v1/approvals,/summary,/:id, withdd:approval-createdanddd:approval-resolvedSSE frames.POST /api/v1/approvals/:id/approve|reject|defer. Approve reserves the row with a compare-and-swap, then runs the exact code pathPOST /containers/:id/updateruns (extracted intocontainer-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 add:approval-decidedSSE frame.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
/api/v1/approvalsroutes.Concerns
app/index.tsimport path. The summary reports./approotions/reconcile.js, which appears to be a typo for./approvals/reconcile.js.