Skip to content

feat(server): ACP session/cancel boundary adapter (ccsc-21x) - #172

Merged
jeremylongshore merged 1 commit into
mainfrom
feat/acp-boundary-adapter-bz-21x
May 18, 2026
Merged

jeremylongshore merged 1 commit into
mainfrom
feat/acp-boundary-adapter-bz-21x

Conversation

@jeremylongshore

Copy link
Copy Markdown
Owner

Beads: `ccsc-21x`
Tracking: #167 (CCSC Rollout: Admin Commands + Audit/Policy/Governance v2 Cluster — PR #2 of 10)

Summary

  • Adds `mapAcpSessionCancel` to `server.ts` — a thin JSON-RPC 2.0 adapter translating Agent Client Protocol `session/cancel` requests onto the existing `supervisor.quiesce(key)` call.
  • Additive only. The supervisor's internal vocabulary (`activate` / `quiesce` / `deactivate` / `quarantine`) is unchanged. The adapter is the ONLY place ACP terminology appears in the codebase.
  • Adds 13 round-trip tests covering happy path, envelope validation (-32600), sessionId parsing (-32602), supervisor failure (-32603), and the "internal vocabulary unchanged" invariant.
  • Updates `000-docs/session-state-machine.md` with § ACP-mapping addendum + invariant ci: enable Gemini PR review (wild ecosystem) #9.
  • CHANGELOG entry under `[Unreleased]`.

Why this lands as PR #2

Per the rollout plan in #167, `ccsc-21x` is the second-of-ten PR. It blocks `ccsc-3w0` (admin commands hardened) because the admin-command dispatcher inherits the `session/cancel` adapter naming for future admin-verb extensions. Landing it now means the ACP boundary is established before the admin module imports it.

Scope

File Change
`server.ts` +118 LoC: `mapAcpSessionCancel` + `AcpSessionCancelRequest` + `AcpResponse` types (no internal API changes)
`server.test.ts` +260 LoC: 13 new tests under `describe('mapAcpSessionCancel (ccsc-21x)', ...)`
`000-docs/session-state-machine.md` +50 LoC: § ACP-mapping section + invariant #9
`CHANGELOG.md` one entry under `[Unreleased]`
`.beads/issues.jsonl` bd update tracking

No schema changes, no harness-hash repinning, no `.dependency-cruiser.js` changes. The adapter is pure addition.

What the adapter does

```
ACP envelope CCSC internal
───────────────── ─────────────────
{ jsonrpc: "2.0", supervisor.quiesce({
id: , channel: "",
method: "session/cancel", ──→ thread: ""
params: { })
sessionId: ":"
} }
↓
{ jsonrpc: "2.0", (quiesce resolves)
id: ,
result: { stopReason: "cancelled" } }
```

Error envelopes:

  • `-32600` Invalid Request — request shape failed Zod validation (fallback id is `null` per JSON-RPC 2.0 §5.1)
  • `-32602` Invalid params — sessionId missing colon, or with leading/trailing colon
  • `-32603` Internal error — `supervisor.quiesce()` rejected (quarantined, save failure); reason captured in `error.data.reason`

What this adapter does NOT do

  • No internal API renames. `supervisor.ts` exports the same surface. `SessionKey` unchanged. No new exports from supervisor.
  • No ACP wire-format adoption. The adapter takes a pre-parsed request object and returns a pre-shaped response object. Stdio framing / JSON parsing is the caller's responsibility. Migration to ACP-on-the-wire is a separate epic gated on `Feature request: External message injection API for active Claude Code sessions anthropics/claude-code#53049`.
  • No lifecycle changes. The full FSM transitions in `session-state-machine.md` § State diagram and § Restart semantics are unaffected.

Test plan

  • `bun run typecheck` — passes
  • `bunx @biomejs/biome check .` — passes (after auto-format)
  • `bun test` — 717 pass (704 → 717), 0 fail
  • `scripts/coverage-floor.sh 95` — line=98.47% func=98.82% (floor=95%) OK
  • `bunx depcruise --config .dependency-cruiser.js .` — no violations
  • `scripts/gherkin-lint.sh --path features/ --strict` — 0 warnings
  • `scripts/harness-hash.sh --verify` — OK
  • `bun audit --audit-level=high --ignore=GHSA-j3q9-mxjg-w52f` — no vulnerabilities
  • `bun scripts/crap-score.ts --threshold 30` — max=28 OK

References

Adds a thin JSON-RPC 2.0 adapter — mapAcpSessionCancel in server.ts —
that translates inbound ACP envelopes onto the existing supervisor
.quiesce(key) call. Additive only: the supervisor's internal vocabulary
(activate / quiesce / deactivate / quarantine) is unchanged.

Rationale: ACP is the converging cross-ecosystem JSON-RPC 2.0 standard
for agent control (Zed adoption; open issues for the same primitive in
google/adk-python#2425 and zed-industries/zed#50592). The day Anthropic
ships external-message-injection mid-turn (claude-code#53049 currently
closed-as-dup), ACP is the standardized envelope. Naming our admin-
command and session-control semantics ACP-compatible at the boundary is
a free forward-compat win.

The adapter is the ONLY place ACP terminology appears in the codebase.
A vocabulary rename would break ~704 tests and the meaning of every
existing entry in audit.log files in the field. The additive shape
mirrors the 31-A.4 manifest/policy isolation pattern: translation at
the boundary, internal vocabulary unchanged. The migration to
ACP-on-the-wire (stdio framing) is a separate epic.

API:
- mapAcpSessionCancel(req: unknown, sup: SessionSupervisor):
    Promise<AcpResponse>
- Returns { result: { stopReason: 'cancelled' } } on success
- Returns JSON-RPC 2.0 error envelopes:
  - -32600 Invalid Request (envelope failed Zod validation; fallback
    id is null per JSON-RPC §5.1)
  - -32602 Invalid params (sessionId malformed: no colon, leading
    colon, or trailing colon)
  - -32603 Internal error (supervisor.quiesce rejected; reason
    captured in error.data.reason)
- sessionId convention: "<channel>:<thread>" — Slack IDs contain only
  alphanumerics and dots, so the first ':' is an unambiguous delimiter

Tests: 13 new round-trip tests pinning the envelope shape, error-code
semantics, and the "internal vocabulary is unchanged" invariant
(adapter is a pure boundary translator — passes channel/thread to
supervisor.quiesce verbatim, no normalisation). Inlined adapter follows
the activateAndTouch pattern (server.ts has bootstrap side-effects
that prevent direct import in the test runner).

Design doc: 000-docs/session-state-machine.md gains a new § ACP-mapping
section (ACP envelope ↔ supervisor method translation table; what the
adapter does NOT do — no API rename, no wire-format adoption, no
lifecycle change) and invariant #9 ("ACP terminology appears only in
the boundary adapter").

CHANGELOG entry under [Unreleased].

PR #2 of 10 in the CCSC Rollout (#167). This unblocks ccsc-3w0 (admin
commands inherit the session/cancel adapter naming for future
admin-verb extensions).

All 9 CI gates green locally: typecheck, biome lint, 717 tests
(704 → 717), coverage 98.47% line / 98.82% func (unchanged), depcruise
clean (7 modules / 17 dependencies), gherkin-lint 0 warnings,
harness-hash OK, bun audit clean, crap-score max 28 (threshold 30).

Refs #167

- Jeremy Longshore
intentsolutions.io
@jeremylongshore
jeremylongshore merged commit f286f52 into main May 18, 2026
4 checks passed
@jeremylongshore
jeremylongshore deleted the feat/acp-boundary-adapter-bz-21x branch May 18, 2026 21:07

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request introduces a boundary adapter in server.ts to map Agent Client Protocol (ACP) session/cancel requests to the internal supervisor.quiesce method, ensuring JSON-RPC 2.0 compliance. Documentation and invariants were updated to reflect this additive change. Feedback from the review highlights that the AcpResponse type and its test counterpart should include null for the id field to fully comply with the JSON-RPC 2.0 specification, which would also resolve unsafe type casts. Additionally, it was suggested to refactor the adapter logic into a separate module to avoid code duplication in the test suite and mitigate maintenance risks.

Comment thread server.ts
Comment on lines +2283 to +2288
| { jsonrpc: '2.0'; id: string | number; result: { stopReason: 'cancelled' } }
| {
jsonrpc: '2.0'
id: string | number
error: { code: number; message: string; data?: unknown }
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The AcpResponse type should include null for the id field to be fully JSON-RPC 2.0 compliant. The specification requires that if an error occurs while detecting the ID in the request (e.g., an invalid request), the response ID must be null. Your implementation at line 2327 correctly identifies this, but the type definition here is missing it, which leads to the unsafe cast at line 2333. Note that the comment at line 2330 even mentions widening the type, suggesting this was the intended shape.

  | { jsonrpc: '2.0'; id: string | number | null; result: { stopReason: 'cancelled' } }
  | {
      jsonrpc: '2.0'
      id: string | number | null
      error: { code: number; message: string; data?: unknown }
    }

Comment thread server.ts
// JSON-RPC spec uses `null` for unknown ids; we widen the response type
// to permit it via the string|number union and pass through null when
// legitimately unknown.
id: fallbackId as string | number,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

This cast is unsafe because fallbackId can be null (as defined on line 2327). Once the AcpResponse type is updated to include null, this cast can be removed to ensure type safety.

      id: fallbackId,

Comment thread server.test.ts
Comment on lines +9852 to +9857
| { jsonrpc: '2.0'; id: string | number; result: { stopReason: 'cancelled' } }
| {
jsonrpc: '2.0'
id: string | number
error: { code: number; message: string; data?: unknown }
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The AcpResponseTest type in the test file should also include null for the id field to match the protocol requirements and the implementation's behavior.

Suggested change
| { jsonrpc: '2.0'; id: string | number; result: { stopReason: 'cancelled' } }
| {
jsonrpc: '2.0'
id: string | number
error: { code: number; message: string; data?: unknown }
}
| { jsonrpc: '2.0'; id: string | number | null; result: { stopReason: 'cancelled' } }
| {
jsonrpc: '2.0'
id: string | number | null
error: { code: number; message: string; data?: unknown }
}

Comment thread server.test.ts
typeof reqRecord.id === 'string' || typeof reqRecord.id === 'number' ? reqRecord.id : null
return {
jsonrpc: '2.0',
id: fallbackId as string | number,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

This cast is unsafe as fallbackId can be null. It should be removed after updating the AcpResponseTest type.

Suggested change
id: fallbackId as string | number,
id: fallbackId,

Comment thread server.test.ts
error: { code: number; message: string; data?: unknown }
}

async function mapAcpSessionCancel(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Duplicating the implementation of mapAcpSessionCancel and its associated types/schemas in the test file is a significant maintenance risk. If the logic in server.ts changes, these tests might continue to pass against the local copy, providing a false sense of security. While the comment mentions avoiding side-effects in server.ts, a more robust approach would be to extract the ACP adapter logic into a separate, side-effect-free module (e.g., acp-adapter.ts) that can be imported by both the server and the tests.

jeremylongshore added a commit that referenced this pull request May 18, 2026
jeremylongshore added a commit that referenced this pull request May 19, 2026
… §5.1 (#173)

* fix(acp-adapter): extract into module + widen id to null per JSON-RPC §5.1

Addresses 5 Gemini comments on PR #172 (all medium priority, all legitimate
per the repo's track record with Gemini's first-pass review):

1. Extract mapAcpSessionCancel + types + schema from server.ts into a new
   acp-adapter.ts module. Eliminates the test-side inlined duplicate that
   Gemini flagged as a maintenance / drift risk. server.test.ts now
   imports the production code path directly — the activateAndTouch
   inline-pattern was the wrong default for side-effect-free functions.

2. Widen AcpResponse.id to `string | number | null` to be fully
   JSON-RPC 2.0 §5.1 compliant — the spec REQUIRES `null` when an error
   occurs detecting the request id (i.e. when the envelope itself failed
   to parse). The two unsafe `as string | number` casts on the fallbackId
   are removed; the value flows through with the correct static type.

The success branch keeps `string | number` (no null) because a successful
response always echoes the client's id verbatim — that's the §4 rule.
Only the error branch widens.

server.ts now re-exports the public surface (AcpResponse,
AcpSessionCancelRequest, mapAcpSessionCancel) from acp-adapter.ts so
callers of `import { ... } from './server.ts'` still resolve identically.
No public-API breakage.

Behavior unchanged. Coverage went UP because tests now exercise the
production code path directly instead of a copy: 98.47% → 98.72% line
(+0.25), 98.82% → 99.02% func (+0.20). All 9 CI gates green: typecheck,
biome, 717 tests pass, depcruise clean (8 modules now / 21 deps),
gherkin-lint 0 warnings, harness-hash OK, bun audit clean, crap-score
max 28 (unchanged), coverage above floor.

This is a follow-up to PR #172 (ccsc-21x, already merged as f286f52).
The bead stays closed — this is structural cleanup, not a re-open.

Refs #167
Refs #172

- Jeremy Longshore
intentsolutions.io

* fix(acp-adapter): simplify malformed-id extraction per Gemini review

Apply Gemini's stylistic suggestion on PR #173: avoid the cast-on-
empty-object pattern by checking the type guard first and extracting
.id directly when the request is an object. Functionally identical;
one fewer cast.

Before:
  const reqRecord = (typeof req === 'object' && req !== null ? req : {})
    as Record<string, unknown>
  const fallbackId = typeof reqRecord.id === 'string' || ...

After:
  const candidateId = typeof req === 'object' && req !== null
    ? (req as Record<string, unknown>).id
    : undefined
  const fallbackId = typeof candidateId === 'string' || ...

13 ACP tests still pass; no behavior change.

- Jeremy Longshore
intentsolutions.io

---------

Co-authored-by: jeremylongshore <[email protected]>
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