@agent-tasks/mcp-server 0.12.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/README.md +108 -23
- package/dist/client.d.ts +88 -21
- package/dist/client.js +189 -14
- package/dist/client.js.map +1 -1
- package/dist/default-workflow.d.ts +23 -0
- package/dist/default-workflow.js +107 -0
- package/dist/default-workflow.js.map +1 -0
- package/dist/errors.d.ts +87 -0
- package/dist/errors.js +1402 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.js +16 -1
- package/dist/index.js.map +1 -1
- package/dist/legacy-flag.d.ts +1 -0
- package/dist/legacy-flag.js +36 -0
- package/dist/legacy-flag.js.map +1 -0
- package/dist/primer.d.ts +15 -0
- package/dist/primer.js +89 -0
- package/dist/primer.js.map +1 -0
- package/dist/read.d.ts +133 -0
- package/dist/read.js +193 -0
- package/dist/read.js.map +1 -0
- package/dist/receipt.d.ts +293 -0
- package/dist/receipt.js +622 -0
- package/dist/receipt.js.map +1 -0
- package/dist/server.d.ts +8 -3
- package/dist/server.js +22 -9
- package/dist/server.js.map +1 -1
- package/dist/tools.d.ts +3 -1
- package/dist/tools.js +417 -70
- package/dist/tools.js.map +1 -1
- package/package.json +4 -2
package/dist/errors.js
ADDED
|
@@ -0,0 +1,1402 @@
|
|
|
1
|
+
// Teaching-error layer (block tier). Normative reference:
|
|
2
|
+
// docs/response-contract-v1.md's "Error shape (block tier)" section. A call
|
|
3
|
+
// that cannot proceed at all returns
|
|
4
|
+
// { ok: false, error: { code, message, recipe, allowedNext, detail? } }
|
|
5
|
+
// instead of a bare HTTP status or a backend error string forwarded
|
|
6
|
+
// verbatim. `recipe` names the concrete corrective call; `allowedNext` lists
|
|
7
|
+
// only verb names the caller can call immediately (machine-checkable,
|
|
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.
|
|
28
|
+
//
|
|
29
|
+
// mapBackendError(status, body, verbContext?) is the single entry point:
|
|
30
|
+
// tools.ts's wrap() is its only call site (mirrors receipt.ts's relationship
|
|
31
|
+
// to the receipt-projection helpers). `verbContext`, when supplied, is the
|
|
32
|
+
// calling tool's own registered name (e.g. "task_finish") — used only where
|
|
33
|
+
// the correct recipe genuinely depends on which verb was called (today:
|
|
34
|
+
// `precondition_failed`, which the live backend can raise from task_start,
|
|
35
|
+
// task_finish, and two deprecated v1 routes with different correct retry
|
|
36
|
+
// targets; and `cross_repo_pr_rejected`, whose pull_requests_create emit
|
|
37
|
+
// site sends owner/repo rather than a prUrl, so the default task_submit_pr
|
|
38
|
+
// recipe would misdirect it). Every other catalog entry is verb-independent
|
|
39
|
+
// by construction.
|
|
40
|
+
//
|
|
41
|
+
// Catalog seed (docs/response-contract-v1.md's "Catalog seed" list, plus
|
|
42
|
+
// pr_author_mismatch from the read_first context on backend/src/routes/
|
|
43
|
+
// tasks.ts): not_claimed, already_claimed, precondition_failed,
|
|
44
|
+
// cross_repo_pr_rejected, pr_author_mismatch, force_admin_only,
|
|
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
|
|
49
|
+
// pre-claim confidence gate on task_start / the deprecated tasks_claim,
|
|
50
|
+
// backend/src/services/confidence-gate.ts via backend/src/middleware/
|
|
51
|
+
// error.ts's lowConfidence helper): NOT in the contract's original seed
|
|
52
|
+
// list, added on review (rc-v1-C005 round 1) to close an information-loss
|
|
53
|
+
// gap the generic degrade path left on the highest-traffic verb — see
|
|
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
|
|
58
|
+
// generic shape (status-derived code, message passthrough, recipe ->
|
|
59
|
+
// workflow_primer, and now also a clamped passthrough of any structured
|
|
60
|
+
// body.details — see genericDegrade) rather than being forwarded as raw
|
|
61
|
+
// text. rc-v1-C006 adds two more client-side-only entries for the
|
|
62
|
+
// projectSlug addressing feature: project_addressing_conflict and
|
|
63
|
+
// unknown_project_slug (see both below, near the end of the catalog
|
|
64
|
+
// section) — neither is a backend error mapBackendError ever sees.
|
|
65
|
+
//
|
|
66
|
+
// No em dashes in this file's exported/emitted prose (repo convention,
|
|
67
|
+
// enforced today only for primer.ts's exported strings, applied here too
|
|
68
|
+
// since these messages are caller-facing prose of the same kind).
|
|
69
|
+
//
|
|
70
|
+
// ── Response budget invariant ───────────────────────────────────────────
|
|
71
|
+
//
|
|
72
|
+
// INVARIANT: the serialized form of any TeachingError this module builds
|
|
73
|
+
// (serializeTeachingError's output, exactly what a caller receives) is
|
|
74
|
+
// always <= ERROR_BUDGET_CHARS (1200 chars, the wire-format size measured
|
|
75
|
+
// through serializeResult exactly as server.ts emits it) for arbitrary
|
|
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.
|
|
103
|
+
//
|
|
104
|
+
// The per-field clamps below (DETAIL_CLAMP, DETAIL_KEY_CLAMP,
|
|
105
|
+
// DETAIL_ENTRY_CHAR_BUDGET, MESSAGE_CHAR_BUDGET, RECIPE_CHAR_BUDGET) each
|
|
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
|
|
108
|
+
// (precondition_failed's failed[] with several entries, each carrying an
|
|
109
|
+
// optional `error` string alongside rule/message, or a wide generic
|
|
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.
|
|
135
|
+
// ── Budget / clamp constants ────────────────────────────────────────────
|
|
136
|
+
//
|
|
137
|
+
// Mirrors receipt.ts's DETAIL_CLAMP / ENTRY_CHAR_BUDGET convention (same
|
|
138
|
+
// reason: an unclamped array or a long backend string can blow the response
|
|
139
|
+
// budget on its own). Kept local to this module rather than imported from
|
|
140
|
+
// receipt.ts since the two layers clamp different shapes (string[] there,
|
|
141
|
+
// {rule,message} objects here) and have independent budgets.
|
|
142
|
+
/** Max entries kept in a detail array before it is clamped + counted. */
|
|
143
|
+
const DETAIL_CLAMP = 5;
|
|
144
|
+
/** Max distinct keys kept in a detail OBJECT before it is clamped + counted
|
|
145
|
+
* (the object counterpart to DETAIL_CLAMP's array-entry cap). An object
|
|
146
|
+
* with many keys, or long key names, is exactly as capable of blowing the
|
|
147
|
+
* response budget as an oversized array or string, and per-VALUE clamping
|
|
148
|
+
* alone does nothing to bound key count or key-name length. */
|
|
149
|
+
const DETAIL_KEY_CLAMP = 12;
|
|
150
|
+
/** Per-entry char bound for a detail array's own string fields, and for a
|
|
151
|
+
* detail object's own key names and string values. */
|
|
152
|
+
const DETAIL_ENTRY_CHAR_BUDGET = 60;
|
|
153
|
+
/** Char bound for the top-level `message` and `recipe` strings — these can
|
|
154
|
+
* carry a raw backend message (a zod validation error, for one, can run to
|
|
155
|
+
* thousands of chars) or, for `recipe`, a hand-authored corrective sentence
|
|
156
|
+
* that must itself never grow into a prose blob. */
|
|
157
|
+
const MESSAGE_CHAR_BUDGET = 300;
|
|
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;
|
|
177
|
+
const TRUNCATION_MARKER = "...";
|
|
178
|
+
/** Hard ceiling on the whole serialized teaching error (JSON.stringify(x,
|
|
179
|
+
* null, 2), the exact wire format serializeTeachingError/serializeResult
|
|
180
|
+
* emit). See the file header's "Response budget invariant" section: this
|
|
181
|
+
* is the number enforceErrorBudget (below) actually holds the line at,
|
|
182
|
+
* since the per-field clamps above only ever bound one field at a time. */
|
|
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";
|
|
201
|
+
/** Tighter versions of DETAIL_CLAMP / DETAIL_KEY_CLAMP /
|
|
202
|
+
* DETAIL_ENTRY_CHAR_BUDGET, used only by enforceErrorBudget's second
|
|
203
|
+
* ("harder reclamp") pass, when the normal clamp still was not enough to
|
|
204
|
+
* bring the total under ERROR_BUDGET_CHARS. */
|
|
205
|
+
const HARD_DETAIL_CLAMP = 2;
|
|
206
|
+
const HARD_DETAIL_KEY_CLAMP = 3;
|
|
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.
|
|
226
|
+
function clamp(value, maxChars) {
|
|
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);
|
|
238
|
+
}
|
|
239
|
+
function buildTeachingError(opts) {
|
|
240
|
+
const err = {
|
|
241
|
+
ok: false,
|
|
242
|
+
error: {
|
|
243
|
+
code: opts.code,
|
|
244
|
+
message: clamp(opts.message, MESSAGE_CHAR_BUDGET),
|
|
245
|
+
recipe: clamp(opts.recipe, RECIPE_CHAR_BUDGET),
|
|
246
|
+
allowedNext: opts.allowedNext,
|
|
247
|
+
...(opts.detail ? { detail: opts.detail } : {}),
|
|
248
|
+
},
|
|
249
|
+
};
|
|
250
|
+
// Single choke point for every TeachingError this module ever constructs
|
|
251
|
+
// (every catalog entry, the generic degrade path, and
|
|
252
|
+
// resultMustBePlainStringError all call buildTeachingError): the response
|
|
253
|
+
// budget invariant documented in the file header is enforced HERE, not
|
|
254
|
+
// duplicated at each call site or bolted onto mapBackendError's return
|
|
255
|
+
// path, so a future catalog entry gets it for free. enforceErrorBudget is
|
|
256
|
+
// defined further down (near clampDetailValue, which it reuses); function
|
|
257
|
+
// declarations are hoisted, so the forward reference is fine.
|
|
258
|
+
return enforceErrorBudget(err);
|
|
259
|
+
}
|
|
260
|
+
/** Serializes a TeachingError exactly as server.ts's serializeResult would
|
|
261
|
+
* (JSON.stringify(x, null, 2) for a non-string result — a teaching error is
|
|
262
|
+
* always an object, never a string, so the two are always equal for this
|
|
263
|
+
* input). Defined locally rather than importing serializeResult from
|
|
264
|
+
* server.ts to avoid a circular import (server.ts -> tools.ts -> errors.ts);
|
|
265
|
+
* tests/errors.test.ts asserts the two stay equal for every catalog entry. */
|
|
266
|
+
export function serializeTeachingError(err) {
|
|
267
|
+
return JSON.stringify(err, null, 2);
|
|
268
|
+
}
|
|
269
|
+
function asBackendBody(body) {
|
|
270
|
+
return body && typeof body === "object" ? body : {};
|
|
271
|
+
}
|
|
272
|
+
function backendMessage(body, status) {
|
|
273
|
+
return typeof body.message === "string" && body.message.length > 0
|
|
274
|
+
? body.message
|
|
275
|
+
: `request failed with status ${status}`;
|
|
276
|
+
}
|
|
277
|
+
// ── Catalog entries ─────────────────────────────────────────────────────
|
|
278
|
+
// 1. Acting without a claim. task_finish, task_submit_pr, and task_abandon
|
|
279
|
+
// all return 403 `forbidden` with a message matching this shape when the
|
|
280
|
+
// caller does not hold the claim on the task (backend/src/routes/tasks.ts:
|
|
281
|
+
// POST /tasks/:id/finish, POST /tasks/:id/submit-pr, POST
|
|
282
|
+
// /tasks/:id/abandon). The backend's own `error` code is the generic
|
|
283
|
+
// "forbidden" (shared with unrelated 403s like missing-scope and
|
|
284
|
+
// access-denied), so this catalog entry is message-pattern matched, not
|
|
285
|
+
// code matched, and mints its own more specific `not_claimed` code.
|
|
286
|
+
const NOT_CLAIMED_PATTERN = /do not hold .*claim/i;
|
|
287
|
+
function notClaimedError(message) {
|
|
288
|
+
return buildTeachingError({
|
|
289
|
+
code: "not_claimed",
|
|
290
|
+
message,
|
|
291
|
+
recipe: "call task_start to claim this task first",
|
|
292
|
+
allowedNext: ["task_start"],
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
// 2. Claim wall / solo multi-task. task_pickup and task_start both return
|
|
296
|
+
// 409 `already_claimed` when the caller already holds an active claim
|
|
297
|
+
// (backend/src/routes/tasks.ts: POST /tasks/pickup, POST
|
|
298
|
+
// /tasks/:id/start). The backend's own code is already specific, so it is
|
|
299
|
+
// kept verbatim as this entry's code.
|
|
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);
|
|
429
|
+
return buildTeachingError({
|
|
430
|
+
code: "already_claimed",
|
|
431
|
+
message,
|
|
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 } } : {}),
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
// 3. Branch precondition. task_start / task_finish / tasks_transition [POST
|
|
451
|
+
// /tasks/:id/transition] / (the two deprecated v1 routes tasks_update
|
|
452
|
+
// [PATCH /tasks/:id] and tasks_claim [POST /tasks/:id/claim]) all return 422
|
|
453
|
+
// `precondition_failed` with a structured `failed: [{rule, message, error?}]`
|
|
454
|
+
// array (backend/src/routes/tasks.ts, backend/src/services/transition-rules.ts:
|
|
455
|
+
// TransitionRule is exactly "branchPresent" | "prPresent" | "ciGreen" |
|
|
456
|
+
// "prMerged", so `failed` never actually exceeds 4 entries today). The
|
|
457
|
+
// per-rule detail is kept STRUCTURED (each rule named individually), not
|
|
458
|
+
// collapsed into the prose `message` the backend also sends (which
|
|
459
|
+
// concatenates every failing rule's own message into one string) — the
|
|
460
|
+
// outer `message` here is a short, own-authored summary instead, so a
|
|
461
|
+
// caller reading just `error.message` still gets something scannable.
|
|
462
|
+
//
|
|
463
|
+
// The clamp (DETAIL_CLAMP entries, DETAIL_ENTRY_CHAR_BUDGET chars each) is
|
|
464
|
+
// applied unconditionally, same as receipt.ts's DETAIL_CLAMP convention,
|
|
465
|
+
// even though the fixed 4-rule set means it can never actually bite against
|
|
466
|
+
// the live backend — a future rule addition, or a malformed/spoofed body in
|
|
467
|
+
// a test fixture, must not be able to blow the response budget. This clamp
|
|
468
|
+
// bounds each FIELD on its own, not the sum of all of them; the aggregate
|
|
469
|
+
// invariant that the WHOLE response never blows the budget is what
|
|
470
|
+
// buildTeachingError's enforceErrorBudget step (see the file header)
|
|
471
|
+
// actually guarantees, since several near-max failed[] entries at once can
|
|
472
|
+
// still add up past ERROR_BUDGET_CHARS even though each stayed clamped.
|
|
473
|
+
//
|
|
474
|
+
// The real backend's TransitionRule values (backend/src/services/
|
|
475
|
+
// transition-rules.ts) and their RULE_MESSAGES prose. That prose is
|
|
476
|
+
// diagnostic ("what's wrong"), not corrective ("what to do"): at
|
|
477
|
+
// DETAIL_ENTRY_CHAR_BUDGET (60 chars) every one of the four real messages
|
|
478
|
+
// gets clamped exactly where its instruction half starts (measured:
|
|
479
|
+
// branchPresent's own message truncates to "No branch recorded on this
|
|
480
|
+
// task. PATCH /api/tasks/:id with branchNam..."). Rather than truncate the
|
|
481
|
+
// corrective away, each known rule gets its own short, own-authored
|
|
482
|
+
// corrective here instead of the backend's message, kept whole. The
|
|
483
|
+
// truncating clamp is kept as the fallback for any OTHER rule name (a
|
|
484
|
+
// future rule addition, or a malformed/spoofed body in a test fixture), so
|
|
485
|
+
// the unconditional-clamp property above still holds for anything this
|
|
486
|
+
// module does not know about.
|
|
487
|
+
// Exported so tests/errors.test.ts can assert this map's key set stays in
|
|
488
|
+
// sync with the real backend's transition-rules.ts RULE_MESSAGES (a
|
|
489
|
+
// same-workspace-idiom drift guard, not a runtime consumer outside this
|
|
490
|
+
// module).
|
|
491
|
+
export const KNOWN_RULE_CORRECTIVES = {
|
|
492
|
+
branchPresent: "record the branch via task_submit_pr",
|
|
493
|
+
prPresent: "create the PR then task_submit_pr",
|
|
494
|
+
ciGreen: "wait for CI to pass on the PR",
|
|
495
|
+
prMerged: "merge the PR first",
|
|
496
|
+
};
|
|
497
|
+
function preconditionFailedError(body, verbContext) {
|
|
498
|
+
const rawFailed = Array.isArray(body.failed) ? body.failed : [];
|
|
499
|
+
const rules = rawFailed.map((f) => (typeof f.rule === "string" ? f.rule : "unknown"));
|
|
500
|
+
// `rule` is clamped even though the real backend's TransitionRule values
|
|
501
|
+
// are short: this function's input is untrusted response data, not a
|
|
502
|
+
// value this module controls, so a malformed/oversized `rule` string
|
|
503
|
+
// must not be able to blow the per-field budget either. Three near-max
|
|
504
|
+
// fields (rule/message/error) on several entries at once can still add
|
|
505
|
+
// up past the RESPONSE budget even with every field individually
|
|
506
|
+
// clamped here; buildTeachingError's enforceErrorBudget step is what
|
|
507
|
+
// actually holds that aggregate line (see the file header). `message`
|
|
508
|
+
// is the known rule's own-authored corrective (whole, never truncated)
|
|
509
|
+
// when the rule is one of the four real ones, or the backend's own
|
|
510
|
+
// message clamped otherwise (see KNOWN_RULE_CORRECTIVES above). The
|
|
511
|
+
// optional per-rule `error` field (present today on ciGreen/prMerged
|
|
512
|
+
// when the underlying GitHub call itself failed — e.g. "GitHub
|
|
513
|
+
// unreachable" vs. a clean "CI red", the only thing distinguishing the
|
|
514
|
+
// two) is included, clamped, whenever the backend actually sent one.
|
|
515
|
+
const clampedFailed = rawFailed.slice(0, DETAIL_CLAMP).map((f) => {
|
|
516
|
+
const rawRule = typeof f.rule === "string" ? f.rule : "unknown";
|
|
517
|
+
const rawMessage = typeof f.message === "string" ? f.message : "";
|
|
518
|
+
const corrective = KNOWN_RULE_CORRECTIVES[rawRule];
|
|
519
|
+
return {
|
|
520
|
+
rule: clamp(rawRule, DETAIL_ENTRY_CHAR_BUDGET),
|
|
521
|
+
message: corrective ?? clamp(rawMessage, DETAIL_ENTRY_CHAR_BUDGET),
|
|
522
|
+
...(typeof f.error === "string" && f.error.length > 0
|
|
523
|
+
? { error: clamp(f.error, DETAIL_ENTRY_CHAR_BUDGET) }
|
|
524
|
+
: {}),
|
|
525
|
+
};
|
|
526
|
+
});
|
|
527
|
+
const needsSubmitPr = rules.includes("branchPresent") || rules.includes("prPresent");
|
|
528
|
+
// task_finish is the contract's own documented context for this trap
|
|
529
|
+
// ("blocks task_finish with 422 precondition_failed") and the correct
|
|
530
|
+
// fallback for every call site this module does not thread verbContext
|
|
531
|
+
// through today (only task_start, task_finish, tasks_claim, tasks_update,
|
|
532
|
+
// and tasks_transition can actually raise this error; see tools.ts's
|
|
533
|
+
// wrap() call sites for those five).
|
|
534
|
+
const retryVerb = verbContext ?? "task_finish";
|
|
535
|
+
const recipe = needsSubmitPr
|
|
536
|
+
? `run \`gh pr create\`, call task_submit_pr with the branch/PR metadata, then retry ${retryVerb}`
|
|
537
|
+
: `wait for the remaining precondition(s) to clear (see error.detail.failed), then retry ${retryVerb}`;
|
|
538
|
+
const allowedNext = needsSubmitPr ? ["task_submit_pr", retryVerb] : [retryVerb];
|
|
539
|
+
return buildTeachingError({
|
|
540
|
+
code: "precondition_failed",
|
|
541
|
+
message: rules.length > 0
|
|
542
|
+
? `${rules.length} workflow gate${rules.length === 1 ? "" : "s"} not yet satisfied: ${rules
|
|
543
|
+
.slice(0, DETAIL_CLAMP)
|
|
544
|
+
.join(", ")}`
|
|
545
|
+
: "a workflow gate is not yet satisfied",
|
|
546
|
+
recipe,
|
|
547
|
+
allowedNext: Array.from(new Set(allowedNext)),
|
|
548
|
+
detail: { failed: clampedFailed, totalFailed: rawFailed.length },
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
// 4. cross_repo_pr_rejected. A prUrl (or, for pull_requests_create, an
|
|
552
|
+
// owner/repo pair) that does not point at project.githubRepo is rejected
|
|
553
|
+
// with 400 from four backend sites: POST /tasks/:id/submit-pr
|
|
554
|
+
// (task_submit_pr's own emit site), POST /tasks/:id/finish (a work-claim
|
|
555
|
+
// task_finish call that also carries prUrl), PATCH /tasks/:id (the
|
|
556
|
+
// deprecated tasks_update agent-write path), and, differently shaped, POST
|
|
557
|
+
// /pull-requests (backend/src/routes/github.ts, pull_requests_create's own
|
|
558
|
+
// emit site — rejected BEFORE a PR is even created on GitHub, from an
|
|
559
|
+
// owner/repo pair rather than a prUrl). Backend code kept verbatim; the
|
|
560
|
+
// recipe branches on verbContext because pull_requests_create's own caller
|
|
561
|
+
// sent owner/repo, not a prUrl (see crossRepoRejectedError below).
|
|
562
|
+
function crossRepoRejectedError(message, verbContext) {
|
|
563
|
+
if (verbContext === "pull_requests_create") {
|
|
564
|
+
return buildTeachingError({
|
|
565
|
+
code: "cross_repo_pr_rejected",
|
|
566
|
+
message,
|
|
567
|
+
recipe: "call pull_requests_create again with owner/repo matching this project's own repo",
|
|
568
|
+
allowedNext: ["pull_requests_create"],
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
return buildTeachingError({
|
|
572
|
+
code: "cross_repo_pr_rejected",
|
|
573
|
+
message,
|
|
574
|
+
recipe: "call task_submit_pr again with a prUrl on this project's own repo, or set deliverableRepo at create time when the deliverable is intentionally a different repo",
|
|
575
|
+
allowedNext: ["task_submit_pr"],
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
// 5. pr_author_mismatch. task_submit_pr rejects a prUrl whose PR was not
|
|
579
|
+
// authored by the delegation user, 403 (backend/src/routes/tasks.ts:
|
|
580
|
+
// POST /tasks/:id/submit-pr). Backend code kept verbatim.
|
|
581
|
+
function prAuthorMismatchError(message) {
|
|
582
|
+
return buildTeachingError({
|
|
583
|
+
code: "pr_author_mismatch",
|
|
584
|
+
message,
|
|
585
|
+
recipe: "open the PR under the delegation user's own GitHub login, then call task_submit_pr again with that prUrl",
|
|
586
|
+
allowedNext: ["task_submit_pr"],
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
// 6. transition force=admin-only. tasks_transition / POST
|
|
590
|
+
// /tasks/:id/transition { force: true } returns 403 `forbidden` for
|
|
591
|
+
// non-admins (backend/src/routes/tasks.ts: POST /tasks/:id/transition,
|
|
592
|
+
// message "Only team admins can force a transition"). Same generic backend
|
|
593
|
+
// code as not_claimed, message-pattern matched, own code minted. No self-service
|
|
594
|
+
// corrective call exists (this is genuinely an admin-only wall), so
|
|
595
|
+
// allowedNext is empty by design, not an oversight — the recipe itself
|
|
596
|
+
// still names the concrete action ("do not pass force:true"), satisfying
|
|
597
|
+
// the "never just 'invalid request'" rule without inventing a verb.
|
|
598
|
+
const FORCE_ADMIN_ONLY_PATTERN = /admins? can force a transition/i;
|
|
599
|
+
function forceAdminOnlyError(message) {
|
|
600
|
+
return buildTeachingError({
|
|
601
|
+
code: "force_admin_only",
|
|
602
|
+
message,
|
|
603
|
+
recipe: "do not pass force:true; only a project admin can use the force-transition escape hatch",
|
|
604
|
+
allowedNext: [],
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
// 7. Description immutability. task_respec only edits an OPEN, unclaimed
|
|
608
|
+
// task; any other state is rejected with 409 `conflict` (backend/src/
|
|
609
|
+
// routes/tasks.ts, RESPEC_STATE_CONFLICT_MESSAGE = "Task must be open and
|
|
610
|
+
// unclaimed to respec"). The backend's own code ("conflict") is shared with
|
|
611
|
+
// other unrelated 409s (middleware/error.ts's generic conflict() helper),
|
|
612
|
+
// so this entry is message-pattern matched and mints its own code.
|
|
613
|
+
const RESPEC_CONFLICT_PATTERN = /open and unclaimed to respec/i;
|
|
614
|
+
function respecConflictError(message) {
|
|
615
|
+
return buildTeachingError({
|
|
616
|
+
code: "respec_conflict",
|
|
617
|
+
message,
|
|
618
|
+
recipe: "task_respec only works on an open, unclaimed task; call task_abandon first if you hold the claim, then retry task_respec",
|
|
619
|
+
allowedNext: ["task_abandon", "task_respec"],
|
|
620
|
+
});
|
|
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
|
+
}
|
|
678
|
+
// 8. task_finish `result` (and the deprecated tasks_update's) as plain
|
|
679
|
+
// string. Unlike the other catalog entries, the backend performs NO
|
|
680
|
+
// validation of this today (`result` is stored verbatim as free text) —
|
|
681
|
+
// this trap exists only at the mcp-server layer, triggered locally in
|
|
682
|
+
// tools.ts's task_finish and tasks_update handlers BEFORE any request is
|
|
683
|
+
// sent, not mapped from a backend error. Exported separately (not reachable
|
|
684
|
+
// via mapBackendError, which only ever sees a real AgentTasksApiError) and
|
|
685
|
+
// paired with looksLikeStructuredWrapper, the detector tools.ts calls.
|
|
686
|
+
// Inline formatting tags a caller might legitimately use in ordinary prose
|
|
687
|
+
// (markdown-adjacent emphasis, e.g. "<b>Done</b>" as a whole result). A LONE
|
|
688
|
+
// pair using one of these is never, on its own, a structured-wrapper signal
|
|
689
|
+
// — see hasSuspiciousTagPair below. An unlisted tag (<result>, <Foo>, <div>,
|
|
690
|
+
// ...) is still suspect, and MULTIPLE tag pairs (even multiple inline-
|
|
691
|
+
// formatting ones) are still suspect: the allowance is deliberately scoped
|
|
692
|
+
// to a single lone pair.
|
|
693
|
+
const INLINE_FORMATTING_TAGS = new Set(["b", "i", "em", "strong", "code"]);
|
|
694
|
+
// Finds every non-overlapping complete "<tag ...>...</tag>" pair in a
|
|
695
|
+
// string (global, lazy inner match so a sibling pair right after a closing
|
|
696
|
+
// tag is found as its own match rather than the scan running past it to a
|
|
697
|
+
// later same-named closing tag).
|
|
698
|
+
const TAG_PAIR_PATTERN = /<([a-zA-Z][\w:-]*)\b[^>]*>[\s\S]*?<\/\1>/g;
|
|
699
|
+
// A pathological string (many '<' characters with no matching closing tag)
|
|
700
|
+
// can make TAG_PAIR_PATTERN's lazy, backtracking-capable inner match blow up
|
|
701
|
+
// combinatorially on long input (measured: ~18.4s scanning a single 400k-char
|
|
702
|
+
// adversarial string). tools.ts's task_finish and tasks_update both cap
|
|
703
|
+
// `result` at 5000 chars today, but this guard must not itself become the
|
|
704
|
+
// next unbounded-input path for some future caller that forgets to cap its
|
|
705
|
+
// own input before handing it to looksLikeStructuredWrapper, so it is
|
|
706
|
+
// bounded here too, defensively, independent of any caller-side cap. Only
|
|
707
|
+
// the leading TAG_SCAN_CHAR_LIMIT chars are scanned for a suspicious tag
|
|
708
|
+
// pair; a legitimate tag pair sitting entirely past that point in an
|
|
709
|
+
// already-pathologically-long value is missed, an accepted trade-off since a
|
|
710
|
+
// value that long is already well outside "plain prose result text"
|
|
711
|
+
// territory regardless.
|
|
712
|
+
const TAG_SCAN_CHAR_LIMIT = 6000;
|
|
713
|
+
/** True when `trimmed` contains a tag pair this guard treats as suspicious.
|
|
714
|
+
* Zero matches: never suspicious (plain prose that merely mentions an
|
|
715
|
+
* unclosed tag, e.g. "fixed the <Foo> component", never matches at all).
|
|
716
|
+
* More than one matched pair: always suspicious, regardless of tag name —
|
|
717
|
+
* a caller wrapping two separate pieces in their own tags (or repeating an
|
|
718
|
+
* inline-formatting tag) is exactly the kind of LLM mistake this guard
|
|
719
|
+
* exists to catch, so the inline-formatting allowance below is
|
|
720
|
+
* deliberately scoped to a LONE pair only. Exactly one matched pair: a
|
|
721
|
+
* lone INLINE_FORMATTING_TAGS pair is never suspicious (regardless of
|
|
722
|
+
* position — a bolded lead-in like "<b>Warning:</b> ..." is ordinary
|
|
723
|
+
* prose); any other single tag is suspicious only when it sits at the
|
|
724
|
+
* leading or trailing edge of the value (a whole-string wrap, a tag
|
|
725
|
+
* followed by trailing prose, or leading prose followed by a tag) — NOT
|
|
726
|
+
* when it is embedded mid-sentence with prose on both sides, which stays
|
|
727
|
+
* deliberately uncovered (indistinguishable from a caller quoting a
|
|
728
|
+
* tag-like token in normal prose; see tests/errors.test.ts's
|
|
729
|
+
* "embedded mid-sentence" case for the documented boundary). */
|
|
730
|
+
function hasSuspiciousTagPair(trimmed) {
|
|
731
|
+
const matches = Array.from(trimmed.matchAll(TAG_PAIR_PATTERN));
|
|
732
|
+
if (matches.length === 0)
|
|
733
|
+
return false;
|
|
734
|
+
if (matches.length > 1)
|
|
735
|
+
return true;
|
|
736
|
+
const [match] = matches;
|
|
737
|
+
const tag = match[1].toLowerCase();
|
|
738
|
+
if (INLINE_FORMATTING_TAGS.has(tag))
|
|
739
|
+
return false;
|
|
740
|
+
const start = match.index ?? 0;
|
|
741
|
+
const end = start + match[0].length;
|
|
742
|
+
return start === 0 || end === trimmed.length;
|
|
743
|
+
}
|
|
744
|
+
/** True when `value` (trimmed) looks like an LLM-style structured wrapper
|
|
745
|
+
* around what should be plain prose: an `<?xml` preamble, a fenced code
|
|
746
|
+
* block (the single most common mistake — wrapping the whole answer, or a
|
|
747
|
+
* JSON payload, in a \`\`\` / \`\`\`json fence), valid whole-string JSON, or
|
|
748
|
+
* a suspicious tag pair (see hasSuspiciousTagPair). Deliberately NOT
|
|
749
|
+
* triggered by a value that merely contains an angle bracket or a brace
|
|
750
|
+
* somewhere in ordinary prose, or by a single inline-formatting tag pair
|
|
751
|
+
* (e.g. a result of exactly "<b>Done</b>") — both stay legitimate prose. */
|
|
752
|
+
export function looksLikeStructuredWrapper(value) {
|
|
753
|
+
const trimmed = value.trim();
|
|
754
|
+
if (trimmed.length === 0)
|
|
755
|
+
return false;
|
|
756
|
+
// <?xml preamble: an LLM that started emitting an XML document.
|
|
757
|
+
if (/^<\?xml\b/i.test(trimmed))
|
|
758
|
+
return true;
|
|
759
|
+
// A fenced code block anywhere, so long as the fence starts at the
|
|
760
|
+
// beginning of a line — not just when it opens the whole string, since a
|
|
761
|
+
// caller often prefaces the fence with a sentence of prose.
|
|
762
|
+
if (/^```/m.test(trimmed))
|
|
763
|
+
return true;
|
|
764
|
+
if ((trimmed.startsWith("{") && trimmed.endsWith("}")) ||
|
|
765
|
+
(trimmed.startsWith("[") && trimmed.endsWith("]"))) {
|
|
766
|
+
try {
|
|
767
|
+
JSON.parse(trimmed);
|
|
768
|
+
return true;
|
|
769
|
+
}
|
|
770
|
+
catch {
|
|
771
|
+
// Starts/ends with a brace but is not valid JSON on its own — fall
|
|
772
|
+
// through to the tag-pair check below rather than assuming prose.
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
return hasSuspiciousTagPair(trimmed.length > TAG_SCAN_CHAR_LIMIT ? trimmed.slice(0, TAG_SCAN_CHAR_LIMIT) : trimmed);
|
|
776
|
+
}
|
|
777
|
+
export function resultMustBePlainStringError(verb = "task_finish") {
|
|
778
|
+
return buildTeachingError({
|
|
779
|
+
code: "result_not_plain_string",
|
|
780
|
+
message: "result must be plain prose or markdown text, not wrapped in XML or JSON tags",
|
|
781
|
+
recipe: `resubmit ${verb} with result as plain text (no <tag>...</tag> or {...} wrapping)`,
|
|
782
|
+
allowedNext: [verb],
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
// 9. low_confidence. task_start's (and the deprecated tasks_claim's)
|
|
786
|
+
// pre-claim confidence gate rejects a claim below the project's confidence
|
|
787
|
+
// threshold with 422 `low_confidence` (backend/src/services/
|
|
788
|
+
// confidence-gate.ts's evaluateConfidenceGate, via backend/src/middleware/
|
|
789
|
+
// error.ts's lowConfidence helper: POST /tasks/:id/start, POST
|
|
790
|
+
// /tasks/:id/claim). NOT in the contract's original catalog seed (see the
|
|
791
|
+
// file header above) — added on review because the generic degrade path
|
|
792
|
+
// was silently DROPPING body.details (score, threshold, missing[],
|
|
793
|
+
// nextActions) on this specific, highest-traffic verb: a caller saw only a
|
|
794
|
+
// generic message and a workflow_primer recipe, with no way to learn WHY
|
|
795
|
+
// the claim was blocked short of re-deriving it independently. task_respec
|
|
796
|
+
// is the contract's own documented corrective for CONFIDENCE_BELOW_THRESHOLD
|
|
797
|
+
// (docs/response-contract-v1.md's deviation catalog; receipt.ts's
|
|
798
|
+
// confidenceDeviation uses the same corrective for task_create/
|
|
799
|
+
// task_respec's own low-score case), so it is named here too.
|
|
800
|
+
function lowConfidenceError(body, message) {
|
|
801
|
+
const details = body.details && typeof body.details === "object" && !Array.isArray(body.details)
|
|
802
|
+
? body.details
|
|
803
|
+
: {};
|
|
804
|
+
const score = typeof details.score === "number" ? details.score : undefined;
|
|
805
|
+
const threshold = typeof details.threshold === "number" ? details.threshold : undefined;
|
|
806
|
+
const rawMissing = Array.isArray(details.missing)
|
|
807
|
+
? details.missing.filter((m) => typeof m === "string")
|
|
808
|
+
: [];
|
|
809
|
+
// Same DETAIL_CLAMP/DETAIL_ENTRY_CHAR_BUDGET convention as
|
|
810
|
+
// precondition_failed's `failed[]` above: the backend scorer can
|
|
811
|
+
// populate up to 9 field names (see receipt.ts's confidenceDeviation),
|
|
812
|
+
// already in surfacing-priority order.
|
|
813
|
+
const missing = rawMissing.slice(0, DETAIL_CLAMP).map((m) => clamp(m, DETAIL_ENTRY_CHAR_BUDGET));
|
|
814
|
+
return buildTeachingError({
|
|
815
|
+
code: "low_confidence",
|
|
816
|
+
message,
|
|
817
|
+
recipe: "call task_respec to raise the description/templateData above the confidence threshold, then retry",
|
|
818
|
+
allowedNext: ["task_respec"],
|
|
819
|
+
detail: {
|
|
820
|
+
...(score !== undefined ? { score } : {}),
|
|
821
|
+
...(threshold !== undefined ? { threshold } : {}),
|
|
822
|
+
missing,
|
|
823
|
+
totalMissing: rawMissing.length,
|
|
824
|
+
},
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
// 10. project_addressing_conflict / unknown_project_slug. rc-v1-C006's
|
|
828
|
+
// projectSlug alternative to projectId (task_create, and project_tasks via
|
|
829
|
+
// the same client-side resolver, client.ts's withResolvedProjectSlug):
|
|
830
|
+
// neither trap is a backend error the real API ever raises with these
|
|
831
|
+
// codes, so neither is reachable via mapBackendError below. Both are raised
|
|
832
|
+
// directly by the calling tool's own handler in tools.ts, same pattern as
|
|
833
|
+
// catalog entry #8 (resultMustBePlainStringError) — a client-side guard
|
|
834
|
+
// checked before, or in place of, any network call.
|
|
835
|
+
//
|
|
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
|
|
841
|
+
// through this catalog. Rather than mint a second, near-duplicate code for
|
|
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.
|
|
859
|
+
//
|
|
860
|
+
// rc-v1-C007 pruned projects_list out of the DEFAULT tool registration
|
|
861
|
+
// (tools.ts's LEGACY_VERB_NAMES); it is opt-in only via
|
|
862
|
+
// AGENT_TASKS_MCP_LEGACY=1 now. task_create and project_tasks (this
|
|
863
|
+
// catalog entry's only two real call sites) both stay in the default
|
|
864
|
+
// registration, so a default-mode caller can trip "neither_provided"
|
|
865
|
+
// without ever having projects_list available to them. `allowedNext` MUST
|
|
866
|
+
// list only verb names callable immediately (docs/response-contract-v1.md's
|
|
867
|
+
// error-shape section), so "neither"'s allowedNext no longer names
|
|
868
|
+
// projects_list unconditionally; `recipe` still mentions it, but only as
|
|
869
|
+
// the legacy-flag option, alongside the always-available "ask the
|
|
870
|
+
// operator" fallback.
|
|
871
|
+
export function projectAddressingConflictError(verb, reason = "both_provided") {
|
|
872
|
+
if (reason === "neither_provided") {
|
|
873
|
+
return buildTeachingError({
|
|
874
|
+
code: "project_addressing_conflict",
|
|
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`,
|
|
893
|
+
allowedNext: [verb],
|
|
894
|
+
});
|
|
895
|
+
}
|
|
896
|
+
return buildTeachingError({
|
|
897
|
+
code: "project_addressing_conflict",
|
|
898
|
+
message: "projectId and projectSlug were both provided; pass exactly one",
|
|
899
|
+
recipe: `resubmit ${verb} with only one of projectId or projectSlug`,
|
|
900
|
+
allowedNext: [verb],
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
// Raised when client.ts's slug resolver gets a 404 on a FRESH (not
|
|
904
|
+
// cache-served) slug lookup — see client.ts's ProjectSlugNotFoundError and
|
|
905
|
+
// withResolvedProjectSlug. `recipe` used to name projects_list
|
|
906
|
+
// unconditionally as the concrete corrective call for "how do I find the
|
|
907
|
+
// actual available slugs". Same rc-v1-C007 constraint as
|
|
908
|
+
// projectAddressingConflictError above: projects_list is legacy-gated now,
|
|
909
|
+
// task_create and project_tasks (both default-registered) are this
|
|
910
|
+
// catalog entry's real call sites, so `allowedNext` no longer names it
|
|
911
|
+
// (only the calling verb does); `recipe` still offers it as the
|
|
912
|
+
// legacy-flag option alongside the always-available operator fallback.
|
|
913
|
+
export function unknownProjectSlugError(slug, verb) {
|
|
914
|
+
return buildTeachingError({
|
|
915
|
+
code: "unknown_project_slug",
|
|
916
|
+
message: `no project found for slug "${slug}"`,
|
|
917
|
+
recipe: "ask the operator for the correct project slug or id (or, with AGENT_TASKS_MCP_LEGACY=1 set, call projects_list to see the available slugs)",
|
|
918
|
+
allowedNext: [verb],
|
|
919
|
+
});
|
|
920
|
+
}
|
|
921
|
+
// ── Generic degrade path ────────────────────────────────────────────────
|
|
922
|
+
//
|
|
923
|
+
// Any backend error not matched by one of the catalog entries above
|
|
924
|
+
// degrades structurally instead of being forwarded as raw text: the code is
|
|
925
|
+
// derived from the HTTP status (NOT the backend's own `error` field — that
|
|
926
|
+
// field is only trustworthy as a catalog SIGNAL, matched explicitly above;
|
|
927
|
+
// echoing it verbatim here would silently grow the catalog by accident
|
|
928
|
+
// every time the backend adds a new code), the message is passed through
|
|
929
|
+
// (clamped), the recipe points at workflow_primer, the one call every
|
|
930
|
+
// caller can always make to recover — AND, when the backend body carried a
|
|
931
|
+
// structured `details` object, a clamped copy of it survives into
|
|
932
|
+
// `error.detail` instead of being dropped. Before this, any uncataloged
|
|
933
|
+
// error with a `details` payload (not just low_confidence, which is now
|
|
934
|
+
// its own catalog entry above) silently lost that payload; this closes the
|
|
935
|
+
// gap for the whole degrade class, not just the one verb that happened to
|
|
936
|
+
// earn its own catalog entry.
|
|
937
|
+
const GENERIC_DETAIL_MAX_DEPTH = 3;
|
|
938
|
+
/** Writes `key: value` into `out`, disambiguating on collision instead of
|
|
939
|
+
* silently overwriting the earlier entry. A collision here means two
|
|
940
|
+
* DISTINCT original keys clamped down to the identical truncated name
|
|
941
|
+
* (e.g. several keys sharing a long common prefix beyond the char
|
|
942
|
+
* budget). Without this, the second write would clobber the first with
|
|
943
|
+
* no trace, which is exactly the kind of silent data loss this whole
|
|
944
|
+
* module exists to avoid. */
|
|
945
|
+
function setClampedKey(out, key, value) {
|
|
946
|
+
if (!(key in out)) {
|
|
947
|
+
out[key] = value;
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
950
|
+
let suffix = 2;
|
|
951
|
+
while (`${key}~${suffix}` in out)
|
|
952
|
+
suffix++;
|
|
953
|
+
out[`${key}~${suffix}`] = value;
|
|
954
|
+
}
|
|
955
|
+
/** Recursively clamps an arbitrary JSON-ish detail value: every string is
|
|
956
|
+
* char-clamped, every array is entry-clamped, and every object's key
|
|
957
|
+
* COUNT is entry-clamped too (an object with many keys, or long key
|
|
958
|
+
* names, is exactly as capable of blowing the response budget as an
|
|
959
|
+
* oversized array or string, and per-VALUE clamping alone does nothing to
|
|
960
|
+
* bound key count or key-name length). Surviving keys' NAMES are
|
|
961
|
+
* themselves char-clamped, colliding clamped names are disambiguated
|
|
962
|
+
* rather than overwritten (see setClampedKey), and a `totalKeys` marker
|
|
963
|
+
* is added whenever any key was dropped, so the drop is never silent.
|
|
964
|
+
* Kept values are clamped the same way, recursively. `depth` guards
|
|
965
|
+
* against a pathological/cyclic input from untrusted response data. */
|
|
966
|
+
function clampDetailValue(value, depth, opts = {}) {
|
|
967
|
+
const arrayClamp = opts.arrayClamp ?? DETAIL_CLAMP;
|
|
968
|
+
const keyClamp = opts.keyClamp ?? DETAIL_KEY_CLAMP;
|
|
969
|
+
const entryChars = opts.entryChars ?? DETAIL_ENTRY_CHAR_BUDGET;
|
|
970
|
+
if (depth > GENERIC_DETAIL_MAX_DEPTH)
|
|
971
|
+
return "[detail nested too deep, truncated]";
|
|
972
|
+
if (typeof value === "string")
|
|
973
|
+
return clamp(value, entryChars);
|
|
974
|
+
if (Array.isArray(value)) {
|
|
975
|
+
return value.slice(0, arrayClamp).map((v) => clampDetailValue(v, depth + 1, opts));
|
|
976
|
+
}
|
|
977
|
+
if (value && typeof value === "object") {
|
|
978
|
+
const entries = Object.entries(value);
|
|
979
|
+
const out = {};
|
|
980
|
+
for (const [k, v] of entries.slice(0, keyClamp)) {
|
|
981
|
+
setClampedKey(out, clamp(k, entryChars), clampDetailValue(v, depth + 1, opts));
|
|
982
|
+
}
|
|
983
|
+
if (entries.length > keyClamp)
|
|
984
|
+
out.totalKeys = entries.length;
|
|
985
|
+
return out;
|
|
986
|
+
}
|
|
987
|
+
// number, boolean, null, undefined: passed through unchanged.
|
|
988
|
+
return value;
|
|
989
|
+
}
|
|
990
|
+
/** Clamps a whole `details` object for the generic degrade path. Returns
|
|
991
|
+
* undefined (so buildTeachingError omits `detail` entirely) when the
|
|
992
|
+
* backend sent nothing usable — not an object, an array, or empty.
|
|
993
|
+
* Delegates straight to clampDetailValue (depth 0) rather than its own
|
|
994
|
+
* parallel key-walk: the top-level object needs exactly the same
|
|
995
|
+
* key-count/key-name clamping clampDetailValue's object branch already
|
|
996
|
+
* does for every NESTED object, so a wide top-level `details` (many keys,
|
|
997
|
+
* or long key names) and a wide NESTED object are both bounded by the one
|
|
998
|
+
* code path. */
|
|
999
|
+
function clampGenericDetail(details) {
|
|
1000
|
+
if (!details || typeof details !== "object" || Array.isArray(details))
|
|
1001
|
+
return undefined;
|
|
1002
|
+
const out = clampDetailValue(details, 0);
|
|
1003
|
+
return Object.keys(out).length > 0 ? out : undefined;
|
|
1004
|
+
}
|
|
1005
|
+
// Bookkeeping fields a catalog entry or clampDetailValue itself may already
|
|
1006
|
+
// have set to record a TRUE original count (precondition_failed's
|
|
1007
|
+
// totalFailed, low_confidence's totalMissing, clampDetailValue's own
|
|
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"];
|
|
1015
|
+
/** Re-clamps a detail object with the HARD_* limits, WITHOUT letting the
|
|
1016
|
+
* pass corrupt any totalFailed/totalMissing/totalKeys marker already
|
|
1017
|
+
* present (see DETAIL_TOTAL_MARKER_KEYS): those numbers are pulled out
|
|
1018
|
+
* first, the remaining data-bearing keys are clamped harder on their own,
|
|
1019
|
+
* and the original markers are restored afterward, overwriting whatever
|
|
1020
|
+
* (smaller, intermediate-count) marker clampDetailValue's own object
|
|
1021
|
+
* branch may have added while re-clamping the rest. */
|
|
1022
|
+
function reclampDetailHarder(detail) {
|
|
1023
|
+
const preservedMarkers = {};
|
|
1024
|
+
const rest = {};
|
|
1025
|
+
for (const [k, v] of Object.entries(detail)) {
|
|
1026
|
+
if (DETAIL_TOTAL_MARKER_KEYS.includes(k) && typeof v === "number") {
|
|
1027
|
+
preservedMarkers[k] = v;
|
|
1028
|
+
}
|
|
1029
|
+
else {
|
|
1030
|
+
rest[k] = v;
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
const reclampedRest = clampDetailValue(rest, 0, {
|
|
1034
|
+
arrayClamp: HARD_DETAIL_CLAMP,
|
|
1035
|
+
keyClamp: HARD_DETAIL_KEY_CLAMP,
|
|
1036
|
+
entryChars: HARD_DETAIL_ENTRY_CHAR_BUDGET,
|
|
1037
|
+
});
|
|
1038
|
+
return { ...reclampedRest, ...preservedMarkers };
|
|
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
|
+
}
|
|
1091
|
+
/** Enforces the response budget invariant documented in the file header.
|
|
1092
|
+
* buildTeachingError's own per-field clamps (MESSAGE_CHAR_BUDGET,
|
|
1093
|
+
* RECIPE_CHAR_BUDGET) and each catalog entry's own array/key clamps
|
|
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) {
|
|
1125
|
+
if (serializeTeachingError(err).length <= ERROR_BUDGET_CHARS)
|
|
1126
|
+
return err;
|
|
1127
|
+
if (err.error.detail) {
|
|
1128
|
+
const reclamped = {
|
|
1129
|
+
...err,
|
|
1130
|
+
error: {
|
|
1131
|
+
...err.error,
|
|
1132
|
+
detail: reclampDetailHarder(err.error.detail),
|
|
1133
|
+
},
|
|
1134
|
+
};
|
|
1135
|
+
if (serializeTeachingError(reclamped).length <= ERROR_BUDGET_CHARS)
|
|
1136
|
+
return reclamped;
|
|
1137
|
+
}
|
|
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;
|
|
1148
|
+
const priorDetail = err.error.detail;
|
|
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.
|
|
1186
|
+
return {
|
|
1187
|
+
...trimmed,
|
|
1188
|
+
error: {
|
|
1189
|
+
...trimmed.error,
|
|
1190
|
+
code: ERROR_BUDGET_OVERFLOW_CODE,
|
|
1191
|
+
},
|
|
1192
|
+
};
|
|
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
|
+
}
|
|
1337
|
+
// The backend's own body.error string is the most specific code available
|
|
1338
|
+
// and consumers key on it (the mcp-bridge governance suite asserts a 409
|
|
1339
|
+
// claim_blocked stays visible end to end), so the degrade passes it
|
|
1340
|
+
// through when present; the status-derived http_<status> form is only the
|
|
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
|
|
1344
|
+
// caller-visible string so a pathological body cannot blow the budget.
|
|
1345
|
+
function genericDegrade(status, message, details, bodyError) {
|
|
1346
|
+
const code = typeof bodyError === "string" && bodyError.length > 0
|
|
1347
|
+
? clamp(bodyError, CODE_CHAR_BUDGET)
|
|
1348
|
+
: `http_${status}`;
|
|
1349
|
+
return buildTeachingError({
|
|
1350
|
+
code,
|
|
1351
|
+
message,
|
|
1352
|
+
recipe: "call workflow_primer for the full lifecycle reference and today's known traps",
|
|
1353
|
+
allowedNext: ["workflow_primer"],
|
|
1354
|
+
detail: clampGenericDetail(deriveGenericDetailSource(details, bodyError)),
|
|
1355
|
+
});
|
|
1356
|
+
}
|
|
1357
|
+
/**
|
|
1358
|
+
* Maps a backend AgentTasksApiError's (status, body) to the teaching-error
|
|
1359
|
+
* shape. `verbContext`, when supplied, is the calling tool's own registered
|
|
1360
|
+
* name — see the precondition_failed catalog entry above for the one place
|
|
1361
|
+
* it changes the output.
|
|
1362
|
+
*/
|
|
1363
|
+
export function mapBackendError(status, rawBody, verbContext) {
|
|
1364
|
+
const body = asBackendBody(rawBody);
|
|
1365
|
+
const code = typeof body.error === "string" ? body.error : undefined;
|
|
1366
|
+
const message = backendMessage(body, status);
|
|
1367
|
+
if (status === 403 && code === "forbidden" && NOT_CLAIMED_PATTERN.test(message)) {
|
|
1368
|
+
return notClaimedError(message);
|
|
1369
|
+
}
|
|
1370
|
+
if (status === 403 && code === "forbidden" && FORCE_ADMIN_ONLY_PATTERN.test(message)) {
|
|
1371
|
+
return forceAdminOnlyError(message);
|
|
1372
|
+
}
|
|
1373
|
+
if (status === 409 && code === "already_claimed") {
|
|
1374
|
+
return alreadyClaimedError(body, message);
|
|
1375
|
+
}
|
|
1376
|
+
if (status === 422 && code === "precondition_failed") {
|
|
1377
|
+
return preconditionFailedError(body, verbContext);
|
|
1378
|
+
}
|
|
1379
|
+
if (status === 422 && code === "low_confidence") {
|
|
1380
|
+
return lowConfidenceError(body, message);
|
|
1381
|
+
}
|
|
1382
|
+
if (status === 400 && code === "cross_repo_pr_rejected") {
|
|
1383
|
+
return crossRepoRejectedError(message, verbContext);
|
|
1384
|
+
}
|
|
1385
|
+
if (status === 403 && code === "pr_author_mismatch") {
|
|
1386
|
+
return prAuthorMismatchError(message);
|
|
1387
|
+
}
|
|
1388
|
+
if (status === 409 && code === "conflict" && RESPEC_CONFLICT_PATTERN.test(message)) {
|
|
1389
|
+
return respecConflictError(message);
|
|
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
|
+
}
|
|
1400
|
+
return genericDegrade(status, message, body.details, body.error);
|
|
1401
|
+
}
|
|
1402
|
+
//# sourceMappingURL=errors.js.map
|