Skip to content

Add disabled Context accounting fixtures with strict CI coverage - #1254

Merged
sswiftdrtv merged 9 commits into
mainfrom
codex/context-accounting-strict-ci
Nov 17, 2026
Merged

sswiftdrtv merged 9 commits into
mainfrom
codex/context-accounting-strict-ci

Conversation

@sidneyswift

@sidneyswift sidneyswift commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Problem and behavior

Context request/pilot accounting needs admission ceilings and replay-safe reservation handling. This isolated successor of #1250 carries its disabled, dependency-injected adapter and 36 offline fixtures, composes current main (10fce9198fc4bacf184405e7792563fec90f7496) through a normal merge, and closes review comment 4604591480 by adding ongoing strict type coverage.

The separate Context Accounting Strict Types workflow runs on pull requests to main and pushes to main. It follows the repository Node22/pnpm9 setup and directly runs pnpm exec tsc --noEmit --project tsconfig.context-accounting.json, including negative assertions for Promise-returning and value-or-Promise transaction callbacks. No package.json, existing test workflow, lockfile, or runtime accounting code changes were made relative to the composed candidate. README now describes the automated gate. The fixture transaction method also enforces the synchronous callback constraint directly, rejects thenables before committing draft changes, and consumes late rejections. Direct compile regressions, rollback/queue-continuation tests, a bounded reuse assertion and a specific billing rejection assertion cover the four reviewed quality findings; a comment clarifies the zero-credit validation placeholder without changing billing.

Original #1250 and its sealed evidence remain unchanged. This PR is the reviewable successor, not a second rollout. No production caller, wallet, provider, policy, migration or activation is added. This remains a partial fixture-only contribution toward recoupable/app#2123; the shared reservation composition and intended-account acceptance gates remain separately owned.

Validation

  • Strict source/fixture checker and all 36 accounting tests pass on the hardening delta. The 21 incoming Sites repair tests passed at main composition; their source is unchanged.
  • Negative proof: removing the callback restriction in a temporary source copy fails with both unused expected-error diagnostics, demonstrating that the checker catches regression of the synchronous contract.
  • Workflow/README formatting and whitespace checks pass.
  • Independent review passed for hardening head 9929d685ba8784f6b7529bb4893527eea7f2e1f7, retaining the normal main composition. All exact-head required checks passed, including the strict callback checker and full test workflow. Automated delta review found zero new issues; prior review threads remain for human disposition.

Merge remains held for explicit approval.


Summary by cubic

Adds a disabled, dependency-injected context accounting adapter with 32 offline fixtures, plus a dedicated strict type-checking CI workflow, without wiring it into any production path.

The adapter stays fixture-only: no production caller, wallet, provider, policy, migration, or activation is added, and all services and ceilings must be supplied.

Behavior covered

  • Enforces admission ceilings per request and pilot with payer-partitioned ledger isolation and replay-safe settlement/release.
  • Reused reservations never authorize dispatch; lost or ambiguous replies retain maximum exposure without auto-release or redispatch.
  • Cancellation before durable dispatch intent releases the hold; cancellation after intent never refunds potentially paid work.
  • Zero-customer-charge completions release the reservation instead of settling zero, and billing: "endpoint_owned" is rejected.

CI gate

  • New Context Accounting Strict Types workflow runs tsc --noEmit on tsconfig.context-accounting.json for PRs and pushes to main.
  • Negative assertions verify transaction callbacks must be synchronous and that async callbacks never commit draft mutations; removing the restriction fails the build.
  • No package.json, lockfile, or runtime accounting changes; existing CI continues to execute the fixtures.

Written for commit 9929d68. Summary will update on new commits.

View guided diff Turn on auto-fix

Coordinator source disposition

Recoup OS accepts exact 9929d685ba8784f6b7529bb4893527eea7f2e1f7 as a disabled, unwired accounting contract and its strict CI gate. The synchronous fixture boundary, bounded wait and specific validation regressions are fixed and independently reviewed; exact-head required checks pass. No production route, workflow or provider imports this consumer.

The remaining suggestions are non-blocking in this scope: UUID syntax is followed by required injected payer authorization before admission, so accepting UUID sentinels does not establish an authorization bypass; cohesive phase orchestration has no verified universal 100-line cap; current terminal projections and reservation patterns agree and their behavior is regression-covered. No live identity policy or broad refactor is silently adopted. Before wiring, actual authenticated attribution, durable storage, approved policy, reservation composition and reconciliation must be qualified. This source release supplies none of those runtime prerequisites and does not close the owning epic.

@vercel

vercel Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

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

Project Deployment Actions Updated
api Ready Ready Preview Nov 17, 2026 8:16pm UTC

Request Review

@coderabbitai

coderabbitai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Pre-merge checks: Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Solid & Clean Code Warning Summary: The PR adds 12 new files under lib/context/accounting at head 9929d685ba8784f6b7529bb4893527eea7f2e1f7. The current code still breaks the stated SOLID and Clean Code criteria. The pri… Refactor before merge. Keep behavior unchanged and keep the existing fixtures passing. 1. Split runContextAccountingAttempt into named step functions. Use one function per file, named after the function. Cover prior-attempt resolution, ad…
Full details: Solid & Clean Code

Explanation

Summary: The PR adds 12 new files under lib/context/accounting at head 9929d685ba8784f6b7529bb4893527eea7f2e1f7. The current code still breaks the stated SOLID and Clean Code criteria. The prior FAIL claims hold. I checked each one against the current files. SRP and function length (criterion: functions over 20 lines, one job per function) - runContextAccountingAttempt spans runContextAccountingAttempt.ts lines 11–112, about 102 lines. It handles input validation, authorization, prior-attempt lookup, reuse lookup, admission, reservation, the dispatch-intent transition, dispatch, completion, and settlement. - finishContextAccountingAttempt.ts spans lines 4–69. It handles release, settlement, two receipt schemas, the ledger phase update, and error handling in one function. - Both functions have multiple responsibilities. Both break the 20-line guidance by a wide margin. Nesting (criterion: max 3 levels) - runContextAccountingAttempt nests an inner try at line 80 inside the outer try at line 57. An if at line 65 and another at line 73 sit inside the outer try. DRY and repeated values (criterion: constants for repeated values, shared modules) - The terminal-phase list ["settled", "released", "insufficient", "reused"] appears in runContextAccountingAttempt.ts (lines 25, 51) and reconcileContextAccountingAttempt.ts (line 19). No shared constant exists. - The reservation-ID regex /^hold-v1-[a-f0-9]{64}$/ appears in validateContextReservationReceipt.ts (lines 8, 14), finishContextAccountingAttempt.ts (lines 19, 34), and runContextAccountingAttempt.ts (line 76). - The ledger.attempts.get(operationKey)! pattern appears in runContextAccountingAttempt.ts (lines 68, 86, 101) and finishContextAccountingAttempt.ts (line 56). Clean code - validateContextAccountingCompletion.ts line 31 uses completion.customerCredits || 1. A comment documents it. The fallback stays implicit. - finishContextAccountingAttempt.ts uses completion! at lines 43, 44, 50, 51. The type is not narrowed first. What complies - Each new file exports one named function, and the file name matches it. - types.ts holds types only. - Dependencies arrive through the injected ContextAccountingServices interface. Assessment of the PR's rebuttal - The coordinator note says the phase orchestration has no verified universal 100-line cap. The check does not require a universal cap. It states a function-length heuristic of 20 lines. The check also requires DRY and constants for repeated values. The commit 9929d685 adds fixtures and tests. It does not split the long functions or remove the duplicated literals. Verdict basis: The new code in this PR violates the explicit SRP, function-length, nesting, DRY, and constants criteria. The violations come from the PR's own added files, so they are causally tied to this PR.

Resolution

Refactor before merge. Keep behavior unchanged and keep the existing fixtures passing. 1. Split runContextAccountingAttempt into named step functions. Use one function per file, named after the function. Cover prior-attempt resolution, admission, reservation, the dispatch-intent transition, dispatch and completion, and settlement. Keep the orchestrator short. Remove the nested try. 2. Split finishContextAccountingAttempt into releaseContextAccountingAttempt and settleContextAccountingAttempt. Put a small dispatcher in front of them. Move the receipt schemas into their own modules. 3. Add a TERMINAL_CONTEXT_PHASES constant. Use it at every call site, including reconcileContextAccountingAttempt.ts. Add one reservation-ID schema and use it at every call site. Add a helper such as getAttemptOrThrow(ledger, operationKey) to replace the repeated ! lookups. 4. Keep the documented customerCredits || 1 placeholder, or replace it with explicit handling for a waived completion. Remove the completion! assertions by narrowing the type first. 5. Keep each new function under about 20 lines. 6. Re-run pnpm exec tsc --noEmit --project tsconfig.context-accounting.json and vitest run lib/context/accounting after the refactor.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

4 issues found across 14 files

Confidence score: 4/5

  • validateContextAccountingInput.ts accepts the nil and max UUIDs as payerId, even though they are sentinel values rather than authenticated payers. Reject those values so they cannot be used as payer IDs.
  • runContextAccountingAttempt.ts is 112 lines, over the stated 100-line limit. Extract the attempt phases into focused helpers.
  • reconcileContextAccountingAttempt.ts duplicates the terminal-result projection from runContextAccountingAttempt.ts, which risks the two paths drifting. Extract a shared helper and use it in both places.
  • The hold-v1- reservation ID pattern is repeated in validateContextReservationReceipt.ts and other files, so the pinned format could drift. Define a shared schema and reuse it, including in finishContextAccountingAttempt.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="lib/context/accounting/validateContextReservationReceipt.ts">

<violation number="1" location="lib/context/accounting/validateContextReservationReceipt.ts:8">
P3: The `hold-v1-` reservation-ID pattern is now repeated across several files. Extract one shared schema (for example `reservationIdSchema`) and reuse it here and in `finishContextAccountingAttempt`, so the pinned format has a single source of truth.</violation>
</file>

<file name="lib/context/accounting/validateContextAccountingInput.ts">

<violation number="1" location="lib/context/accounting/validateContextAccountingInput.ts:10">
P3: `z.uuid()` accepts the nil UUID `00000000-0000-0000-0000-000000000000` and the max UUID `ffffffff-ffff-ffff-ffff-ffffffffffff` as `payerId`. Those are sentinel values, not authenticated payers, and they would become a shared ledger partition and wallet account key. Reject them explicitly in the payer schema.</violation>
</file>

<file name="lib/context/accounting/runContextAccountingAttempt.ts">

<violation number="1" location="lib/context/accounting/runContextAccountingAttempt.ts:11">
P2: Custom agent: **Enforce Clear Code Style and Maintainability Practices**

This 112-line module exceeds the rule’s under-100-line limit. Extract the attempt phases into focused helpers so the file stays below the cap.</violation>
</file>

<file name="lib/context/accounting/reconcileContextAccountingAttempt.ts">

<violation number="1" location="lib/context/accounting/reconcileContextAccountingAttempt.ts:19">
P3: This terminal-phase mapping and reused-result shape duplicate the `if (prior)` branch in `runContextAccountingAttempt`. Extract one shared helper for the terminal-result projection and call it from both places, so a future phase change cannot update only one path.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant CI as CI Workflow
    participant TS as tsc (Strict Types)
    participant Tests as Vitest Fixtures
    participant Fixture as Accounting Fixture
    participant Adapter as Context Accounting Adapter
    participant Services as Injected Services
    participant Ledger as Payer Ledger
    participant Wallet as Credit Wallet (Mock)

    Note over CI,TS: NEW: Strict Type Checking Gate
    CI->>TS: pnpm exec tsc --noEmit (context-accounting)
    TS-->>CI: Type check result
    CI->>Tests: pnpm exec vitest run lib/context/accounting
    Tests->>Fixture: Create test fixture
    Fixture->>Adapter: runContextAccountingAttempt(input)
    Adapter->>Services: authorize(input)
    Services-->>Adapter: OK
    Adapter->>Ledger: transact(payerId, check prior attempt)
    Ledger-->>Adapter: No prior attempt
    Adapter->>Services: findAcceptedReuse(input)
    Services-->>Adapter: null (no reuse)
    Adapter->>Ledger: transact(payerId, admitContextAccountingAttempt)
    Ledger->>Ledger: Check request/pilot ceilings
    Ledger-->>Adapter: Admitted (created: true)
    Adapter->>Services: reserveCreditsOnce({operationKey})
    Services->>Wallet: Reserve credits
    Wallet-->>Services: Reservation held
    Services-->>Adapter: Reservation receipt (held)
    Adapter->>Services: authorize(input) - recheck
    Services-->>Adapter: OK
    Adapter->>Ledger: transact(payerId, set phase to dispatching)
    Ledger-->>Adapter: Attempt dispatching
    Adapter->>Services: dispatch(input)
    Services-->>Adapter: Completion (0-4 credits)
    Adapter->>Ledger: transact(payerId, set completed)
    Ledger-->>Adapter: Attempt completed
    Adapter->>Services: settleCreditReservation or releaseCreditReservation
    Services->>Wallet: Settle/release hold
    Wallet-->>Services: Receipt
    Services-->>Adapter: Updated state
    Adapter-->>Fixture: Final state (settled/released/pending)
    
    Note over Adapter,Services: Error/Reconciliation Path
    Adapter->>Services: reserveCreditsOnce fails or ambiguous
    Services-->>Adapter: Error or reused hold
    Adapter->>Ledger: Keep phase admitted/pending
    Adapter-->>Fixture: pending_reconciliation (full exposure retained)
    
    Note over Fixture,Wallet: Reconciliation (separate entry point)
    Tests->>Fixture: reconcileContextAccountingAttempt(input)
    Fixture->>Adapter: Reconcile attempt
    Adapter->>Ledger: Check attempt state
    Ledger-->>Adapter: Found (completed/cancelled)
    Adapter->>Services: finishContextAccountingAttempt
    Services->>Wallet: Settle or release
    Wallet-->>Services: Receipt
    Services-->>Adapter: State updated
    Adapter-->>Fixture: Final reconciled state
Loading

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

import type { ContextAccountingServices } from "./types";

/** Disabled consumer: all effects injected; no production caller, wallet, provider or policy defaults. */
export async function runContextAccountingAttempt(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: Custom agent: Enforce Clear Code Style and Maintainability Practices

This 112-line module exceeds the rule’s under-100-line limit. Extract the attempt phases into focused helpers so the file stays below the cap.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/context/accounting/runContextAccountingAttempt.ts, line 11:

<comment>This 112-line module exceeds the rule’s under-100-line limit. Extract the attempt phases into focused helpers so the file stays below the cap.</comment>

<file context>
@@ -0,0 +1,112 @@
+import type { ContextAccountingServices } from "./types";
+
+/** Disabled consumer: all effects injected; no production caller, wallet, provider or policy defaults. */
+export async function runContextAccountingAttempt(
+  raw: unknown,
+  services: ContextAccountingServices,
</file context>

.discriminatedUnion("state", [
z.strictObject({
state: z.literal("held"),
reservationId: z.string().regex(/^hold-v1-[a-f0-9]{64}$/),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The hold-v1- reservation-ID pattern is now repeated across several files. Extract one shared schema (for example reservationIdSchema) and reuse it here and in finishContextAccountingAttempt, so the pinned format has a single source of truth.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/context/accounting/validateContextReservationReceipt.ts, line 8:

<comment>The `hold-v1-` reservation-ID pattern is now repeated across several files. Extract one shared schema (for example `reservationIdSchema`) and reuse it here and in `finishContextAccountingAttempt`, so the pinned format has a single source of truth.</comment>

<file context>
@@ -0,0 +1,25 @@
+    .discriminatedUnion("state", [
+      z.strictObject({
+        state: z.literal("held"),
+        reservationId: z.string().regex(/^hold-v1-[a-f0-9]{64}$/),
+        creditsHeld: z.number().int().positive().safe(),
+        spendableCredits: z.number().int().nonnegative().safe(),
</file context>

.strictObject({
mode: z.literal("fixture"),
billing: z.literal("context_owned"),
payerId: z.uuid(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: z.uuid() accepts the nil UUID 00000000-0000-0000-0000-000000000000 and the max UUID ffffffff-ffff-ffff-ffff-ffffffffffff as payerId. Those are sentinel values, not authenticated payers, and they would become a shared ledger partition and wallet account key. Reject them explicitly in the payer schema.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/context/accounting/validateContextAccountingInput.ts, line 10:

<comment>`z.uuid()` accepts the nil UUID `00000000-0000-0000-0000-000000000000` and the max UUID `ffffffff-ffff-ffff-ffff-ffffffffffff` as `payerId`. Those are sentinel values, not authenticated payers, and they would become a shared ledger partition and wallet account key. Reject them explicitly in the payer schema.</comment>

<file context>
@@ -0,0 +1,22 @@
+    .strictObject({
+      mode: z.literal("fixture"),
+      billing: z.literal("context_owned"),
+      payerId: z.uuid(),
+      requestId: id,
+      pilotId: id,
</file context>
Suggested change
payerId: z.uuid(),
payerId: z.uuid().refine(value => !/^(0{8}-0{4}-0{4}-0{4}-0{12}|f{8}-f{4}-f{4}-f{4}-f{12})$/i.test(value), "payerId must not be a sentinel UUID"),

throw new Error("Attempt unavailable or changed");
return structuredClone(current);
});
if (["settled", "released", "insufficient", "reused"].includes(attempt.phase))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: This terminal-phase mapping and reused-result shape duplicate the if (prior) branch in runContextAccountingAttempt. Extract one shared helper for the terminal-result projection and call it from both places, so a future phase change cannot update only one path.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/context/accounting/reconcileContextAccountingAttempt.ts, line 19:

<comment>This terminal-phase mapping and reused-result shape duplicate the `if (prior)` branch in `runContextAccountingAttempt`. Extract one shared helper for the terminal-result projection and call it from both places, so a future phase change cannot update only one path.</comment>

<file context>
@@ -0,0 +1,29 @@
+      throw new Error("Attempt unavailable or changed");
+    return structuredClone(current);
+  });
+  if (["settled", "released", "insufficient", "reused"].includes(attempt.phase))
+    return {
+      state: attempt.phase,
</file context>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

0 issues found across 1 file (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Requires human review: Auto-approval blocked by 8 unresolved issues from previous reviews.

View guided diff | Turn on auto-fix | Re-trigger cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

0 issues found across 3 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Requires human review: Auto-approval blocked by 4 unresolved issues from previous reviews.

View guided diff | Turn on auto-fix | Re-trigger cubic

@sswiftdrtv
sswiftdrtv merged commit 9dd657c into main Nov 17, 2026
8 checks passed

This branch was successfully deployed

1 active deployment
Preview — 9929d685 Deployed Nov 17, 2026 by vercel[bot]
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