Skip to content

feat(decisioning): ProposalManager v1.5 + mock recipes + canonical proposal-mode adapter - #1557

Merged
bokelley merged 10 commits into
mainfrom
bokelley/proposal-manager
May 4, 2026
Merged

bokelley merged 10 commits into
mainfrom
bokelley/proposal-manager

Conversation

@bokelley

@bokelley bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor

Summary

Ports adcp-client-python PRs #504 + #538 + #550 (ProposalManager v1.5 — primitives + lifecycle helpers + dispatch wiring) and validates the design against an actual adopter shape via a new hello_seller_adapter_proposal_mode.ts reference. Three commits, four changesets.

What lands

1. ProposalManager v1.5 primitives + dispatch wiring (src/lib/server/decisioning/proposal/)

  • ProposalManager<TRecipe, TCtxMeta> interface with getProducts (required) + capability-gated refineProducts / finalizeProposal. Wired as DecisioningPlatform.proposalManager?.
  • Recipe typed-discriminator base + CapabilityOverlap (4 axes: pricingModels, targetingDimensions, deliveryTypes, signalTypes).
  • ProposalStore<TRecipe> interface + InMemoryProposalStore reference impl with the four-state machine draft → committed → consuming → consumed, reverse-index by (accountId, mediaBuyId), lazy TTL eviction with injectable clock, cross-tenant defense.
  • MockProposalManager — fetch-based forwarder for adopters who don't yet have proposal logic of their own.
  • enforceProposalExpiry, validateCapabilityOverlap, validateOverlapSubsetOfWire, detectFinalizeAction lifecycle helpers + structured-log emitters.
  • Five framework dispatch seams wired into runtime/from-platform.ts: maybeInterceptFinalize, maybePersistDraftAfterGetProducts, maybeReserveProposalForCreateMediaBuy, finalizeProposalConsumption, releaseProposalReservation, maybeHydrateRecipesForMediaBuyId.
  • New proposalStore? opt on createAdcpServerFromPlatform. RequestContext.recipes field — framework writes it before the adapter runs.
  • 96 new tests (39 primitives + 47 lifecycle + 5 e2e via dispatchTestRequest + 5 mock-server lifecycle). Full lib suite: 6154/6154 pre-existing tests green.
  • Stub pre-v6 ProposalManager class deleted (no observable behavior; isSupported() === false everywhere). Breaking — major changeset.
  • HITL TaskHandoff[FinalizeProposalSuccess] commit hook deferred to v1.6+ (rejects with INTERNAL_ERROR for now).

2. Canonical mock-server recipes + sales-guaranteed proposal lifecycle (src/lib/mock-server/)

  • GAMLikeRecipe { recipe_kind: 'gam', network_code, ad_unit_ids[], line_item_priority, pricing, delivery_type, availability_window?, min_spend?, upstream_ids? } + GAM_LIKE_OVERLAP + buildGAMLikeRecipe(mockProduct) — re-exported from @adcp/sdk/mock-server for hello adapters wrapping the sales-guaranteed mock.
  • KevelLikeRecipe { recipe_kind: 'kevel', network_code, zone_ids[], weight, pricing: { floor_cpm, target_cpm? }, goal_type, min_spend?, upstream_ids? } — auction-cleared remnant counterpart for sales-non-guaranteed.
  • New sales-guaranteed mock-server endpoints: POST /v1/proposals (draft creation w/ even allocation across guaranteed products), GET /v1/proposals/{id}, POST /v1/proposals/{id}/refine (allocation overrides + free-text steering, draft-only), POST /v1/proposals/{id}/finalize (lock pricing, allocate upstream_line_item_template_id, 24h hold, idempotent).

3. Reference adapter: hello_seller_adapter_proposal_mode.ts (~550 LOC)

  • Wraps the new mock-server proposal endpoints. proposalManager curates drafts, refines, finalizes; sales.createMediaBuy reads ctx.recipes (hydrated by the framework) to drive line-item creation off recipe.upstream_ids.line_item_template_id.
  • Smoke-tested end-to-end: brief → draft (3 allocations) → refine ("shift more to ctv" biases mix) → finalize (status=committed, expires_at populated, locked CPM, line-item template ids allocated) → create_media_buy(proposal_id) → upstream order + 2 line items per recipe.
  • 549 LOC vs. 1213 LOC for the existing direct-buy hello_seller_adapter_guaranteed.ts — even though the new adapter covers the full proposal lifecycle which the existing one doesn't have. The framework absorbs the ceremony; adopters write business logic against typed recipes.
  • Three-gate CI suite passes (strict tsc, storyboard, façade upstream-traffic).

Real bugs surfaced + fixed by validation play

  • Per-product capability overlap derivation: static platform-wide overlap constants don't pass validateOverlapSubsetOfWire. A CPM-only product can't carry an overlap claiming cpv and cpcv. buildGAMLikeRecipe / buildKevelLikeRecipe now derive pricingModels and deliveryTypes from each product's actual wire shape.
  • Lowercase pricing-model literals ('cpm', 'cpv', 'cpcv') match the AdCP wire enum. Caught the case-sensitivity mismatch before adopters hit it.
  • Strict tsc catches real bugs: AccountReference is a discriminated union, Product/Proposal not re-exported from @adcp/sdk/types, CreateMediaBuySuccess has no buyer_ref / package status, UpdateMediaBuy signature is (buyId, patch, ctx) not (req, ctx), DeliveryMetrics.spend is a number, reporting_period uses {start, end}, DecisioningCapabilities requires config. All silent under the lenient project tsconfig; the strict adapter-test gate caught them.

Storyboard CI gate result

media_buy_seller/proposal_finalize storyboard: 4/5 phases pass (setup, brief_with_proposals, finalize_proposal, accept_proposal). One allowlisted failure on refine_proposal traces to a spec-side gap: the scenario yaml doesn't declare context_outputs / context_inputs to chain the seller-minted proposal_id from brief_with_proposals into the refine step — the runner sends the literal placeholder balanced_reach_q2. Smoke tests confirm the lifecycle works when a real buyer threads the prior proposal_id. Spec issue forthcoming on adcontextprotocol/adcp.

Test plan

  • npx tsc --noEmit clean (strict tsc passes for the new adapter)
  • prettier --check clean
  • 96 new lib tests pass + full lib suite green (6154/6154 pre-existing tests, zero regressions)
  • 5 mock-server lifecycle + recipe builder tests pass
  • Three-gate CI suite passes for hello_seller_adapter_proposal_mode (strict tsc, storyboard, façade)
  • Manual smoke test: brief → draft → refine → finalize → create_media_buy(proposal_id) → upstream order with 2 line items keyed off the recipe

Follow-ups (separate branches)

  • Spec issue on adcontextprotocol/adcp: proposal_finalize.yaml scenario needs context_outputs / context_inputs for proposal_id chaining.
  • HITL TaskHandoff[FinalizeProposalSuccess] commit hook (v1.6+).
  • Rebuild hello_seller_adapter_guaranteed.ts around the v1.5 surface — would mostly be deletions if the design holds.

🤖 Generated with Claude Code

bokelley and others added 3 commits May 4, 2026 09:52
…cipes

Three logical pieces, each with its own changeset:

Phase 0+1 — primitives + stub cleanup:
  - Delete the pre-v6 stub `ProposalManager` class (no observable behavior).
  - New `src/lib/server/decisioning/proposal/`: `ProposalManager` interface,
    `Recipe` typed-discriminator base, `CapabilityOverlap`, `ProposalStore` +
    `InMemoryProposalStore` with the four-state machine
    (`draft → committed → consuming → consumed`), `MockProposalManager`
    forwarder. `DecisioningPlatform.proposalManager?` field wired.

Phase 2+3 — lifecycle helpers + dispatch wiring:
  - `proposal/lifecycle.ts`: `enforceProposalExpiry`,
    `validateCapabilityOverlap`, `validateOverlapSubsetOfWire`,
    `detectFinalizeAction`, structured-log helpers.
  - `proposal/dispatch.ts`: five framework seams mirroring Python's
    proposal_dispatch.py (`maybeInterceptFinalize`,
    `maybePersistDraftAfterGetProducts`,
    `maybeReserveProposalForCreateMediaBuy`, `finalizeProposalConsumption`,
    `releaseProposalReservation`, `maybeHydrateRecipesForMediaBuyId`).
  - `runtime/from-platform.ts`: wired the five seams into
    getProducts / createMediaBuy / updateMediaBuy / getMediaBuyDelivery.
    New `proposalStore?` opt on `createAdcpServerFromPlatform`.
    `RequestContext.recipes` field added; framework writes it before
    adapter runs.

Mock-server recipes + proposal lifecycle (the validation play):
  - `GAMLikeRecipe` + `GAM_LIKE_OVERLAP` + `buildGAMLikeRecipe()` for
    `sales-guaranteed` (re-exported from `@adcp/sdk/mock-server`).
  - `KevelLikeRecipe` + `KEVEL_LIKE_OVERLAP` + `buildKevelLikeRecipe()` for
    `sales-non-guaranteed`.
  - sales-guaranteed mock now exposes `POST /v1/proposals` (draft creation),
    `GET /v1/proposals/{id}`, `POST /v1/proposals/{id}/refine` (allocation
    overrides + free-text steering, draft-only), `POST /v1/proposals/{id}/finalize`
    (lock pricing, allocate upstream_line_item_template_id, 24h hold,
    idempotent).

Tests: 140/140 new tests pass (39 primitives + 47 lifecycle + 5 e2e via
dispatchTestRequest + 38 mock-server lifecycle/recipes + 11 existing
sales-guaranteed). Full lib suite green (6154/6154 tests, 0 regressions).
tsc --noEmit clean. prettier --check clean.

HITL `TaskHandoff[FinalizeProposalSuccess]` commit hook deferred to v1.6+.
sales-non-guaranteed recipe published; no draft→committed lifecycle (auction
remnant model). Ports adcp-client-python PRs #504 + #538 + #550 + the
mock-server recipe-publication step that doesn't have a Python equivalent
(Python's mock-server is AdCP-shaped; ours is upstream-shaped, so recipes
are an adapter-side concern we lift to a published canonical shape).

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

Canonical reference for the ProposalManager + DecisioningPlatform two-
platform composition. Wraps the sales-guaranteed mock's proposal-lifecycle
endpoints (added in the previous commit). Smoke-tested end-to-end against
the live mock — full brief → draft → refine → finalize → committed →
accept flow works.

LOC comparison: 549 LOC vs. 1213 LOC for the existing direct-buy
hello_seller_adapter_guaranteed.ts. The v1.5 surface absorbs the lifecycle
ceremony into the framework — adopters write business logic against a
typed recipe instead of hand-rolling state machines.

Lesson surfaced and folded back: capability_overlap pricingModels /
deliveryTypes axes must be derived per-product from the wire shape, not
pulled from a static platform-wide constant. validateOverlapSubsetOfWire
correctly rejects a CPM-only product carrying an overlap claiming cpv +
cpcv. buildGAMLikeRecipe / buildKevelLikeRecipe now derive overlap from
product.pricing.model and product.delivery_type. Lowercase pricing-model
literals (cpm, cpv) match the AdCP wire enum.

Companion CI gate: test/examples/hello-seller-adapter-proposal-mode.test.js
runs the standard three-gate suite (strict tsc, storyboard pass,
façade upstream-traffic check) against media_buy_seller/proposal_finalize.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The strict-tsc gate (target ES2022 + --strict + --noUncheckedIndexedAccess +
--exactOptionalPropertyTypes + --noPropertyAccessFromIndexSignature) caught
real wire-shape bugs the lenient project tsconfig had silently allowed:

- AccountReference is a discriminated union ({account_id} OR {brand,
  operator, sandbox?}) — narrow before reading.
- Product / Proposal not re-exported from @adcp/sdk/types — derive via
  GetProductsResponse['products'][number].
- CreateMediaBuyRequest has no buyer_ref field; CreateMediaBuySuccess
  has no buyer_ref / status on packages.
- UpdateMediaBuy method is `(buyId: string, patch: UpdateMediaBuyRequest, ctx)`,
  not `(req, ctx)`. UpdateMediaBuySuccess has no `packages` field
  (uses `affected_packages?` only).
- DeliveryMetrics.spend is a number, not {amount, currency}.
- reporting_period uses {start, end}, not {start_date, end_date}.
- DecisioningCapabilities requires a `config` field; no `adcp_version`.

Plus: implementation_config rides on Product via cast (the wire schema
doesn't enumerate it; the framework reads it back via cast in the
dispatch helpers).

Storyboard CI gate now wired and passing 3/3 against
media_buy_seller/proposal_finalize:
  - strict tsc: ✓
  - storyboard pass: ✓ (with one allowlisted failure on refine_proposal —
    the `proposal_finalize.yaml` scenario is missing context_outputs /
    context_inputs declarations to chain proposal_id between steps; the
    runner sends the literal `balanced_reach_q2` placeholder. Spec-side
    fix; lifecycle works when a real buyer threads the prior step's id.)
  - façade upstream-traffic: ✓ (brief → draft creation hits all 3
    expected proposal-mode routes)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
bokelley and others added 2 commits May 4, 2026 11:11
Closes the v1.6+ deferral from the original v1.5 dispatch wiring.
Adopters whose finalize logic needs human review can now return
ctx.handoffToTask(fn) from proposalManager.finalizeProposal — the
framework wraps the handoff so:

  - Buyer receives the spec's Submitted envelope immediately.
  - Background task runs via standard TaskRegistry flow.
  - On resolution: framework commits the proposal via
    ProposalStore.commit, emits proposal.finalized log with
    path:'handoff', and projects the wire GetProductsResponse
    (committed proposal) as the task's terminal artifact.
  - On throw: task-registry treats as failed; proposal stays draft
    so the buyer can retry.

FinalizeInterceptResult gains a third arm: { kind: 'handoff',
handoff: TaskHandoff<GetProductsResponse> }. Runtime routes through
routeIfHandoff (same machinery createMediaBuy uses for HITL ad-server
review).

Test coverage: new e2e test exercises the full flow via
dispatchTestRequest — adopter returns ctx.handoffToTask(fn),
framework commits store + emits path:'handoff' log when the
background task resolves.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Surgical change — preserves the agent's direct-buy flow (sales_guaranteed
storyboard) and HITL semantics. Each Product returned by getProducts now
carries a typed `implementation_config: GAMLikeRecipe`, built via the
new `buildGAMLikeRecipe` helper from @adcp/sdk/mock-server.

The recipe is opt-in: direct-buy buyers ignore it; future buyers routing
through proposal-mode (via a different adapter) read the same recipe via
`ctx.recipes` after the framework hydrates from the committed proposal.

Why surgical instead of full rebuild: v1.5's value lands in proposal-mode
adapters — direct-buy adapters don't engage ctx.recipes. The big-LOC-
reduction story for v1.5 is in hello_seller_adapter_proposal_mode.ts
(549 LOC vs. 1213 LOC here, with a +full proposal lifecycle this direct-
buy agent doesn't have). Forcibly threading proposal-mode through this
agent would break the existing storyboard or balloon LOC; this change
demonstrates v1.5 *interoperability* instead.

Verified: existing three-gate CI (strict tsc, sales_guaranteed
storyboard, façade upstream-traffic) passes 3/3 unchanged.

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

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Pushed two follow-up commits to this branch:

feat(decisioning): wire HITL TaskHandoff finalize commit hook — closes the v1.5 deferral. Adopters can now return ctx.handoffToTask(fn) from proposalManager.finalizeProposal; framework wraps the handoff so ProposalStore.commit + proposal.finalized log (with path: 'handoff') fire when the background task resolves. New FinalizeInterceptResult arm { kind: 'handoff', handoff: TaskHandoff<GetProductsResponse> } routed through the existing routeIfHandoff machinery. New e2e test in proposal-manager-e2e.test.js exercises the full HITL flow via dispatchTestRequest.

feat(examples): hello_seller_adapter_guaranteed attaches v1.5 recipes — surgical interop change (~30 LOC). The existing direct-buy guaranteed agent now emits implementation_config: GAMLikeRecipe on each Product via buildGAMLikeRecipe. Direct-buy flow unchanged (sales_guaranteed storyboard still passes 3/3); future proposal-mode buyers routed against this agent's products read the same recipe via ctx.recipes.

Honest framing on the rebuild question: the big LOC-reduction story for v1.5 is in hello_seller_adapter_proposal_mode.ts (549 LOC vs. 1213 LOC for the direct-buy agent — a +full proposal lifecycle the direct-buy agent doesn't have). v1.5 is fundamentally a proposal-mode feature. Direct-buy adapters don't engage ctx.recipes at runtime, so a full rebuild of the guaranteed agent around v1.5 wouldn't shrink it — it would either break the existing storyboard (proposal-mode-only) or balloon LOC (hybrid). The surgical "attach the typed recipe" change demonstrates interop without disrupting today's flow.

Spec issue tracking the runner-side proposal_finalize.yaml context-chaining gap: adcontextprotocol/adcp#4086 — once that lands, the EXPECTED_FAILURES allowlist entry in the proposal-mode adapter's gate test goes away and the storyboard passes 5/5.

@bokelley

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Acknowledged. The HITL TaskHandoff commit hook and the surgical hello_seller_adapter_guaranteed recipe attachment look like the right scope boundary — no further action needed from triage. The rationale on the direct-buy rebuild is clear and the EXPECTED_FAILURES allowlist entry tied to adcp#4086 is a clean audit trail for when the spec-side context_outputs / context_inputs gap closes.


Generated by Claude Code

@bokelley

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Noted — standing by. No triage action on this end.


Triaged by Claude Code. Session: https://claude.ai/code/session_01JPSvkme8vWQPYZBVSU4m3U


Generated by Claude Code

…angeset migration

Addresses four review concerns on PR #1557:

1. Cross-tenant isolation on ProposalStore.get
   `expectedAccountId` was optional on `get`; framework dispatch always
   passed it but adopters reaching into the store directly could read
   across tenants. Tightened the interface to require it. JS callers
   omitting the arg get a TypeError; TS callers fail at compile time.
   The dispatch path already supplies the authenticated principal's
   accountId; no runtime behavior change for the framework path.

   Other read methods (tryReserveConsumption, finalizeConsumption,
   releaseConsumption, getByMediaBuyId) already required
   expectedAccountId. Write paths (commit, markConsumed) follow a
   prior tenant-checked read in the dispatch path; tightening those
   too would be defense-in-depth without a closed gap, deferred.

2. Stub deletion migration guidance
   proposal-manager-primitives.md changeset now spells out the exact
   import diff downstream needs (old `ProposalManager` class →
   new `ProposalManager` interface + `MockProposalManager`), why it
   was a no-op stub, and the error-code mapping replacement.

3. Stale "HITL deferred to v1.6+" text
   proposal-manager-lifecycle.md draft text was authored before HITL
   landed in this same release. Removed the deferral note; pointer
   added to the companion `proposal-manager-hitl-finalize` changeset
   which lands the wrapped-handoff commit path.

4. MockProposalManager fetch polyfill note
   Added a Runtime requirement note in the JSDoc header — Node 18+
   has globalThis.fetch built-in (matches package.json
   "engines": { "node": ">=18.0.0" }); older Node, Bun-without-global,
   and other environments pass an explicit `fetch` impl via the
   constructor option (already typed as such).

Test fallout: ~25 test sites that called `store.get('p1')` without
the tenant arg updated to pass `{ expectedAccountId: 'acct_1' }`. Plus
a new test asserting `store.get` rejects calls without the arg at
runtime — failing closed loudly is the contract.

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

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 70e7017f addressing the review comments:

1. Cross-tenant isolation on ProposalStore.get — real gap, fixed. expectedAccountId was optional; an adopter reaching into the store directly could read across tenants. Now required at the interface level. Framework dispatch path was always passing it correctly; no runtime behavior change for the supported flow. Other read methods (tryReserveConsumption, finalizeConsumption, releaseConsumption, getByMediaBuyId) already required it. The two write paths (commit, markConsumed) follow a prior tenant-checked read in the dispatch — tightening those too would be defense-in-depth without a closed gap, deferred unless we see a use case.

2. Stub deletion migration — proposal-manager-primitives.md now includes the exact import diff downstream needs (old ProposalManager class → new interface + MockProposalManager), the no-op-stub rationale, and the error-code mapping replacement. Adopters who imported the stub names should be able to grep-fix without spelunking.

3. HITL deferral text was stale — the lifecycle changeset's "deferred to v1.6+" line was authored before HITL landed in this same release (commit d57b8f2d — feat(decisioning): wire HITL TaskHandoff finalize commit hook). Updated; pointer added to the proposal-manager-hitl-finalize companion changeset. The committed-state extension question you raised is good — and the answer is: HITL is additive on the same FinalizeProposalSuccess shape (sync returns it directly; HITL returns a TaskHandoff<FinalizeProposalSuccess> and the framework's wrapped handoff commits when it resolves). No separate "v1.6 migration" because both modes share the success shape.

4. MockProposalManager fetch — engines: { node: '>=18.0.0' } so global fetch is built-in. Added a JSDoc Runtime requirement note pointing adopters on older Node / Bun-without-global to the existing fetch constructor option (which was already there but undocumented as the polyfill seam).

5. Spec issue — adcp#4086 already filed; allowlist entry on refine_proposal references it directly.

@bokelley

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Acknowledged — all five points resolved in 70e7017f. Cross-tenant isolation fix, migration docs, HITL lifecycle clarification, fetch runtime note, and the adcp#4086 allowlist entry all look coherent from here. No further action needed from this side.


Generated by Claude Code

@bokelley

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Noted — thanks for the confirmation. No further action from this side either.


Generated by Claude Code

Pull the custom _createTaskHandoff wrapper. Finalize HITL now uses the
framework's standard routeIfHandoff dispatch — same machinery
createMediaBuy and syncCreatives use for their HITL paths.

The change: maybeInterceptFinalize returns the raw adopter result
(FinalizeProposalSuccess | TaskHandoff<FinalizeProposalSuccess>) plus a
projection callback. The runtime threads both through routeIfHandoff,
which runs the projection synchronously for sync arms and inside the
background task for HITL arms. The projection commits the proposal,
emits the proposal.finalized log, and projects the wire response.

Why this matters: there's nothing special about finalize relative to
other async tools. The earlier custom wrapper:

  - Reinvented the projection callback routeIfHandoff already accepts.
  - Disconnected commit from the framework's task lifecycle. The
    wrapper's commit fired inside the handoff fn, before the framework's
    TaskRegistry saw the result. Cancellation / restart / timeout
    guarantees the registry provides for createMediaBuy HITL didn't
    apply to finalize HITL.
  - Created a fake asymmetry — finalize had its own special HITL path,
    every other unified-hybrid tool used routeIfHandoff. Future
    maintainers would wonder why.

The unified pattern means finalize HITL inherits whatever guarantees
the framework's task lifecycle provides for every other unified-hybrid
tool. If those improve in a future release, finalize benefits without
code changes.

FinalizeInterceptResult.intercepted shape changed: now carries
{ result, project } instead of a pre-projected `response`. The two
unit tests that consumed the old shape were updated to call
project(result) themselves; the e2e test (which goes through
routeIfHandoff naturally) needed no changes.

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

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Pushed df45c621 — your question landed. There was nothing special about finalize relative to other async tools. The custom _createTaskHandoff wrapper I'd written was reinventing the projection callback that routeIfHandoff already accepts on every unified-hybrid dispatch site (createMediaBuy, syncCreatives).

The refactor:

  • maybeInterceptFinalize now returns { kind: 'intercepted', result, project } where result is the raw adopter return (FinalizeProposalSuccess OR TaskHandoff<FinalizeProposalSuccess>) and project is a closure that does store.commit + log + wire-response shaping.
  • The runtime threads both through routeIfHandoff(taskRegistry, opts, intercept.result, intercept.project) — same call shape createMediaBuy HITL uses with persistTargetingOverlayFromCreate as its projection.

What this means in practice:

  • Finalize HITL inherits the framework's task lifecycle. Whatever cancellation, restart-via-durable-store, deadline, webhook-delivery semantics routeIfHandoff + TaskRegistry provide, finalize benefits from. If those harden later, finalize benefits without code changes here.
  • The "v1.6 HITL design problem" you flagged is a framework concern, not a finalize concern. Cancellation propagation, durable handoff state, deadline policy — those are improvements to routeIfHandoff / TaskRegistry that affect every unified-hybrid tool, fixable in one place.
  • Net diff: 107 insertions, 132 deletions. The custom wrapper, special handoff arm on FinalizeInterceptResult, and _createTaskHandoff import are gone. Finalize is now boring plumbing on top of the existing async-task surface, which is the right answer.

92 unit tests pass, 3/3 storyboard gates pass, prettier + tsc clean.

@bokelley

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough walkthrough. The routeIfHandoff alignment is the right call — finalize being boring plumbing on top of the existing async-task surface is exactly what makes v1.6 improvements land for free. Net deletion is a good sign too. Will let this proceed to human review.


Generated by Claude Code

@bokelley

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Acknowledged — thanks for the review. Passing to human reviewers as-is.


Generated by Claude Code

@bokelley

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Understood — standing by. Good luck with the human review pass.


Generated by Claude Code

bokelley and others added 3 commits May 4, 2026 13:06
… public

CI's `check:adopter-types` gate caught the published-types/published-source
mismatch:

  proposal/index.d.ts(17,10): error TS2724:
    '"./types"' has no exported member named 'validateProposalCapabilities'.
  proposal/index.d.ts(22,111): error TS2724:
    '"./lifecycle"' has no exported member named 'setProposalLifecycleLogger'.

Both functions were tagged `@internal`. `tsconfig.lib.json` has
`stripInternal: true` so their declarations got removed from the
published .d.ts — but `proposal/index.ts` re-exports them as public
surface, leaving a dangling reference in the consumed types.

Both functions ARE legitimately useful adopter-side:

  - `validateProposalCapabilities`: adopters call it from their own
    config-validation paths to fail fast on misconfiguration. Same
    rationale as exposing `validatePlatform`.
  - `setProposalLifecycleLogger`: adopters wire it to their existing
    logger (pino, bunyan, etc.) so proposal lifecycle events
    (proposal.draft_persisted, proposal.finalized, etc.) route through
    the same pipeline as the rest of their server logs. Tests use it
    to capture structured emissions for assertion.

The `@internal` tag was wrong. Promoted to `@public` with sharper
JSDoc explaining the adopter-side use case in each.

Verified: `npm run check:adopter-types` now passes locally.

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

CodeQL `js/polynomial-redos` (high-severity) flagged the trailing-slash
strip in `MockProposalManager`:

  this.url = options.mockUpstreamUrl.replace(/\/+$/, '');

The pattern `\/+$` has a quantifier-and-anchor shape that CodeQL flags
even though modern regex engines run it in linear time. Real-world risk
is essentially zero — `mockUpstreamUrl` is adopter-supplied at
construction (not user input), so an attacker can't drive a malicious
input. But there's no reason to keep a regex CodeQL flags as
high-severity when a `while (endsWith)` loop is byte-equivalent.

Replaced with a loop-based strip; behavior identical, no regex, no
ReDoS surface.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…XPIRED recovery, drop markConsumed

Three concrete fixes from the parallel expert review (code-reviewer,
ad-tech-protocol-expert, security-reviewer, adtech-product-expert):

1. Strip stale "Status: primitives only / wiring lands later" doc-strings
   from `proposal/types.ts`, `proposal/dispatch.ts`, `proposal/index.ts`.
   The wiring landed in this same PR; the deferred-status JSDoc would
   have shipped in published .d.ts contradicting the changesets and
   confusing adopters reading the typed surface.

2. PROPOSAL_EXPIRED recovery: terminal → correctable. Per AdCP 3.0.6
   schemas/cache/3.0.6/enums/error-code.json, PROPOSAL_EXPIRED is
   `correctable (re-discover with get_products to get a fresh
   proposal)`. The PR labeled it `terminal`, which is a wire-spec
   contradiction the storyboard runner would eventually catch.
   Surfaced by the protocol-expert review.

3. Drop the legacy `markConsumed` method from ProposalStore. The
   security-reviewer M1 finding: markConsumed lacks `expectedAccountId`
   while every other write/read on the surface requires it. The
   "preserved for v1.5 alpha back-compat" rationale is moot — this is
   the FIRST v1.5 release. No alpha adopters exist. Removing the
   method eliminates the cross-tenant surface entirely; the two-phase
   tryReserveConsumption + finalizeConsumption is the only path.
   Test sites that used it (proposal-manager-lifecycle.test.js) now
   call the two-phase pair directly.

Other expert findings explicitly NOT blocking, deferred to follow-ups:
  - detectFinalizeAction first-entry-only (matches Python; spec issue
    sibling to adcp#4086)
  - HITL finalize → orphan COMMITTED on tasks_cancel (parallel deferral
    to the createMediaBuy HITL one — `routeIfHandoff` framework
    concern, not finalize-specific)
  - KevelLikeRecipe naming (`AuctionLikeRecipe` would be more honest;
    pre-GA polish)
  - Recipe extensibility for adopters wrapping richer GAM/FreeWheel
    (extensions field; pre-GA polish)
  - implementation_config wire leakage (additionalProperties: true is
    legal in 3.0.6; spec issue for `writeOnly` annotation as future
    polish)

Verified: tsc clean, prettier clean, 141/141 targeted tests pass,
check:adopter-types passes.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@bokelley
bokelley merged commit 65333ea into main May 4, 2026
10 checks passed
bokelley added a commit that referenced this pull request May 5, 2026
… leak surfaced by security review

PR #1562 security review caught a ship-blocker the parent PR (#1557)
also inherited: the wire-strip chokepoint in projectSync only covers
the sync arm. The HITL handoff path runs the projection callback
inside dispatchHitl, then writes the projected result directly to
taskRegistry.complete + emitTaskWebhook without re-stripping. Buyers
polling tasks_get see ctx_metadata + implementation_config verbatim;
webhook receivers see them too.

Three fixes:

1. stripCtxMetadata + stripImplementationConfig now run inside
   dispatchHitl before taskRegistry.complete. Mirrors projectSync's
   chokepoint pattern. Every downstream consumer (tasks/get polling
   at line 1826, emitTaskWebhook at line 2493, idempotency replays of
   the Submitted envelope) inherits a clean payload.

2. CARRIER_KEYS extended with 'proposal' / 'proposals'. Without it,
   server-only fields on proposals[].products[] survived the strip —
   a proposal-mode-specific nesting the pre-existing carrier list
   didn't anticipate. Pre-existing latent ctx_metadata leak too.

3. stripImplementationConfig now reuses CARRIER_KEYS rather than
   maintaining its own narrower list. The two strips share a
   carrier set so future spec additions can't silently extend one
   and not the other.

Also adds credential-leak warning to the recipe `extensions` slot
JSDoc on both GAMLikeRecipe and AuctionLikeRecipe (security M3 from
the review): adopters putting credentials there are protected only
by coincidence of the implementation_config strip, not by a
credential scanner.

Test coverage:
- New e2e regression in test/lib/proposal-manager-e2e.test.js drives
  a finalize HITL → tasks/get round-trip with both server-only
  fields embedded; asserts no leak via either path.
- New shared-carrier test asserts implementation_config strip walks
  media_buys[].products[] and creatives[].product (carriers the
  narrower original list missed).

148/148 targeted tests pass (proposal primitives + lifecycle + e2e +
strip + recipes + mock-server). 46/46 existing ctx_metadata tests
still pass. check:adopter-types passes. prettier + tsc clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
bokelley added a commit that referenced this pull request May 5, 2026
…recipe rename, extensibility) (#1562)

* feat(decisioning): ProposalManager v1.5 follow-ups — wire-leak strip, recipe rename, extensibility

Addresses every actionable concern from the parallel expert review on
PR #1557 (code-reviewer / ad-tech-protocol-expert / security-reviewer /
adtech-product-expert). Stacks on the v1.5 base; will be opened as a
follow-up PR once #1557 lands.

1. Wire-leak prevention: strip Product.implementation_config

   Recipe data (network_code, ad_unit_ids, line_item_template_id, GAM
   line-item priority) rides on Product.implementation_config server-
   side as the typed contract between ProposalManager and
   DecisioningPlatform. The wire schema is additionalProperties: true
   so the field is technically legal — but emitting it leaks publisher
   topology to buyers. Framework now runs stripImplementationConfig at
   the dispatcher response-boundary chokepoint right after
   stripCtxMetadata, parallel pattern. New helpers re-exported from
   @adcp/sdk/server. Test coverage in
   test/lib/proposal-implementation-config-strip.test.js.

2. Recipe rename: KevelLikeRecipe → AuctionLikeRecipe

   Conflating a decision-engine (Kevel) with a wire protocol (OpenRTB)
   under one recipe_kind: 'kevel' was a category error per product-
   expert review. Renamed to AuctionLikeRecipe with recipe_kind:
   'auction'. Adopters who want sharper-typed shapes declare their own
   recipe_kind subtype on top. Breaking but pre-release.

3. Recipe extensibility: extensions slot

   Both GAMLikeRecipe and AuctionLikeRecipe gain an optional
   extensions?: Record<string, unknown> field. Adopters carrying
   richer upstream payloads (GAM creative_placeholders, Kevel
   frequency_caps, OpenRTB private_auction, FreeWheel placement_types)
   use this slot rather than forking recipe_kind. Adopters with
   stricter shape requirements declare a typed subtype literal on top.

4. HITL finalize cancel-race documentation

   Inline comment in runtime/from-platform.ts at the finalize-intercept
   site documents the known gap: if the buyer cancels mid-handoff, the
   framework marks the task cancelled but intercept.project still runs
   store.commit. Same gap exists for createMediaBuy HITL today.
   Mitigations: 7-day eviction window in InMemoryProposalStore +
   optional task-registry sweep by production stores. End-to-end fix
   requires AbortSignal propagation into projection callbacks — a
   framework-level concern, not finalize-specific.

5. projectFinalizeResponse products echo: explicit decision

   Inline comment documents the products: [] choice. Echoing would
   either re-emit from the persisted draft (extra wire bytes) or call
   back into the adopter (extra round-trip). Buyers fetching products
   on the finalize response use a follow-up get_products call keyed
   off proposals[0].allocations[].product_id.

6. Spec issue filed: adcp#4107

   Clarifies refine[] mixed-action semantics when finalize is one of
   multiple entries. Spec is silent today; both SDKs implement
   first-finalize-only by convention. Companion to adcp#4086.

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

* fix(decisioning): HITL handoff result wire-strip — close pre-existing leak surfaced by security review

PR #1562 security review caught a ship-blocker the parent PR (#1557)
also inherited: the wire-strip chokepoint in projectSync only covers
the sync arm. The HITL handoff path runs the projection callback
inside dispatchHitl, then writes the projected result directly to
taskRegistry.complete + emitTaskWebhook without re-stripping. Buyers
polling tasks_get see ctx_metadata + implementation_config verbatim;
webhook receivers see them too.

Three fixes:

1. stripCtxMetadata + stripImplementationConfig now run inside
   dispatchHitl before taskRegistry.complete. Mirrors projectSync's
   chokepoint pattern. Every downstream consumer (tasks/get polling
   at line 1826, emitTaskWebhook at line 2493, idempotency replays of
   the Submitted envelope) inherits a clean payload.

2. CARRIER_KEYS extended with 'proposal' / 'proposals'. Without it,
   server-only fields on proposals[].products[] survived the strip —
   a proposal-mode-specific nesting the pre-existing carrier list
   didn't anticipate. Pre-existing latent ctx_metadata leak too.

3. stripImplementationConfig now reuses CARRIER_KEYS rather than
   maintaining its own narrower list. The two strips share a
   carrier set so future spec additions can't silently extend one
   and not the other.

Also adds credential-leak warning to the recipe `extensions` slot
JSDoc on both GAMLikeRecipe and AuctionLikeRecipe (security M3 from
the review): adopters putting credentials there are protected only
by coincidence of the implementation_config strip, not by a
credential scanner.

Test coverage:
- New e2e regression in test/lib/proposal-manager-e2e.test.js drives
  a finalize HITL → tasks/get round-trip with both server-only
  fields embedded; asserts no leak via either path.
- New shared-carrier test asserts implementation_config strip walks
  media_buys[].products[] and creatives[].product (carriers the
  narrower original list missed).

148/148 targeted tests pass (proposal primitives + lifecycle + e2e +
strip + recipes + mock-server). 46/46 existing ctx_metadata tests
still pass. check:adopter-types passes. prettier + tsc clean.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@github-actions github-actions Bot mentioned this pull request May 5, 2026
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