@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.
@@ -0,0 +1,622 @@
1
+ // Central receipt layer for write-verb responses. Normative reference:
2
+ // docs/response-contract-v1.md. This is the "new responsibility at the
3
+ // choke point" the contract calls out for tools.ts's wrap() helper — this
4
+ // module is that responsibility, kept separate from wrap() itself so wrap()
5
+ // stays a pure error-mapping helper and the receipt projection stays
6
+ // independently testable.
7
+ //
8
+ // A receipt has three tiers layered in one object:
9
+ // Tier 1 (confirm) — always present, <= ~60 tokens.
10
+ // Tier 2 (deviations) — present only when something needs the caller's
11
+ // attention, <= ~400 tokens.
12
+ // Tier 3 (next) — optional, 1-3 free-form hints, present only when
13
+ // there is an obvious follow-up call.
14
+ //
15
+ // Every verb's `include: ["task"]` valve returns the backend object
16
+ // verbatim, bypassing the tier machinery entirely — the old, pre-contract
17
+ // shape stays reachable unchanged. Most write verbs check this in their
18
+ // tools.ts handler before calling into this module at all; task_pickup's
19
+ // projectPickup and task_start's receiptForStart instead own the check
20
+ // themselves, since both verbs' `include` vocabulary is wider than the
21
+ // single "task" value the other write verbs accept, so the valve lives at
22
+ // the same layer as the rest of their include handling.
23
+ import { DEFAULT_WORKFLOW_AGENT_INSTRUCTIONS, DEFAULT_WORKFLOW_TRANSITIONS, } from "./default-workflow.js";
24
+ /** Low-level composer. Every receiptFor* builder below funnels through this
25
+ * so the tier layering (present/absent rules) lives in exactly one place. */
26
+ export function buildReceipt(opts) {
27
+ const receipt = {
28
+ ok: true,
29
+ task: opts.status !== undefined
30
+ ? { id: opts.taskId, status: opts.status }
31
+ : { id: opts.taskId },
32
+ };
33
+ if (opts.transition)
34
+ receipt.transition = opts.transition;
35
+ if (opts.confidence !== undefined)
36
+ receipt.confidence = opts.confidence;
37
+ if (opts.deviations && opts.deviations.length > 0)
38
+ receipt.deviations = opts.deviations;
39
+ if (opts.next && opts.next.length > 0)
40
+ receipt.next = opts.next;
41
+ return receipt;
42
+ }
43
+ // Shared clamp for every deviation's array-valued detail field (`missing[]`
44
+ // on CONFIDENCE_BELOW_THRESHOLD, `rejected[]` on DEPENDS_ON_REJECTED,
45
+ // `dropped[]` on LABELS_DROPPED, `skipped[]` on WORKFLOW_GATE_SKIPPED):
46
+ // first N entries plus an explicit total count, so a caller at the tail of
47
+ // a long list still learns "there were more" instead of the array being
48
+ // silently truncated with no signal. This is a contract-wide rule (see
49
+ // docs/response-contract-v1.md's "Detail arrays are clamped" paragraph),
50
+ // applied unconditionally so it holds without exceptions, even for fields
51
+ // (like `skipped[]`, bounded by the fixed set of workflow gates) that can
52
+ // never actually reach the clamp in practice.
53
+ export const DETAIL_CLAMP = 5;
54
+ // Per-entry byte bound layered on top of DETAIL_CLAMP. DETAIL_CLAMP alone
55
+ // only bounds array LENGTH: a caller-influenced string entering a detail
56
+ // array (today: LABELS_DROPPED's `dropped[]`, sourced from task_create's
57
+ // `labels` schema, each up to 100 chars per tools.ts inputShape) can still
58
+ // blow the tier-2 budget at its own declared maximum even with only 5
59
+ // entries kept, measured at 1731 emitted chars (already over the
60
+ // 1600-char cap) with an unbounded entry length, before this clamp existed.
61
+ //
62
+ // 19 is not a round guess, it is the largest value that clears the tier-2
63
+ // budget with real headroom at the worst case (all three array-bearing
64
+ // task_create deviations firing at once, each at its schema/backend
65
+ // maximum): measured via tests/receipt.test.ts's maxima test at each
66
+ // candidate value. 20 chars already regresses to 1551 (over budget), 19
67
+ // measures 1541 (comfortable margin below both the test's 1550 floor and
68
+ // the 1600 cap itself). 19 also happens to be exactly long enough that the
69
+ // backend's longest `missing[]` field name ("acceptanceCriteria", 19
70
+ // chars) never truncates; the 36-char dependsOn UUIDs still do truncate
71
+ // under this bound, since there is no room left for a higher,
72
+ // ID-preserving value once labels are at their real maximum. This is an
73
+ // accepted, visible (ends in "...") consequence of one shared per-entry
74
+ // bound applying uniformly to every future detector, not a special case
75
+ // per field.
76
+ export const ENTRY_CHAR_BUDGET = 19;
77
+ // Visible truncation marker: a shortened entry must not look complete, so
78
+ // the caller can tell at the string level (not just via the totalX count)
79
+ // that this particular entry was cut.
80
+ export const ENTRY_TRUNCATION_MARKER = "...";
81
+ /**
82
+ * Byte-bounds a detail array by construction: caps the element COUNT (as
83
+ * DETAIL_CLAMP alone already did) AND caps each surviving entry's own
84
+ * length, so a future detector cannot blow the tier-2 budget just by
85
+ * carrying long strings inside an already-short array. Truncation is never
86
+ * silent: a shortened entry visibly ends with ENTRY_TRUNCATION_MARKER, and
87
+ * the deviation's own totalX field already reports the untruncated
88
+ * cardinality.
89
+ *
90
+ * Exported for reuse by read.ts (rc-v1-C006): tasks_get's summary
91
+ * projection and the block-tier's client-side project-addressing errors
92
+ * clamp their own arrays the same way, at their own (different) budgets, by
93
+ * calling this shared helper rather than re-implementing the clamp+marker
94
+ * logic a second time.
95
+ */
96
+ export function clampEntries(values, opts = {}) {
97
+ const max = opts.max ?? DETAIL_CLAMP;
98
+ const entryChars = opts.entryChars ?? ENTRY_CHAR_BUDGET;
99
+ return values.slice(0, max).map((v) => v.length > entryChars
100
+ ? v.slice(0, entryChars - ENTRY_TRUNCATION_MARKER.length) + ENTRY_TRUNCATION_MARKER
101
+ : v);
102
+ }
103
+ // ── task_create / task_respec: confidence deviation ─────────────────────────
104
+ //
105
+ // Trigger per the contract's create catalog: "confidence score is below the
106
+ // project's threshold" — this is `score < threshold`, deliberately NOT the
107
+ // backend's own `blocking` flag (backend/src/lib/confidence.ts: `blocking`
108
+ // is narrower, "a hard, threshold-INDEPENDENT keystone is violated"; using
109
+ // it here would under-report the contract's stated trigger).
110
+ function confidenceDeviation(c) {
111
+ if (!c || c.score >= c.threshold)
112
+ return null;
113
+ const missing = c.missing ?? [];
114
+ return {
115
+ code: "CONFIDENCE_BELOW_THRESHOLD",
116
+ detail: {
117
+ score: c.score,
118
+ threshold: c.threshold,
119
+ enforcementMode: c.enforcementMode,
120
+ // Clamped like DEPENDS_ON_REJECTED/LABELS_DROPPED below: the backend
121
+ // scorer (backend/src/lib/confidence.ts) can populate up to 9 entries
122
+ // (title, description, goal, acceptanceCriteria, scope, outOfScope,
123
+ // dependencies, risk, agentPrompt), already in surfacing-priority
124
+ // order, so the clamp keeps the entries that matter most.
125
+ missing: clampEntries(missing, { max: DETAIL_CLAMP, entryChars: ENTRY_CHAR_BUDGET }),
126
+ totalMissing: missing.length,
127
+ },
128
+ // Kept short on purpose: at the missing[]/dependsOn/labels maxima, all
129
+ // four task_create deviations firing together leaves little headroom
130
+ // under the tier-2 cap (see the "clamps ... at the schemas' and
131
+ // backend's declared maxima" test in tests/receipt.test.ts).
132
+ actNow: c.enforcementMode === "BLOCK"
133
+ ? "Description/templateData not editable after create except via task_respec; at BLOCK, task_pickup/task_start rejects until the score improves."
134
+ : "Description/templateData not editable after create except via task_respec; not BLOCK, so advisory only for now.",
135
+ next: ["task_respec to raise the score above the threshold"],
136
+ };
137
+ }
138
+ // ── task_create: DEDUPED_EXTERNAL_REF ────────────────────────────────────────
139
+ //
140
+ // KNOWN GAP (see the implementer's summary / open_questions): the live
141
+ // backend (backend/src/routes/tasks.ts, POST /projects/:projectId/tasks)
142
+ // rejects a duplicate (projectId, externalRef) with an HTTP 409 P2002
143
+ // conflict BEFORE a task is created — it never returns 200 with the
144
+ // existing task, so this deviation cannot fire against the current backend.
145
+ // It is implemented here for contract-shape completeness (and is exercised
146
+ // in tests against a constructed 200 response) so it activates the moment
147
+ // the backend gains a soft dedupe-return, without another mcp-server change.
148
+ //
149
+ // Detection heuristic (the backend provides no explicit dedupe flag on a
150
+ // hypothetical 200 response): createdAt !== updatedAt. This is imperfect —
151
+ // an existing task that was never touched after its own creation would
152
+ // coincidentally have createdAt === updatedAt and be missed — but it is the
153
+ // best signal available without a backend change, per the task brief's
154
+ // explicit fallback ("createdAt != updatedAt or a backend flag").
155
+ //
156
+ // Scope gate: the contract's trigger for this deviation is "(projectId,
157
+ // externalRef) already exists", the dedupe is keyed on externalRef, so a
158
+ // create call that sent no externalRef at all cannot have hit that path,
159
+ // regardless of what the createdAt/updatedAt heuristic says. Callers that
160
+ // omit externalRef must never see this code.
161
+ function dedupedExternalRefDeviation(task, externalRef) {
162
+ if (!externalRef)
163
+ return null;
164
+ if (!task.createdAt || !task.updatedAt)
165
+ return null;
166
+ if (task.createdAt === task.updatedAt)
167
+ return null;
168
+ return {
169
+ code: "DEDUPED_EXTERNAL_REF",
170
+ detail: { existingTaskId: task.id, existingStatus: task.status },
171
+ next: ["tasks_get"],
172
+ };
173
+ }
174
+ // Both DEPENDS_ON_REJECTED and LABELS_DROPPED echo a slice of the caller's
175
+ // own input back in `detail`. Both schema fields have generous array
176
+ // maxima (dependsOn 50, labels 20; see tools.ts's task_create inputShape),
177
+ // and at those maxima an unclamped detail array alone blows past the
178
+ // tier-2 budget several times over. They reuse DETAIL_CLAMP (defined above,
179
+ // next to ConfidenceObj) for the same reason CONFIDENCE_BELOW_THRESHOLD's
180
+ // `missing[]` does.
181
+ // ── task_create: DEPENDS_ON_REJECTED ─────────────────────────────────────────
182
+ //
183
+ // KNOWN GAP: the live backend validates `dependsOn` before insert and 400s
184
+ // the WHOLE create request if any id is missing/cross-project (tasks.ts
185
+ // ~lines 795-813) rather than creating the task with the valid subset and
186
+ // reporting the rejected ids as a deviation. On today's backend this
187
+ // comparison can only ever find zero missing ids on a successful create
188
+ // (all-or-nothing), so this detector is inert in production until/unless
189
+ // the backend adopts a soft-accept model. Implemented + tested against a
190
+ // constructed response for contract-shape completeness (see above).
191
+ function dependsOnRejectedDeviation(sentDependsOn, blockedBy) {
192
+ if (!sentDependsOn || sentDependsOn.length === 0)
193
+ return null;
194
+ const present = new Set((blockedBy ?? []).map((b) => b.id));
195
+ const rejectedIds = sentDependsOn.filter((id) => !present.has(id));
196
+ if (rejectedIds.length === 0)
197
+ return null;
198
+ return {
199
+ code: "DEPENDS_ON_REJECTED",
200
+ detail: {
201
+ // Every rejected id shares the same reason today (the backend gives
202
+ // no per-id detail), so the reason is hoisted out of the array
203
+ // instead of repeated per entry: that repetition was itself most
204
+ // of the bloat this clamp fixes.
205
+ rejected: clampEntries(rejectedIds, { max: DETAIL_CLAMP, entryChars: ENTRY_CHAR_BUDGET }),
206
+ reason: "not found or cross-project",
207
+ totalRejected: rejectedIds.length,
208
+ },
209
+ next: ["task_create again with corrected dependsOn"],
210
+ };
211
+ }
212
+ // ── task_create: LABELS_DROPPED ──────────────────────────────────────────────
213
+ //
214
+ // KNOWN GAP: the live backend stores `labels` verbatim (trimmed by zod, but
215
+ // not deduped/normalized/soft-rejected) — see createTaskSchema in
216
+ // backend/src/routes/tasks.ts. No label is ever silently dropped today, so
217
+ // this detector is inert in production until/unless the backend adopts
218
+ // normalization or a per-label rejection policy. Implemented + tested
219
+ // against a constructed response for contract-shape completeness.
220
+ function labelsDroppedDeviation(sentLabels, responseLabels) {
221
+ if (!sentLabels || sentLabels.length === 0)
222
+ return null;
223
+ const present = new Set(responseLabels ?? []);
224
+ const dropped = sentLabels.filter((l) => !present.has(l));
225
+ if (dropped.length === 0)
226
+ return null;
227
+ return {
228
+ code: "LABELS_DROPPED",
229
+ detail: {
230
+ dropped: clampEntries(dropped, { max: DETAIL_CLAMP, entryChars: ENTRY_CHAR_BUDGET }),
231
+ totalDropped: dropped.length,
232
+ },
233
+ next: ["task_create again (agents cannot set labels post-create)"],
234
+ };
235
+ }
236
+ // ── Per-verb receipt builders ────────────────────────────────────────────────
237
+ //
238
+ // Defensive guard shared by every builder below: each one is fed a `response`
239
+ // that arrived through an `as` cast in tools.ts (the real runtime shape is
240
+ // only as trustworthy as the backend's success body). Dereferencing
241
+ // `response.task.id` without checking first throws a raw, unhelpful
242
+ // TypeError on a malformed body. Every builder therefore checks
243
+ // `response?.task?.id` up front and, when it's missing, returns the raw
244
+ // response unprojected instead of crashing: the caller still gets
245
+ // something machine-usable, just not the small receipt. This is a
246
+ // deliberate, documented exemption from the contract's "no echo, ever"
247
+ // rule (docs/response-contract-v1.md): a malformed success body falls
248
+ // outside the receipt/tier machinery entirely, so returning it raw is not
249
+ // an echo of caller-sent content, it's the only fallback that avoids
250
+ // crashing on an unexpected backend shape.
251
+ function hasTaskId(response) {
252
+ return !!response?.task?.id;
253
+ }
254
+ export function receiptForCreate(response, input) {
255
+ if (!hasTaskId(response))
256
+ return response;
257
+ const deviations = [];
258
+ const confDev = confidenceDeviation(response.confidence);
259
+ if (confDev)
260
+ deviations.push(confDev);
261
+ const dedupeDev = dedupedExternalRefDeviation(response.task, input.externalRef);
262
+ if (dedupeDev)
263
+ deviations.push(dedupeDev);
264
+ const dependsOnDev = dependsOnRejectedDeviation(input.dependsOn, response.task.blockedBy);
265
+ if (dependsOnDev)
266
+ deviations.push(dependsOnDev);
267
+ const labelsDev = labelsDroppedDeviation(input.labels, response.task.labels);
268
+ if (labelsDev)
269
+ deviations.push(labelsDev);
270
+ // v1 backlog routing (backend/src/routes/tasks.ts): every agent-created
271
+ // task lands in `backlog`, not `open` -- "task_start to begin work on
272
+ // this task" would be actively wrong advice here (task_start 403s with
273
+ // backlog_not_promoted until an operator promotes it), so a backlog task
274
+ // gets its own next hint instead, regardless of whether any deviation
275
+ // also fired.
276
+ const next = response.task.status === "backlog"
277
+ ? ["awaits operator promotion; task_start rejects a backlog task until an operator promotes it to open"]
278
+ : deviations.length === 0
279
+ ? ["task_start to begin work on this task"]
280
+ : undefined;
281
+ return buildReceipt({
282
+ taskId: response.task.id,
283
+ status: response.task.status,
284
+ confidence: response.confidence?.score,
285
+ deviations,
286
+ next,
287
+ });
288
+ }
289
+ export function receiptForRespec(response) {
290
+ if (!hasTaskId(response))
291
+ return response;
292
+ const deviations = [];
293
+ const confDev = confidenceDeviation(response.confidence);
294
+ if (confDev)
295
+ deviations.push(confDev);
296
+ return buildReceipt({
297
+ taskId: response.task.id,
298
+ status: response.task.status,
299
+ confidence: response.confidence?.score,
300
+ deviations,
301
+ });
302
+ }
303
+ // task_finish: `transition.from` would require either an extra pre-fetch
304
+ // (defeats the whole point of the receipt) or hardcoding a "from" state that
305
+ // varies per custom workflow (finish resolves its pre/post states via
306
+ // resolveEffectiveDefinition, not literal status strings) — so it is
307
+ // deliberately omitted here; `task.status` alone reports the outcome. The
308
+ // one deviation this verb DOES carry is grounded in a real backend field:
309
+ // `skippedGates`, populated when autoMerge skips the normally-required
310
+ // `prMerged` precondition (tasks.ts work/review/self-approve branches all
311
+ // echo it back verbatim when non-empty).
312
+ export function receiptForFinish(response) {
313
+ if (!hasTaskId(response))
314
+ return response;
315
+ const deviations = [];
316
+ if (response.skippedGates && response.skippedGates.length > 0) {
317
+ deviations.push({
318
+ code: "WORKFLOW_GATE_SKIPPED",
319
+ detail: {
320
+ // Clamped like every other deviation's array-valued detail field
321
+ // (see DETAIL_CLAMP above), even though the fixed set of workflow
322
+ // gates (branchPresent, prPresent, ciGreen, prMerged) means this
323
+ // can never actually reach 5 entries today. The point is that the
324
+ // clamping rule holds unconditionally, not just where it currently
325
+ // bites.
326
+ skipped: clampEntries(response.skippedGates, { max: DETAIL_CLAMP, entryChars: ENTRY_CHAR_BUDGET }),
327
+ totalSkipped: response.skippedGates.length,
328
+ },
329
+ actNow: `autoMerge bypassed the normally-required workflow gate(s) before this transition: ${response.skippedGates.join(", ")}.`,
330
+ });
331
+ }
332
+ return buildReceipt({
333
+ taskId: response.task.id,
334
+ status: response.task.status,
335
+ deviations,
336
+ });
337
+ }
338
+ // task_submit_pr: the contract's "Known catalogs to fill in" table lists
339
+ // "unmet workflow gates" for this verb, but the live backend performs NO
340
+ // gate evaluation at submit-pr time (see the block comment directly above
341
+ // the route in backend/src/routes/tasks.ts: "No gate evaluation — that
342
+ // happens on the next task_finish call") — there is no backend signal to
343
+ // detect it from without either an extra `projects_get_effective_gates`
344
+ // round trip (defeats the budget goal) or duplicating the backend's gate
345
+ // engine client-side (out of scope). No deviation catalog is implemented
346
+ // for this verb; see open_questions in the implementer's report.
347
+ export function receiptForSubmitPr(response) {
348
+ if (!hasTaskId(response))
349
+ return response;
350
+ return buildReceipt({
351
+ taskId: response.task.id,
352
+ status: response.task.status,
353
+ next: ["task_finish once CI is green"],
354
+ });
355
+ }
356
+ // task_merge: no `transition` field. The route admits both `review` and an
357
+ // idempotent `done` retry as valid starting states (tasks.ts ~lines
358
+ // 3697-3700), and `alreadyMerged` describes the GitHub PR's own merge
359
+ // state (github-merge.ts ~lines 158-161), not whether a DB transition
360
+ // happened on THIS call: a PR merged out-of-band via the GitHub UI can
361
+ // leave the task at `review`, and a subsequent task_merge call both gets
362
+ // `alreadyMerged: true` from GitHub AND performs a real review→done
363
+ // transition in the DB. Keying `transition` off `alreadyMerged` would
364
+ // therefore report a fabricated transition in that case (and a missing one
365
+ // on the true idempotent retry, where it happens to be correct by
366
+ // coincidence). `task.status` alone reports the outcome; it needs no
367
+ // inference.
368
+ export function receiptForMerge(response) {
369
+ if (!hasTaskId(response))
370
+ return response;
371
+ return buildReceipt({
372
+ taskId: response.task.id,
373
+ status: response.task.status,
374
+ });
375
+ }
376
+ export function receiptForAbandon(response) {
377
+ if (!hasTaskId(response))
378
+ return response;
379
+ return buildReceipt({
380
+ taskId: response.task.id,
381
+ status: response.task.status,
382
+ });
383
+ }
384
+ // task_note / tasks_comment: the backend's POST /tasks/:id/comments returns
385
+ // only `{comment}` — there is no `task` object and no `status` field on the
386
+ // comment row, so `task.status` is genuinely unknown without an extra GET
387
+ // (which would double the round trip for the cheapest verb in the surface).
388
+ // The receipt therefore carries `task.id` only, sourced from the response's
389
+ // `comment.taskId` when present (falling back to the caller's own taskId,
390
+ // which is safe to surface: the no-echo rule throughout this module targets
391
+ // CONTENT the caller sent (description, templateData, comment body, and
392
+ // so on), not correlation ids. Every other receipt in this module already
393
+ // carries `task.id` unconditionally).
394
+ export function receiptForNote(taskId, response) {
395
+ return buildReceipt({ taskId: response.comment?.taskId ?? taskId });
396
+ }
397
+ function deriveInferredTaskType(task) {
398
+ const taskType = task.templateData?.taskType;
399
+ return typeof taskType === "string" && taskType.length > 0 ? taskType : undefined;
400
+ }
401
+ /**
402
+ * Resolves the `requires` gate list for task.status -> expectedFinishState
403
+ * WITHOUT the backend's rc-v1-B001 `effectiveGates` field. Called only by
404
+ * resolveGateExpectations below, and only when `response.effectiveGates` is
405
+ * absent (a pre-B001 backend); on any backend that sends it,
406
+ * `effectiveGates` is authoritative (it is resolved server-side from the
407
+ * exact same effectiveDefinition this function can only approximate
408
+ * client-side) and this function is never consulted. Kept for that
409
+ * version-tolerance case only; its own KNOWN GAPs below are pre-existing
410
+ * and unrelated to that gating.
411
+ *
412
+ * Dynamic path: when the raw response embeds `task.workflow.definition`
413
+ * (today: both sub-paths of the review-claim branch of POST
414
+ * /tasks/:id/start — see the KNOWN GAP on StartTask.workflow above), it is
415
+ * authoritative for this project and takes priority.
416
+ *
417
+ * Static fallback: `task.workflowId === null` does NOT prove the task runs
418
+ * the built-in default workflow. Per the backend's resolveEffectiveDefinition
419
+ * chain (backend/src/services/default-workflow.ts, ADR-0008 §50-56):
420
+ * 1. task.workflowId set -> that Workflow row's definition (the dynamic
421
+ * path above, when embedded).
422
+ * 2. a project-default Workflow row (isDefault: true, looked up by
423
+ * projectId) -> a CUSTOMIZED workflow that a project admin created via
424
+ * POST /projects/:projectId/workflow/customize. Tasks governed by this
425
+ * row still carry `workflowId === null`, and its gate structure can
426
+ * differ from the built-in table below.
427
+ * 3. the built-in defaultWorkflowDefinition() -> what DEFAULT_WORKFLOW_
428
+ * TRANSITIONS mirrors.
429
+ * `workflowId === null` is therefore consistent with EITHER step 2 or step
430
+ * 3, and this function cannot distinguish them without the embedded
431
+ * definition. Falling back to the built-in table is an assumption, not a
432
+ * guarantee, so the result carries `source: "assumed-default-workflow"`
433
+ * whenever it fires, so the caller can tell the gate list is unconfirmed.
434
+ *
435
+ * A non-null `workflowId` without an embedded `workflow` relation means a
436
+ * CUSTOM workflow governs this task but its definition was not sent —
437
+ * guessing its gates from the default table would be actively wrong, so
438
+ * gates is omitted (no source marker either) rather than guessed in that
439
+ * case.
440
+ */
441
+ function deriveGateExpectations(task, expectedFinishState) {
442
+ if (!expectedFinishState || !task.status)
443
+ return {};
444
+ const dynamicTransitions = task.workflow?.definition?.transitions;
445
+ if (dynamicTransitions) {
446
+ const match = dynamicTransitions.find((t) => t.from === task.status && t.to === expectedFinishState);
447
+ const gates = match?.requires && match.requires.length > 0 ? match.requires : undefined;
448
+ return gates ? { gates } : {};
449
+ }
450
+ if (task.workflowId)
451
+ return {}; // custom workflow, definition not sent: do not guess
452
+ const fallback = DEFAULT_WORKFLOW_TRANSITIONS[task.status]?.find((t) => t.to === expectedFinishState);
453
+ const gates = fallback?.requires && fallback.requires.length > 0 ? fallback.requires : undefined;
454
+ return gates ? { gates, source: "assumed-default-workflow" } : {};
455
+ }
456
+ /**
457
+ * Maps a raw backend gate list (`string[] | null`) to StartSlice's
458
+ * convention: `null` (the edge is absent) passes through unchanged, exactly
459
+ * the value that must stay distinguishable from "no requires" per
460
+ * rc-v1-B001's contract (see StartEffectiveGates); a non-empty array
461
+ * passes through unchanged, and an empty array (edge exists, nothing
462
+ * required) collapses to `undefined` so the happy, nothing-to-report case
463
+ * costs no bytes in the receipt (report-by-exception, same rationale the
464
+ * pre-existing fallback logic already applied to its own gate lists).
465
+ */
466
+ function projectGateList(gates) {
467
+ if (gates === undefined || gates === null)
468
+ return gates;
469
+ return gates.length > 0 ? gates : undefined;
470
+ }
471
+ /**
472
+ * Resolves task_start's three gate-expectation slice fields
473
+ * (gateExpectations, gateExpectationsSource, requestChangesGateExpectations)
474
+ * from the raw response. Two paths:
475
+ *
476
+ * Authoritative (rc-v1-B001+): `response.effectiveGates.finish` is
477
+ * present (checked as `!== undefined`, not truthiness of the parent
478
+ * `effectiveGates` object, since `finish` is the field this layer
479
+ * actually consumes and can legitimately BE `null`, `[]`, or a non-empty
480
+ * array while still being "present"; a malformed/partial backend body
481
+ * that sends `effectiveGates: {}` with no `finish` key at all must fall
482
+ * through to the client-side fallback below instead of silently
483
+ * resolving to "nothing required" with no provenance marker). `finish`
484
+ * (and, on a review claim, `requestChanges`) are passed through
485
+ * projectGateList as-is, with no gateExpectationsSource, since the
486
+ * backend's own value needs no "assumed" caveat.
487
+ *
488
+ * Fallback (pre-B001 backends, or a present-but-partial `effectiveGates`
489
+ * missing its own `finish` key): deriveGateExpectations' existing
490
+ * dynamic-then-static resolution runs unchanged for `finish`. There is no
491
+ * fallback for `requestChanges` at all (the pre-B001 code never computed
492
+ * it), so it is always omitted on this path.
493
+ */
494
+ function resolveGateExpectations(response) {
495
+ if (response.effectiveGates?.finish !== undefined) {
496
+ return {
497
+ finish: projectGateList(response.effectiveGates.finish),
498
+ requestChanges: projectGateList(response.effectiveGates.requestChanges),
499
+ };
500
+ }
501
+ const { gates, source } = deriveGateExpectations(response.task, response.expectedFinishState);
502
+ return { finish: gates, finishSource: source };
503
+ }
504
+ /**
505
+ * Same dynamic-then-static resolution as deriveGateExpectations, for the
506
+ * per-state instructions prose instead of the per-edge gate list — and the
507
+ * SAME provenance rule. An embedded `workflow.definition.states` entry is
508
+ * authoritative and carries no marker. A set `task.workflowId` without an
509
+ * embedded definition means a task-level custom workflow whose prose we do
510
+ * not have: omitted outright, never guessed (wrong instructions read as
511
+ * authoritative are actively harmful — they can tell an agent to do the
512
+ * wrong thing next). A `null` `workflowId` does NOT prove the built-in
513
+ * default (a project-default customized Workflow row can apply, see
514
+ * deriveGateExpectations' KNOWN GAP), so the static built-in prose is
515
+ * surfaced WITH `instructionsSource: "assumed-default-workflow"` — correct
516
+ * for the common built-in case, honestly labeled for the customized one.
517
+ * Recovery path when instructions are omitted: the `tasks_instructions`
518
+ * verb (GET /tasks/:id/instructions) — NOT include:["task"], because the
519
+ * work-claim raw response never embeds the workflow relation either.
520
+ */
521
+ function deriveStartInstructions(task) {
522
+ const dynamicState = task.workflow?.definition?.states?.find((s) => s.name === task.status);
523
+ if (dynamicState?.agentInstructions)
524
+ return { text: dynamicState.agentInstructions };
525
+ if (task.workflowId)
526
+ return {}; // custom workflow, definition not sent: do not guess wrong prose
527
+ if (!task.status)
528
+ return {};
529
+ const text = DEFAULT_WORKFLOW_AGENT_INSTRUCTIONS[task.status];
530
+ return text ? { text, source: "assumed-default-workflow" } : {};
531
+ }
532
+ /**
533
+ * Compacts a debugFlavor groundingHint down to its actionable part: the
534
+ * callable recipe (`mcpToolHint`) alone. `backendSessionRef` is deliberately
535
+ * dropped from this string entirely, not merely de-prioritized: per
536
+ * GroundingHint's own doc comment in backend/src/lib/debug-flavor.ts, that
537
+ * field is named "backendSessionRef" (not "sessionId") specifically because
538
+ * it is NOT usable as a grounding-mcp sessionId — appending it into the
539
+ * actionable `next[]` string would present a value the caller cannot
540
+ * actually pass to any grounding-mcp tool as if it were one. `mcpToolHint`
541
+ * already carries a self-sufficient recipe on its own. `backendSessionRef`
542
+ * remains reachable via include:["task"] for forensic/debugging purposes;
543
+ * it just does not belong in the actionable hint. Also deliberately drops
544
+ * `recommendedAction` (a restated sentence, not an action), `currentPhase`,
545
+ * `mandatorySequence`, and `activeGuardrails` (verbose, not actionable for
546
+ * THIS call) — the full hint remains reachable via include:["task"]. This is
547
+ * also where `metadata.groundingSessionState` (the large persisted session
548
+ * blob) is kept OUT of the default response: this function never reads
549
+ * `metadata` at all, only the already-compact `groundingHint` field.
550
+ */
551
+ function deriveGroundingNext(hint) {
552
+ if (!hint)
553
+ return undefined;
554
+ return [hint.mcpToolHint];
555
+ }
556
+ export function receiptForStart(response, include) {
557
+ // Compatibility valve: bypasses the tier machinery entirely, same as
558
+ // projectPickup's own include:["task"] check for task_pickup. Checked
559
+ // first, unconditionally, regardless of whether `response` even carries
560
+ // a task.id — the caller asked for the raw object back.
561
+ if (include?.includes("task"))
562
+ return response;
563
+ if (!hasTaskId(response))
564
+ return response;
565
+ const slice = {
566
+ ok: true,
567
+ task: response.task.status !== undefined
568
+ ? { id: response.task.id, status: response.task.status }
569
+ : { id: response.task.id },
570
+ };
571
+ // Same "only on a state change" rule as the general Receipt.transition
572
+ // field (docs/response-contract-v1.md): a review-claim's previousStatus
573
+ // equals its (unchanged) task.status, so no transition is reported there.
574
+ // Absent entirely against a pre-rc-v1-B001 backend (previousStatus
575
+ // undefined), no guess is made.
576
+ if (response.previousStatus !== undefined &&
577
+ response.task.status !== undefined &&
578
+ response.previousStatus !== response.task.status) {
579
+ slice.transition = { from: response.previousStatus, to: response.task.status };
580
+ }
581
+ if (response.confidence?.score !== undefined)
582
+ slice.confidence = response.confidence.score;
583
+ const inferredTaskType = deriveInferredTaskType(response.task);
584
+ if (inferredTaskType)
585
+ slice.inferredTaskType = inferredTaskType;
586
+ if (response.expectedFinishState)
587
+ slice.expectedFinishState = response.expectedFinishState;
588
+ const { finish: gateExpectations, finishSource: gateExpectationsSource, requestChanges: requestChangesGateExpectations, } = resolveGateExpectations(response);
589
+ if (gateExpectations !== undefined)
590
+ slice.gateExpectations = gateExpectations;
591
+ if (gateExpectationsSource)
592
+ slice.gateExpectationsSource = gateExpectationsSource;
593
+ if (requestChangesGateExpectations !== undefined) {
594
+ slice.requestChangesGateExpectations = requestChangesGateExpectations;
595
+ }
596
+ const next = deriveGroundingNext(response.groundingHint);
597
+ if (next)
598
+ slice.next = next;
599
+ if (include?.includes("description") && response.task.description) {
600
+ slice.description = response.task.description;
601
+ }
602
+ if (include?.includes("comments") && response.task.comments) {
603
+ slice.comments = response.task.comments;
604
+ }
605
+ if (include?.includes("instructions")) {
606
+ const { text: instructions, source: instructionsSource } = deriveStartInstructions(response.task);
607
+ if (instructions)
608
+ slice.instructions = instructions;
609
+ if (instructionsSource)
610
+ slice.instructionsSource = instructionsSource;
611
+ }
612
+ return slice;
613
+ }
614
+ export function projectPickup(response, include) {
615
+ if (include?.includes("task") || include?.includes("comments"))
616
+ return response;
617
+ if (!response.task || !("comments" in response.task))
618
+ return response;
619
+ const { comments: _comments, ...taskWithoutComments } = response.task;
620
+ return { ...response, task: taskWithoutComments };
621
+ }
622
+ //# sourceMappingURL=receipt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"receipt.js","sourceRoot":"","sources":["../src/receip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