@agent-tasks/mcp-server 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/errors.js CHANGED
@@ -6,6 +6,25 @@
6
6
  // verbatim. `recipe` names the concrete corrective call; `allowedNext` lists
7
7
  // only verb names the caller can call immediately (machine-checkable,
8
8
  // unlike the receipt layer's free-form `next[]` — see receipt.ts).
9
+ // `allowedNext` is a SUPERSET of the verb(s) `recipe` names, never a
10
+ // mismatched or narrower set: every verb the recipe's prose actually names
11
+ // as a corrective call MUST be present in `allowedNext` (this is the
12
+ // invariant tests/errors.test.ts's catalog-wide coherence guard checks,
13
+ // entry by entry), but `allowedNext` may ALSO carry discovery/read verbs
14
+ // the recipe text never mentions by name (e.g. already_claimed's
15
+ // `tasks_get`, added so a caller can check the held claim's status
16
+ // programmatically -- see the ALREADY_CLAIMED_CASES comment below) when
17
+ // they are a genuinely useful next call for at least one of the entry's
18
+ // documented cases. The reverse constraint (recipe MUST name every verb
19
+ // allowedNext lists) does not hold and is not enforced. One named
20
+ // exception to the forward direction: a legacy-gated verb `recipe`
21
+ // mentions only as a conditional aside (today `projects_list`, offered
22
+ // only behind `AGENT_TASKS_MCP_LEGACY=1` -- see
23
+ // projectAddressingConflictError's and unknownProjectSlugError's own
24
+ // comments below) is NOT required in `allowedNext`, since `allowedNext`
25
+ // may only ever list verbs the caller can call IMMEDIATELY, and a
26
+ // legacy-gated verb is not immediately callable in the default
27
+ // configuration.
9
28
  //
10
29
  // mapBackendError(status, body, verbContext?) is the single entry point:
11
30
  // tools.ts's wrap() is its only call site (mirrors receipt.ts's relationship
@@ -23,13 +42,19 @@
23
42
  // pr_author_mismatch from the read_first context on backend/src/routes/
24
43
  // tasks.ts): not_claimed, already_claimed, precondition_failed,
25
44
  // cross_repo_pr_rejected, pr_author_mismatch, force_admin_only,
26
- // respec_conflict, result_not_plain_string. Plus low_confidence (422, the
45
+ // respec_conflict, result_not_plain_string. Plus creator_abandon_conflict
46
+ // (409, task_creator_abandon's CAS/state-conflict sibling to respec_conflict,
47
+ // added task 7a1360da follow-up, batch 19 round 2 -- see
48
+ // creatorAbandonConflictError below) and low_confidence (422, the
27
49
  // pre-claim confidence gate on task_start / the deprecated tasks_claim,
28
50
  // backend/src/services/confidence-gate.ts via backend/src/middleware/
29
51
  // error.ts's lowConfidence helper): NOT in the contract's original seed
30
52
  // list, added on review (rc-v1-C005 round 1) to close an information-loss
31
53
  // gap the generic degrade path left on the highest-traffic verb — see
32
- // lowConfidenceError below. Every other backend error degrades to the
54
+ // lowConfidenceError below. Plus backlog_routing_enforced (400, task_create)
55
+ // and backlog_not_promoted (403, task_start / the deprecated tasks_claim
56
+ // alias), the v1 backlog-routing pair -- see backlogRoutingEnforcedError and
57
+ // backlogNotPromotedError below. Every other backend error degrades to the
33
58
  // generic shape (status-derived code, message passthrough, recipe ->
34
59
  // workflow_primer, and now also a clamped passthrough of any structured
35
60
  // body.details — see genericDegrade) rather than being forwarded as raw
@@ -44,31 +69,71 @@
44
69
  //
45
70
  // ── Response budget invariant ───────────────────────────────────────────
46
71
  //
47
- // INVARIANT: the serialized form of any TeachingError this module builds
48
- // (serializeTeachingError's output, exactly what a caller receives) is
49
- // always <= ERROR_BUDGET_CHARS (1200 chars, the wire-format size measured
50
- // through serializeResult exactly as server.ts emits it) for arbitrary
51
- // adversarial backend input. `code`, `message` (itself already clamped to
52
- // MESSAGE_CHAR_BUDGET), `recipe` (clamped to RECIPE_CHAR_BUDGET), and
53
- // `allowedNext` are always preserved WHOLE regardless of size, since the
54
- // contract mandates all four unconditionally; `detail` is the one
55
- // auxiliary field, and the only field this module ever sacrifices to hold
56
- // the invariant.
72
+ // INVARIANT: error results built through buildTeachingError are always <=
73
+ // ERROR_BUDGET_CHARS (1200 chars, the wire-format size measured through
74
+ // serializeResult exactly as server.ts emits it) for arbitrary adversarial
75
+ // backend input. The narrow pull_requests_create github_error passthrough is
76
+ // the deliberate exception: it preserves GitHub's decoded body and is not
77
+ // truncated or passed through enforceErrorBudget. This is a genuine ceiling
78
+ // on the SERIALIZED (wire) size for the teaching-error catalog, not just on
79
+ // each field's own JS string length: a per-field
80
+ // codepoint clamp (MESSAGE_CHAR_BUDGET, RECIPE_CHAR_BUDGET, the
81
+ // DETAIL_* family) bounds how many characters a field's own VALUE holds,
82
+ // but JSON.stringify can expand a single character into a much longer
83
+ // escape sequence (e.g. a JSON-unescaped control character like U+0001
84
+ // becomes the 6-char \u0001 escape), so a field that is short in JS
85
+ // terms can still be long on the wire. `code`, `recipe`, and `allowedNext` are
86
+ // preserved WHOLE regardless of size (the contract mandates all four
87
+ // unconditionally, and none of the three is ever backend-controlled raw
88
+ // text at any of today's catalog call sites -- recipe is always a
89
+ // hand-authored fixed string, code is either a fixed string or a
90
+ // backend code clamped to its own CODE_CHAR_BUDGET (see genericDegrade;
91
+ // kept a separate constant from DETAIL_ENTRY_CHAR_BUDGET precisely so
92
+ // raising the detail budget can never silently raise how much of `code`
93
+ // this module is willing to carry through), and allowedNext is always a
94
+ // small fixed verb-name list); `detail` and, as of this hardening pass,
95
+ // `message` (which DOES carry raw, potentially escape-heavy backend
96
+ // text -- see `backendMessage`) are the two fields this module will
97
+ // actually shrink, in that order, to hold the invariant for arbitrary
98
+ // adversarial input. This "code/recipe/allowedNext never touched"
99
+ // assumption is itself only as good as CODE_CHAR_BUDGET/RECIPE_CHAR_BUDGET
100
+ // staying small enough that the rest of the envelope (those three plus a
101
+ // fully-minimized-or-absent `detail`) always leaves room for at least an
102
+ // empty `message` -- see the envelope-floor test in
103
+ // tests/errors.test.ts and enforceErrorBudget's own handling of the case
104
+ // where that floor assumption fails.
57
105
  //
58
106
  // The per-field clamps below (DETAIL_CLAMP, DETAIL_KEY_CLAMP,
59
107
  // DETAIL_ENTRY_CHAR_BUDGET, MESSAGE_CHAR_BUDGET, RECIPE_CHAR_BUDGET) each
60
- // bound a single field, never their sum: several near-max fields at once
108
+ // bound a single field's codepoint count, never the field's escaped wire
109
+ // cost nor the whole object's sum: several near-max fields at once
61
110
  // (precondition_failed's failed[] with several entries, each carrying an
62
111
  // optional `error` string alongside rule/message, or a wide generic
63
- // `details` object) can still exceed the budget in total even when every
64
- // individual field stayed within its own clamp. buildTeachingError's own
65
- // enforceErrorBudget step is the single place that actually guarantees the
66
- // TOTAL: it re-measures the whole serialized object after construction
67
- // and, only when still over budget, first re-clamps `detail` harder (same
68
- // recursive clamp, tighter limits), then, if that is still not enough,
69
- // replaces `detail` entirely with a small, visible summary object instead
70
- // of truncating it into something silently misleading or dropping it
71
- // without a trace.
112
+ // `details` object), or a single escape-heavy `message`, can still exceed
113
+ // the budget even when every individual field stayed within its own
114
+ // codepoint clamp (measured: a 1000-codepoint message of pure U+0001
115
+ // characters clamps to MESSAGE_CHAR_BUDGET=300 codepoints by field-count,
116
+ // but serializes to 1877 wire chars on its own, already over
117
+ // ERROR_BUDGET_CHARS with an empty `detail` -- see
118
+ // tests/errors.test.ts's "not_claimed, no detail: an escape-heavy message
119
+ // alone still respects ERROR_BUDGET_CHARS" test (describe block
120
+ // "escape-aware message trim: true wire-format ceiling (task 18e54531)")
121
+ // for the measured number; it is not separately re-asserted as an exact
122
+ // pin anywhere, only via the <= ERROR_BUDGET_CHARS check that test makes.
123
+ // buildTeachingError's own enforceErrorBudget step is the single
124
+ // place that actually guarantees the TOTAL: it re-measures the whole
125
+ // serialized object after construction and, only when still over budget,
126
+ // first re-clamps `detail` harder (same recursive clamp, tighter limits),
127
+ // then, if that is still not enough, replaces `detail` entirely with a
128
+ // small, visible summary object (added only when this entry actually HAD
129
+ // a `detail` to begin with -- never fabricated out of nothing) instead of
130
+ // truncating it into something silently misleading or dropping it
131
+ // without a trace, and, only if the total STILL exceeds budget even with
132
+ // `detail` minimized as far as it goes, shortens `message` itself as the
133
+ // last resort (codepoint-safe, via `clamp`, so this can never reintroduce
134
+ // the surrogate-splitting bug the codepoint-safe `clamp` above exists to
135
+ // close) down to whatever room remains after the rest of the envelope
136
+ // (code/recipe/allowedNext/detail) is accounted for.
72
137
  // ── Budget / clamp constants ────────────────────────────────────────────
73
138
  //
74
139
  // Mirrors receipt.ts's DETAIL_CLAMP / ENTRY_CHAR_BUDGET convention (same
@@ -93,13 +158,49 @@ const DETAIL_ENTRY_CHAR_BUDGET = 60;
93
158
  * that must itself never grow into a prose blob. */
94
159
  const MESSAGE_CHAR_BUDGET = 300;
95
160
  const RECIPE_CHAR_BUDGET = 240;
161
+ /** Char bound for `code` on the generic degrade path (genericDegrade), the
162
+ * one call site where `code` carries raw backend text (the backend's own
163
+ * `error` string, passed through verbatim -- see genericDegrade's own
164
+ * comment) rather than a short hand-authored literal. Deliberately its
165
+ * OWN constant, not DETAIL_ENTRY_CHAR_BUDGET reused: `code` sits in the
166
+ * part of the envelope enforceErrorBudget never re-visits (see the file
167
+ * header), so its clamp is one of the inputs the "envelope always leaves
168
+ * room for at least an empty `message`" assumption depends on. Sharing
169
+ * DETAIL_ENTRY_CHAR_BUDGET would silently couple that assumption to
170
+ * whatever value `detail` clamping happens to want, with nothing
171
+ * documenting the link -- raising DETAIL_ENTRY_CHAR_BUDGET to, say, 250
172
+ * for an unrelated detail-sizing reason would silently let `code` grow to
173
+ * 250 codepoints too, which alone can cost up to ~6x that on the wire for
174
+ * escape-heavy input (see the file header), enough to blow
175
+ * ERROR_BUDGET_CHARS on `code` alone even with an empty `message` and no
176
+ * `detail`. See the envelope-floor test in tests/errors.test.ts, which
177
+ * pins this budget's effect on the worst-case envelope size directly. */
178
+ const CODE_CHAR_BUDGET = 60;
96
179
  const TRUNCATION_MARKER = "...";
97
- /** Hard ceiling on the whole serialized teaching error (JSON.stringify(x,
98
- * null, 2), the exact wire format serializeTeachingError/serializeResult
99
- * emit). See the file header's "Response budget invariant" section: this
100
- * is the number enforceErrorBudget (below) actually holds the line at,
101
- * since the per-field clamps above only ever bound one field at a time. */
180
+ /** Hard ceiling on serialized errors constructed through buildTeachingError
181
+ * (JSON.stringify(x, null, 2), the exact wire format
182
+ * serializeTeachingError/serializeResult emit). The dedicated
183
+ * pull_requests_create github_error passthrough intentionally preserves its
184
+ * decoded GitHub body without this ceiling. See the file header's "Response
185
+ * budget invariant" section. */
102
186
  const ERROR_BUDGET_CHARS = 1200;
187
+ /** `code` marker for the (not achievable by any catalog entry today, see
188
+ * the envelope-floor test in tests/errors.test.ts) case where
189
+ * enforceErrorBudget's own envelope-floor assumption fails: `detail` is
190
+ * fully minimized or was never present, `message` has been trimmed all
191
+ * the way down to `""`, and the response STILL exceeds ERROR_BUDGET_CHARS
192
+ * -- meaning the fixed part of the envelope (code/recipe/allowedNext)
193
+ * alone is over budget. enforceErrorBudget overwrites `code` with this
194
+ * marker in that case, the one place it is ever touched there, so the
195
+ * condition is visible (greppable in logs, assertable in a test) instead
196
+ * of silently returning an over-budget response while claiming success.
197
+ * Deliberately never thrown as an exception: this module IS the
198
+ * production error-serialization path server.ts's wrap() depends on for
199
+ * every failed tool call, and an exception thrown from inside it would
200
+ * surface as an unhandled crash of that call instead of a graceful (if,
201
+ * in this unreachable-today case, still oversized) response -- strictly
202
+ * worse for a caller than a marked, still-served response. */
203
+ const ERROR_BUDGET_OVERFLOW_CODE = "error_budget_overflow";
103
204
  /** Tighter versions of DETAIL_CLAMP / DETAIL_KEY_CLAMP /
104
205
  * DETAIL_ENTRY_CHAR_BUDGET, used only by enforceErrorBudget's second
105
206
  * ("harder reclamp") pass, when the normal clamp still was not enough to
@@ -107,10 +208,36 @@ const ERROR_BUDGET_CHARS = 1200;
107
208
  const HARD_DETAIL_CLAMP = 2;
108
209
  const HARD_DETAIL_KEY_CLAMP = 3;
109
210
  const HARD_DETAIL_ENTRY_CHAR_BUDGET = 20;
211
+ // Codepoint-safe, not grapheme-safe: truncates on Unicode codepoint
212
+ // boundaries (via Array.from, which groups a UTF-16 surrogate pair into one
213
+ // iteration step) so a clamp can never split a surrogate pair and leave a
214
+ // lone high/low surrogate in the output -- the failure mode a 100-emoji
215
+ // title hits under plain `value.slice(0, n)` (each emoji here is one
216
+ // astral codepoint = one surrogate pair; slicing at an odd code-unit
217
+ // offset keeps the high surrogate and drops its low half). This does NOT
218
+ // guarantee every clamp lands on a grapheme-CLUSTER boundary (e.g. a
219
+ // base+combining-mark or ZWJ sequence spanning several codepoints could
220
+ // still be split mid-cluster, same as before) -- Intl.Segmenter would be
221
+ // needed for that, and today's reported failure is specifically a split
222
+ // surrogate PAIR (one codepoint), not a split grapheme cluster, so
223
+ // codepoint-safety is the precise, minimal fix; see
224
+ // tests/errors.test.ts's "a 100-emoji activeClaim.title clamps to
225
+ // DETAIL_ENTRY_CHAR_BUDGET without leaving a lone surrogate, and
226
+ // round-trips through a strict UTF-8 re-encode" test (describe block
227
+ // "clamp is surrogate-safe: codepoint-based truncation (task 18e54531)")
228
+ // for the boundary this closes.
110
229
  function clamp(value, maxChars) {
111
- return value.length > maxChars
112
- ? value.slice(0, maxChars - TRUNCATION_MARKER.length) + TRUNCATION_MARKER
113
- : value;
230
+ // value.length (UTF-16 code units) is always >= the codepoint count (an
231
+ // astral codepoint is 2 units, a BMP codepoint is 1), so if the code-unit
232
+ // length already fits the budget the codepoint count fits too -- skips
233
+ // the Array.from allocation on the overwhelmingly common
234
+ // ASCII/no-truncation-needed path.
235
+ if (value.length <= maxChars)
236
+ return value;
237
+ const codepoints = Array.from(value);
238
+ if (codepoints.length <= maxChars)
239
+ return value;
240
+ return (codepoints.slice(0, Math.max(0, maxChars - TRUNCATION_MARKER.length)).join("") + TRUNCATION_MARKER);
114
241
  }
115
242
  function buildTeachingError(opts) {
116
243
  const err = {
@@ -133,6 +260,33 @@ function buildTeachingError(opts) {
133
260
  // declarations are hoisted, so the forward reference is fine.
134
261
  return enforceErrorBudget(err);
135
262
  }
263
+ function githubCreateError(status, body, message) {
264
+ const existing = body.existingPullRequest;
265
+ const existingPullRequest = existing &&
266
+ typeof existing === "object" &&
267
+ typeof existing.number === "number" &&
268
+ typeof existing.url === "string"
269
+ ? {
270
+ number: existing.number,
271
+ url: existing.url,
272
+ }
273
+ : undefined;
274
+ // Unlike the generic teaching-error path, this narrowly scoped mapping
275
+ // intentionally preserves GitHub's decoded failure body. The caller needs
276
+ // it to distinguish a final upstream outage from an already-created PR.
277
+ return {
278
+ ok: false,
279
+ error: {
280
+ code: "github_error",
281
+ message: clamp(message, MESSAGE_CHAR_BUDGET),
282
+ recipe: "inspect the GitHub failure and retry pull_requests_create only when the upstream condition is resolved",
283
+ allowedNext: ["pull_requests_create"],
284
+ status,
285
+ ...(Object.prototype.hasOwnProperty.call(body, "github") ? { github: body.github } : {}),
286
+ ...(existingPullRequest ? { existingPullRequest } : {}),
287
+ },
288
+ };
289
+ }
136
290
  /** Serializes a TeachingError exactly as server.ts's serializeResult would
137
291
  * (JSON.stringify(x, null, 2) for a non-string result — a teaching error is
138
292
  * always an object, never a string, so the two are always equal for this
@@ -173,12 +327,154 @@ function notClaimedError(message) {
173
327
  // (backend/src/routes/tasks.ts: POST /tasks/pickup, POST
174
328
  // /tasks/:id/start). The backend's own code is already specific, so it is
175
329
  // kept verbatim as this entry's code.
176
- function alreadyClaimedError(message) {
330
+ //
331
+ // Review-retention case (rc-v1-C008 Cold-Start-Eval, 2026-08-12 live
332
+ // finding; generalized on the rc-v1-already-claimed-review-recipe review
333
+ // round, H1): task_finish's own documented semantics clear the work claim
334
+ // only when the task lands on a TERMINAL state, and keep it on EVERY finish
335
+ // that instead lands the task back on `review` -- there is no separate
336
+ // request_changes-only code path (backend/src/routes/tasks.ts ~3150-3156:
337
+ // `if (isTerminalState(...)) { clear claim fields }`, no `else`).
338
+ // request_changes (the rework loop keeping the original author's claim so
339
+ // they resume automatically) is the one caller-visible EXAMPLE of this, not
340
+ // the definition: an ordinary multi-step workflow whose own
341
+ // expectedFinishState is `review` keeps the claim the exact same way, with
342
+ // no request_changes outcome involved at all. A recipe that names only
343
+ // request_changes reads as a scope test to a caller whose task landed in
344
+ // review some other way, who could then wrongly conclude task_abandon is
345
+ // safe. Named below as "work claim on an in-review task" instead, with no
346
+ // reference to how the task got there.
347
+ //
348
+ // Reviewer branch (H2): this same 409 fires identically for a REVIEW claim
349
+ // wall, not just a work claim -- task_pickup's and task_start's own
350
+ // claim-wall queries both match `reviewClaimedByAgentId === actor.tokenId
351
+ // && status === "review"` too (backend/src/routes/tasks.ts ~1462-1465 for
352
+ // /tasks/pickup, ~1681-1684 for /tasks/:id/start), and by construction ANY
353
+ // review claim sits on a task currently in review. For that caller,
354
+ // task_abandon on the held claim IS the correct, immediate, clean exit: the
355
+ // abandon route's "cannot abandon while in review" guard
356
+ // (backend/src/routes/tasks.ts ~3540-3541: `if (holdsWorkClaim &&
357
+ // !holdsReviewClaim && isReviewState(...))`) is scoped to a WORK claim only
358
+ // and never fires for a review claim. A recipe that tells a role=reviewer
359
+ // caller to wait, merge, or avoid task_abandon would be actively wrong for
360
+ // them.
361
+ //
362
+ // Whether the held claim is an ordinary in_progress work claim, a work
363
+ // claim retained on a task now in review, or a review claim is only
364
+ // PARTIALLY determinable from this catalog entry's only input. The 409 body
365
+ // both real call sites send is `{ error: "already_claimed", message,
366
+ // activeClaim: { taskId, title, role } }` (verified at
367
+ // backend/src/routes/tasks.ts:1469-1480 for /tasks/pickup and :1688-1699
368
+ // for /tasks/:id/start, and documented at docs/okf/claim-model.md:19).
369
+ // `role` ("author" vs "reviewer", derived from which claim column matched)
370
+ // DOES cleanly separate the reviewer case from both author cases (a
371
+ // role="reviewer" claim is always a review claim, per the query above) --
372
+ // it is only WITHIN role="author" that an ordinary in_progress claim and a
373
+ // work claim retained on a review-state task stay indistinguishable from
374
+ // this input alone (there is no `status` field on activeClaim). This
375
+ // input is not status-BLIND, though: the caller already has taskId in hand
376
+ // and is one tasks_get call away from the actual status if it needs to
377
+ // decide programmatically rather than read the recipe's cases -- M3
378
+ // (rc-v1-already-claimed-review-recipe review round, task 008ac513, the
379
+ // follow-up this comment used to point at) closes that gap: extractActiveClaim
380
+ // below passes the backend's own `activeClaim: { taskId, title, role }`
381
+ // through, clamped, as this entry's `detail.activeClaim`, and `tasks_get`
382
+ // is added to `allowedNext` so the check-its-status call is itself
383
+ // immediately callable per the allowedNext contract, not just implied by
384
+ // the prose. This entry still names all three cases explicitly in the
385
+ // recipe text, keyed by claim kind / state rather than by role, so the
386
+ // caller self-selects the right one instead of defaulting to task_abandon,
387
+ // which is safe for two of the three cases and rejected outright for the
388
+ // third; `detail.activeClaim` is the machine-readable input a caller can
389
+ // use to do that same selection programmatically instead of reading prose.
390
+ //
391
+ // task_finish is deliberately NOT offered as a blanket corrective for the
392
+ // workClaimInReview case below: on that task it is either rejected outright
393
+ // (403 when a distinct reviewer already holds the review claim on a
394
+ // REQUIRES_DISTINCT_REVIEWER project, backend/src/routes/tasks.ts
395
+ // ~2825-2831; 409 `reviewer_conflict` when a distinct reviewer already
396
+ // holds the claim on a non-DR project, ~2805-2818) or is the deliberate
397
+ // self-approve branch on a non-DR project with no reviewer claim yet held
398
+ // (~2539-2557, `outcome` required). It is therefore SAFE when it works,
399
+ // just often unavailable to a caller who cannot know in advance which of
400
+ // those applies -- "wait for the reviewer" is offered as the option that is
401
+ // always safe regardless.
402
+ //
403
+ // ALREADY_CLAIMED_CASES (M6) names the three case-sentences as individually
404
+ // testable, exported constants instead of one hand-assembled string tests
405
+ // would otherwise have to slice out of by searching for a substring like
406
+ // "review": a slice-by-indexOf assertion breaks on any semantically-safe
407
+ // reword that keeps the meaning but moves the words (see
408
+ // tests/errors.test.ts for the constant-based assertions this enables).
409
+ export const ALREADY_CLAIMED_CASES = {
410
+ inProgress: "In-progress claim: task_finish or task_abandon on it.",
411
+ workClaimInReview: "Work claim on an in-review task: abandon is rejected (409); wait for the reviewer, or task_merge + task_finish outcome=approve.",
412
+ reviewClaim: "Review claim: task_abandon frees the review lock.",
413
+ };
414
+ const ALREADY_CLAIMED_RECIPE = [
415
+ ALREADY_CLAIMED_CASES.inProgress,
416
+ ALREADY_CLAIMED_CASES.workClaimInReview,
417
+ ALREADY_CLAIMED_CASES.reviewClaim,
418
+ ].join(" ");
419
+ // M3 follow-up (task 008ac513): pulls the backend's own `activeClaim: {
420
+ // taskId, title, role }` (see the file comment above this catalog entry)
421
+ // out of the 409 body and clamps it for `detail.activeClaim`, the same
422
+ // DETAIL_ENTRY_CHAR_BUDGET convention every other structured detail field
423
+ // in this module uses. Untrusted response data, same stance as the other
424
+ // extract-from-body helpers in this file (asBackendBody, preconditionFailedError's
425
+ // rawFailed mapping): every field is validated by type AND non-emptiness
426
+ // before use (`isUsableString` below), and a missing/malformed activeClaim
427
+ // (or one with no usable field at all -- absent, wrong type, or present as
428
+ // an empty string) degrades to `undefined` -- the caller then just sees the
429
+ // recipe prose with no detail, the exact behavior before this change,
430
+ // rather than a detail object with fabricated, empty, or non-string fields.
431
+ // The field SET this function looks at is fixed at exactly these three
432
+ // (taskId, title, role): a present-but-non-string field (e.g. a numeric
433
+ // taskId) is dropped the same way a missing field is, not surfaced under a
434
+ // different name or flagged separately -- this is a deliberate, narrower
435
+ // exception to the "the drop is never silent" stance the rest of this
436
+ // module's clampDetailValue path takes for arbitrary detail objects, scoped
437
+ // to this one small, fixed, backend-controlled shape.
438
+ function isUsableString(value) {
439
+ return typeof value === "string" && value.length > 0;
440
+ }
441
+ function extractActiveClaim(body) {
442
+ const raw = body.activeClaim;
443
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
444
+ return undefined;
445
+ const claim = raw;
446
+ const taskId = isUsableString(claim.taskId) ? clamp(claim.taskId, DETAIL_ENTRY_CHAR_BUDGET) : undefined;
447
+ const title = isUsableString(claim.title) ? clamp(claim.title, DETAIL_ENTRY_CHAR_BUDGET) : undefined;
448
+ const role = isUsableString(claim.role) ? clamp(claim.role, DETAIL_ENTRY_CHAR_BUDGET) : undefined;
449
+ if (taskId === undefined && title === undefined && role === undefined)
450
+ return undefined;
451
+ return {
452
+ ...(taskId !== undefined ? { taskId } : {}),
453
+ ...(title !== undefined ? { title } : {}),
454
+ ...(role !== undefined ? { role } : {}),
455
+ };
456
+ }
457
+ function alreadyClaimedError(body, message) {
458
+ const activeClaim = extractActiveClaim(body);
177
459
  return buildTeachingError({
178
460
  code: "already_claimed",
179
461
  message,
180
- recipe: "call task_finish or task_abandon on your current task before claiming another",
181
- allowedNext: ["task_finish", "task_abandon"],
462
+ recipe: ALREADY_CLAIMED_RECIPE,
463
+ // M4: deliberately the UNION over all three ALREADY_CLAIMED_CASES above,
464
+ // not just the in-progress pair task_finish/task_abandon -- task_merge
465
+ // is the corrective action the workClaimInReview case's own sentence
466
+ // names (merge, then task_finish outcome=approve), so it must be
467
+ // immediately callable per the allowedNext contract
468
+ // (docs/response-contract-v1.md's "verb names the caller can call
469
+ // immediately"). The recipe text is what actually SELECTS the right
470
+ // case for the caller's own claim; allowedNext only has to list every
471
+ // verb any one of the three cases could legitimately call next.
472
+ // M3 follow-up: tasks_get is added too -- it is the concrete corrective
473
+ // for "check its status" (see the M3 comment above extractActiveClaim),
474
+ // and, same as task_merge, must be immediately callable per the
475
+ // allowedNext contract rather than only implied by prose.
476
+ allowedNext: ["task_finish", "task_abandon", "task_merge", "tasks_get"],
477
+ ...(activeClaim ? { detail: { activeClaim } } : {}),
182
478
  });
183
479
  }
184
480
  // 3. Branch precondition. task_start / task_finish / tasks_transition [POST
@@ -353,6 +649,62 @@ function respecConflictError(message) {
353
649
  allowedNext: ["task_abandon", "task_respec"],
354
650
  });
355
651
  }
652
+ // 7a. Creator-abandon conflict. task_creator_abandon only retires an OPEN,
653
+ // unclaimed task the caller created (backend/src/routes/tasks.ts,
654
+ // CREATOR_ABANDON_STATE_CONFLICT_MESSAGE = "Task must be open and unclaimed
655
+ // to creator-abandon") -- any other state, or a lost CAS race, is rejected
656
+ // with 409 `conflict`. Same generic backend code ("conflict") as
657
+ // RESPEC_CONFLICT_PATTERN immediately above and several other unrelated
658
+ // 409s, so this entry is message-pattern matched and mints its own code,
659
+ // sibling to respec_conflict. Unlike respec_conflict there is no
660
+ // self-service corrective to name: this verb never holds a claim to release
661
+ // first, and a lost CAS race means some other actor already changed the row
662
+ // out from under the caller. `recipe` deliberately avoids the literal
663
+ // `task_creator_abandon` token (the recipe-vs-allowedNext coherence guard
664
+ // in tests/errors.test.ts would then require it in `allowedNext`, and
665
+ // blindly retrying the same call is not a reliable next step here) --
666
+ // allowedNext offers only `tasks_get` so the caller can see the task's
667
+ // current state and decide what to do next.
668
+ const CREATOR_ABANDON_CONFLICT_PATTERN = /open and unclaimed to creator-abandon/i;
669
+ function creatorAbandonConflictError(message) {
670
+ return buildTeachingError({
671
+ code: "creator_abandon_conflict",
672
+ message,
673
+ recipe: "creator-abandon only works on an open, unclaimed task; call tasks_get to see its current state",
674
+ allowedNext: ["tasks_get"],
675
+ });
676
+ }
677
+ // 7b/7c. v1 backlog routing (backend/src/routes/tasks.ts): every
678
+ // agent-created task lands in `backlog` and waits for an operator to
679
+ // promote it to `open` -- an agent cannot create a directly-claimable task
680
+ // in v1. Two distinct backend codes, each already its own (not a shared
681
+ // generic code needing message-pattern matching, unlike respec_conflict/
682
+ // creator_abandon_conflict above): backlog_routing_enforced (400,
683
+ // task_create rejects an explicit non-backlog status from an agent caller)
684
+ // and backlog_not_promoted (403, task_start and the deprecated tasks_claim
685
+ // alias reject a backlog task no operator has promoted yet).
686
+ function backlogRoutingEnforcedError(message) {
687
+ return buildTeachingError({
688
+ code: "backlog_routing_enforced",
689
+ message,
690
+ recipe: 'omit status (or pass status: "backlog") on task_create; agent-created tasks always land in backlog and wait for an operator to promote them to open',
691
+ allowedNext: ["task_create"],
692
+ });
693
+ }
694
+ // backlog_not_promoted's recipe deliberately avoids the literal task_start /
695
+ // task_pickup tokens (the message already says "before an agent can start
696
+ // it") -- same allowedNext-vs-recipe discipline as
697
+ // creatorAbandonConflictError's own comment above: there is no self-service
698
+ // way to promote a backlog task (that edge is human-only), so the recipe
699
+ // names only the two verbs an agent CAN still call while it waits.
700
+ function backlogNotPromotedError(message) {
701
+ return buildTeachingError({
702
+ code: "backlog_not_promoted",
703
+ message,
704
+ recipe: "this task awaits operator promotion from backlog to open; call task_respec to refine it while it waits, or task_creator_abandon to withdraw it if you created it",
705
+ allowedNext: ["task_respec", "task_creator_abandon"],
706
+ });
707
+ }
356
708
  // 8. task_finish `result` (and the deprecated tasks_update's) as plain
357
709
  // string. Unlike the other catalog entries, the backend performs NO
358
710
  // validation of this today (`result` is stored verbatim as free text) —
@@ -511,17 +863,29 @@ function lowConfidenceError(body, message) {
511
863
  // catalog entry #8 (resultMustBePlainStringError) — a client-side guard
512
864
  // checked before, or in place of, any network call.
513
865
  //
514
- // project_addressing_conflict covers BOTH directions of the same "exactly
515
- // one of projectId/projectSlug" requirement, not just "both provided":
516
- // task_create's own client-side guard (tools.ts) also rejects the mirror-
517
- // image mistake, neither field set. That case used to throw a bare,
518
- // unteaching Error (rc-v1-C006 round-2 review, LOW) instead of going
866
+ // project_addressing_conflict covers every direction of the same "exactly
867
+ // one of project/projectId/projectSlug" requirement, not just "both
868
+ // provided": task_create's own client-side guard (tools.ts) also rejects
869
+ // the mirror-image mistake, no field set at all. That case used to throw a
870
+ // bare, unteaching Error (rc-v1-C006 round-2 review, LOW) instead of going
519
871
  // through this catalog. Rather than mint a second, near-duplicate code for
520
- // what is really the same "exactly one" constraint violated the other way,
521
- // `reason` selects direction-specific message/recipe/allowedNext under the
522
- // SAME code: "both" needs no extra corrective (the caller already named
523
- // both candidates, it just needs to pick one), but "neither" used to point
524
- // at projects_list as the self-service way to find the project.
872
+ // what is really the same "exactly one" constraint violated a different
873
+ // way, `reason` selects a direction-specific message/recipe/allowedNext
874
+ // under the SAME code: any "both provided" pairing needs no extra
875
+ // corrective (the caller already named both candidates, it just needs to
876
+ // pick one), but "neither" used to point at projects_list as the
877
+ // self-service way to find the project.
878
+ //
879
+ // task_create's own unified `project` field (added alongside project_tasks's
880
+ // pre-existing one) widens the "exactly one" constraint from a pair to a
881
+ // triple: `project` conflicting with EITHER projectId or projectSlug is its
882
+ // own reason (project_and_projectId / project_and_projectSlug) rather than
883
+ // folded into "both_provided", so the message names the two fields that
884
+ // actually collided instead of a generic "more than one". projectId and
885
+ // projectSlug conflicting with EACH OTHER keeps the original "both_provided"
886
+ // reason and wording unchanged (byte-identical for any caller not using the
887
+ // new field). "neither_provided"'s message/recipe now names all three
888
+ // fields, since a caller who provides none of them can now choose any one.
525
889
  //
526
890
  // rc-v1-C007 pruned projects_list out of the DEFAULT tool registration
527
891
  // (tools.ts's LEGACY_VERB_NAMES); it is opt-in only via
@@ -538,8 +902,24 @@ export function projectAddressingConflictError(verb, reason = "both_provided") {
538
902
  if (reason === "neither_provided") {
539
903
  return buildTeachingError({
540
904
  code: "project_addressing_conflict",
541
- message: "neither projectId nor projectSlug was provided; pass exactly one",
542
- recipe: `ask the operator for this project's slug or id (or, with AGENT_TASKS_MCP_LEGACY=1 set, call projects_list), then resubmit ${verb} with projectId or projectSlug set`,
905
+ message: "none of project, projectId, or projectSlug was provided; pass exactly one",
906
+ recipe: `ask the operator for this project's slug or id (or, with AGENT_TASKS_MCP_LEGACY=1 set, call projects_list), then resubmit ${verb} with project, projectId, or projectSlug set`,
907
+ allowedNext: [verb],
908
+ });
909
+ }
910
+ if (reason === "project_and_projectId") {
911
+ return buildTeachingError({
912
+ code: "project_addressing_conflict",
913
+ message: "project and projectId were both provided; pass exactly one",
914
+ recipe: `resubmit ${verb} with only one of project or projectId`,
915
+ allowedNext: [verb],
916
+ });
917
+ }
918
+ if (reason === "project_and_projectSlug") {
919
+ return buildTeachingError({
920
+ code: "project_addressing_conflict",
921
+ message: "project and projectSlug were both provided; pass exactly one",
922
+ recipe: `resubmit ${verb} with only one of project or projectSlug`,
543
923
  allowedNext: [verb],
544
924
  });
545
925
  }
@@ -655,11 +1035,13 @@ function clampGenericDetail(details) {
655
1035
  // Bookkeeping fields a catalog entry or clampDetailValue itself may already
656
1036
  // have set to record a TRUE original count (precondition_failed's
657
1037
  // totalFailed, low_confidence's totalMissing, clampDetailValue's own
658
- // totalKeys). A second, harder clamp pass over an already-clamped object
659
- // must not re-derive these from the intermediate object's own (already
660
- // shrunk) entry count -- that would silently replace an accurate original
661
- // count with a smaller, misleading one. See reclampDetailHarder below.
662
- const DETAIL_TOTAL_MARKER_KEYS = ["totalFailed", "totalMissing", "totalKeys"];
1038
+ // totalKeys, and the generic degrade path's own totalIssues -- see
1039
+ // deriveGenericDetailSource). A second, harder clamp pass over an
1040
+ // already-clamped object must not re-derive these from the intermediate
1041
+ // object's own (already shrunk) entry count -- that would silently replace
1042
+ // an accurate original count with a smaller, misleading one. See
1043
+ // reclampDetailHarder below.
1044
+ const DETAIL_TOTAL_MARKER_KEYS = ["totalFailed", "totalMissing", "totalKeys", "totalIssues"];
663
1045
  /** Re-clamps a detail object with the HARD_* limits, WITHOUT letting the
664
1046
  * pass corrupt any totalFailed/totalMissing/totalKeys marker already
665
1047
  * present (see DETAIL_TOTAL_MARKER_KEYS): those numbers are pulled out
@@ -685,20 +1067,94 @@ function reclampDetailHarder(detail) {
685
1067
  });
686
1068
  return { ...reclampedRest, ...preservedMarkers };
687
1069
  }
688
- /** Enforces the response budget invariant documented in the file header.
1070
+ /** True wire-format fit check: builds the candidate error with `message`
1071
+ * swapped in and measures the actual serialized (escaped) length, rather
1072
+ * than trusting `candidateMessage`'s own JS length as a proxy for its
1073
+ * wire cost. JSON.stringify's own escaping rules are the single source of
1074
+ * truth for that cost; re-deriving them analytically here would just be a
1075
+ * second, driftable copy of the same logic. */
1076
+ function fitsWithMessage(err, candidateMessage) {
1077
+ return (serializeTeachingError({ ...err, error: { ...err.error, message: candidateMessage } }).length <=
1078
+ ERROR_BUDGET_CHARS);
1079
+ }
1080
+ /** Last-resort step in enforceErrorBudget: shortens `message` itself when
1081
+ * the serialized total still exceeds ERROR_BUDGET_CHARS even after
1082
+ * `detail` has already been minimized as far as it can go. `message` can
1083
+ * carry raw, untrusted backend text (see `backendMessage`); a per-field
1084
+ * codepoint clamp (MESSAGE_CHAR_BUDGET, applied earlier in
1085
+ * buildTeachingError) bounds its JS string length but not its escaped
1086
+ * WIRE size, since JSON.stringify can expand a single character (a
1087
+ * control character outside \n\t\r\b\f) into a 6-char \uXXXX escape -- see
1088
+ * the file header's "Response budget invariant" section. This is the one
1089
+ * place `message` is ever shortened past MESSAGE_CHAR_BUDGET; `code`,
1090
+ * `recipe`, and `allowedNext` are still never touched here.
1091
+ *
1092
+ * Binary search over codepoint-prefix length, reusing `clamp` (already
1093
+ * codepoint-safe) for each candidate rather than slicing directly, so
1094
+ * this can never reintroduce the surrogate-splitting bug `clamp`'s own
1095
+ * codepoint-safety fix exists to close. `best` starts at `""` and is only
1096
+ * ever raised by a candidate that actually fits, so if even an empty
1097
+ * message does not fit (the surrounding code/recipe/allowedNext/detail
1098
+ * envelope alone already exceeds the budget -- not achievable by any
1099
+ * catalog entry today, see the file header and the envelope-floor test in
1100
+ * tests/errors.test.ts) `best` stays `""`: this function alone does NOT
1101
+ * guarantee the result fits (see enforceErrorBudget's own handling of
1102
+ * that case, immediately after its call to this function). */
1103
+ function trimMessageForBudget(err) {
1104
+ const codepointCount = Array.from(err.error.message).length;
1105
+ let lo = 0;
1106
+ let hi = codepointCount;
1107
+ let best = "";
1108
+ while (lo <= hi) {
1109
+ const mid = Math.floor((lo + hi) / 2);
1110
+ const candidate = clamp(err.error.message, mid);
1111
+ if (fitsWithMessage(err, candidate)) {
1112
+ best = candidate;
1113
+ lo = mid + 1;
1114
+ }
1115
+ else {
1116
+ hi = mid - 1;
1117
+ }
1118
+ }
1119
+ return { ...err, error: { ...err.error, message: best } };
1120
+ }
1121
+ /** Enforces the response budget invariant documented in the file header for
1122
+ * errors built through buildTeachingError (not the dedicated
1123
+ * pull_requests_create github_error passthrough).
689
1124
  * buildTeachingError's own per-field clamps (MESSAGE_CHAR_BUDGET,
690
1125
  * RECIPE_CHAR_BUDGET) and each catalog entry's own array/key clamps
691
- * bound individual FIELDS, never their sum: several near-max fields at
692
- * once can still exceed ERROR_BUDGET_CHARS in total. This is the one
693
- * place that actually guarantees the total. `code`, `message`, `recipe`,
694
- * and `allowedNext` are never touched here (the contract mandates them
695
- * whole, regardless of size). Only `detail`, the one field the contract
696
- * marks auxiliary, is ever degraded, and NEVER silently: first a harder
697
- * recursive re-clamp (same clampDetailValue walk, tighter HARD_* limits),
698
- * and, only if that still is not enough, a small visible summary object
699
- * replaces `detail` entirely, so a caller always sees that something was
700
- * omitted rather than getting a truncated, possibly-misleading fragment. */
701
- function enforceErrorBudget(err) {
1126
+ * bound individual FIELDS' codepoint counts, never their escaped wire
1127
+ * cost nor their sum: several near-max fields at once, or a single
1128
+ * escape-heavy `message`, can still exceed ERROR_BUDGET_CHARS in total.
1129
+ * This is the one place that actually guarantees the total for that
1130
+ * teaching-error catalog. `code`,
1131
+ * `recipe`, and `allowedNext` are never touched here EXCEPT in the
1132
+ * unreachable-today overflow case described on ERROR_BUDGET_OVERFLOW_CODE
1133
+ * (the contract otherwise mandates them whole, regardless of size, and
1134
+ * none of the three carries raw untrusted text at any of today's catalog
1135
+ * call sites -- see the file header). `detail` is degraded first, and
1136
+ * NEVER silently: first a harder recursive re-clamp (same
1137
+ * clampDetailValue walk, tighter HARD_* limits), and, only if that still
1138
+ * is not enough AND this entry actually had a `detail` to begin with, a
1139
+ * small visible summary object replaces it entirely, so a caller always
1140
+ * sees that something was omitted rather than getting a truncated,
1141
+ * possibly-misleading fragment (an entry with no `detail` at all never
1142
+ * has one fabricated here -- see the `if (priorDetail)` guard below).
1143
+ * Only if the total STILL exceeds budget after `detail` is fully
1144
+ * minimized (or was never present) does `message` itself get shortened,
1145
+ * via trimMessageForBudget above -- the one scenario the per-field clamps
1146
+ * alone cannot catch, since an escape-heavy `message` can blow the wire
1147
+ * budget even with an empty `detail`.
1148
+ *
1149
+ * Exported so tests/errors.test.ts can exercise the
1150
+ * ERROR_BUDGET_OVERFLOW_CODE fallback directly with a synthetic,
1151
+ * hand-built TeachingError whose code/recipe alone already exceed
1152
+ * ERROR_BUDGET_CHARS -- not a runtime consumer outside this module (same
1153
+ * idiom as KNOWN_RULE_CORRECTIVES/ALREADY_CLAIMED_CASES above), and the
1154
+ * only way to reach that fallback deterministically in a test, since no
1155
+ * real catalog entry's own code/recipe/allowedNext gets anywhere close
1156
+ * to ERROR_BUDGET_CHARS today (see the envelope-floor tests). */
1157
+ export function enforceErrorBudget(err) {
702
1158
  if (serializeTeachingError(err).length <= ERROR_BUDGET_CHARS)
703
1159
  return err;
704
1160
  if (err.error.detail) {
@@ -712,51 +1168,223 @@ function enforceErrorBudget(err) {
712
1168
  if (serializeTeachingError(reclamped).length <= ERROR_BUDGET_CHARS)
713
1169
  return reclamped;
714
1170
  }
715
- // Still over budget even after the harder reclamp (or there was no
716
- // `detail` to reclamp at all): replace `detail` with a small, fixed-size
717
- // summary instead of silently dropping or truncating it. `totalFailed` /
718
- // `totalKeys` are carried over when cheaply available (already computed
719
- // by the catalog entry or by clampDetailValue's own key-count marker)
720
- // since a caller who cannot see the detail at least learns how much of
721
- // it there was.
1171
+ // Still over budget even after the harder reclamp: replace `detail` with
1172
+ // a small, fixed-size summary instead of silently dropping or truncating
1173
+ // it, but only when this entry actually HAD a `detail` to summarize --
1174
+ // fabricating a `detail: {omitted: true, ...}` out of nothing (when
1175
+ // `err.error.detail` was never set) would itself be a misleading claim.
1176
+ // `totalFailed` / `totalKeys` are carried over when cheaply available
1177
+ // (already computed by the catalog entry or by clampDetailValue's own
1178
+ // key-count marker) since a caller who cannot see the detail at least
1179
+ // learns how much of it there was.
1180
+ let withMinimizedDetail = err;
722
1181
  const priorDetail = err.error.detail;
723
- const totalFailed = typeof priorDetail?.totalFailed === "number" ? priorDetail.totalFailed : undefined;
724
- const totalMissing = typeof priorDetail?.totalMissing === "number" ? priorDetail.totalMissing : undefined;
725
- const totalKeys = typeof priorDetail?.totalKeys === "number"
726
- ? priorDetail.totalKeys
727
- : priorDetail && typeof priorDetail === "object"
728
- ? Object.keys(priorDetail).length
729
- : undefined;
1182
+ if (priorDetail) {
1183
+ const totalFailed = typeof priorDetail.totalFailed === "number" ? priorDetail.totalFailed : undefined;
1184
+ const totalMissing = typeof priorDetail.totalMissing === "number" ? priorDetail.totalMissing : undefined;
1185
+ const totalIssues = typeof priorDetail.totalIssues === "number" ? priorDetail.totalIssues : undefined;
1186
+ const totalKeys = typeof priorDetail.totalKeys === "number" ? priorDetail.totalKeys : Object.keys(priorDetail).length;
1187
+ withMinimizedDetail = {
1188
+ ...err,
1189
+ error: {
1190
+ ...err.error,
1191
+ detail: {
1192
+ omitted: true,
1193
+ reason: "detail exceeded the error budget",
1194
+ ...(totalFailed !== undefined ? { totalFailed } : {}),
1195
+ ...(totalMissing !== undefined ? { totalMissing } : {}),
1196
+ ...(totalIssues !== undefined ? { totalIssues } : {}),
1197
+ ...(totalKeys !== undefined ? { totalKeys } : {}),
1198
+ },
1199
+ },
1200
+ };
1201
+ }
1202
+ if (serializeTeachingError(withMinimizedDetail).length <= ERROR_BUDGET_CHARS)
1203
+ return withMinimizedDetail;
1204
+ // `detail` is now as small as this module ever makes it (summarized, or
1205
+ // never present) and the total STILL exceeds budget: the escape-expanded
1206
+ // wire cost of `message` itself is what is blowing the ceiling. Shorten
1207
+ // it, escape-aware, as the true last resort.
1208
+ const trimmed = trimMessageForBudget(withMinimizedDetail);
1209
+ if (serializeTeachingError(trimmed).length <= ERROR_BUDGET_CHARS)
1210
+ return trimmed;
1211
+ // Still over budget with `message` trimmed all the way down to `""`: the
1212
+ // envelope-floor assumption documented in the file header and on
1213
+ // CODE_CHAR_BUDGET has failed -- code/recipe/allowedNext (plus the now
1214
+ // fully-minimized-or-absent `detail`) exceed ERROR_BUDGET_CHARS on their
1215
+ // own, with no `message` left to shrink. Not achievable by any catalog
1216
+ // entry today (see the envelope-floor test in tests/errors.test.ts). See
1217
+ // ERROR_BUDGET_OVERFLOW_CODE's own comment for why this is surfaced as a
1218
+ // `code` marker rather than thrown.
730
1219
  return {
731
- ...err,
1220
+ ...trimmed,
732
1221
  error: {
733
- ...err.error,
734
- detail: {
735
- omitted: true,
736
- reason: "detail exceeded the error budget",
737
- ...(totalFailed !== undefined ? { totalFailed } : {}),
738
- ...(totalMissing !== undefined ? { totalMissing } : {}),
739
- ...(totalKeys !== undefined ? { totalKeys } : {}),
740
- },
1222
+ ...trimmed.error,
1223
+ code: ERROR_BUDGET_OVERFLOW_CODE,
741
1224
  },
742
1225
  };
743
1226
  }
1227
+ // Observed live during rc-v1-C008 (2026-08-12): POST /tasks with an invalid
1228
+ // templateData shape (acceptanceCriteria sent as an array, the schema wants
1229
+ // a string) 400s with a raw zod SafeParseError spread verbatim into the
1230
+ // body -- `@hono/zod-validator`'s default (no custom hook) failure path is
1231
+ // `c.json(result, 400)` for `result = { success: false, error: ZodError }` --
1232
+ // so the wire body is `{ success: false, error: { issues: [...], name:
1233
+ // "ZodError" } }`, no top-level `details` field at all. Before this, the
1234
+ // generic degrade path only ever looked at `body.details` for `detail` and
1235
+ // only ever looked at `body.error` for a STRING code passthrough (see
1236
+ // genericDegrade below); an OBJECT `body.error` matched neither, so this
1237
+ // case degraded to `http_400` with NO detail whatsoever -- the caller had
1238
+ // to go read backend source to find the actual schema mismatch.
1239
+ // deriveGenericDetailSource picks what feeds clampGenericDetail: the
1240
+ // backend's own top-level `details` (existing behavior, e.g. any future
1241
+ // code's hand-rolled `details`, or the formErrors/fieldErrors zod-flatten
1242
+ // shape covered by the tests above) is preferred when present and usable;
1243
+ // otherwise, when `body.error` is itself an object (not a string code) and
1244
+ // carries an `issues` array, a compact summary is built from it -- each
1245
+ // surviving issue's own path/code/message, the three fields that actually
1246
+ // explain WHAT was wrong and WHERE, same convention as the catalog
1247
+ // entries' own structured detail shapes above (precondition_failed's
1248
+ // failed[], low_confidence's missing[]).
1249
+ //
1250
+ // M2 fix-round finding (rc-v1-zod-degrade-details review): this summary
1251
+ // used to feed ALL issues through the module's general DETAIL_CLAMP (5
1252
+ // entries) / DETAIL_ENTRY_CHAR_BUDGET (60 chars), applied only later by
1253
+ // clampGenericDetail. Measured: a realistic 5-issue zod-400 payload
1254
+ // (templateData.acceptanceCriteria sent as an array, one issue per array
1255
+ // index, "Expected string, received array") already sat at 1151/1200
1256
+ // chars (96% of ERROR_BUDGET_CHARS) under that path; a longer but still
1257
+ // perfectly ordinary message pushed the SAME 5-issue payload over budget
1258
+ // and into enforceErrorBudget's emergency hard reclamp (2 entries, 20
1259
+ // usable chars each) -- MORE issues produced STRICTLY LESS information.
1260
+ // GENERIC_ISSUES_CLAMP / GENERIC_ISSUE_ENTRY_CHAR_BUDGET below give this
1261
+ // summary its own tighter budget applied HERE, at derive time, before the
1262
+ // general pass ever runs, so the common case never needs the general
1263
+ // clamp or the emergency reclamp at all (measured post-fix: comfortably
1264
+ // under half of ERROR_BUDGET_CHARS for the same 5-issue fixture -- see
1265
+ // tests/errors.test.ts).
1266
+ //
1267
+ // L3 fix-round finding: a mapped issue with no recognizable path/code/
1268
+ // message (a null/number/string/array entry, or an object missing all
1269
+ // three) is dropped BEFORE the GENERIC_ISSUES_CLAMP cut, not after --
1270
+ // slicing by raw position first (this module's usual idiom, e.g.
1271
+ // preconditionFailedError's rawFailed.slice(0, DETAIL_CLAMP).map(...)
1272
+ // above) would let leading junk push a real issue out of the window
1273
+ // entirely (measured: 5 null entries then 1 real one used to clamp down
1274
+ // to 5 EMPTY {} objects, silently losing the only informative issue).
1275
+ // `failed[]`/`missing[]` are backend-contract-bounded arrays where every
1276
+ // entry is already usable by construction, so slicing first is safe
1277
+ // there; `issues` is explicitly untrusted (this whole branch exists
1278
+ // because it can be a raw SafeParseError), so usability has to be checked
1279
+ // first. The one-time O(issues.length) map+filter this costs is the same
1280
+ // order of work the pre-fix version of this function already did
1281
+ // unconditionally (it mapped the WHOLE array with no clamp at all), so
1282
+ // this is not a new cost, just a reordering of an existing one. If
1283
+ // nothing in `issues` survives the filter (including the plain `issues:
1284
+ // []` case), this falls through to the same object-passthrough branch
1285
+ // used when `issues` is not a recognizable array at all, rather than
1286
+ // emitting a misleading {issues: [], totalIssues: N}.
1287
+ //
1288
+ // `path` (zod's own array-of-string|number) is joined into a single
1289
+ // dot-separated string rather than kept as a nested array: clampDetailValue
1290
+ // caps recursion at GENERIC_DETAIL_MAX_DEPTH (3), and this summary's own
1291
+ // container nesting (the top-level object -> issues[] -> issue object)
1292
+ // already spends 2 of those 3 levels before `path` is even reached, so a
1293
+ // nested array here would push every path SEGMENT one level past the
1294
+ // depth guard and silently replace each with the truncation marker
1295
+ // instead of clamping it -- verified against clampDetailValue directly
1296
+ // before landing this. A joined string is exactly one more clamped level,
1297
+ // well within budget, and reads just as well ("acceptanceCriteria" or
1298
+ // "tags.2.name" for a nested/array path). L4 fix-round finding: a path
1299
+ // segment that is itself not a string or number (malformed/hostile input)
1300
+ // used to be silently filtered OUT of the joined path -- a real 6-segment
1301
+ // path could read as a plausible 2-segment one ("ok.3"), directly
1302
+ // contradicting this module's never-silent doctrine. Each unusable
1303
+ // segment is now rendered as a visible '?' placeholder instead, so the
1304
+ // segment COUNT stays honest even when a segment's own value cannot be
1305
+ // shown.
1306
+ //
1307
+ // `code` itself still stays `http_<status>` in this case (an object is not
1308
+ // a code -- see genericDegrade's own check below, unchanged). When
1309
+ // `body.error` is an object but carries no recognizable `issues` array (or
1310
+ // `issues` carried nothing usable, per L3 above), the object itself is
1311
+ // passed through instead of staying completely silent -- a judgment call:
1312
+ // any structured object the backend sends as `error` is more useful
1313
+ // surfaced (clamped, by the same machinery) than dropped outright, even
1314
+ // when this module cannot name its shape specifically. L6 fix-round
1315
+ // finding: that passthrough used to forward the object VERBATIM, including
1316
+ // a `stack` key when present -- measured live, a raw backend/framework
1317
+ // error object can carry a full server-side stack trace (internal file
1318
+ // paths, and, for a Prisma error, query metadata), which this module must
1319
+ // never leak to a caller. `stack` is dropped before passthrough,
1320
+ // unconditionally, whether or not this particular object actually has one.
1321
+ const GENERIC_ISSUES_CLAMP = 3;
1322
+ const GENERIC_ISSUE_ENTRY_CHAR_BUDGET = 40;
1323
+ /** Summarizes a single zod issue (untrusted -- may not even be an object)
1324
+ * into {path?, code?, message?}, each clamped to
1325
+ * GENERIC_ISSUE_ENTRY_CHAR_BUDGET. Never throws regardless of input shape:
1326
+ * a non-object issue, or one missing every recognizable field, degrades to
1327
+ * an EMPTY object, which deriveGenericDetailSource's caller filters out
1328
+ * (see the L3 fix-round finding in the comment above). See the same
1329
+ * comment's L4 entry for why an unusable `path` segment becomes a visible
1330
+ * '?' rather than being filtered out of the path. */
1331
+ function summarizeZodIssue(issue) {
1332
+ const i = issue && typeof issue === "object" ? issue : {};
1333
+ const entry = {};
1334
+ if (Array.isArray(i.path) && i.path.length > 0) {
1335
+ const rendered = i.path
1336
+ .map((seg) => (typeof seg === "string" || typeof seg === "number" ? seg : "?"))
1337
+ .join(".");
1338
+ entry.path = clamp(rendered, GENERIC_ISSUE_ENTRY_CHAR_BUDGET);
1339
+ }
1340
+ if (typeof i.code === "string")
1341
+ entry.code = clamp(i.code, GENERIC_ISSUE_ENTRY_CHAR_BUDGET);
1342
+ if (typeof i.message === "string")
1343
+ entry.message = clamp(i.message, GENERIC_ISSUE_ENTRY_CHAR_BUDGET);
1344
+ return entry;
1345
+ }
1346
+ function deriveGenericDetailSource(details, bodyError) {
1347
+ if (details && typeof details === "object" && !Array.isArray(details))
1348
+ return details;
1349
+ if (bodyError && typeof bodyError === "object" && !Array.isArray(bodyError)) {
1350
+ const body = bodyError;
1351
+ const issues = body.issues;
1352
+ if (Array.isArray(issues)) {
1353
+ const usable = issues
1354
+ .map(summarizeZodIssue)
1355
+ .filter((entry) => Object.keys(entry).length > 0)
1356
+ .slice(0, GENERIC_ISSUES_CLAMP);
1357
+ if (usable.length > 0) {
1358
+ // totalIssues is always the TRUE original count, never the
1359
+ // filtered/sliced length.
1360
+ return { issues: usable, totalIssues: issues.length };
1361
+ }
1362
+ // Nothing usable survived (see L3 above) -- fall through to the
1363
+ // object-passthrough branch below.
1364
+ }
1365
+ const { stack: _stack, ...rest } = body; // L6: never leak a backend stack trace.
1366
+ return rest;
1367
+ }
1368
+ return details;
1369
+ }
744
1370
  // The backend's own body.error string is the most specific code available
745
1371
  // and consumers key on it (the mcp-bridge governance suite asserts a 409
746
1372
  // claim_blocked stays visible end to end), so the degrade passes it
747
1373
  // through when present; the status-derived http_<status> form is only the
748
- // fallback for bodies that carry no code at all. Clamped like every other
1374
+ // fallback for bodies that carry no code at all (including an OBJECT
1375
+ // body.error -- an object is not a code, see deriveGenericDetailSource
1376
+ // above for how it is used instead). Clamped like every other
749
1377
  // caller-visible string so a pathological body cannot blow the budget.
750
- function genericDegrade(status, message, details, bodyCode) {
751
- const code = typeof bodyCode === "string" && bodyCode.length > 0
752
- ? clamp(bodyCode, DETAIL_ENTRY_CHAR_BUDGET)
1378
+ function genericDegrade(status, message, details, bodyError) {
1379
+ const code = typeof bodyError === "string" && bodyError.length > 0
1380
+ ? clamp(bodyError, CODE_CHAR_BUDGET)
753
1381
  : `http_${status}`;
754
1382
  return buildTeachingError({
755
1383
  code,
756
1384
  message,
757
1385
  recipe: "call workflow_primer for the full lifecycle reference and today's known traps",
758
1386
  allowedNext: ["workflow_primer"],
759
- detail: clampGenericDetail(details),
1387
+ detail: clampGenericDetail(deriveGenericDetailSource(details, bodyError)),
760
1388
  });
761
1389
  }
762
1390
  /**
@@ -776,7 +1404,7 @@ export function mapBackendError(status, rawBody, verbContext) {
776
1404
  return forceAdminOnlyError(message);
777
1405
  }
778
1406
  if (status === 409 && code === "already_claimed") {
779
- return alreadyClaimedError(message);
1407
+ return alreadyClaimedError(body, message);
780
1408
  }
781
1409
  if (status === 422 && code === "precondition_failed") {
782
1410
  return preconditionFailedError(body, verbContext);
@@ -793,6 +1421,18 @@ export function mapBackendError(status, rawBody, verbContext) {
793
1421
  if (status === 409 && code === "conflict" && RESPEC_CONFLICT_PATTERN.test(message)) {
794
1422
  return respecConflictError(message);
795
1423
  }
1424
+ if (status === 409 && code === "conflict" && CREATOR_ABANDON_CONFLICT_PATTERN.test(message)) {
1425
+ return creatorAbandonConflictError(message);
1426
+ }
1427
+ if (status === 400 && code === "backlog_routing_enforced") {
1428
+ return backlogRoutingEnforcedError(message);
1429
+ }
1430
+ if (status === 403 && code === "backlog_not_promoted") {
1431
+ return backlogNotPromotedError(message);
1432
+ }
1433
+ if (verbContext === "pull_requests_create" && code === "github_error") {
1434
+ return githubCreateError(status, body, message);
1435
+ }
796
1436
  return genericDegrade(status, message, body.details, body.error);
797
1437
  }
798
1438
  //# sourceMappingURL=errors.js.map