@agent-tasks/mcp-server 0.13.0 → 0.14.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
@@ -48,27 +73,65 @@
48
73
  // (serializeTeachingError's output, exactly what a caller receives) is
49
74
  // always <= ERROR_BUDGET_CHARS (1200 chars, the wire-format size measured
50
75
  // 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.
76
+ // adversarial backend input. This is a genuine ceiling on the SERIALIZED
77
+ // (wire) size, not just on each field's own JS string length: a per-field
78
+ // codepoint clamp (MESSAGE_CHAR_BUDGET, RECIPE_CHAR_BUDGET, the
79
+ // DETAIL_* family) bounds how many characters a field's own VALUE holds,
80
+ // but JSON.stringify can expand a single character into a much longer
81
+ // escape sequence (e.g. a JSON-unescaped control character like U+0001
82
+ // becomes the 6-char \u0001 escape), so a field that is short in JS
83
+ // terms can still be long on the wire. `code`, `recipe`, and `allowedNext` are
84
+ // preserved WHOLE regardless of size (the contract mandates all four
85
+ // unconditionally, and none of the three is ever backend-controlled raw
86
+ // text at any of today's catalog call sites -- recipe is always a
87
+ // hand-authored fixed string, code is either a fixed string or a
88
+ // backend code clamped to its own CODE_CHAR_BUDGET (see genericDegrade;
89
+ // kept a separate constant from DETAIL_ENTRY_CHAR_BUDGET precisely so
90
+ // raising the detail budget can never silently raise how much of `code`
91
+ // this module is willing to carry through), and allowedNext is always a
92
+ // small fixed verb-name list); `detail` and, as of this hardening pass,
93
+ // `message` (which DOES carry raw, potentially escape-heavy backend
94
+ // text -- see `backendMessage`) are the two fields this module will
95
+ // actually shrink, in that order, to hold the invariant for arbitrary
96
+ // adversarial input. This "code/recipe/allowedNext never touched"
97
+ // assumption is itself only as good as CODE_CHAR_BUDGET/RECIPE_CHAR_BUDGET
98
+ // staying small enough that the rest of the envelope (those three plus a
99
+ // fully-minimized-or-absent `detail`) always leaves room for at least an
100
+ // empty `message` -- see the envelope-floor test in
101
+ // tests/errors.test.ts and enforceErrorBudget's own handling of the case
102
+ // where that floor assumption fails.
57
103
  //
58
104
  // The per-field clamps below (DETAIL_CLAMP, DETAIL_KEY_CLAMP,
59
105
  // 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
106
+ // bound a single field's codepoint count, never the field's escaped wire
107
+ // cost nor the whole object's sum: several near-max fields at once
61
108
  // (precondition_failed's failed[] with several entries, each carrying an
62
109
  // 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.
110
+ // `details` object), or a single escape-heavy `message`, can still exceed
111
+ // the budget even when every individual field stayed within its own
112
+ // codepoint clamp (measured: a 1000-codepoint message of pure U+0001
113
+ // characters clamps to MESSAGE_CHAR_BUDGET=300 codepoints by field-count,
114
+ // but serializes to 1877 wire chars on its own, already over
115
+ // ERROR_BUDGET_CHARS with an empty `detail` -- see
116
+ // tests/errors.test.ts's "not_claimed, no detail: an escape-heavy message
117
+ // alone still respects ERROR_BUDGET_CHARS" test (describe block
118
+ // "escape-aware message trim: true wire-format ceiling (task 18e54531)")
119
+ // for the measured number; it is not separately re-asserted as an exact
120
+ // pin anywhere, only via the <= ERROR_BUDGET_CHARS check that test makes.
121
+ // buildTeachingError's own enforceErrorBudget step is the single
122
+ // place that actually guarantees the TOTAL: it re-measures the whole
123
+ // serialized object after construction and, only when still over budget,
124
+ // first re-clamps `detail` harder (same recursive clamp, tighter limits),
125
+ // then, if that is still not enough, replaces `detail` entirely with a
126
+ // small, visible summary object (added only when this entry actually HAD
127
+ // a `detail` to begin with -- never fabricated out of nothing) instead of
128
+ // truncating it into something silently misleading or dropping it
129
+ // without a trace, and, only if the total STILL exceeds budget even with
130
+ // `detail` minimized as far as it goes, shortens `message` itself as the
131
+ // last resort (codepoint-safe, via `clamp`, so this can never reintroduce
132
+ // the surrogate-splitting bug the codepoint-safe `clamp` above exists to
133
+ // close) down to whatever room remains after the rest of the envelope
134
+ // (code/recipe/allowedNext/detail) is accounted for.
72
135
  // ── Budget / clamp constants ────────────────────────────────────────────
73
136
  //
74
137
  // Mirrors receipt.ts's DETAIL_CLAMP / ENTRY_CHAR_BUDGET convention (same
@@ -93,6 +156,24 @@ const DETAIL_ENTRY_CHAR_BUDGET = 60;
93
156
  * that must itself never grow into a prose blob. */
94
157
  const MESSAGE_CHAR_BUDGET = 300;
95
158
  const RECIPE_CHAR_BUDGET = 240;
159
+ /** Char bound for `code` on the generic degrade path (genericDegrade), the
160
+ * one call site where `code` carries raw backend text (the backend's own
161
+ * `error` string, passed through verbatim -- see genericDegrade's own
162
+ * comment) rather than a short hand-authored literal. Deliberately its
163
+ * OWN constant, not DETAIL_ENTRY_CHAR_BUDGET reused: `code` sits in the
164
+ * part of the envelope enforceErrorBudget never re-visits (see the file
165
+ * header), so its clamp is one of the inputs the "envelope always leaves
166
+ * room for at least an empty `message`" assumption depends on. Sharing
167
+ * DETAIL_ENTRY_CHAR_BUDGET would silently couple that assumption to
168
+ * whatever value `detail` clamping happens to want, with nothing
169
+ * documenting the link -- raising DETAIL_ENTRY_CHAR_BUDGET to, say, 250
170
+ * for an unrelated detail-sizing reason would silently let `code` grow to
171
+ * 250 codepoints too, which alone can cost up to ~6x that on the wire for
172
+ * escape-heavy input (see the file header), enough to blow
173
+ * ERROR_BUDGET_CHARS on `code` alone even with an empty `message` and no
174
+ * `detail`. See the envelope-floor test in tests/errors.test.ts, which
175
+ * pins this budget's effect on the worst-case envelope size directly. */
176
+ const CODE_CHAR_BUDGET = 60;
96
177
  const TRUNCATION_MARKER = "...";
97
178
  /** Hard ceiling on the whole serialized teaching error (JSON.stringify(x,
98
179
  * null, 2), the exact wire format serializeTeachingError/serializeResult
@@ -100,6 +181,23 @@ const TRUNCATION_MARKER = "...";
100
181
  * is the number enforceErrorBudget (below) actually holds the line at,
101
182
  * since the per-field clamps above only ever bound one field at a time. */
102
183
  const ERROR_BUDGET_CHARS = 1200;
184
+ /** `code` marker for the (not achievable by any catalog entry today, see
185
+ * the envelope-floor test in tests/errors.test.ts) case where
186
+ * enforceErrorBudget's own envelope-floor assumption fails: `detail` is
187
+ * fully minimized or was never present, `message` has been trimmed all
188
+ * the way down to `""`, and the response STILL exceeds ERROR_BUDGET_CHARS
189
+ * -- meaning the fixed part of the envelope (code/recipe/allowedNext)
190
+ * alone is over budget. enforceErrorBudget overwrites `code` with this
191
+ * marker in that case, the one place it is ever touched there, so the
192
+ * condition is visible (greppable in logs, assertable in a test) instead
193
+ * of silently returning an over-budget response while claiming success.
194
+ * Deliberately never thrown as an exception: this module IS the
195
+ * production error-serialization path server.ts's wrap() depends on for
196
+ * every failed tool call, and an exception thrown from inside it would
197
+ * surface as an unhandled crash of that call instead of a graceful (if,
198
+ * in this unreachable-today case, still oversized) response -- strictly
199
+ * worse for a caller than a marked, still-served response. */
200
+ const ERROR_BUDGET_OVERFLOW_CODE = "error_budget_overflow";
103
201
  /** Tighter versions of DETAIL_CLAMP / DETAIL_KEY_CLAMP /
104
202
  * DETAIL_ENTRY_CHAR_BUDGET, used only by enforceErrorBudget's second
105
203
  * ("harder reclamp") pass, when the normal clamp still was not enough to
@@ -107,10 +205,36 @@ const ERROR_BUDGET_CHARS = 1200;
107
205
  const HARD_DETAIL_CLAMP = 2;
108
206
  const HARD_DETAIL_KEY_CLAMP = 3;
109
207
  const HARD_DETAIL_ENTRY_CHAR_BUDGET = 20;
208
+ // Codepoint-safe, not grapheme-safe: truncates on Unicode codepoint
209
+ // boundaries (via Array.from, which groups a UTF-16 surrogate pair into one
210
+ // iteration step) so a clamp can never split a surrogate pair and leave a
211
+ // lone high/low surrogate in the output -- the failure mode a 100-emoji
212
+ // title hits under plain `value.slice(0, n)` (each emoji here is one
213
+ // astral codepoint = one surrogate pair; slicing at an odd code-unit
214
+ // offset keeps the high surrogate and drops its low half). This does NOT
215
+ // guarantee every clamp lands on a grapheme-CLUSTER boundary (e.g. a
216
+ // base+combining-mark or ZWJ sequence spanning several codepoints could
217
+ // still be split mid-cluster, same as before) -- Intl.Segmenter would be
218
+ // needed for that, and today's reported failure is specifically a split
219
+ // surrogate PAIR (one codepoint), not a split grapheme cluster, so
220
+ // codepoint-safety is the precise, minimal fix; see
221
+ // tests/errors.test.ts's "a 100-emoji activeClaim.title clamps to
222
+ // DETAIL_ENTRY_CHAR_BUDGET without leaving a lone surrogate, and
223
+ // round-trips through a strict UTF-8 re-encode" test (describe block
224
+ // "clamp is surrogate-safe: codepoint-based truncation (task 18e54531)")
225
+ // for the boundary this closes.
110
226
  function clamp(value, maxChars) {
111
- return value.length > maxChars
112
- ? value.slice(0, maxChars - TRUNCATION_MARKER.length) + TRUNCATION_MARKER
113
- : value;
227
+ // value.length (UTF-16 code units) is always >= the codepoint count (an
228
+ // astral codepoint is 2 units, a BMP codepoint is 1), so if the code-unit
229
+ // length already fits the budget the codepoint count fits too -- skips
230
+ // the Array.from allocation on the overwhelmingly common
231
+ // ASCII/no-truncation-needed path.
232
+ if (value.length <= maxChars)
233
+ return value;
234
+ const codepoints = Array.from(value);
235
+ if (codepoints.length <= maxChars)
236
+ return value;
237
+ return (codepoints.slice(0, Math.max(0, maxChars - TRUNCATION_MARKER.length)).join("") + TRUNCATION_MARKER);
114
238
  }
115
239
  function buildTeachingError(opts) {
116
240
  const err = {
@@ -173,12 +297,154 @@ function notClaimedError(message) {
173
297
  // (backend/src/routes/tasks.ts: POST /tasks/pickup, POST
174
298
  // /tasks/:id/start). The backend's own code is already specific, so it is
175
299
  // kept verbatim as this entry's code.
176
- function alreadyClaimedError(message) {
300
+ //
301
+ // Review-retention case (rc-v1-C008 Cold-Start-Eval, 2026-08-12 live
302
+ // finding; generalized on the rc-v1-already-claimed-review-recipe review
303
+ // round, H1): task_finish's own documented semantics clear the work claim
304
+ // only when the task lands on a TERMINAL state, and keep it on EVERY finish
305
+ // that instead lands the task back on `review` -- there is no separate
306
+ // request_changes-only code path (backend/src/routes/tasks.ts ~3150-3156:
307
+ // `if (isTerminalState(...)) { clear claim fields }`, no `else`).
308
+ // request_changes (the rework loop keeping the original author's claim so
309
+ // they resume automatically) is the one caller-visible EXAMPLE of this, not
310
+ // the definition: an ordinary multi-step workflow whose own
311
+ // expectedFinishState is `review` keeps the claim the exact same way, with
312
+ // no request_changes outcome involved at all. A recipe that names only
313
+ // request_changes reads as a scope test to a caller whose task landed in
314
+ // review some other way, who could then wrongly conclude task_abandon is
315
+ // safe. Named below as "work claim on an in-review task" instead, with no
316
+ // reference to how the task got there.
317
+ //
318
+ // Reviewer branch (H2): this same 409 fires identically for a REVIEW claim
319
+ // wall, not just a work claim -- task_pickup's and task_start's own
320
+ // claim-wall queries both match `reviewClaimedByAgentId === actor.tokenId
321
+ // && status === "review"` too (backend/src/routes/tasks.ts ~1462-1465 for
322
+ // /tasks/pickup, ~1681-1684 for /tasks/:id/start), and by construction ANY
323
+ // review claim sits on a task currently in review. For that caller,
324
+ // task_abandon on the held claim IS the correct, immediate, clean exit: the
325
+ // abandon route's "cannot abandon while in review" guard
326
+ // (backend/src/routes/tasks.ts ~3540-3541: `if (holdsWorkClaim &&
327
+ // !holdsReviewClaim && isReviewState(...))`) is scoped to a WORK claim only
328
+ // and never fires for a review claim. A recipe that tells a role=reviewer
329
+ // caller to wait, merge, or avoid task_abandon would be actively wrong for
330
+ // them.
331
+ //
332
+ // Whether the held claim is an ordinary in_progress work claim, a work
333
+ // claim retained on a task now in review, or a review claim is only
334
+ // PARTIALLY determinable from this catalog entry's only input. The 409 body
335
+ // both real call sites send is `{ error: "already_claimed", message,
336
+ // activeClaim: { taskId, title, role } }` (verified at
337
+ // backend/src/routes/tasks.ts:1469-1480 for /tasks/pickup and :1688-1699
338
+ // for /tasks/:id/start, and documented at docs/okf/claim-model.md:19).
339
+ // `role` ("author" vs "reviewer", derived from which claim column matched)
340
+ // DOES cleanly separate the reviewer case from both author cases (a
341
+ // role="reviewer" claim is always a review claim, per the query above) --
342
+ // it is only WITHIN role="author" that an ordinary in_progress claim and a
343
+ // work claim retained on a review-state task stay indistinguishable from
344
+ // this input alone (there is no `status` field on activeClaim). This
345
+ // input is not status-BLIND, though: the caller already has taskId in hand
346
+ // and is one tasks_get call away from the actual status if it needs to
347
+ // decide programmatically rather than read the recipe's cases -- M3
348
+ // (rc-v1-already-claimed-review-recipe review round, task 008ac513, the
349
+ // follow-up this comment used to point at) closes that gap: extractActiveClaim
350
+ // below passes the backend's own `activeClaim: { taskId, title, role }`
351
+ // through, clamped, as this entry's `detail.activeClaim`, and `tasks_get`
352
+ // is added to `allowedNext` so the check-its-status call is itself
353
+ // immediately callable per the allowedNext contract, not just implied by
354
+ // the prose. This entry still names all three cases explicitly in the
355
+ // recipe text, keyed by claim kind / state rather than by role, so the
356
+ // caller self-selects the right one instead of defaulting to task_abandon,
357
+ // which is safe for two of the three cases and rejected outright for the
358
+ // third; `detail.activeClaim` is the machine-readable input a caller can
359
+ // use to do that same selection programmatically instead of reading prose.
360
+ //
361
+ // task_finish is deliberately NOT offered as a blanket corrective for the
362
+ // workClaimInReview case below: on that task it is either rejected outright
363
+ // (403 when a distinct reviewer already holds the review claim on a
364
+ // REQUIRES_DISTINCT_REVIEWER project, backend/src/routes/tasks.ts
365
+ // ~2825-2831; 409 `reviewer_conflict` when a distinct reviewer already
366
+ // holds the claim on a non-DR project, ~2805-2818) or is the deliberate
367
+ // self-approve branch on a non-DR project with no reviewer claim yet held
368
+ // (~2539-2557, `outcome` required). It is therefore SAFE when it works,
369
+ // just often unavailable to a caller who cannot know in advance which of
370
+ // those applies -- "wait for the reviewer" is offered as the option that is
371
+ // always safe regardless.
372
+ //
373
+ // ALREADY_CLAIMED_CASES (M6) names the three case-sentences as individually
374
+ // testable, exported constants instead of one hand-assembled string tests
375
+ // would otherwise have to slice out of by searching for a substring like
376
+ // "review": a slice-by-indexOf assertion breaks on any semantically-safe
377
+ // reword that keeps the meaning but moves the words (see
378
+ // tests/errors.test.ts for the constant-based assertions this enables).
379
+ export const ALREADY_CLAIMED_CASES = {
380
+ inProgress: "In-progress claim: task_finish or task_abandon on it.",
381
+ workClaimInReview: "Work claim on an in-review task: abandon is rejected (409); wait for the reviewer, or task_merge + task_finish outcome=approve.",
382
+ reviewClaim: "Review claim: task_abandon frees the review lock.",
383
+ };
384
+ const ALREADY_CLAIMED_RECIPE = [
385
+ ALREADY_CLAIMED_CASES.inProgress,
386
+ ALREADY_CLAIMED_CASES.workClaimInReview,
387
+ ALREADY_CLAIMED_CASES.reviewClaim,
388
+ ].join(" ");
389
+ // M3 follow-up (task 008ac513): pulls the backend's own `activeClaim: {
390
+ // taskId, title, role }` (see the file comment above this catalog entry)
391
+ // out of the 409 body and clamps it for `detail.activeClaim`, the same
392
+ // DETAIL_ENTRY_CHAR_BUDGET convention every other structured detail field
393
+ // in this module uses. Untrusted response data, same stance as the other
394
+ // extract-from-body helpers in this file (asBackendBody, preconditionFailedError's
395
+ // rawFailed mapping): every field is validated by type AND non-emptiness
396
+ // before use (`isUsableString` below), and a missing/malformed activeClaim
397
+ // (or one with no usable field at all -- absent, wrong type, or present as
398
+ // an empty string) degrades to `undefined` -- the caller then just sees the
399
+ // recipe prose with no detail, the exact behavior before this change,
400
+ // rather than a detail object with fabricated, empty, or non-string fields.
401
+ // The field SET this function looks at is fixed at exactly these three
402
+ // (taskId, title, role): a present-but-non-string field (e.g. a numeric
403
+ // taskId) is dropped the same way a missing field is, not surfaced under a
404
+ // different name or flagged separately -- this is a deliberate, narrower
405
+ // exception to the "the drop is never silent" stance the rest of this
406
+ // module's clampDetailValue path takes for arbitrary detail objects, scoped
407
+ // to this one small, fixed, backend-controlled shape.
408
+ function isUsableString(value) {
409
+ return typeof value === "string" && value.length > 0;
410
+ }
411
+ function extractActiveClaim(body) {
412
+ const raw = body.activeClaim;
413
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
414
+ return undefined;
415
+ const claim = raw;
416
+ const taskId = isUsableString(claim.taskId) ? clamp(claim.taskId, DETAIL_ENTRY_CHAR_BUDGET) : undefined;
417
+ const title = isUsableString(claim.title) ? clamp(claim.title, DETAIL_ENTRY_CHAR_BUDGET) : undefined;
418
+ const role = isUsableString(claim.role) ? clamp(claim.role, DETAIL_ENTRY_CHAR_BUDGET) : undefined;
419
+ if (taskId === undefined && title === undefined && role === undefined)
420
+ return undefined;
421
+ return {
422
+ ...(taskId !== undefined ? { taskId } : {}),
423
+ ...(title !== undefined ? { title } : {}),
424
+ ...(role !== undefined ? { role } : {}),
425
+ };
426
+ }
427
+ function alreadyClaimedError(body, message) {
428
+ const activeClaim = extractActiveClaim(body);
177
429
  return buildTeachingError({
178
430
  code: "already_claimed",
179
431
  message,
180
- recipe: "call task_finish or task_abandon on your current task before claiming another",
181
- allowedNext: ["task_finish", "task_abandon"],
432
+ recipe: ALREADY_CLAIMED_RECIPE,
433
+ // M4: deliberately the UNION over all three ALREADY_CLAIMED_CASES above,
434
+ // not just the in-progress pair task_finish/task_abandon -- task_merge
435
+ // is the corrective action the workClaimInReview case's own sentence
436
+ // names (merge, then task_finish outcome=approve), so it must be
437
+ // immediately callable per the allowedNext contract
438
+ // (docs/response-contract-v1.md's "verb names the caller can call
439
+ // immediately"). The recipe text is what actually SELECTS the right
440
+ // case for the caller's own claim; allowedNext only has to list every
441
+ // verb any one of the three cases could legitimately call next.
442
+ // M3 follow-up: tasks_get is added too -- it is the concrete corrective
443
+ // for "check its status" (see the M3 comment above extractActiveClaim),
444
+ // and, same as task_merge, must be immediately callable per the
445
+ // allowedNext contract rather than only implied by prose.
446
+ allowedNext: ["task_finish", "task_abandon", "task_merge", "tasks_get"],
447
+ ...(activeClaim ? { detail: { activeClaim } } : {}),
182
448
  });
183
449
  }
184
450
  // 3. Branch precondition. task_start / task_finish / tasks_transition [POST
@@ -353,6 +619,62 @@ function respecConflictError(message) {
353
619
  allowedNext: ["task_abandon", "task_respec"],
354
620
  });
355
621
  }
622
+ // 7a. Creator-abandon conflict. task_creator_abandon only retires an OPEN,
623
+ // unclaimed task the caller created (backend/src/routes/tasks.ts,
624
+ // CREATOR_ABANDON_STATE_CONFLICT_MESSAGE = "Task must be open and unclaimed
625
+ // to creator-abandon") -- any other state, or a lost CAS race, is rejected
626
+ // with 409 `conflict`. Same generic backend code ("conflict") as
627
+ // RESPEC_CONFLICT_PATTERN immediately above and several other unrelated
628
+ // 409s, so this entry is message-pattern matched and mints its own code,
629
+ // sibling to respec_conflict. Unlike respec_conflict there is no
630
+ // self-service corrective to name: this verb never holds a claim to release
631
+ // first, and a lost CAS race means some other actor already changed the row
632
+ // out from under the caller. `recipe` deliberately avoids the literal
633
+ // `task_creator_abandon` token (the recipe-vs-allowedNext coherence guard
634
+ // in tests/errors.test.ts would then require it in `allowedNext`, and
635
+ // blindly retrying the same call is not a reliable next step here) --
636
+ // allowedNext offers only `tasks_get` so the caller can see the task's
637
+ // current state and decide what to do next.
638
+ const CREATOR_ABANDON_CONFLICT_PATTERN = /open and unclaimed to creator-abandon/i;
639
+ function creatorAbandonConflictError(message) {
640
+ return buildTeachingError({
641
+ code: "creator_abandon_conflict",
642
+ message,
643
+ recipe: "creator-abandon only works on an open, unclaimed task; call tasks_get to see its current state",
644
+ allowedNext: ["tasks_get"],
645
+ });
646
+ }
647
+ // 7b/7c. v1 backlog routing (backend/src/routes/tasks.ts): every
648
+ // agent-created task lands in `backlog` and waits for an operator to
649
+ // promote it to `open` -- an agent cannot create a directly-claimable task
650
+ // in v1. Two distinct backend codes, each already its own (not a shared
651
+ // generic code needing message-pattern matching, unlike respec_conflict/
652
+ // creator_abandon_conflict above): backlog_routing_enforced (400,
653
+ // task_create rejects an explicit non-backlog status from an agent caller)
654
+ // and backlog_not_promoted (403, task_start and the deprecated tasks_claim
655
+ // alias reject a backlog task no operator has promoted yet).
656
+ function backlogRoutingEnforcedError(message) {
657
+ return buildTeachingError({
658
+ code: "backlog_routing_enforced",
659
+ message,
660
+ 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',
661
+ allowedNext: ["task_create"],
662
+ });
663
+ }
664
+ // backlog_not_promoted's recipe deliberately avoids the literal task_start /
665
+ // task_pickup tokens (the message already says "before an agent can start
666
+ // it") -- same allowedNext-vs-recipe discipline as
667
+ // creatorAbandonConflictError's own comment above: there is no self-service
668
+ // way to promote a backlog task (that edge is human-only), so the recipe
669
+ // names only the two verbs an agent CAN still call while it waits.
670
+ function backlogNotPromotedError(message) {
671
+ return buildTeachingError({
672
+ code: "backlog_not_promoted",
673
+ message,
674
+ 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",
675
+ allowedNext: ["task_respec", "task_creator_abandon"],
676
+ });
677
+ }
356
678
  // 8. task_finish `result` (and the deprecated tasks_update's) as plain
357
679
  // string. Unlike the other catalog entries, the backend performs NO
358
680
  // validation of this today (`result` is stored verbatim as free text) —
@@ -511,17 +833,29 @@ function lowConfidenceError(body, message) {
511
833
  // catalog entry #8 (resultMustBePlainStringError) — a client-side guard
512
834
  // checked before, or in place of, any network call.
513
835
  //
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
836
+ // project_addressing_conflict covers every direction of the same "exactly
837
+ // one of project/projectId/projectSlug" requirement, not just "both
838
+ // provided": task_create's own client-side guard (tools.ts) also rejects
839
+ // the mirror-image mistake, no field set at all. That case used to throw a
840
+ // bare, unteaching Error (rc-v1-C006 round-2 review, LOW) instead of going
519
841
  // 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.
842
+ // what is really the same "exactly one" constraint violated a different
843
+ // way, `reason` selects a direction-specific message/recipe/allowedNext
844
+ // under the SAME code: any "both provided" pairing needs no extra
845
+ // corrective (the caller already named both candidates, it just needs to
846
+ // pick one), but "neither" used to point at projects_list as the
847
+ // self-service way to find the project.
848
+ //
849
+ // task_create's own unified `project` field (added alongside project_tasks's
850
+ // pre-existing one) widens the "exactly one" constraint from a pair to a
851
+ // triple: `project` conflicting with EITHER projectId or projectSlug is its
852
+ // own reason (project_and_projectId / project_and_projectSlug) rather than
853
+ // folded into "both_provided", so the message names the two fields that
854
+ // actually collided instead of a generic "more than one". projectId and
855
+ // projectSlug conflicting with EACH OTHER keeps the original "both_provided"
856
+ // reason and wording unchanged (byte-identical for any caller not using the
857
+ // new field). "neither_provided"'s message/recipe now names all three
858
+ // fields, since a caller who provides none of them can now choose any one.
525
859
  //
526
860
  // rc-v1-C007 pruned projects_list out of the DEFAULT tool registration
527
861
  // (tools.ts's LEGACY_VERB_NAMES); it is opt-in only via
@@ -538,8 +872,24 @@ export function projectAddressingConflictError(verb, reason = "both_provided") {
538
872
  if (reason === "neither_provided") {
539
873
  return buildTeachingError({
540
874
  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`,
875
+ message: "none of project, projectId, or projectSlug was provided; pass exactly one",
876
+ 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`,
877
+ allowedNext: [verb],
878
+ });
879
+ }
880
+ if (reason === "project_and_projectId") {
881
+ return buildTeachingError({
882
+ code: "project_addressing_conflict",
883
+ message: "project and projectId were both provided; pass exactly one",
884
+ recipe: `resubmit ${verb} with only one of project or projectId`,
885
+ allowedNext: [verb],
886
+ });
887
+ }
888
+ if (reason === "project_and_projectSlug") {
889
+ return buildTeachingError({
890
+ code: "project_addressing_conflict",
891
+ message: "project and projectSlug were both provided; pass exactly one",
892
+ recipe: `resubmit ${verb} with only one of project or projectSlug`,
543
893
  allowedNext: [verb],
544
894
  });
545
895
  }
@@ -655,11 +1005,13 @@ function clampGenericDetail(details) {
655
1005
  // Bookkeeping fields a catalog entry or clampDetailValue itself may already
656
1006
  // have set to record a TRUE original count (precondition_failed's
657
1007
  // 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"];
1008
+ // totalKeys, and the generic degrade path's own totalIssues -- see
1009
+ // deriveGenericDetailSource). A second, harder clamp pass over an
1010
+ // already-clamped object must not re-derive these from the intermediate
1011
+ // object's own (already shrunk) entry count -- that would silently replace
1012
+ // an accurate original count with a smaller, misleading one. See
1013
+ // reclampDetailHarder below.
1014
+ const DETAIL_TOTAL_MARKER_KEYS = ["totalFailed", "totalMissing", "totalKeys", "totalIssues"];
663
1015
  /** Re-clamps a detail object with the HARD_* limits, WITHOUT letting the
664
1016
  * pass corrupt any totalFailed/totalMissing/totalKeys marker already
665
1017
  * present (see DETAIL_TOTAL_MARKER_KEYS): those numbers are pulled out
@@ -685,20 +1037,91 @@ function reclampDetailHarder(detail) {
685
1037
  });
686
1038
  return { ...reclampedRest, ...preservedMarkers };
687
1039
  }
1040
+ /** True wire-format fit check: builds the candidate error with `message`
1041
+ * swapped in and measures the actual serialized (escaped) length, rather
1042
+ * than trusting `candidateMessage`'s own JS length as a proxy for its
1043
+ * wire cost. JSON.stringify's own escaping rules are the single source of
1044
+ * truth for that cost; re-deriving them analytically here would just be a
1045
+ * second, driftable copy of the same logic. */
1046
+ function fitsWithMessage(err, candidateMessage) {
1047
+ return (serializeTeachingError({ ...err, error: { ...err.error, message: candidateMessage } }).length <=
1048
+ ERROR_BUDGET_CHARS);
1049
+ }
1050
+ /** Last-resort step in enforceErrorBudget: shortens `message` itself when
1051
+ * the serialized total still exceeds ERROR_BUDGET_CHARS even after
1052
+ * `detail` has already been minimized as far as it can go. `message` can
1053
+ * carry raw, untrusted backend text (see `backendMessage`); a per-field
1054
+ * codepoint clamp (MESSAGE_CHAR_BUDGET, applied earlier in
1055
+ * buildTeachingError) bounds its JS string length but not its escaped
1056
+ * WIRE size, since JSON.stringify can expand a single character (a
1057
+ * control character outside \n\t\r\b\f) into a 6-char \uXXXX escape -- see
1058
+ * the file header's "Response budget invariant" section. This is the one
1059
+ * place `message` is ever shortened past MESSAGE_CHAR_BUDGET; `code`,
1060
+ * `recipe`, and `allowedNext` are still never touched here.
1061
+ *
1062
+ * Binary search over codepoint-prefix length, reusing `clamp` (already
1063
+ * codepoint-safe) for each candidate rather than slicing directly, so
1064
+ * this can never reintroduce the surrogate-splitting bug `clamp`'s own
1065
+ * codepoint-safety fix exists to close. `best` starts at `""` and is only
1066
+ * ever raised by a candidate that actually fits, so if even an empty
1067
+ * message does not fit (the surrounding code/recipe/allowedNext/detail
1068
+ * envelope alone already exceeds the budget -- not achievable by any
1069
+ * catalog entry today, see the file header and the envelope-floor test in
1070
+ * tests/errors.test.ts) `best` stays `""`: this function alone does NOT
1071
+ * guarantee the result fits (see enforceErrorBudget's own handling of
1072
+ * that case, immediately after its call to this function). */
1073
+ function trimMessageForBudget(err) {
1074
+ const codepointCount = Array.from(err.error.message).length;
1075
+ let lo = 0;
1076
+ let hi = codepointCount;
1077
+ let best = "";
1078
+ while (lo <= hi) {
1079
+ const mid = Math.floor((lo + hi) / 2);
1080
+ const candidate = clamp(err.error.message, mid);
1081
+ if (fitsWithMessage(err, candidate)) {
1082
+ best = candidate;
1083
+ lo = mid + 1;
1084
+ }
1085
+ else {
1086
+ hi = mid - 1;
1087
+ }
1088
+ }
1089
+ return { ...err, error: { ...err.error, message: best } };
1090
+ }
688
1091
  /** Enforces the response budget invariant documented in the file header.
689
1092
  * buildTeachingError's own per-field clamps (MESSAGE_CHAR_BUDGET,
690
1093
  * 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) {
1094
+ * bound individual FIELDS' codepoint counts, never their escaped wire
1095
+ * cost nor their sum: several near-max fields at once, or a single
1096
+ * escape-heavy `message`, can still exceed ERROR_BUDGET_CHARS in total.
1097
+ * This is the one place that actually guarantees the total. `code`,
1098
+ * `recipe`, and `allowedNext` are never touched here EXCEPT in the
1099
+ * unreachable-today overflow case described on ERROR_BUDGET_OVERFLOW_CODE
1100
+ * (the contract otherwise mandates them whole, regardless of size, and
1101
+ * none of the three carries raw untrusted text at any of today's catalog
1102
+ * call sites -- see the file header). `detail` is degraded first, and
1103
+ * NEVER silently: first a harder recursive re-clamp (same
1104
+ * clampDetailValue walk, tighter HARD_* limits), and, only if that still
1105
+ * is not enough AND this entry actually had a `detail` to begin with, a
1106
+ * small visible summary object replaces it entirely, so a caller always
1107
+ * sees that something was omitted rather than getting a truncated,
1108
+ * possibly-misleading fragment (an entry with no `detail` at all never
1109
+ * has one fabricated here -- see the `if (priorDetail)` guard below).
1110
+ * Only if the total STILL exceeds budget after `detail` is fully
1111
+ * minimized (or was never present) does `message` itself get shortened,
1112
+ * via trimMessageForBudget above -- the one scenario the per-field clamps
1113
+ * alone cannot catch, since an escape-heavy `message` can blow the wire
1114
+ * budget even with an empty `detail`.
1115
+ *
1116
+ * Exported so tests/errors.test.ts can exercise the
1117
+ * ERROR_BUDGET_OVERFLOW_CODE fallback directly with a synthetic,
1118
+ * hand-built TeachingError whose code/recipe alone already exceed
1119
+ * ERROR_BUDGET_CHARS -- not a runtime consumer outside this module (same
1120
+ * idiom as KNOWN_RULE_CORRECTIVES/ALREADY_CLAIMED_CASES above), and the
1121
+ * only way to reach that fallback deterministically in a test, since no
1122
+ * real catalog entry's own code/recipe/allowedNext gets anywhere close
1123
+ * to ERROR_BUDGET_CHARS today (see the envelope-floor tests). */
1124
+ export function enforceErrorBudget(err) {
702
1125
  if (serializeTeachingError(err).length <= ERROR_BUDGET_CHARS)
703
1126
  return err;
704
1127
  if (err.error.detail) {
@@ -712,51 +1135,223 @@ function enforceErrorBudget(err) {
712
1135
  if (serializeTeachingError(reclamped).length <= ERROR_BUDGET_CHARS)
713
1136
  return reclamped;
714
1137
  }
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.
1138
+ // Still over budget even after the harder reclamp: replace `detail` with
1139
+ // a small, fixed-size summary instead of silently dropping or truncating
1140
+ // it, but only when this entry actually HAD a `detail` to summarize --
1141
+ // fabricating a `detail: {omitted: true, ...}` out of nothing (when
1142
+ // `err.error.detail` was never set) would itself be a misleading claim.
1143
+ // `totalFailed` / `totalKeys` are carried over when cheaply available
1144
+ // (already computed by the catalog entry or by clampDetailValue's own
1145
+ // key-count marker) since a caller who cannot see the detail at least
1146
+ // learns how much of it there was.
1147
+ let withMinimizedDetail = err;
722
1148
  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;
1149
+ if (priorDetail) {
1150
+ const totalFailed = typeof priorDetail.totalFailed === "number" ? priorDetail.totalFailed : undefined;
1151
+ const totalMissing = typeof priorDetail.totalMissing === "number" ? priorDetail.totalMissing : undefined;
1152
+ const totalIssues = typeof priorDetail.totalIssues === "number" ? priorDetail.totalIssues : undefined;
1153
+ const totalKeys = typeof priorDetail.totalKeys === "number" ? priorDetail.totalKeys : Object.keys(priorDetail).length;
1154
+ withMinimizedDetail = {
1155
+ ...err,
1156
+ error: {
1157
+ ...err.error,
1158
+ detail: {
1159
+ omitted: true,
1160
+ reason: "detail exceeded the error budget",
1161
+ ...(totalFailed !== undefined ? { totalFailed } : {}),
1162
+ ...(totalMissing !== undefined ? { totalMissing } : {}),
1163
+ ...(totalIssues !== undefined ? { totalIssues } : {}),
1164
+ ...(totalKeys !== undefined ? { totalKeys } : {}),
1165
+ },
1166
+ },
1167
+ };
1168
+ }
1169
+ if (serializeTeachingError(withMinimizedDetail).length <= ERROR_BUDGET_CHARS)
1170
+ return withMinimizedDetail;
1171
+ // `detail` is now as small as this module ever makes it (summarized, or
1172
+ // never present) and the total STILL exceeds budget: the escape-expanded
1173
+ // wire cost of `message` itself is what is blowing the ceiling. Shorten
1174
+ // it, escape-aware, as the true last resort.
1175
+ const trimmed = trimMessageForBudget(withMinimizedDetail);
1176
+ if (serializeTeachingError(trimmed).length <= ERROR_BUDGET_CHARS)
1177
+ return trimmed;
1178
+ // Still over budget with `message` trimmed all the way down to `""`: the
1179
+ // envelope-floor assumption documented in the file header and on
1180
+ // CODE_CHAR_BUDGET has failed -- code/recipe/allowedNext (plus the now
1181
+ // fully-minimized-or-absent `detail`) exceed ERROR_BUDGET_CHARS on their
1182
+ // own, with no `message` left to shrink. Not achievable by any catalog
1183
+ // entry today (see the envelope-floor test in tests/errors.test.ts). See
1184
+ // ERROR_BUDGET_OVERFLOW_CODE's own comment for why this is surfaced as a
1185
+ // `code` marker rather than thrown.
730
1186
  return {
731
- ...err,
1187
+ ...trimmed,
732
1188
  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
- },
1189
+ ...trimmed.error,
1190
+ code: ERROR_BUDGET_OVERFLOW_CODE,
741
1191
  },
742
1192
  };
743
1193
  }
1194
+ // Observed live during rc-v1-C008 (2026-08-12): POST /tasks with an invalid
1195
+ // templateData shape (acceptanceCriteria sent as an array, the schema wants
1196
+ // a string) 400s with a raw zod SafeParseError spread verbatim into the
1197
+ // body -- `@hono/zod-validator`'s default (no custom hook) failure path is
1198
+ // `c.json(result, 400)` for `result = { success: false, error: ZodError }` --
1199
+ // so the wire body is `{ success: false, error: { issues: [...], name:
1200
+ // "ZodError" } }`, no top-level `details` field at all. Before this, the
1201
+ // generic degrade path only ever looked at `body.details` for `detail` and
1202
+ // only ever looked at `body.error` for a STRING code passthrough (see
1203
+ // genericDegrade below); an OBJECT `body.error` matched neither, so this
1204
+ // case degraded to `http_400` with NO detail whatsoever -- the caller had
1205
+ // to go read backend source to find the actual schema mismatch.
1206
+ // deriveGenericDetailSource picks what feeds clampGenericDetail: the
1207
+ // backend's own top-level `details` (existing behavior, e.g. any future
1208
+ // code's hand-rolled `details`, or the formErrors/fieldErrors zod-flatten
1209
+ // shape covered by the tests above) is preferred when present and usable;
1210
+ // otherwise, when `body.error` is itself an object (not a string code) and
1211
+ // carries an `issues` array, a compact summary is built from it -- each
1212
+ // surviving issue's own path/code/message, the three fields that actually
1213
+ // explain WHAT was wrong and WHERE, same convention as the catalog
1214
+ // entries' own structured detail shapes above (precondition_failed's
1215
+ // failed[], low_confidence's missing[]).
1216
+ //
1217
+ // M2 fix-round finding (rc-v1-zod-degrade-details review): this summary
1218
+ // used to feed ALL issues through the module's general DETAIL_CLAMP (5
1219
+ // entries) / DETAIL_ENTRY_CHAR_BUDGET (60 chars), applied only later by
1220
+ // clampGenericDetail. Measured: a realistic 5-issue zod-400 payload
1221
+ // (templateData.acceptanceCriteria sent as an array, one issue per array
1222
+ // index, "Expected string, received array") already sat at 1151/1200
1223
+ // chars (96% of ERROR_BUDGET_CHARS) under that path; a longer but still
1224
+ // perfectly ordinary message pushed the SAME 5-issue payload over budget
1225
+ // and into enforceErrorBudget's emergency hard reclamp (2 entries, 20
1226
+ // usable chars each) -- MORE issues produced STRICTLY LESS information.
1227
+ // GENERIC_ISSUES_CLAMP / GENERIC_ISSUE_ENTRY_CHAR_BUDGET below give this
1228
+ // summary its own tighter budget applied HERE, at derive time, before the
1229
+ // general pass ever runs, so the common case never needs the general
1230
+ // clamp or the emergency reclamp at all (measured post-fix: comfortably
1231
+ // under half of ERROR_BUDGET_CHARS for the same 5-issue fixture -- see
1232
+ // tests/errors.test.ts).
1233
+ //
1234
+ // L3 fix-round finding: a mapped issue with no recognizable path/code/
1235
+ // message (a null/number/string/array entry, or an object missing all
1236
+ // three) is dropped BEFORE the GENERIC_ISSUES_CLAMP cut, not after --
1237
+ // slicing by raw position first (this module's usual idiom, e.g.
1238
+ // preconditionFailedError's rawFailed.slice(0, DETAIL_CLAMP).map(...)
1239
+ // above) would let leading junk push a real issue out of the window
1240
+ // entirely (measured: 5 null entries then 1 real one used to clamp down
1241
+ // to 5 EMPTY {} objects, silently losing the only informative issue).
1242
+ // `failed[]`/`missing[]` are backend-contract-bounded arrays where every
1243
+ // entry is already usable by construction, so slicing first is safe
1244
+ // there; `issues` is explicitly untrusted (this whole branch exists
1245
+ // because it can be a raw SafeParseError), so usability has to be checked
1246
+ // first. The one-time O(issues.length) map+filter this costs is the same
1247
+ // order of work the pre-fix version of this function already did
1248
+ // unconditionally (it mapped the WHOLE array with no clamp at all), so
1249
+ // this is not a new cost, just a reordering of an existing one. If
1250
+ // nothing in `issues` survives the filter (including the plain `issues:
1251
+ // []` case), this falls through to the same object-passthrough branch
1252
+ // used when `issues` is not a recognizable array at all, rather than
1253
+ // emitting a misleading {issues: [], totalIssues: N}.
1254
+ //
1255
+ // `path` (zod's own array-of-string|number) is joined into a single
1256
+ // dot-separated string rather than kept as a nested array: clampDetailValue
1257
+ // caps recursion at GENERIC_DETAIL_MAX_DEPTH (3), and this summary's own
1258
+ // container nesting (the top-level object -> issues[] -> issue object)
1259
+ // already spends 2 of those 3 levels before `path` is even reached, so a
1260
+ // nested array here would push every path SEGMENT one level past the
1261
+ // depth guard and silently replace each with the truncation marker
1262
+ // instead of clamping it -- verified against clampDetailValue directly
1263
+ // before landing this. A joined string is exactly one more clamped level,
1264
+ // well within budget, and reads just as well ("acceptanceCriteria" or
1265
+ // "tags.2.name" for a nested/array path). L4 fix-round finding: a path
1266
+ // segment that is itself not a string or number (malformed/hostile input)
1267
+ // used to be silently filtered OUT of the joined path -- a real 6-segment
1268
+ // path could read as a plausible 2-segment one ("ok.3"), directly
1269
+ // contradicting this module's never-silent doctrine. Each unusable
1270
+ // segment is now rendered as a visible '?' placeholder instead, so the
1271
+ // segment COUNT stays honest even when a segment's own value cannot be
1272
+ // shown.
1273
+ //
1274
+ // `code` itself still stays `http_<status>` in this case (an object is not
1275
+ // a code -- see genericDegrade's own check below, unchanged). When
1276
+ // `body.error` is an object but carries no recognizable `issues` array (or
1277
+ // `issues` carried nothing usable, per L3 above), the object itself is
1278
+ // passed through instead of staying completely silent -- a judgment call:
1279
+ // any structured object the backend sends as `error` is more useful
1280
+ // surfaced (clamped, by the same machinery) than dropped outright, even
1281
+ // when this module cannot name its shape specifically. L6 fix-round
1282
+ // finding: that passthrough used to forward the object VERBATIM, including
1283
+ // a `stack` key when present -- measured live, a raw backend/framework
1284
+ // error object can carry a full server-side stack trace (internal file
1285
+ // paths, and, for a Prisma error, query metadata), which this module must
1286
+ // never leak to a caller. `stack` is dropped before passthrough,
1287
+ // unconditionally, whether or not this particular object actually has one.
1288
+ const GENERIC_ISSUES_CLAMP = 3;
1289
+ const GENERIC_ISSUE_ENTRY_CHAR_BUDGET = 40;
1290
+ /** Summarizes a single zod issue (untrusted -- may not even be an object)
1291
+ * into {path?, code?, message?}, each clamped to
1292
+ * GENERIC_ISSUE_ENTRY_CHAR_BUDGET. Never throws regardless of input shape:
1293
+ * a non-object issue, or one missing every recognizable field, degrades to
1294
+ * an EMPTY object, which deriveGenericDetailSource's caller filters out
1295
+ * (see the L3 fix-round finding in the comment above). See the same
1296
+ * comment's L4 entry for why an unusable `path` segment becomes a visible
1297
+ * '?' rather than being filtered out of the path. */
1298
+ function summarizeZodIssue(issue) {
1299
+ const i = issue && typeof issue === "object" ? issue : {};
1300
+ const entry = {};
1301
+ if (Array.isArray(i.path) && i.path.length > 0) {
1302
+ const rendered = i.path
1303
+ .map((seg) => (typeof seg === "string" || typeof seg === "number" ? seg : "?"))
1304
+ .join(".");
1305
+ entry.path = clamp(rendered, GENERIC_ISSUE_ENTRY_CHAR_BUDGET);
1306
+ }
1307
+ if (typeof i.code === "string")
1308
+ entry.code = clamp(i.code, GENERIC_ISSUE_ENTRY_CHAR_BUDGET);
1309
+ if (typeof i.message === "string")
1310
+ entry.message = clamp(i.message, GENERIC_ISSUE_ENTRY_CHAR_BUDGET);
1311
+ return entry;
1312
+ }
1313
+ function deriveGenericDetailSource(details, bodyError) {
1314
+ if (details && typeof details === "object" && !Array.isArray(details))
1315
+ return details;
1316
+ if (bodyError && typeof bodyError === "object" && !Array.isArray(bodyError)) {
1317
+ const body = bodyError;
1318
+ const issues = body.issues;
1319
+ if (Array.isArray(issues)) {
1320
+ const usable = issues
1321
+ .map(summarizeZodIssue)
1322
+ .filter((entry) => Object.keys(entry).length > 0)
1323
+ .slice(0, GENERIC_ISSUES_CLAMP);
1324
+ if (usable.length > 0) {
1325
+ // totalIssues is always the TRUE original count, never the
1326
+ // filtered/sliced length.
1327
+ return { issues: usable, totalIssues: issues.length };
1328
+ }
1329
+ // Nothing usable survived (see L3 above) -- fall through to the
1330
+ // object-passthrough branch below.
1331
+ }
1332
+ const { stack: _stack, ...rest } = body; // L6: never leak a backend stack trace.
1333
+ return rest;
1334
+ }
1335
+ return details;
1336
+ }
744
1337
  // The backend's own body.error string is the most specific code available
745
1338
  // and consumers key on it (the mcp-bridge governance suite asserts a 409
746
1339
  // claim_blocked stays visible end to end), so the degrade passes it
747
1340
  // 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
1341
+ // fallback for bodies that carry no code at all (including an OBJECT
1342
+ // body.error -- an object is not a code, see deriveGenericDetailSource
1343
+ // above for how it is used instead). Clamped like every other
749
1344
  // 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)
1345
+ function genericDegrade(status, message, details, bodyError) {
1346
+ const code = typeof bodyError === "string" && bodyError.length > 0
1347
+ ? clamp(bodyError, CODE_CHAR_BUDGET)
753
1348
  : `http_${status}`;
754
1349
  return buildTeachingError({
755
1350
  code,
756
1351
  message,
757
1352
  recipe: "call workflow_primer for the full lifecycle reference and today's known traps",
758
1353
  allowedNext: ["workflow_primer"],
759
- detail: clampGenericDetail(details),
1354
+ detail: clampGenericDetail(deriveGenericDetailSource(details, bodyError)),
760
1355
  });
761
1356
  }
762
1357
  /**
@@ -776,7 +1371,7 @@ export function mapBackendError(status, rawBody, verbContext) {
776
1371
  return forceAdminOnlyError(message);
777
1372
  }
778
1373
  if (status === 409 && code === "already_claimed") {
779
- return alreadyClaimedError(message);
1374
+ return alreadyClaimedError(body, message);
780
1375
  }
781
1376
  if (status === 422 && code === "precondition_failed") {
782
1377
  return preconditionFailedError(body, verbContext);
@@ -793,6 +1388,15 @@ export function mapBackendError(status, rawBody, verbContext) {
793
1388
  if (status === 409 && code === "conflict" && RESPEC_CONFLICT_PATTERN.test(message)) {
794
1389
  return respecConflictError(message);
795
1390
  }
1391
+ if (status === 409 && code === "conflict" && CREATOR_ABANDON_CONFLICT_PATTERN.test(message)) {
1392
+ return creatorAbandonConflictError(message);
1393
+ }
1394
+ if (status === 400 && code === "backlog_routing_enforced") {
1395
+ return backlogRoutingEnforcedError(message);
1396
+ }
1397
+ if (status === 403 && code === "backlog_not_promoted") {
1398
+ return backlogNotPromotedError(message);
1399
+ }
796
1400
  return genericDegrade(status, message, body.details, body.error);
797
1401
  }
798
1402
  //# sourceMappingURL=errors.js.map