Skip to content

feat: AdCP v3 idempotency (client #568 + server #569) - #590

Merged
bokelley merged 4 commits into
mainfrom
bokelley/pr-2315-review
Apr 19, 2026
Merged

bokelley merged 4 commits into
mainfrom
bokelley/pr-2315-review

Conversation

@bokelley

Copy link
Copy Markdown
Contributor

Implements #568 (client ergonomics) and #569 (server middleware) for the required-key changes from adcp#2315. End-to-end validated: a fresh claude CLI builds a compliant signals agent from the updated skill on first try and passes the signal_marketplace storyboard (1/0/0/0).

Summary

  • Client: mutating tools auto-inject idempotency_key (UUID v4) when the caller omits it. Retries reuse the key. result.metadata.idempotency_key + result.metadata.replayed surface on every result. Typed IdempotencyConflictError + IdempotencyExpiredError.
  • Server: createIdempotencyStore with memoryBackend + pgBackend. JCS-canonicalized payload hashing. Per-principal scoping (plus per-session scoping for si_send_message). Atomic putIfAbsent claim closes the concurrent-same-key race. replayed: true injected on cached envelopes. Auto-declares adcp.idempotency.replay_ttl_seconds on capabilities.
  • Skills: all 8 build-*-agent/SKILL.md updated with idempotency sections. Heavy rewrites in seller, si, signals, governance. Examples are now single runnable blocks (not skeleton + fragment).
  • Tests: 88 new tests + 18 pg integration tests (DATABASE_URL-gated). Full suite: 3450 pass / 9 fail (9 are pre-existing storyboard schema gaps unrelated to this work).

Things downstream users need to do

Three real things, beyond npm update @adcp/client:

  1. If your agent emits side effects on response (notifications, LLM memory writes, downstream tool calls), you MUST check result.metadata.replayed before acting. A cached replay means the side effects already fired.
  2. If you catch errors broadly, IdempotencyConflictError and IdempotencyExpiredError are new subclasses. Mint a fresh UUID v4 for conflict; fall back to natural-key lookup for expired if you know the prior call succeeded.
  3. If you BYOK (persist keys across process restarts), you own the TTL boundary — compare key age against adcp.idempotency.replay_ttl_seconds from get_adcp_capabilities.

Dogfood validation

test-agents/test-agent-build.sh claude signals: fresh Claude builds a 202-line agent from the updated skill → compiles clean → Storyboard overall: passing (tracks: 1 pass / 0 fail / 0 partial / 0 skip). Seller + governance compile clean; their storyboard reporting is blocked by #588 (CLI stdout log leak) and adcp#2349 (upstream governance storyboard sample bug) — filed separately.

Expert review

code-reviewer + dx-expert both cleared for ship after resolving 4 first-pass blockers (seller as const compile errors, updateMediaBuy wholesale param merge, governance undefined-principal 503s, governance status enum). Final pass caught one signals-skill idempotency snippet still using ctx.account?.id — fixed before commit.

Follow-up issues (filed separately, not blocking)

  • #588 — storyboard CLI --json stdout mixes non-JSON log output, breaks naive parsers
  • #589 — 'escalated' governance status is out-of-spec but supported by SDK (pre-existing legacy behavior; decision needed: keep as extension or remap at ingest)
  • adcp#2349 — upstream governance storyboard sends sync_plans sample missing spec-required fields

Test plan

  • npm run build:lib — clean compile
  • node --test test/skill-examples-compile.test.js — all 21 TypeScript blocks in skills compile
  • node --test test/lib/jcs.test.js test/lib/idempotency*.test.js test/server-idempotency.test.js — 88/88 pass
  • DATABASE_URL=postgres://localhost/adcp_test npm test — pg integration tests run (18 more pass)
  • npm test — 3450 pass / 9 pre-existing fails
  • test-agents/test-agent-build.sh claude signals — fresh Claude builds passing compliance agent
  • Manual seller dogfood (.context/seller-test/): build, compile, run, 3/3 idempotency scenarios (fresh → replay → conflict) pass
  • Seller storyboard validation — blocked on storyboard CLI --json output mixes non-JSON stdout, breaks parsers #588
  • Governance storyboard validation — blocked on adcp#2349

🤖 Generated with Claude Code

bokelley and others added 2 commits April 18, 2026 18:36
…ll updates

Implements #568 (client) and #569 (server middleware) in one branch. End-to-
end validated: fresh Claude builds a compliant signals agent from the
updated skill on first try (signal_marketplace storyboard: 1/0/0/0).

## Client (#568)

- Auto-generate idempotency_key (UUID v4) for mutating tools when caller
  omits it. Key is injected before schema validation so the request never
  trips SingleAgentClient.validateRequest for missing the required field.
- Retries reuse the same key — regenerating defeats the envelope.
- Surface result.metadata.idempotency_key + result.metadata.replayed so
  callers can log the key and check replayed before acting on side effects.
- Typed errors: IdempotencyConflictError, IdempotencyExpiredError, both
  extend ADCPError and carry the idempotency_key.
- MutatingRequestInput<T> utility loosens the 28 mutating-tool method
  signatures so callers can omit idempotency_key at the call site.

## Server (#569)

- createIdempotencyStore({ backend, ttlSeconds }) with pluggable backends:
  memoryBackend (deep-clones on read, atomic putIfAbsent claim),
  pgBackend (centralized quoteIdent, DDL + cleanup helpers). pgBackend
  gets 18 DATABASE_URL-gated integration tests.
- Middleware wired inside createAdcpServer: key-pattern enforcement,
  IDEMPOTENCY_CONFLICT on same-key-different-payload (no payload leak),
  IDEMPOTENCY_EXPIRED past TTL with ±60s clock-skew tolerance, replayed:
  true injected on cached envelope, auto-declares replay_ttl_seconds
  capability.
- Per-session scoping for si_send_message — session_id folds into the
  scope tuple so the same key under two sessions doesn't cross-replay.
- In-flight claim step closes the concurrent-same-key race (both callers
  see miss, both execute, both save). Parallel callers now see
  SERVICE_UNAVAILABLE retry_after:1 while the winner finishes.
- Only successful responses cache — errors release the claim so retries
  re-execute instead of replaying a transient failure.
- Cache the *formatted* envelope (not raw handler output) so non-
  deterministic wrap fields (mediaBuyResponse's confirmed_at = new Date)
  pin to first-execution values on replay.
- JCS canonicalization per RFC 8785 with closed exclusion list:
  idempotency_key, governance_context, object-shaped context (string
  context on SI tools stays in the hash), and
  push_notification_config.authentication.credentials.
- ttlSeconds throws at construction on out-of-range values (1h–7d)
  instead of silent-clamping — hides operator misconfig otherwise.
- warn (don't throw) at server-creation when mutating handlers register
  without idempotency, so existing test suites aren't disrupted.

## Skill + example updates

Applied to all 8 build-*-agent skills. Heaviest rewrites in seller, si,
signals, governance; minor idempotency-section additions to the others.

- Seller: merged skeleton + idempotency into one runnable example,
  added updateMediaBuy handler body, fixed resolveSessionKey fallback
  (`() => 'default-principal'` — `ctx.account?.id` fails TS strict when
  TAccount = unknown), corrected syncCreatives response shape to
  `{ creatives: [{ creative_id, action }] }`, removed "Do not read
  additional docs" line, documented the ^[A-Za-z0-9_.:-]{16,255}$ key
  pattern, added a full "Going to Production" section (pgBackend +
  PostgresStateStore + PostgresTaskStore + migrations + cleanup +
  DATABASE_URL guard).
- SI: replaced sess_${Date.now()} with crypto.randomUUID() + entropy
  note (≥122 bits per spec), documented the framework's auto-scope-by-
  session_id so builders don't try to implement it themselves.
- Signals: fixed activateSignal to emit compliant shape — platform is
  async (is_live: false + estimated_activation_duration_minutes +
  activation_key committed up front), agent is sync (is_live: true +
  activation_key + deployed_at). Updated response-shape prose to match.
- Governance: fixed check_governance status enum (`'escalate'` →
  `'conditions'` per schema, in 2 places), added missing randomUUID
  import.
- throw adcpError() → return adcpError() in signals + SI (throw gets
  caught by framework and converted to SERVICE_UNAVAILABLE, hiding the
  custom code).

examples/signals-agent.ts migrated from deprecated createTaskCapableServer
to createAdcpServer pattern with idempotency wired and the correct
async/sync Deployment shape per destination type.

## Tests

- 88 new tests across jcs, idempotency utils, store, client, server
  integration. All pass (66+22 = 88 + 18 pg integration = 106 total).
- Full suite: 3450 pass / 9 fail. The 9 are pre-existing storyboard
  schema coverage failures unrelated to this work.

## Public API additions

Client: IdempotencyConflictError, IdempotencyExpiredError,
generateIdempotencyKey, isMutatingTask, isValidIdempotencyKey,
IDEMPOTENCY_KEY_PATTERN, MUTATING_TASKS, MutatingRequestInput,
canonicalize, canonicalJsonSha256, closeMCPConnections (now re-exported
from root — previously only via ./protocols subpath which package
exports block).

Server: createIdempotencyStore, memoryBackend, pgBackend,
getIdempotencyMigration, IDEMPOTENCY_MIGRATION,
cleanupExpiredIdempotency, hashPayload, plus all related types.

## Follow-ups (tracked as GitHub issues)

- adcp-client#588: storyboard CLI --json output mixes non-JSON stdout
- adcp-client#589: 'escalated' governance status drift vs spec
- adcp#2349: governance_spend_authority/sync_plans sample_request
  omits spec-required fields (upstream)

## Expert reviews

code-reviewer + dx-expert both cleared for ship. Blockers from the first
pass (seller as-const compile errors, updateMediaBuy wholesale param
merge, governance undefined-principal 503s, governance status enum) all
resolved. Final pass caught one signals-skill idempotency snippet still
using ctx.account?.id — fixed before commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Resolve conflicts with upstream changes since branch-point:
- #567 security_baseline storyboard runner (adds undici dep)
- #571 compliance domain → protocol rename
- #580 property-list account migration
- #586 brand/account invariant
- #587 RFC 9421 request-signing profile

Conflicts resolved:
- docs/TYPE-SUMMARY.md, docs/llms.txt — generated, took main's version
  then re-ran generate-agent-docs so the idempotency section is preserved.
- src/lib/types/{core,schemas,tools}.generated.ts — generated, took
  main's version then re-ran sync-schemas + generate-types.
- src/lib/server/create-adcp-server.ts — merged the two `idempotency`
  property declarations on AdcpCapabilitiesConfig (both branches added
  one); kept the optional/with-docs form from this branch and merged
  the "defaults to 86400 per spec" intent from main. Kept the
  clampReplayTtl-guarded capability declaration that reads from the
  wired idempotency store's ttlSeconds.
- src/lib/core/GovernanceMiddleware.ts — dropped the duplicate
  `idempotency_key: randomUUID()` that main added (this branch already
  mints the key via getOrMintOutcomeKey for the (checkId, outcome)
  tuple so retries share a key).
- test/lib/governance-stub.test.js — dropped duplicate idempotency_key
  entries from three test calls (merge union of this branch's hardcoded
  keys + main's randomUUID calls); kept randomUUID which matches the
  spec pattern at runtime.
- test/lib/storyboard-drift.test.js — trivial comment merge around the
  `replayed` envelope-path entry.
- test/lib/zod-schemas.test.js — merged cleanly via git.

Build: tsc --project tsconfig.lib.json clean.
Tests: 3571 pass / 0 fail.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread test/lib/zod-schemas.test.js Fixed
bokelley and others added 2 commits April 18, 2026 19:15
CI Code Quality job flagged formatting drift on files added or substantially
rewritten in this branch. Running prettier with the repo's config
(printWidth, arrow parens, quote style) normalizes them. No semantic
changes.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Code-quality bot flagged the merge residue on PR #590 (discussion_r3105957914):
both my branch and main added an `idempotency_key` to `planWithAudience` in
the same test. The later entry (a UUID-shaped value from main) overwrote
mine at runtime, so the test was functionally fine, but the overwritten
property warning is real. Keep the final UUID value, drop the earlier
duplicate.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@bokelley
bokelley merged commit d666e51 into main Apr 19, 2026
14 checks passed
@bokelley
bokelley deleted the bokelley/pr-2315-review branch April 19, 2026 00:17
bokelley added a commit that referenced this pull request Apr 19, 2026
Finishes the remaining #568 work left open after #590: typed errors are
now surfaced on TaskResult, `replay_ttl_seconds` is exposed on the client
with fail-closed semantics, `useIdempotencyKey()` validates BYOK input
up front, and idempotency keys are redacted from debug logs by default.

- TaskResult.errorInstance: IdempotencyConflictError / IdempotencyExpiredError
  attached automatically when the seller returns those codes. The SDK pulls
  the sent idempotency_key from task state — the server intentionally omits
  it from error bodies (it's a read-oracle).
- adcpErrorToTypedError helper lets callers that already hold an AdcpErrorInfo
  type-narrow it themselves.
- getIdempotencyReplayTtlSeconds() on SingleAgentClient / AgentClient reads
  adcp.idempotency.replay_ttl_seconds from cached capabilities. Throws on
  v3 sellers that omit the (required) declaration rather than defaulting
  to 24h, which would mislead retry-sensitive flows.
- useIdempotencyKey(key) validates against IDEMPOTENCY_KEY_PATTERN up front.
- redactIdempotencyKey / redactIdempotencyKeyInArgs truncate keys to 8 chars
  in MCP and A2A debug logs. ADCP_LOG_IDEMPOTENCY_KEYS=1 opts into full
  logging for local debugging.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
bokelley added a commit that referenced this pull request Apr 19, 2026
* feat: complete client-side idempotency gaps from #568

Finishes the remaining #568 work left open after #590: typed errors are
now surfaced on TaskResult, `replay_ttl_seconds` is exposed on the client
with fail-closed semantics, `useIdempotencyKey()` validates BYOK input
up front, and idempotency keys are redacted from debug logs by default.

- TaskResult.errorInstance: IdempotencyConflictError / IdempotencyExpiredError
  attached automatically when the seller returns those codes. The SDK pulls
  the sent idempotency_key from task state — the server intentionally omits
  it from error bodies (it's a read-oracle).
- adcpErrorToTypedError helper lets callers that already hold an AdcpErrorInfo
  type-narrow it themselves.
- getIdempotencyReplayTtlSeconds() on SingleAgentClient / AgentClient reads
  adcp.idempotency.replay_ttl_seconds from cached capabilities. Throws on
  v3 sellers that omit the (required) declaration rather than defaulting
  to 24h, which would mislead retry-sensitive flows.
- useIdempotencyKey(key) validates against IDEMPOTENCY_KEY_PATTERN up front.
- redactIdempotencyKey / redactIdempotencyKeyInArgs truncate keys to 8 chars
  in MCP and A2A debug logs. ADCP_LOG_IDEMPOTENCY_KEYS=1 opts into full
  logging for local debugging.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

* style: prettier --write src/lib/core/TaskExecutor.ts

Format-only change to satisfy the Code Quality CI job.

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

* fix: address expert-review findings on PR #604

Security (security-reviewer):
- Redact idempotency_key in Activity.payload.params — this is the
  observability hook buyers typically pipe into Datadog/Sentry, so the
  key was leaving the process in the clear.
- Tighten useIdempotencyKey() invalid-key preview from 32 chars to 8
  to match the redactIdempotencyKey() policy — near-valid 16-char keys
  were flowing verbatim into exception messages.
- Make idempotencyKey non-enumerable on IdempotencyConflictError /
  IdempotencyExpiredError so console.log(err) and JSON.stringify
  don't leak the key (parameter properties are enumerable by default
  in TS; explicit Object.defineProperty fixes it).

DX (dx-expert):
- Teach docs/llms.txt the errorInstance instanceof pattern, the
  getIdempotencyReplayTtlSeconds() fail-closed behaviour, and the
  useIdempotencyKey() BYOK helper — previously only mentioned in the
  changeset.
- Add an Idempotency section to README with the four-line happy path.

Code quality (code-reviewer):
- Add tests for redactIdempotencyKeyInArgs covering the referential-
  equality contract the A2A rebuild-only-when-changed logic depends on,
  plus JSON-serialization leak tests for the non-enumerable key fix.

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

* fix: move llms.txt idempotency additions into the generator source

docs/llms.txt is generated by scripts/generate-agent-docs.ts — editing
the output directly lost on CI regenerate. Move the errorInstance
instanceof, useIdempotencyKey, and getIdempotencyReplayTtlSeconds
sections into the generator so they survive regeneration.

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 Apr 19, 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.

1 participant