@deliverd/sdk 0.11.1 → 0.12.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/src/dev.ts CHANGED
@@ -1,868 +1,1274 @@
1
- import type {
2
- ApprovalData,
3
- CollectionData,
4
- EvidencePack,
5
- FlowData,
6
- GateData,
7
- ReviewData,
8
- } from "./types.js";
9
-
10
- /**
11
- * Development mode: the whole loop, on your machine, with nobody in it.
12
- *
13
- * ```ts
14
- * const deliverd = new Deliverd({ mode: "development" });
15
- * const decision = await deliverd.approve({ title: "Deploy production" });
16
- * ```
17
- *
18
- * No key, no network, no colleague to interrupt — and the four things that
19
- * can happen to a real request all reachable before you have an account:
20
- * approved, rejected, nobody answered, and somebody asked you a question.
21
- * That last one is the path people forget to write, which is exactly why it
22
- * should be one line to try.
23
- *
24
- * Implemented as a stand-in `fetch` rather than a branch inside the client,
25
- * so development mode runs the *same* code as production — the same retries,
26
- * the same error mapping, the same polling in `wait()`. A simulator that
27
- * bypassed all that would prove your integration works against the simulator.
28
- */
29
-
30
- /**
31
- * What development mode makes happen.
32
- *
33
- * Four for the primitives that ask a person, and a fifth for the gate:
34
- * `denied` is a **policy** refusal, which nothing else can have — an approval
35
- * cannot be refused without somebody refusing it. It is the outcome an agent
36
- * must handle by not retrying, and rehearsing that offline is worth a word of
37
- * its own. The four that involve a person mean the same thing everywhere;
38
- * `denied` on an approval is treated as `rejected`, because a request nobody
39
- * was asked about is not a thing that surface can represent.
40
- */
41
- export type DevelopmentOutcome = "approved" | "rejected" | "denied" | "timeout" | "question";
42
-
43
- export interface DevelopmentOptions {
44
- /**
45
- * What the imaginary approver does. Default `approved`, or the value of
46
- * `DELIVERD_DEV_OUTCOME`, so a whole test suite can be flipped from the
47
- * command line without touching the code.
48
- */
49
- outcome?: DevelopmentOutcome | ((request: ApprovalData) => DevelopmentOutcome);
50
- /** How long they take to do it, in milliseconds. Default 0. */
51
- delay?: number;
52
- /** What they say. Defaults suit the outcome. */
53
- note?: string;
54
- /**
55
- * Corrections the imaginary approver makes when approving a request that
56
- * sent an `input`, so the approve-with-changes path can be run offline.
57
- * Only fields you named in `editableFields` are applied, as in production.
58
- */
59
- edits?: Record<string, unknown>;
60
- /** What they ask, when the outcome is `question`. */
61
- question?: string;
62
- /** Print what the approver would have seen. Default true. */
63
- log?: boolean;
64
- }
65
-
66
- const DEFAULT_QUESTION = "Has this been through staging?";
67
-
68
- let counter = 0;
69
-
70
- interface Stored {
71
- data: ApprovalData;
72
- /** When the imaginary approver acts. */
73
- decideAt: number;
74
- outcome: DevelopmentOutcome;
75
- options: DevelopmentOptions;
76
- }
77
-
78
- /**
79
- * A `fetch` that serves the approvals, reviews and collections APIs from memory.
80
- *
81
- * Deliberately narrow: it answers the calls the primitives make and 501s the
82
- * rest, with a message saying so, rather than pretending to be the whole API
83
- * and quietly returning something plausible.
84
- */
85
- export function developmentFetch(options: DevelopmentOptions = {}): typeof globalThis.fetch {
86
- const store = new Map<string, Stored>();
87
- const reviewStore = new Map<string, StoredReview>();
88
- const gateStore = new Map<string, StoredGate>();
89
- const collectionStore = new Map<string, StoredCollection>();
90
- const flowStore = new Map<string, FlowData>();
91
-
92
- return (async (input: string | URL | Request, init?: RequestInit) => {
93
- const url = new URL(String(input));
94
- const path = url.pathname.replace(/^\/api\/v1/, "");
95
- const method = (init?.method ?? "GET").toUpperCase();
96
- const body = init?.body ? (JSON.parse(String(init.body)) as Record<string, unknown>) : {};
97
-
98
- const json = (payload: unknown, status = 200) =>
99
- new Response(JSON.stringify(payload), {
100
- status,
101
- headers: { "content-type": "application/json" },
102
- });
103
-
104
- if (method === "POST" && path === "/approvals") {
105
- const id = `apr_dev_${++counter}`;
106
- const outcome = resolveOutcome(options.outcome, body);
107
- const data: ApprovalData = {
108
- id,
109
- status: "pending",
110
- url: `https://deliverd.dev/approve/${id}`,
111
- title: String(body.title ?? "Untitled"),
112
- description: (body.description as string | undefined) ?? null,
113
- risk: (body.risk as ApprovalData["risk"] | undefined) ?? "medium",
114
- factors: (body.factors as ApprovalData["factors"]) ?? [],
115
- links: (body.links as ApprovalData["links"]) ?? [],
116
- reportId: (body.reportId as string | undefined) ?? null,
117
- externalId: (body.externalId as string | undefined) ?? null,
118
- metadata: (body.metadata as Record<string, unknown>) ?? {},
119
- input: (body.input as Record<string, unknown> | undefined) ?? null,
120
- editableFields: (body.editableFields as string[] | undefined) ?? [],
121
- approvedInput: null,
122
- changes: [],
123
- concerns: [],
124
- requestedBy: "You (development mode)",
125
- approvers: (body.approvers as string[] | undefined) ?? [],
126
- /*
127
- * One, always. A standing rule could raise it on a real organisation,
128
- * but development mode has no rules to read and an imaginary approver
129
- * cannot be two people — pretending otherwise would let a caller test
130
- * an escalation that never happened.
131
- */
132
- requiredApprovals: 1,
133
- approvalsSoFar: 0,
134
- decidedBy: null,
135
- decidedById: null,
136
- decidedAt: null,
137
- note: null,
138
- expiresAt: (body.expiresAt as string | undefined) ?? null,
139
- questions:
140
- outcome === "question"
141
- ? [
142
- {
143
- id: `q_dev_${counter}`,
144
- question: options.question ?? DEFAULT_QUESTION,
145
- answer: null,
146
- askedAt: new Date().toISOString(),
147
- answeredAt: null,
148
- },
149
- ]
150
- : [],
151
- createdAt: new Date().toISOString(),
152
- };
153
- store.set(id, {
154
- data,
155
- decideAt: Date.now() + (options.delay ?? 0),
156
- outcome,
157
- options,
158
- });
159
- if (options.log !== false) announce(data, outcome);
160
- return json(data, 201);
161
- }
162
-
163
- const match = /^\/approvals\/([^/]+)(\/answers|\/cancel)?$/.exec(path);
164
- if (match) {
165
- const stored = store.get(match[1]!);
166
- if (!stored) {
167
- return json({ error: { code: "not_found", message: "No such approval in this development session." } }, 404);
168
- }
169
- if (match[2] === "/answers") {
170
- const question = stored.data.questions.find((q) => q.id === body.questionId);
171
- if (!question) {
172
- return json({ error: { code: "question_not_found", message: "No such question." } }, 404);
173
- }
174
- question.answer = String(body.answer);
175
- question.answeredAt = new Date().toISOString();
176
- // Answered: the imaginary approver is satisfied and approves.
177
- stored.outcome = "approved";
178
- stored.decideAt = Date.now() + (stored.options.delay ?? 0);
179
- if (stored.options.log !== false) {
180
- console.log(` ↳ answered: ${question.answer}\n`);
181
- }
182
- return json(stored.data);
183
- }
184
- if (match[2] === "/cancel") {
185
- stored.data.status = "cancelled";
186
- return json(stored.data);
187
- }
188
- settle(stored);
189
- return json(stored.data);
190
- }
191
-
192
- if (method === "POST" && path === "/reviews") {
193
- const id = `rev_dev_${++counter}`;
194
- /*
195
- * The same outcome switch as approvals, mapped onto a review's endings:
196
- * a rejection is "changes requested", because that is what saying no to
197
- * a piece of work means. A simulated question has nothing to ask about
198
- * here — there is no question mechanism on a review — so it approves.
199
- */
200
- const outcome = resolveOutcome(options.outcome, body);
201
- const verdict = outcome === "rejected" ? "changes_requested" : "approved";
202
- const reviewers = ((body.reviewers as string[] | undefined) ?? []).map((email, i) => ({
203
- kind: "user" as const,
204
- id: `usr_dev_${i + 1}`,
205
- label: email,
206
- }));
207
- const data: ReviewData = {
208
- id,
209
- status: "pending",
210
- url: `https://deliverd.dev/reviews/${id}`,
211
- title: String(body.title ?? "Untitled"),
212
- instructions: (body.instructions as string | undefined) ?? null,
213
- reportId: (body.reportId as string | undefined) ?? null,
214
- versionId: (body.versionId as string | undefined) ?? null,
215
- externalId: (body.externalId as string | undefined) ?? null,
216
- metadata: (body.metadata as Record<string, unknown>) ?? {},
217
- requestedBy: "You (development mode)",
218
- requiredApprovals: (body.requiredApprovals as number | undefined) ?? 1,
219
- reviewers,
220
- verdicts: [],
221
- /*
222
- * A review that asks for changes has something to read, and the count
223
- * is what the caller acts on. Zero made the one path that matters read
224
- * as "changes requested — 0 threads", which tells somebody running
225
- * this for the first time that the feature does not work.
226
- */
227
- threadCount: verdict === "changes_requested" ? 2 : 0,
228
- settledAt: null,
229
- expiresAt: (body.expiresAt as string | undefined) ?? null,
230
- createdAt: new Date().toISOString(),
231
- };
232
- reviewStore.set(id, {
233
- data,
234
- settleAt: Date.now() + (options.delay ?? 0),
235
- verdict,
236
- timeout: outcome === "timeout",
237
- });
238
- if (options.log !== false) announceReview(data, verdict, outcome === "timeout");
239
- return json(data, 201);
240
- }
241
-
242
- /*
243
- * The gate, offline.
244
- *
245
- * `DELIVERD_DEV_OUTCOME` means the same thing here as everywhere else, with
246
- * one addition: `denied` is a *policy* refusal, which has no equivalent on
247
- * the other primitives because nothing else can be refused without a person
248
- * being asked. The default stays `approved`, so `gate()` runs green out of
249
- * the box and the interesting cases are the ones you opt into.
250
- *
251
- * `allowed` and `denied` settle instantly, as a real rule does. `approved`
252
- * and `rejected` go through `pending` first, because that is the path with
253
- * a `wait()` in it and the one worth being able to rehearse.
254
- */
255
- if (method === "POST" && path === "/gates") {
256
- const id = `gat_dev_${++counter}`;
257
- const externalId = String(body.externalId ?? "");
258
-
259
- /*
260
- * Server-side reuse, which the real endpoint enforces in the database.
261
- * Offline it is a map lookup, and it is here rather than left out
262
- * because the one thing `gate()` promises over `approve()` is that a
263
- * retry re-reads its decision — testing that without an account is the
264
- * whole point of this file.
265
- */
266
- for (const stored of gateStore.values()) {
267
- if (stored.data.externalId === externalId) {
268
- settleGate(stored);
269
- return json({ ...stored.data.gate, reused: true });
270
- }
271
- }
272
-
273
- const outcome = resolveOutcome(options.outcome, body);
274
- /*
275
- * `denied` is settled by a rule and reaches nobody; everything else goes
276
- * through a person, which is where `wait()` earns its place. The default
277
- * `approved` therefore rehearses the escalation path rather than the
278
- * auto-allow — the opposite of production's common case, and the right
279
- * default here, because the path with a wait in it is the one worth
280
- * being able to run before you have an account.
281
- */
282
- const byRule = outcome === "denied";
283
- const gate: GateData = {
284
- id,
285
- status: byRule ? "denied" : "pending",
286
- allowed: false,
287
- input: (body.input as Record<string, unknown>) ?? {},
288
- changes: [],
289
- concerns: [],
290
- basis: byRule ? "policy" : "human",
291
- reason: byRule
292
- ? "Development mode refused it. A real rule would say which one and why."
293
- : "No rule covers this action yet, so it needs a person.",
294
- rule: byRule ? "Development mode" : null,
295
- policyVersionId: null,
296
- approvalId: byRule ? null : `apr_dev_${id}`,
297
- approvalUrl: byRule ? null : `https://deliverd.dev/approve/apr_dev_${id}`,
298
- outcome: null,
299
- settledAt: null,
300
- reused: false,
301
- decision: byRule ? "DENY" : "APPROVAL_REQUIRED",
302
- canExecute: false,
303
- blockedBecause: byRule ? "Policy does not allow this action." : "Waiting for a person to decide.",
304
- scope: {
305
- destination: (body.destination as GateData["scope"]["destination"]) ?? null,
306
- // Offline there is no directory to consult, so nothing is known to be internal.
307
- recipientScope: body.destination ? "external" : null,
308
- classification: (body.classification as GateData["scope"]["classification"]) ?? null,
309
- risk: (body.risk as GateData["scope"]["risk"]) ?? null,
310
- artifact: body.artifact
311
- ? {
312
- kind: (body.artifact as { versionId?: string }).versionId ? "report_version" : "external",
313
- reportId: (body.artifact as { reportId?: string }).reportId ?? null,
314
- versionId: (body.artifact as { versionId?: string }).versionId ?? null,
315
- versionNumber: null,
316
- sha256: ((body.artifact as { sha256?: string }).sha256 ?? null)?.toLowerCase() ?? null,
317
- name: (body.artifact as { name?: string }).name ?? null,
318
- mimeType: null,
319
- size: null,
320
- uri: null,
321
- verified: false,
322
- }
323
- : null,
324
- digest: null,
325
- },
326
- authorisation: { validUntil: null, maxUses: 1, usesRemaining: 1 },
327
- actionId: String(body.actionId ?? ""),
328
- agentId: null,
329
- flowId: (body.flowId as string | undefined) ?? null,
330
- supersedesGateId: (body.supersedesGateId as string | undefined) ?? null,
331
- description: ((body.description ?? body.reason) as string | undefined) ?? null,
332
- requestedBy: "Development agent",
333
- createdAt: new Date().toISOString(),
334
- };
335
- gateStore.set(id, {
336
- data: { gate, externalId },
337
- outcome,
338
- decideAt: Date.now() + (options.delay ?? 0),
339
- });
340
- return json(gate, 201);
341
- }
342
-
343
- /*
344
- * What was done with a permission, offline: one use, spent by the first
345
- * claim, and a hash that has to match the one asked about — the two
346
- * refusals worth rehearsing before there is an account to be refused by.
347
- */
348
- const executionMatch = /^\/gates\/([^/]+)\/(execution|cancel)$/.exec(path);
349
- if (executionMatch && method === "POST") {
350
- const stored = gateStore.get(executionMatch[1]!);
351
- if (!stored) {
352
- return json({ error: { code: "not_found", message: "No such gate in this development session." } }, 404);
353
- }
354
- settleGate(stored);
355
- const gate = stored.data.gate;
356
- if (executionMatch[2] === "cancel") {
357
- gate.status = "cancelled";
358
- gate.canExecute = false;
359
- gate.blockedBecause = "This request was withdrawn.";
360
- return json(gate);
361
- }
362
- if (!gate.canExecute) {
363
- const code = gate.status === "used" ? "gate_used" : "not_authorised";
364
- return json({ error: { code, message: gate.blockedBecause ?? "Not authorised." } }, code === "gate_used" ? 409 : 403);
365
- }
366
- const sha = typeof body.artifactSha256 === "string" ? body.artifactSha256.toLowerCase() : null;
367
- if (gate.scope.artifact?.sha256 && sha !== gate.scope.artifact.sha256) {
368
- return json(
369
- { error: { code: sha ? "approval_invalidated" : "artifact_missing", message: "The artifact is not the one that was approved." } },
370
- sha ? 409 : 400
371
- );
372
- }
373
- gate.status = "used";
374
- gate.canExecute = false;
375
- gate.blockedBecause = "This permission has been used. A further action needs a new request.";
376
- gate.authorisation = { ...gate.authorisation, usesRemaining: 0 };
377
- const receipt = {
378
- id: `exe_dev_${++counter}`,
379
- gateId: gate.id,
380
- phase: (body.phase as string | undefined) ?? "completed",
381
- claimId: null,
382
- executedAt: new Date().toISOString(),
383
- artifactSha256: sha,
384
- destination: (body.destination as GateData["scope"]["destination"]) ?? null,
385
- result: (body.result as Record<string, unknown> | undefined) ?? {},
386
- verification: gate.scope.artifact?.sha256 ? "hash_matched" : "reported",
387
- detail: (body.detail as string | undefined) ?? null,
388
- reportedBy: "Development agent",
389
- createdAt: new Date().toISOString(),
390
- };
391
- return json({ receipt, gate }, 201);
392
- }
393
-
394
- const gateMatch = /^\/gates\/([^/]+)$/.exec(path);
395
- if (gateMatch && method === "GET") {
396
- const stored = gateStore.get(gateMatch[1]!);
397
- if (!stored) {
398
- return json(
399
- { error: { code: "not_found", message: "No such gate in this development session." } },
400
- 404
401
- );
402
- }
403
- settleGate(stored);
404
- return json(stored.data.gate);
405
- }
406
-
407
- const reviewMatch = /^\/reviews\/([^/]+)(\/cancel)?$/.exec(path);
408
- if (reviewMatch) {
409
- const stored = reviewStore.get(reviewMatch[1]!);
410
- if (!stored) {
411
- return json(
412
- { error: { code: "not_found", message: "No such review in this development session." } },
413
- 404
414
- );
415
- }
416
- if (reviewMatch[2] === "/cancel") {
417
- stored.data.status = "cancelled";
418
- return json(stored.data);
419
- }
420
- settleReview(stored);
421
- return json(stored.data);
422
- }
423
-
424
- /*
425
- * Listing approvals, which `findByExternalId` needs.
426
- *
427
- * Missing until an example used `externalId` for retry safety and got a
428
- * 501 instead. Reviews, collections and flows all had their list route
429
- * from the start; approvals — the primitive the feature is most documented
430
- * on — did not, so the one thing that stops a restarted agent asking twice
431
- * was the one thing you could not try without an account.
432
- */
433
- if (method === "GET" && path === "/approvals") {
434
- const externalId = url.searchParams.get("externalId");
435
- const status = url.searchParams.get("status");
436
- // Settle first: a caller listing before polling should see the same
437
- // state a poll would have shown it, not a stale `pending`.
438
- for (const stored of store.values()) settle(stored);
439
- let all = [...store.values()].map((a) => a.data);
440
- if (externalId) all = all.filter((a) => a.externalId === externalId);
441
- if (status) all = all.filter((a) => a.status === status);
442
- return json({ approvals: all });
443
- }
444
-
445
- if (method === "GET" && path === "/reviews") {
446
- const externalId = url.searchParams.get("externalId");
447
- const all = [...reviewStore.values()].map((r) => r.data);
448
- return json({
449
- reviews: externalId ? all.filter((r) => r.externalId === externalId) : all,
450
- });
451
- }
452
-
453
- if (method === "POST" && path === "/collections") {
454
- const id = `col_dev_${++counter}`;
455
- const outcome = resolveOutcome(options.outcome, body);
456
- const asked = ((body.respondents as string[] | undefined) ?? []).map(String);
457
- const questions = ((body.questions as Record<string, unknown>[] | undefined) ?? []).map(
458
- (q, i) => ({
459
- id: `q_dev_${i + 1}`,
460
- prompt: String(q.prompt ?? "Question"),
461
- help: (q.help as string | undefined) ?? null,
462
- kind: (q.kind as CollectionData["questions"][number]["kind"]) ?? "text",
463
- required: q.required !== false,
464
- options: (q.options as string[] | undefined) ?? [],
465
- })
466
- );
467
- const data: CollectionData = {
468
- id,
469
- status: "pending",
470
- url: `https://deliverd.dev/collect/${id}`,
471
- title: String(body.title ?? "Untitled"),
472
- instructions: (body.instructions as string | undefined) ?? null,
473
- reportId: (body.reportId as string | undefined) ?? null,
474
- externalId: (body.externalId as string | undefined) ?? null,
475
- metadata: (body.metadata as Record<string, unknown>) ?? {},
476
- requestedBy: "You (development mode)",
477
- requiredResponses: (body.requiredResponses as number | undefined) ?? (asked.length || 1),
478
- questions,
479
- responses: asked.map((who) => ({
480
- respondent: who,
481
- status: "pending" as const,
482
- submittedAt: null,
483
- answers: [],
484
- })),
485
- submittedCount: 0,
486
- askedCount: asked.length,
487
- settledAt: null,
488
- dueAt: (body.dueAt as string | undefined) ?? null,
489
- expiresAt: (body.expiresAt as string | undefined) ?? null,
490
- createdAt: new Date().toISOString(),
491
- };
492
- collectionStore.set(id, {
493
- data,
494
- settleAt: Date.now() + (options.delay ?? 0),
495
- /*
496
- * A simulated rejection becomes an expiry here: there is no way to
497
- * say no to a question, only to leave it unanswered, and that is the
498
- * ending a caller most needs to have thought about.
499
- */
500
- expire: outcome === "rejected",
501
- timeout: outcome === "timeout",
502
- });
503
- if (options.log !== false) announceCollection(data, outcome);
504
- return json(data, 201);
505
- }
506
-
507
- const collectionMatch = /^\/collections\/([^/]+)(\/cancel)?$/.exec(path);
508
- if (collectionMatch) {
509
- const stored = collectionStore.get(collectionMatch[1]!);
510
- if (!stored) {
511
- return json(
512
- { error: { code: "not_found", message: "No such request in this development session." } },
513
- 404
514
- );
515
- }
516
- if (collectionMatch[2] === "/cancel") {
517
- stored.data.status = "cancelled";
518
- return json(stored.data);
519
- }
520
- settleCollection(stored);
521
- return json(stored.data);
522
- }
523
-
524
- if (method === "GET" && path === "/collections") {
525
- const externalId = url.searchParams.get("externalId");
526
- const all = [...collectionStore.values()].map((c) => c.data);
527
- return json({
528
- collections: externalId ? all.filter((c) => c.externalId === externalId) : all,
529
- });
530
- }
531
-
532
- /*
533
- * Flows in development are real objects with no simulation attached:
534
- * there is nobody to imagine, and the thing worth exercising offline is
535
- * that `flow.approve()` reaches the same code as `deliverd.approve()`.
536
- * Members are not tracked here — the server derives them from rows this
537
- * store does not keep — so a development flow reports what it knows and
538
- * does not invent a membership.
539
- */
540
- if (method === "POST" && path === "/flows") {
541
- const id = `flw_dev_${++counter}`;
542
- const data: FlowData = {
543
- id,
544
- status: "open",
545
- url: `https://deliverd.dev/flows/${id}`,
546
- title: String(body.title ?? "Untitled"),
547
- description: (body.description as string | undefined) ?? null,
548
- externalId: (body.externalId as string | undefined) ?? null,
549
- metadata: (body.metadata as Record<string, unknown>) ?? {},
550
- startedBy: "You (development mode)",
551
- members: [],
552
- memberCount: 0,
553
- openCount: 0,
554
- allSettled: false,
555
- timeline: [],
556
- settledAt: null,
557
- createdAt: new Date().toISOString(),
558
- };
559
- flowStore.set(id, data);
560
- if (options.log !== false) {
561
- console.log(`\n \u25B8 Flow started: ${data.title}\n ${data.url}\n`);
562
- }
563
- return json(data, 201);
564
- }
565
-
566
- /*
567
- * Evidence in development is the shape and not the substance: this store
568
- * holds no audit rows, so the pack comes back with the subject and an
569
- * empty record rather than an invented one. What it proves is that
570
- * `flow.evidence()` reaches the right path and returns something a caller
571
- * can destructure — an imaginary approval trail would be worse than none.
572
- */
573
- const evidenceMatch = /^\/(flows|reports)\/([^/]+)\/evidence$/.exec(path);
574
- if (evidenceMatch && method === "GET") {
575
- const kind = evidenceMatch[1] === "flows" ? "flow" : "report";
576
- const id = evidenceMatch[2]!;
577
- const title = kind === "flow" ? (flowStore.get(id)?.title ?? "A flow") : "A report";
578
- const now = new Date().toISOString();
579
- const pack: EvidencePack = {
580
- packVersion: 2,
581
- generatedAt: now,
582
- generatedBy: "You (development mode)",
583
- organisation: { id: "org_dev", name: "Development" },
584
- subject: {
585
- kind,
586
- id,
587
- title,
588
- url: `https://deliverd.dev/${evidenceMatch[1]}/${id}`,
589
- status: "open",
590
- startedBy: "You (development mode)",
591
- startedAt: now,
592
- },
593
- summary: { steps: 0, events: 0, firstEventAt: null, lastEventAt: null },
594
- steps: [],
595
- timeline: [],
596
- integrity: {
597
- algorithm: "sha256",
598
- digest: "development",
599
- covers: "Nothing: this pack was produced in development mode and holds no records.",
600
- doesNotCover: "Everything. Do not hand this to anybody.",
601
- recordsAreInsertOnly: true,
602
- },
603
- };
604
- return json(pack);
605
- }
606
-
607
- const flowMatch = /^\/flows\/([^/]+)(\/complete|\/cancel)?$/.exec(path);
608
- if (flowMatch) {
609
- const flow = flowStore.get(flowMatch[1]!);
610
- if (!flow) {
611
- return json(
612
- { error: { code: "not_found", message: "No such flow in this development session." } },
613
- 404
614
- );
615
- }
616
- if (flowMatch[2] === "/complete" || flowMatch[2] === "/cancel") {
617
- if (flow.status !== "open") {
618
- return json(
619
- { error: { code: "not_open", message: `This flow is already ${flow.status}.` } },
620
- 409
621
- );
622
- }
623
- flow.status = flowMatch[2] === "/complete" ? "complete" : "cancelled";
624
- flow.settledAt = new Date().toISOString();
625
- }
626
- return json(flow);
627
- }
628
-
629
- if (method === "GET" && path === "/flows") {
630
- const externalId = url.searchParams.get("externalId");
631
- const all = [...flowStore.values()];
632
- return json({ flows: externalId ? all.filter((f) => f.externalId === externalId) : all });
633
- }
634
-
635
- return json(
636
- {
637
- error: {
638
- code: "not_in_development_mode",
639
- message: `Development mode simulates approvals, reviews and collections only, and something called ${method} ${path}. Use a real API key for the rest of the API.`,
640
- },
641
- },
642
- 501
643
- );
644
- }) as typeof globalThis.fetch;
645
- }
646
-
647
- function resolveOutcome(
648
- outcome: DevelopmentOptions["outcome"],
649
- body: Record<string, unknown>
650
- ): DevelopmentOutcome {
651
- const fromEnv = process.env.DELIVERD_DEV_OUTCOME as DevelopmentOutcome | undefined;
652
- const chosen = outcome ?? fromEnv ?? "approved";
653
- return typeof chosen === "function" ? chosen(body as unknown as ApprovalData) : chosen;
654
- }
655
-
656
- /** Move a pending request to its outcome once the imaginary approver has had time. */
657
- function settle(stored: Stored): void {
658
- if (stored.data.status !== "pending") return;
659
- if (Date.now() < stored.decideAt) return;
660
- if (stored.outcome === "timeout") return;
661
- if (stored.outcome === "question" && stored.data.questions.some((q) => !q.answer)) return;
662
-
663
- stored.data.status = stored.outcome === "rejected" ? "rejected" : "approved";
664
- /*
665
- * The same shape production sends: a person's name in `decidedBy` and the
666
- * key in `decidedById`. It used to be an email-shaped string alone, so the
667
- * offline loop taught a shape a real organisation never delivers.
668
- */
669
- stored.data.decidedBy = "Development approver";
670
- stored.data.decidedById = "00000000-0000-0000-0000-00000000dev0";
671
- stored.data.decidedAt = new Date().toISOString();
672
- stored.data.note =
673
- stored.options.note ??
674
- (stored.data.status === "rejected" ? "Not yet — development mode says no." : null);
675
- if (stored.data.status === "approved" && stored.data.input) {
676
- const proposed = stored.data.input;
677
- const edits = Object.entries(stored.options.edits ?? {}).filter(
678
- ([field, value]) => stored.data.editableFields.includes(field) && !Object.is(proposed[field], value)
679
- );
680
- stored.data.approvedInput = { ...proposed, ...Object.fromEntries(edits) };
681
- stored.data.changes = edits.map(([field, to]) => ({ field, from: proposed[field] ?? null, to }));
682
- }
683
- }
684
-
685
- /**
686
- * What the approver would have seen, in the terminal.
687
- *
688
- * The reason this is worth the lines: the title and the factors are copy
689
- * somebody has to read on a phone at nine at night, and the only way to know
690
- * whether it reads well is to see it written out.
691
- */
692
- function announce(data: ApprovalData, outcome: DevelopmentOutcome): void {
693
- const lines = [
694
- "",
695
- " ┌─ Deliverd · development mode ─────────────────────────",
696
- ` │ ${data.title}`,
697
- ];
698
- if (data.description) lines.push(` │ ${data.description}`);
699
- lines.push(` │ Risk: ${data.risk}`);
700
- for (const factor of data.factors) {
701
- const mark = factor.status === "ok" ? "✓" : factor.status === "warning" ? "⚠" : "·";
702
- lines.push(` │ ${mark} ${factor.label}`);
703
- }
704
- if (data.approvers.length > 0) lines.push(` │ To: ${data.approvers.join(", ")}`);
705
- lines.push(
706
- " │",
707
- ` │ Simulating: ${outcome}${outcome === "question" ? " (needs an onQuestion handler)" : ""}`,
708
- " └───────────────────────────────────────────────────────",
709
- ""
710
- );
711
- console.log(lines.join("\n"));
712
- }
713
-
714
-
715
- interface StoredGate {
716
- /** The decision, plus the caller's id kept beside it for the reuse lookup. */
717
- data: { gate: GateData; externalId: string };
718
- outcome: DevelopmentOutcome;
719
- decideAt: number;
720
- }
721
-
722
- /**
723
- * A gate that went to a person, once that person has answered.
724
- *
725
- * Only the two outcomes that involve one. `allowed` and `denied` were settled
726
- * by a rule at creation and have nothing to wait for — which is the honest
727
- * shape, because in production most gated calls never reach a human either.
728
- */
729
- function settleGate(stored: StoredGate): void {
730
- const gate = stored.data.gate;
731
- if (gate.status !== "pending") return;
732
- if (Date.now() < stored.decideAt) return;
733
- if (stored.outcome === "timeout" || stored.outcome === "question") return;
734
- if (stored.outcome === "denied") return;
735
-
736
- const approved = stored.outcome === "approved";
737
- gate.status = approved ? "approved" : "rejected";
738
- gate.allowed = approved;
739
- gate.canExecute = approved;
740
- gate.blockedBecause = approved ? null : "A person rejected this action.";
741
- gate.outcome = approved ? "approved" : "rejected";
742
- gate.settledAt = new Date().toISOString();
743
- gate.basis = "human";
744
- gate.reason = approved
745
- ? "A development approver agreed to it."
746
- : "A development approver refused it.";
747
- }
748
-
749
- interface StoredReview {
750
- data: ReviewData;
751
- settleAt: number;
752
- verdict: "approved" | "changes_requested";
753
- timeout: boolean;
754
- }
755
-
756
- /** Settle it once its moment has passed, unless it is meant to hang. */
757
- function settleReview(stored: StoredReview): void {
758
- if (stored.timeout || stored.data.status !== "pending") return;
759
- if (Date.now() < stored.settleAt) return;
760
- stored.data.verdicts = [
761
- {
762
- verdict: stored.verdict,
763
- by: stored.data.reviewers[0]?.label ?? "A reviewer (development mode)",
764
- note:
765
- stored.verdict === "changes_requested"
766
- ? "Simulated: the figures on page two do not tie back."
767
- : null,
768
- at: new Date().toISOString(),
769
- },
770
- ];
771
- stored.data.status = stored.verdict;
772
- stored.data.settledAt = new Date().toISOString();
773
- }
774
-
775
- function announceReview(
776
- data: ReviewData,
777
- verdict: "approved" | "changes_requested",
778
- willHang: boolean
779
- ): void {
780
- const lines = [
781
- ` ┌─ Deliverd · development mode ─────────────────────────`,
782
- ` │ ${data.title}`,
783
- ...(data.instructions ? [` │ Check: ${data.instructions}`] : []),
784
- ` │ Reviewers: ${data.reviewers.map((r) => r.label).join(", ") || "nobody named"}`,
785
- ` │`,
786
- ` │ Simulating: ${willHang ? "nobody reviews it" : verdict.replace("_", " ")}`,
787
- ` └───────────────────────────────────────────────────────`,
788
- "",
789
- ];
790
- console.log(lines.join("\n"));
791
- }
792
-
793
-
794
- interface StoredCollection {
795
- data: CollectionData;
796
- settleAt: number;
797
- expire: boolean;
798
- timeout: boolean;
799
- }
800
-
801
- /**
802
- * Everyone answers, at the same moment, with a plausible value for the kind
803
- * of question asked. Plausible rather than empty, because a caller writing
804
- * `answers["Headcount at 30 September"] + 1` should find out here that it is
805
- * a number, not in production.
806
- */
807
- function settleCollection(stored: StoredCollection): void {
808
- if (stored.timeout || stored.data.status !== "pending") return;
809
- if (Date.now() < stored.settleAt) return;
810
- if (stored.expire) {
811
- stored.data.status = "expired";
812
- stored.data.settledAt = new Date().toISOString();
813
- return;
814
- }
815
- const at = new Date().toISOString();
816
- stored.data.responses = stored.data.responses.map((r) => ({
817
- ...r,
818
- status: "submitted" as const,
819
- submittedAt: at,
820
- answers: stored.data.questions.map((q) => ({
821
- question: q.prompt,
822
- kind: q.kind,
823
- value: sampleAnswer(q),
824
- })),
825
- }));
826
- stored.data.submittedCount = stored.data.responses.length;
827
- stored.data.status = "complete";
828
- stored.data.settledAt = at;
829
- }
830
-
831
- function sampleAnswer(q: CollectionData["questions"][number]): string | number | boolean | string[] {
832
- switch (q.kind) {
833
- case "number":
834
- return 42;
835
- case "boolean":
836
- return true;
837
- case "date":
838
- return new Date().toISOString().slice(0, 10);
839
- case "choice":
840
- return q.options[0] ?? "";
841
- case "multi_choice":
842
- return q.options.slice(0, 1);
843
- case "long_text":
844
- return "Simulated: a longer answer than a line.";
845
- default:
846
- return "Simulated answer";
847
- }
848
- }
849
-
850
- function announceCollection(data: CollectionData, outcome: string): void {
851
- const lines = [
852
- ` ┌─ Deliverd · development mode ─────────────────────────`,
853
- ` │ ${data.title}`,
854
- ` │ Asking: ${data.questions.map((q) => q.prompt).join(" · ") || "nothing"}`,
855
- ` │ Of: ${data.responses.map((r) => r.respondent).join(", ") || "nobody named"}`,
856
- ` │`,
857
- ` │ Simulating: ${
858
- outcome === "timeout"
859
- ? "nobody answers"
860
- : outcome === "rejected"
861
- ? "it expires unanswered"
862
- : "everyone answers"
863
- }`,
864
- ` └───────────────────────────────────────────────────────`,
865
- "",
866
- ];
867
- console.log(lines.join("\n"));
868
- }
1
+ import type {
2
+ ApprovalData,
3
+ CollectionData,
4
+ EvidencePack,
5
+ FlowData,
6
+ GateData,
7
+ ReviewData,
8
+ TaskData,
9
+ TaskFinding,
10
+ TaskLink,
11
+ TaskNode,
12
+ TaskState,
13
+ } from "./types.js";
14
+
15
+ /**
16
+ * Development mode: the whole loop, on your machine, with nobody in it.
17
+ *
18
+ * ```ts
19
+ * const deliverd = new Deliverd({ mode: "development" });
20
+ * const decision = await deliverd.approve({ title: "Deploy production" });
21
+ * ```
22
+ *
23
+ * No key, no network, no colleague to interrupt — and the four things that
24
+ * can happen to a real request all reachable before you have an account:
25
+ * approved, rejected, nobody answered, and somebody asked you a question.
26
+ * That last one is the path people forget to write, which is exactly why it
27
+ * should be one line to try.
28
+ *
29
+ * Implemented as a stand-in `fetch` rather than a branch inside the client,
30
+ * so development mode runs the *same* code as production — the same retries,
31
+ * the same error mapping, the same polling in `wait()`. A simulator that
32
+ * bypassed all that would prove your integration works against the simulator.
33
+ */
34
+
35
+ /**
36
+ * What development mode makes happen.
37
+ *
38
+ * Four for the primitives that ask a person, and a fifth for the gate:
39
+ * `denied` is a **policy** refusal, which nothing else can have — an approval
40
+ * cannot be refused without somebody refusing it. It is the outcome an agent
41
+ * must handle by not retrying, and rehearsing that offline is worth a word of
42
+ * its own. The four that involve a person mean the same thing everywhere;
43
+ * `denied` on an approval is treated as `rejected`, because a request nobody
44
+ * was asked about is not a thing that surface can represent.
45
+ */
46
+ export type DevelopmentOutcome = "approved" | "rejected" | "denied" | "timeout" | "question";
47
+
48
+ export interface DevelopmentOptions {
49
+ /**
50
+ * What the imaginary approver does. Default `approved`, or the value of
51
+ * `DELIVERD_DEV_OUTCOME`, so a whole test suite can be flipped from the
52
+ * command line without touching the code.
53
+ */
54
+ outcome?: DevelopmentOutcome | ((request: ApprovalData) => DevelopmentOutcome);
55
+ /** How long they take to do it, in milliseconds. Default 0. */
56
+ delay?: number;
57
+ /** What they say. Defaults suit the outcome. */
58
+ note?: string;
59
+ /**
60
+ * Corrections the imaginary approver makes when approving a request that
61
+ * sent an `input`, so the approve-with-changes path can be run offline.
62
+ * Only fields you named in `editableFields` are applied, as in production.
63
+ */
64
+ edits?: Record<string, unknown>;
65
+ /** What they ask, when the outcome is `question`. */
66
+ question?: string;
67
+ /** Print what the approver would have seen. Default true. */
68
+ log?: boolean;
69
+ }
70
+
71
+ const DEFAULT_QUESTION = "Has this been through staging?";
72
+
73
+ let counter = 0;
74
+
75
+ interface Stored {
76
+ data: ApprovalData;
77
+ /** When the imaginary approver acts. */
78
+ decideAt: number;
79
+ outcome: DevelopmentOutcome;
80
+ options: DevelopmentOptions;
81
+ }
82
+
83
+ /**
84
+ * A `fetch` that serves the approvals, reviews and collections APIs from memory.
85
+ *
86
+ * Deliberately narrow: it answers the calls the primitives make and 501s the
87
+ * rest, with a message saying so, rather than pretending to be the whole API
88
+ * and quietly returning something plausible.
89
+ */
90
+ export function developmentFetch(options: DevelopmentOptions = {}): typeof globalThis.fetch {
91
+ const store = new Map<string, Stored>();
92
+ const reviewStore = new Map<string, StoredReview>();
93
+ const gateStore = new Map<string, StoredGate>();
94
+ const collectionStore = new Map<string, StoredCollection>();
95
+ const flowStore = new Map<string, FlowData>();
96
+ const tasks = developmentTasks(options);
97
+
98
+ return (async (input: string | URL | Request, init?: RequestInit) => {
99
+ const url = new URL(String(input));
100
+ const path = url.pathname.replace(/^\/api\/v1/, "");
101
+ const method = (init?.method ?? "GET").toUpperCase();
102
+ const body = init?.body ? (JSON.parse(String(init.body)) as Record<string, unknown>) : {};
103
+
104
+ const json = (payload: unknown, status = 200) =>
105
+ new Response(JSON.stringify(payload), {
106
+ status,
107
+ headers: { "content-type": "application/json" },
108
+ });
109
+
110
+ if (method === "POST" && path === "/approvals") {
111
+ const id = `apr_dev_${++counter}`;
112
+ const outcome = resolveOutcome(options.outcome, body);
113
+ const data: ApprovalData = {
114
+ id,
115
+ status: "pending",
116
+ url: `https://deliverd.dev/approve/${id}`,
117
+ title: String(body.title ?? "Untitled"),
118
+ description: (body.description as string | undefined) ?? null,
119
+ risk: (body.risk as ApprovalData["risk"] | undefined) ?? "medium",
120
+ factors: (body.factors as ApprovalData["factors"]) ?? [],
121
+ links: (body.links as ApprovalData["links"]) ?? [],
122
+ reportId: (body.reportId as string | undefined) ?? null,
123
+ externalId: (body.externalId as string | undefined) ?? null,
124
+ metadata: (body.metadata as Record<string, unknown>) ?? {},
125
+ input: (body.input as Record<string, unknown> | undefined) ?? null,
126
+ editableFields: (body.editableFields as string[] | undefined) ?? [],
127
+ approvedInput: null,
128
+ changes: [],
129
+ concerns: [],
130
+ requestedBy: "You (development mode)",
131
+ approvers: (body.approvers as string[] | undefined) ?? [],
132
+ /*
133
+ * One, always. A standing rule could raise it on a real organisation,
134
+ * but development mode has no rules to read and an imaginary approver
135
+ * cannot be two people — pretending otherwise would let a caller test
136
+ * an escalation that never happened.
137
+ */
138
+ requiredApprovals: 1,
139
+ approvalsSoFar: 0,
140
+ decidedBy: null,
141
+ decidedById: null,
142
+ decidedAt: null,
143
+ note: null,
144
+ expiresAt: (body.expiresAt as string | undefined) ?? null,
145
+ questions:
146
+ outcome === "question"
147
+ ? [
148
+ {
149
+ id: `q_dev_${counter}`,
150
+ question: options.question ?? DEFAULT_QUESTION,
151
+ answer: null,
152
+ askedAt: new Date().toISOString(),
153
+ answeredAt: null,
154
+ },
155
+ ]
156
+ : [],
157
+ createdAt: new Date().toISOString(),
158
+ };
159
+ store.set(id, {
160
+ data,
161
+ decideAt: Date.now() + (options.delay ?? 0),
162
+ outcome,
163
+ options,
164
+ });
165
+ if (options.log !== false) announce(data, outcome);
166
+ return json(data, 201);
167
+ }
168
+
169
+ const match = /^\/approvals\/([^/]+)(\/answers|\/cancel)?$/.exec(path);
170
+ if (match) {
171
+ const stored = store.get(match[1]!);
172
+ if (!stored) {
173
+ return json({ error: { code: "not_found", message: "No such approval in this development session." } }, 404);
174
+ }
175
+ if (match[2] === "/answers") {
176
+ const question = stored.data.questions.find((q) => q.id === body.questionId);
177
+ if (!question) {
178
+ return json({ error: { code: "question_not_found", message: "No such question." } }, 404);
179
+ }
180
+ question.answer = String(body.answer);
181
+ question.answeredAt = new Date().toISOString();
182
+ // Answered: the imaginary approver is satisfied and approves.
183
+ stored.outcome = "approved";
184
+ stored.decideAt = Date.now() + (stored.options.delay ?? 0);
185
+ if (stored.options.log !== false) {
186
+ console.log(` ↳ answered: ${question.answer}\n`);
187
+ }
188
+ return json(stored.data);
189
+ }
190
+ if (match[2] === "/cancel") {
191
+ stored.data.status = "cancelled";
192
+ return json(stored.data);
193
+ }
194
+ settle(stored);
195
+ return json(stored.data);
196
+ }
197
+
198
+ if (method === "POST" && path === "/reviews") {
199
+ const id = `rev_dev_${++counter}`;
200
+ /*
201
+ * The same outcome switch as approvals, mapped onto a review's endings:
202
+ * a rejection is "changes requested", because that is what saying no to
203
+ * a piece of work means. A simulated question has nothing to ask about
204
+ * here — there is no question mechanism on a review — so it approves.
205
+ */
206
+ const outcome = resolveOutcome(options.outcome, body);
207
+ const verdict = outcome === "rejected" ? "changes_requested" : "approved";
208
+ const reviewers = ((body.reviewers as string[] | undefined) ?? []).map((email, i) => ({
209
+ kind: "user" as const,
210
+ id: `usr_dev_${i + 1}`,
211
+ label: email,
212
+ }));
213
+ const data: ReviewData = {
214
+ id,
215
+ status: "pending",
216
+ url: `https://deliverd.dev/reviews/${id}`,
217
+ title: String(body.title ?? "Untitled"),
218
+ instructions: (body.instructions as string | undefined) ?? null,
219
+ reportId: (body.reportId as string | undefined) ?? null,
220
+ versionId: (body.versionId as string | undefined) ?? null,
221
+ externalId: (body.externalId as string | undefined) ?? null,
222
+ metadata: (body.metadata as Record<string, unknown>) ?? {},
223
+ requestedBy: "You (development mode)",
224
+ requiredApprovals: (body.requiredApprovals as number | undefined) ?? 1,
225
+ reviewers,
226
+ verdicts: [],
227
+ /*
228
+ * A review that asks for changes has something to read, and the count
229
+ * is what the caller acts on. Zero made the one path that matters read
230
+ * as "changes requested — 0 threads", which tells somebody running
231
+ * this for the first time that the feature does not work.
232
+ */
233
+ threadCount: verdict === "changes_requested" ? 2 : 0,
234
+ settledAt: null,
235
+ expiresAt: (body.expiresAt as string | undefined) ?? null,
236
+ createdAt: new Date().toISOString(),
237
+ };
238
+ reviewStore.set(id, {
239
+ data,
240
+ settleAt: Date.now() + (options.delay ?? 0),
241
+ verdict,
242
+ timeout: outcome === "timeout",
243
+ });
244
+ if (options.log !== false) announceReview(data, verdict, outcome === "timeout");
245
+ return json(data, 201);
246
+ }
247
+
248
+ /*
249
+ * The gate, offline.
250
+ *
251
+ * `DELIVERD_DEV_OUTCOME` means the same thing here as everywhere else, with
252
+ * one addition: `denied` is a *policy* refusal, which has no equivalent on
253
+ * the other primitives because nothing else can be refused without a person
254
+ * being asked. The default stays `approved`, so `gate()` runs green out of
255
+ * the box and the interesting cases are the ones you opt into.
256
+ *
257
+ * `allowed` and `denied` settle instantly, as a real rule does. `approved`
258
+ * and `rejected` go through `pending` first, because that is the path with
259
+ * a `wait()` in it and the one worth being able to rehearse.
260
+ */
261
+ if (method === "POST" && path === "/gates") {
262
+ const id = `gat_dev_${++counter}`;
263
+ const externalId = String(body.externalId ?? "");
264
+
265
+ /*
266
+ * Server-side reuse, which the real endpoint enforces in the database.
267
+ * Offline it is a map lookup, and it is here rather than left out
268
+ * because the one thing `gate()` promises over `approve()` is that a
269
+ * retry re-reads its decision — testing that without an account is the
270
+ * whole point of this file.
271
+ */
272
+ for (const stored of gateStore.values()) {
273
+ if (stored.data.externalId === externalId) {
274
+ settleGate(stored);
275
+ return json({ ...stored.data.gate, reused: true });
276
+ }
277
+ }
278
+
279
+ const outcome = resolveOutcome(options.outcome, body);
280
+ /*
281
+ * `denied` is settled by a rule and reaches nobody; everything else goes
282
+ * through a person, which is where `wait()` earns its place. The default
283
+ * `approved` therefore rehearses the escalation path rather than the
284
+ * auto-allow — the opposite of production's common case, and the right
285
+ * default here, because the path with a wait in it is the one worth
286
+ * being able to run before you have an account.
287
+ */
288
+ const byRule = outcome === "denied";
289
+ const gate: GateData = {
290
+ id,
291
+ status: byRule ? "denied" : "pending",
292
+ allowed: false,
293
+ input: (body.input as Record<string, unknown>) ?? {},
294
+ changes: [],
295
+ concerns: [],
296
+ basis: byRule ? "policy" : "human",
297
+ reason: byRule
298
+ ? "Development mode refused it. A real rule would say which one and why."
299
+ : "No rule covers this action yet, so it needs a person.",
300
+ rule: byRule ? "Development mode" : null,
301
+ policyVersionId: null,
302
+ approvalId: byRule ? null : `apr_dev_${id}`,
303
+ approvalUrl: byRule ? null : `https://deliverd.dev/approve/apr_dev_${id}`,
304
+ outcome: null,
305
+ settledAt: null,
306
+ reused: false,
307
+ decision: byRule ? "DENY" : "APPROVAL_REQUIRED",
308
+ canExecute: false,
309
+ blockedBecause: byRule ? "Policy does not allow this action." : "Waiting for a person to decide.",
310
+ scope: {
311
+ destination: (body.destination as GateData["scope"]["destination"]) ?? null,
312
+ // Offline there is no directory to consult, so nothing is known to be internal.
313
+ recipientScope: body.destination ? "external" : null,
314
+ classification: (body.classification as GateData["scope"]["classification"]) ?? null,
315
+ risk: (body.risk as GateData["scope"]["risk"]) ?? null,
316
+ artifact: body.artifact
317
+ ? {
318
+ kind: (body.artifact as { versionId?: string }).versionId ? "report_version" : "external",
319
+ reportId: (body.artifact as { reportId?: string }).reportId ?? null,
320
+ versionId: (body.artifact as { versionId?: string }).versionId ?? null,
321
+ versionNumber: null,
322
+ sha256: ((body.artifact as { sha256?: string }).sha256 ?? null)?.toLowerCase() ?? null,
323
+ name: (body.artifact as { name?: string }).name ?? null,
324
+ mimeType: null,
325
+ size: null,
326
+ uri: null,
327
+ verified: false,
328
+ }
329
+ : null,
330
+ digest: null,
331
+ },
332
+ authorisation: { validUntil: null, maxUses: 1, usesRemaining: 1 },
333
+ actionId: String(body.actionId ?? ""),
334
+ agentId: null,
335
+ flowId: (body.flowId as string | undefined) ?? null,
336
+ supersedesGateId: (body.supersedesGateId as string | undefined) ?? null,
337
+ description: ((body.description ?? body.reason) as string | undefined) ?? null,
338
+ requestedBy: "Development agent",
339
+ createdAt: new Date().toISOString(),
340
+ };
341
+ gateStore.set(id, {
342
+ data: { gate, externalId },
343
+ outcome,
344
+ decideAt: Date.now() + (options.delay ?? 0),
345
+ });
346
+ return json(gate, 201);
347
+ }
348
+
349
+ /*
350
+ * What was done with a permission, offline: one use, spent by the first
351
+ * claim, and a hash that has to match the one asked about — the two
352
+ * refusals worth rehearsing before there is an account to be refused by.
353
+ */
354
+ const executionMatch = /^\/gates\/([^/]+)\/(execution|cancel)$/.exec(path);
355
+ if (executionMatch && method === "POST") {
356
+ const stored = gateStore.get(executionMatch[1]!);
357
+ if (!stored) {
358
+ return json({ error: { code: "not_found", message: "No such gate in this development session." } }, 404);
359
+ }
360
+ settleGate(stored);
361
+ const gate = stored.data.gate;
362
+ if (executionMatch[2] === "cancel") {
363
+ gate.status = "cancelled";
364
+ gate.canExecute = false;
365
+ gate.blockedBecause = "This request was withdrawn.";
366
+ return json(gate);
367
+ }
368
+ if (!gate.canExecute) {
369
+ const code = gate.status === "used" ? "gate_used" : "not_authorised";
370
+ return json({ error: { code, message: gate.blockedBecause ?? "Not authorised." } }, code === "gate_used" ? 409 : 403);
371
+ }
372
+ const sha = typeof body.artifactSha256 === "string" ? body.artifactSha256.toLowerCase() : null;
373
+ if (gate.scope.artifact?.sha256 && sha !== gate.scope.artifact.sha256) {
374
+ return json(
375
+ { error: { code: sha ? "approval_invalidated" : "artifact_missing", message: "The artifact is not the one that was approved." } },
376
+ sha ? 409 : 400
377
+ );
378
+ }
379
+ gate.status = "used";
380
+ gate.canExecute = false;
381
+ gate.blockedBecause = "This permission has been used. A further action needs a new request.";
382
+ gate.authorisation = { ...gate.authorisation, usesRemaining: 0 };
383
+ const receipt = {
384
+ id: `exe_dev_${++counter}`,
385
+ gateId: gate.id,
386
+ phase: (body.phase as string | undefined) ?? "completed",
387
+ claimId: null,
388
+ executedAt: new Date().toISOString(),
389
+ artifactSha256: sha,
390
+ destination: (body.destination as GateData["scope"]["destination"]) ?? null,
391
+ result: (body.result as Record<string, unknown> | undefined) ?? {},
392
+ verification: gate.scope.artifact?.sha256 ? "hash_matched" : "reported",
393
+ detail: (body.detail as string | undefined) ?? null,
394
+ reportedBy: "Development agent",
395
+ createdAt: new Date().toISOString(),
396
+ };
397
+ return json({ receipt, gate }, 201);
398
+ }
399
+
400
+ const gateMatch = /^\/gates\/([^/]+)$/.exec(path);
401
+ if (gateMatch && method === "GET") {
402
+ const stored = gateStore.get(gateMatch[1]!);
403
+ if (!stored) {
404
+ return json(
405
+ { error: { code: "not_found", message: "No such gate in this development session." } },
406
+ 404
407
+ );
408
+ }
409
+ settleGate(stored);
410
+ return json(stored.data.gate);
411
+ }
412
+
413
+ const reviewMatch = /^\/reviews\/([^/]+)(\/cancel)?$/.exec(path);
414
+ if (reviewMatch) {
415
+ const stored = reviewStore.get(reviewMatch[1]!);
416
+ if (!stored) {
417
+ return json(
418
+ { error: { code: "not_found", message: "No such review in this development session." } },
419
+ 404
420
+ );
421
+ }
422
+ if (reviewMatch[2] === "/cancel") {
423
+ stored.data.status = "cancelled";
424
+ return json(stored.data);
425
+ }
426
+ settleReview(stored);
427
+ return json(stored.data);
428
+ }
429
+
430
+ /*
431
+ * Listing approvals, which `findByExternalId` needs.
432
+ *
433
+ * Missing until an example used `externalId` for retry safety and got a
434
+ * 501 instead. Reviews, collections and flows all had their list route
435
+ * from the start; approvals — the primitive the feature is most documented
436
+ * on — did not, so the one thing that stops a restarted agent asking twice
437
+ * was the one thing you could not try without an account.
438
+ */
439
+ if (method === "GET" && path === "/approvals") {
440
+ const externalId = url.searchParams.get("externalId");
441
+ const status = url.searchParams.get("status");
442
+ // Settle first: a caller listing before polling should see the same
443
+ // state a poll would have shown it, not a stale `pending`.
444
+ for (const stored of store.values()) settle(stored);
445
+ let all = [...store.values()].map((a) => a.data);
446
+ if (externalId) all = all.filter((a) => a.externalId === externalId);
447
+ if (status) all = all.filter((a) => a.status === status);
448
+ return json({ approvals: all });
449
+ }
450
+
451
+ if (method === "GET" && path === "/reviews") {
452
+ const externalId = url.searchParams.get("externalId");
453
+ const all = [...reviewStore.values()].map((r) => r.data);
454
+ return json({
455
+ reviews: externalId ? all.filter((r) => r.externalId === externalId) : all,
456
+ });
457
+ }
458
+
459
+ if (method === "POST" && path === "/collections") {
460
+ const id = `col_dev_${++counter}`;
461
+ const outcome = resolveOutcome(options.outcome, body);
462
+ const asked = ((body.respondents as string[] | undefined) ?? []).map(String);
463
+ const questions = ((body.questions as Record<string, unknown>[] | undefined) ?? []).map(
464
+ (q, i) => ({
465
+ id: `q_dev_${i + 1}`,
466
+ prompt: String(q.prompt ?? "Question"),
467
+ help: (q.help as string | undefined) ?? null,
468
+ kind: (q.kind as CollectionData["questions"][number]["kind"]) ?? "text",
469
+ required: q.required !== false,
470
+ options: (q.options as string[] | undefined) ?? [],
471
+ })
472
+ );
473
+ const data: CollectionData = {
474
+ id,
475
+ status: "pending",
476
+ url: `https://deliverd.dev/collect/${id}`,
477
+ title: String(body.title ?? "Untitled"),
478
+ instructions: (body.instructions as string | undefined) ?? null,
479
+ reportId: (body.reportId as string | undefined) ?? null,
480
+ externalId: (body.externalId as string | undefined) ?? null,
481
+ metadata: (body.metadata as Record<string, unknown>) ?? {},
482
+ requestedBy: "You (development mode)",
483
+ requiredResponses: (body.requiredResponses as number | undefined) ?? (asked.length || 1),
484
+ questions,
485
+ responses: asked.map((who) => ({
486
+ respondent: who,
487
+ status: "pending" as const,
488
+ submittedAt: null,
489
+ answers: [],
490
+ })),
491
+ submittedCount: 0,
492
+ askedCount: asked.length,
493
+ settledAt: null,
494
+ dueAt: (body.dueAt as string | undefined) ?? null,
495
+ expiresAt: (body.expiresAt as string | undefined) ?? null,
496
+ createdAt: new Date().toISOString(),
497
+ };
498
+ collectionStore.set(id, {
499
+ data,
500
+ settleAt: Date.now() + (options.delay ?? 0),
501
+ /*
502
+ * A simulated rejection becomes an expiry here: there is no way to
503
+ * say no to a question, only to leave it unanswered, and that is the
504
+ * ending a caller most needs to have thought about.
505
+ */
506
+ expire: outcome === "rejected",
507
+ timeout: outcome === "timeout",
508
+ });
509
+ if (options.log !== false) announceCollection(data, outcome);
510
+ return json(data, 201);
511
+ }
512
+
513
+ const collectionMatch = /^\/collections\/([^/]+)(\/cancel)?$/.exec(path);
514
+ if (collectionMatch) {
515
+ const stored = collectionStore.get(collectionMatch[1]!);
516
+ if (!stored) {
517
+ return json(
518
+ { error: { code: "not_found", message: "No such request in this development session." } },
519
+ 404
520
+ );
521
+ }
522
+ if (collectionMatch[2] === "/cancel") {
523
+ stored.data.status = "cancelled";
524
+ return json(stored.data);
525
+ }
526
+ settleCollection(stored);
527
+ return json(stored.data);
528
+ }
529
+
530
+ if (method === "GET" && path === "/collections") {
531
+ const externalId = url.searchParams.get("externalId");
532
+ const all = [...collectionStore.values()].map((c) => c.data);
533
+ return json({
534
+ collections: externalId ? all.filter((c) => c.externalId === externalId) : all,
535
+ });
536
+ }
537
+
538
+ /*
539
+ * Flows in development are real objects with no simulation attached:
540
+ * there is nobody to imagine, and the thing worth exercising offline is
541
+ * that `flow.approve()` reaches the same code as `deliverd.approve()`.
542
+ * Members are not tracked here — the server derives them from rows this
543
+ * store does not keep — so a development flow reports what it knows and
544
+ * does not invent a membership.
545
+ */
546
+ if (method === "POST" && path === "/flows") {
547
+ const id = `flw_dev_${++counter}`;
548
+ const data: FlowData = {
549
+ id,
550
+ status: "open",
551
+ url: `https://deliverd.dev/flows/${id}`,
552
+ title: String(body.title ?? "Untitled"),
553
+ description: (body.description as string | undefined) ?? null,
554
+ externalId: (body.externalId as string | undefined) ?? null,
555
+ metadata: (body.metadata as Record<string, unknown>) ?? {},
556
+ startedBy: "You (development mode)",
557
+ members: [],
558
+ memberCount: 0,
559
+ openCount: 0,
560
+ allSettled: false,
561
+ timeline: [],
562
+ settledAt: null,
563
+ createdAt: new Date().toISOString(),
564
+ };
565
+ flowStore.set(id, data);
566
+ if (options.log !== false) {
567
+ console.log(`\n \u25B8 Flow started: ${data.title}\n ${data.url}\n`);
568
+ }
569
+ return json(data, 201);
570
+ }
571
+
572
+ /*
573
+ * Evidence in development is the shape and not the substance: this store
574
+ * holds no audit rows, so the pack comes back with the subject and an
575
+ * empty record rather than an invented one. What it proves is that
576
+ * `flow.evidence()` reaches the right path and returns something a caller
577
+ * can destructure — an imaginary approval trail would be worse than none.
578
+ */
579
+ const evidenceMatch = /^\/(flows|reports)\/([^/]+)\/evidence$/.exec(path);
580
+ if (evidenceMatch && method === "GET") {
581
+ const kind = evidenceMatch[1] === "flows" ? "flow" : "report";
582
+ const id = evidenceMatch[2]!;
583
+ const title = kind === "flow" ? (flowStore.get(id)?.title ?? "A flow") : "A report";
584
+ const now = new Date().toISOString();
585
+ const pack: EvidencePack = {
586
+ packVersion: 2,
587
+ generatedAt: now,
588
+ generatedBy: "You (development mode)",
589
+ organisation: { id: "org_dev", name: "Development" },
590
+ subject: {
591
+ kind,
592
+ id,
593
+ title,
594
+ url: `https://deliverd.dev/${evidenceMatch[1]}/${id}`,
595
+ status: "open",
596
+ startedBy: "You (development mode)",
597
+ startedAt: now,
598
+ },
599
+ summary: { steps: 0, events: 0, firstEventAt: null, lastEventAt: null },
600
+ steps: [],
601
+ timeline: [],
602
+ integrity: {
603
+ algorithm: "sha256",
604
+ digest: "development",
605
+ covers: "Nothing: this pack was produced in development mode and holds no records.",
606
+ doesNotCover: "Everything. Do not hand this to anybody.",
607
+ recordsAreInsertOnly: true,
608
+ },
609
+ };
610
+ return json(pack);
611
+ }
612
+
613
+ const flowMatch = /^\/flows\/([^/]+)(\/complete|\/cancel)?$/.exec(path);
614
+ if (flowMatch) {
615
+ const flow = flowStore.get(flowMatch[1]!);
616
+ if (!flow) {
617
+ return json(
618
+ { error: { code: "not_found", message: "No such flow in this development session." } },
619
+ 404
620
+ );
621
+ }
622
+ if (flowMatch[2] === "/complete" || flowMatch[2] === "/cancel") {
623
+ if (flow.status !== "open") {
624
+ return json(
625
+ { error: { code: "not_open", message: `This flow is already ${flow.status}.` } },
626
+ 409
627
+ );
628
+ }
629
+ flow.status = flowMatch[2] === "/complete" ? "complete" : "cancelled";
630
+ flow.settledAt = new Date().toISOString();
631
+ }
632
+ return json(flow);
633
+ }
634
+
635
+ if (method === "GET" && path === "/flows") {
636
+ const externalId = url.searchParams.get("externalId");
637
+ const all = [...flowStore.values()];
638
+ return json({ flows: externalId ? all.filter((f) => f.externalId === externalId) : all });
639
+ }
640
+
641
+ /*
642
+ * Task Graph in development: real objects with no simulation attached,
643
+ * the same reasoning as flows. Nothing here is decided by anybody, so
644
+ * there is nobody to imagine — what is worth running offline is the loop
645
+ * itself: start an objective, branch a side task, complete it, apply it,
646
+ * and read the context the parent comes back with. Putting a decision to
647
+ * an approval is the one call left to the real API, because the approval
648
+ * it raises lives in a store this simulation does not join to.
649
+ */
650
+ if (method === "POST" && path === "/tasks") {
651
+ const { task, resumed } = tasks.create(body);
652
+ return json({ ...task, resumed }, resumed ? 200 : 201);
653
+ }
654
+
655
+ if (method === "GET" && path === "/tasks") {
656
+ return json({ tasks: tasks.list(url.searchParams), nextCursor: null });
657
+ }
658
+
659
+ const taskMatch = /^\/tasks\/([^/]+)(?:\/(context|graph|side-tasks|findings|complete|apply|reopen|cancel|links))?$/.exec(path);
660
+ if (taskMatch) {
661
+ const [status, payload] = tasks.act(method, taskMatch[1]!, taskMatch[2] ?? null, body);
662
+ return json(payload, status);
663
+ }
664
+
665
+ return json(
666
+ {
667
+ error: {
668
+ code: "not_in_development_mode",
669
+ message: `Development mode simulates approvals, reviews, collections, flows and tasks only, and something called ${method} ${path}. Use a real API key for the rest of the API.`,
670
+ },
671
+ },
672
+ 501
673
+ );
674
+ }) as typeof globalThis.fetch;
675
+ }
676
+
677
+ function resolveOutcome(
678
+ outcome: DevelopmentOptions["outcome"],
679
+ body: Record<string, unknown>
680
+ ): DevelopmentOutcome {
681
+ const fromEnv = process.env.DELIVERD_DEV_OUTCOME as DevelopmentOutcome | undefined;
682
+ const chosen = outcome ?? fromEnv ?? "approved";
683
+ return typeof chosen === "function" ? chosen(body as unknown as ApprovalData) : chosen;
684
+ }
685
+
686
+ /** Move a pending request to its outcome once the imaginary approver has had time. */
687
+ function settle(stored: Stored): void {
688
+ if (stored.data.status !== "pending") return;
689
+ if (Date.now() < stored.decideAt) return;
690
+ if (stored.outcome === "timeout") return;
691
+ if (stored.outcome === "question" && stored.data.questions.some((q) => !q.answer)) return;
692
+
693
+ stored.data.status = stored.outcome === "rejected" ? "rejected" : "approved";
694
+ /*
695
+ * The same shape production sends: a person's name in `decidedBy` and the
696
+ * key in `decidedById`. It used to be an email-shaped string alone, so the
697
+ * offline loop taught a shape a real organisation never delivers.
698
+ */
699
+ stored.data.decidedBy = "Development approver";
700
+ stored.data.decidedById = "00000000-0000-0000-0000-00000000dev0";
701
+ stored.data.decidedAt = new Date().toISOString();
702
+ stored.data.note =
703
+ stored.options.note ??
704
+ (stored.data.status === "rejected" ? "Not yet — development mode says no." : null);
705
+ if (stored.data.status === "approved" && stored.data.input) {
706
+ const proposed = stored.data.input;
707
+ const edits = Object.entries(stored.options.edits ?? {}).filter(
708
+ ([field, value]) => stored.data.editableFields.includes(field) && !Object.is(proposed[field], value)
709
+ );
710
+ stored.data.approvedInput = { ...proposed, ...Object.fromEntries(edits) };
711
+ stored.data.changes = edits.map(([field, to]) => ({ field, from: proposed[field] ?? null, to }));
712
+ }
713
+ }
714
+
715
+ /**
716
+ * What the approver would have seen, in the terminal.
717
+ *
718
+ * The reason this is worth the lines: the title and the factors are copy
719
+ * somebody has to read on a phone at nine at night, and the only way to know
720
+ * whether it reads well is to see it written out.
721
+ */
722
+ function announce(data: ApprovalData, outcome: DevelopmentOutcome): void {
723
+ const lines = [
724
+ "",
725
+ " ┌─ Deliverd · development mode ─────────────────────────",
726
+ ` │ ${data.title}`,
727
+ ];
728
+ if (data.description) lines.push(` │ ${data.description}`);
729
+ lines.push(` │ Risk: ${data.risk}`);
730
+ for (const factor of data.factors) {
731
+ const mark = factor.status === "ok" ? "✓" : factor.status === "warning" ? "⚠" : "·";
732
+ lines.push(` │ ${mark} ${factor.label}`);
733
+ }
734
+ if (data.approvers.length > 0) lines.push(` │ To: ${data.approvers.join(", ")}`);
735
+ lines.push(
736
+ " │",
737
+ ` │ Simulating: ${outcome}${outcome === "question" ? " (needs an onQuestion handler)" : ""}`,
738
+ " └───────────────────────────────────────────────────────",
739
+ ""
740
+ );
741
+ console.log(lines.join("\n"));
742
+ }
743
+
744
+
745
+ interface StoredGate {
746
+ /** The decision, plus the caller's id kept beside it for the reuse lookup. */
747
+ data: { gate: GateData; externalId: string };
748
+ outcome: DevelopmentOutcome;
749
+ decideAt: number;
750
+ }
751
+
752
+ /**
753
+ * A gate that went to a person, once that person has answered.
754
+ *
755
+ * Only the two outcomes that involve one. `allowed` and `denied` were settled
756
+ * by a rule at creation and have nothing to wait for — which is the honest
757
+ * shape, because in production most gated calls never reach a human either.
758
+ */
759
+ function settleGate(stored: StoredGate): void {
760
+ const gate = stored.data.gate;
761
+ if (gate.status !== "pending") return;
762
+ if (Date.now() < stored.decideAt) return;
763
+ if (stored.outcome === "timeout" || stored.outcome === "question") return;
764
+ if (stored.outcome === "denied") return;
765
+
766
+ const approved = stored.outcome === "approved";
767
+ gate.status = approved ? "approved" : "rejected";
768
+ gate.allowed = approved;
769
+ gate.canExecute = approved;
770
+ gate.blockedBecause = approved ? null : "A person rejected this action.";
771
+ gate.outcome = approved ? "approved" : "rejected";
772
+ gate.settledAt = new Date().toISOString();
773
+ gate.basis = "human";
774
+ gate.reason = approved
775
+ ? "A development approver agreed to it."
776
+ : "A development approver refused it.";
777
+ }
778
+
779
+ interface StoredReview {
780
+ data: ReviewData;
781
+ settleAt: number;
782
+ verdict: "approved" | "changes_requested";
783
+ timeout: boolean;
784
+ }
785
+
786
+ /** Settle it once its moment has passed, unless it is meant to hang. */
787
+ function settleReview(stored: StoredReview): void {
788
+ if (stored.timeout || stored.data.status !== "pending") return;
789
+ if (Date.now() < stored.settleAt) return;
790
+ stored.data.verdicts = [
791
+ {
792
+ verdict: stored.verdict,
793
+ by: stored.data.reviewers[0]?.label ?? "A reviewer (development mode)",
794
+ note:
795
+ stored.verdict === "changes_requested"
796
+ ? "Simulated: the figures on page two do not tie back."
797
+ : null,
798
+ at: new Date().toISOString(),
799
+ },
800
+ ];
801
+ stored.data.status = stored.verdict;
802
+ stored.data.settledAt = new Date().toISOString();
803
+ }
804
+
805
+ function announceReview(
806
+ data: ReviewData,
807
+ verdict: "approved" | "changes_requested",
808
+ willHang: boolean
809
+ ): void {
810
+ const lines = [
811
+ ` ┌─ Deliverd · development mode ─────────────────────────`,
812
+ ` │ ${data.title}`,
813
+ ...(data.instructions ? [` │ Check: ${data.instructions}`] : []),
814
+ ` │ Reviewers: ${data.reviewers.map((r) => r.label).join(", ") || "nobody named"}`,
815
+ ` │`,
816
+ ` │ Simulating: ${willHang ? "nobody reviews it" : verdict.replace("_", " ")}`,
817
+ ` └───────────────────────────────────────────────────────`,
818
+ "",
819
+ ];
820
+ console.log(lines.join("\n"));
821
+ }
822
+
823
+
824
+ interface StoredCollection {
825
+ data: CollectionData;
826
+ settleAt: number;
827
+ expire: boolean;
828
+ timeout: boolean;
829
+ }
830
+
831
+ /**
832
+ * Everyone answers, at the same moment, with a plausible value for the kind
833
+ * of question asked. Plausible rather than empty, because a caller writing
834
+ * `answers["Headcount at 30 September"] + 1` should find out here that it is
835
+ * a number, not in production.
836
+ */
837
+ function settleCollection(stored: StoredCollection): void {
838
+ if (stored.timeout || stored.data.status !== "pending") return;
839
+ if (Date.now() < stored.settleAt) return;
840
+ if (stored.expire) {
841
+ stored.data.status = "expired";
842
+ stored.data.settledAt = new Date().toISOString();
843
+ return;
844
+ }
845
+ const at = new Date().toISOString();
846
+ stored.data.responses = stored.data.responses.map((r) => ({
847
+ ...r,
848
+ status: "submitted" as const,
849
+ submittedAt: at,
850
+ answers: stored.data.questions.map((q) => ({
851
+ question: q.prompt,
852
+ kind: q.kind,
853
+ value: sampleAnswer(q),
854
+ })),
855
+ }));
856
+ stored.data.submittedCount = stored.data.responses.length;
857
+ stored.data.status = "complete";
858
+ stored.data.settledAt = at;
859
+ }
860
+
861
+ function sampleAnswer(q: CollectionData["questions"][number]): string | number | boolean | string[] {
862
+ switch (q.kind) {
863
+ case "number":
864
+ return 42;
865
+ case "boolean":
866
+ return true;
867
+ case "date":
868
+ return new Date().toISOString().slice(0, 10);
869
+ case "choice":
870
+ return q.options[0] ?? "";
871
+ case "multi_choice":
872
+ return q.options.slice(0, 1);
873
+ case "long_text":
874
+ return "Simulated: a longer answer than a line.";
875
+ default:
876
+ return "Simulated answer";
877
+ }
878
+ }
879
+
880
+ function announceCollection(data: CollectionData, outcome: string): void {
881
+ const lines = [
882
+ ` ┌─ Deliverd · development mode ─────────────────────────`,
883
+ ` │ ${data.title}`,
884
+ ` │ Asking: ${data.questions.map((q) => q.prompt).join(" · ") || "nothing"}`,
885
+ ` │ Of: ${data.responses.map((r) => r.respondent).join(", ") || "nobody named"}`,
886
+ ` │`,
887
+ ` │ Simulating: ${
888
+ outcome === "timeout"
889
+ ? "nobody answers"
890
+ : outcome === "rejected"
891
+ ? "it expires unanswered"
892
+ : "everyone answers"
893
+ }`,
894
+ ` └───────────────────────────────────────────────────────`,
895
+ "",
896
+ ];
897
+ console.log(lines.join("\n"));
898
+ }
899
+
900
+ /* ── Tasks ────────────────────────────────────────────────────────────────── */
901
+
902
+ type TaskReply = [status: number, payload: unknown];
903
+
904
+ const notFound = (what: string): TaskReply => [
905
+ 404,
906
+ { error: { code: "not_found", message: `No such ${what} in this development session.` } },
907
+ ];
908
+ const refused = (code: string, message: string, status = 409): TaskReply => [
909
+ status,
910
+ { error: { code, message } },
911
+ ];
912
+
913
+ function strings(value: unknown): string[] {
914
+ return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string" && v.trim() !== "") : [];
915
+ }
916
+
917
+ function mergeState(current: TaskState, patch: Record<string, unknown> | undefined): TaskState {
918
+ if (!patch) return current;
919
+ const next: TaskState = { ...current };
920
+ if ("currentState" in patch) next.currentState = (patch.currentState as string | null) ?? null;
921
+ if ("nextAction" in patch) next.nextAction = (patch.nextAction as string | null) ?? null;
922
+ if (patch.openQuestions) next.openQuestions = strings(patch.openQuestions);
923
+ if (patch.constraints) next.constraints = strings(patch.constraints);
924
+ if (patch.blockedBy) next.blockedBy = strings(patch.blockedBy);
925
+ for (const q of strings(patch.addOpenQuestions)) {
926
+ if (!next.openQuestions.includes(q)) next.openQuestions = [...next.openQuestions, q];
927
+ }
928
+ const gone = new Set(strings(patch.resolveOpenQuestions).map((q) => q.toLowerCase()));
929
+ if (gone.size) next.openQuestions = next.openQuestions.filter((q) => !gone.has(q.toLowerCase()));
930
+ return next;
931
+ }
932
+
933
+ /**
934
+ * The Task Graph, in memory: enough of the server's rules that the loop an
935
+ * agent actually runs — objective, side task, result, apply, context — does
936
+ * offline what it does live. Not the whole service: no workspaces, no
937
+ * permissions, no audit, and a context assembled from what this store holds.
938
+ */
939
+ function developmentTasks(options: DevelopmentOptions) {
940
+ const store = new Map<string, TaskData>();
941
+ const findings = new Map<string, TaskFinding[]>();
942
+ const links: TaskLink[] = [];
943
+
944
+ const active = (t: TaskData) => t.status !== "completed" && t.status !== "cancelled";
945
+ const childrenOf = (id: string) => [...store.values()].filter((t) => t.parentTaskId === id);
946
+ const node = (t: TaskData): TaskNode => ({
947
+ id: t.id,
948
+ parentTaskId: t.parentTaskId,
949
+ kind: t.kind,
950
+ depth: t.depth,
951
+ status: t.status,
952
+ title: t.title,
953
+ outcome: t.outcome,
954
+ resultSummary: t.result?.summary ?? null,
955
+ url: t.url,
956
+ });
957
+ const pathTo = (t: TaskData) => {
958
+ const path = [];
959
+ for (let at: TaskData | undefined = t; at; at = at.parentTaskId ? store.get(at.parentTaskId) : undefined) {
960
+ path.unshift({ id: at.id, title: at.title, kind: at.kind });
961
+ }
962
+ return path;
963
+ };
964
+ const bump = (t: TaskData) => {
965
+ t.version += 1;
966
+ t.updatedAt = new Date().toISOString();
967
+ };
968
+ const listed = (t: TaskData): TaskData => {
969
+ const { sideTasks: _counts, path: _path, children: _children, findings: _findings, links: _links, resumed: _resumed, ...rest } = t;
970
+ return rest;
971
+ };
972
+
973
+ function make(body: Record<string, unknown>, parent: TaskData | null): TaskData {
974
+ const id = `tsk_dev_${++counter}`;
975
+ const now = new Date().toISOString();
976
+ const parentDecisions = parent
977
+ ? (findings.get(parent.id) ?? []).filter((f) => f.kind === "decision" && f.decisionStatus !== "rejected")
978
+ : [];
979
+ return {
980
+ id,
981
+ kind: parent ? ((body.kind as TaskData["kind"] | undefined) ?? "side_task") : "objective",
982
+ status: "open",
983
+ url: `https://deliverd.dev/tasks/${id}`,
984
+ title: String(body.title ?? "Untitled"),
985
+ objective: String((parent ? body.goal : body.objective) ?? ""),
986
+ rootTaskId: parent ? parent.rootTaskId : id,
987
+ parentTaskId: parent ? parent.id : null,
988
+ depth: parent ? parent.depth + 1 : 0,
989
+ workspaceId: parent ? parent.workspaceId : ((body.workspaceId as string | undefined) ?? null),
990
+ flowId: parent ? parent.flowId : ((body.flowId as string | undefined) ?? null),
991
+ state: mergeState(
992
+ { currentState: null, openQuestions: [], constraints: [], blockedBy: [], nextAction: null },
993
+ body.state as Record<string, unknown> | undefined
994
+ ),
995
+ snapshot: parent
996
+ ? {
997
+ rootObjective: store.get(parent.rootTaskId)?.objective ?? parent.objective,
998
+ parentObjective: parent.objective,
999
+ sideTaskGoal: String(body.goal ?? ""),
1000
+ relevantContext: body.relevantContext
1001
+ ? strings(body.relevantContext)
1002
+ : parent.state.currentState
1003
+ ? [parent.state.currentState]
1004
+ : [],
1005
+ knownConstraints: body.knownConstraints ? strings(body.knownConstraints) : parent.state.constraints,
1006
+ relatedDecisions: parentDecisions.map((d) =>
1007
+ d.decisionStatus === "confirmed" ? d.title : `${d.title} (suggested)`
1008
+ ),
1009
+ resolvesQuestion: (body.resolvesQuestion as string | undefined) ?? null,
1010
+ }
1011
+ : null,
1012
+ result: null,
1013
+ previousResults: [],
1014
+ outcome: null,
1015
+ origin: (body.origin as TaskData["origin"] | undefined) ?? "manual",
1016
+ externalId: parent ? null : ((body.externalId as string | undefined) ?? null),
1017
+ sessionUrl: (body.sessionUrl as string | undefined) ?? null,
1018
+ version: 1,
1019
+ startedBy: "You (development mode)",
1020
+ createdAt: now,
1021
+ updatedAt: now,
1022
+ completedAt: null,
1023
+ };
1024
+ }
1025
+
1026
+ function context(t: TaskData) {
1027
+ const root = store.get(t.rootTaskId) ?? t;
1028
+ const isSideTask = t.kind !== "objective";
1029
+ const own = findings.get(t.id) ?? [];
1030
+ const decisions = [...(t.id === root.id ? [] : (findings.get(root.id) ?? [])), ...own].filter(
1031
+ (f) => f.kind === "decision"
1032
+ );
1033
+ const children = childrenOf(t.id);
1034
+ const finished = children.filter((c) => c.status === "completed");
1035
+ const awaiting = finished.filter((c) => c.outcome === null);
1036
+ const next = t.state.nextAction ?? (isSideTask ? null : root.state.nextAction);
1037
+ return {
1038
+ rootObjective: root.objective,
1039
+ task: { id: t.id, kind: t.kind, title: t.title, objective: t.objective, status: t.status, isSideTask },
1040
+ path: pathTo(t),
1041
+ currentState: t.state.currentState,
1042
+ nextAction: next,
1043
+ openQuestions: t.state.openQuestions,
1044
+ constraints: t.state.constraints.length ? t.state.constraints : (t.snapshot?.knownConstraints ?? []),
1045
+ blockedBy: t.state.blockedBy,
1046
+ decisions: {
1047
+ confirmed: decisions.filter((d) => d.decisionStatus === "confirmed").map((d) => d.title),
1048
+ suggested: decisions.filter((d) => d.decisionStatus === "suggested").map((d) => d.title),
1049
+ },
1050
+ snapshot: t.snapshot,
1051
+ relevantFindings: own
1052
+ .filter((f) => f.kind !== "decision")
1053
+ .slice(0, 12)
1054
+ .map((f) => ({ kind: f.kind, title: f.title, body: f.body })),
1055
+ sideTasks: {
1056
+ active: children.filter(active).map((c) => ({ id: c.id, title: c.title, kind: c.kind, status: c.status })),
1057
+ awaitingOutcome: awaiting.map((c) => ({ id: c.id, title: c.title, summary: c.result?.summary ?? null })),
1058
+ completed: finished
1059
+ .filter((c) => c.outcome !== null)
1060
+ .map((c) => ({ id: c.id, title: c.title, summary: c.result?.summary ?? null, outcome: c.outcome })),
1061
+ },
1062
+ reanchor: [
1063
+ `Objective: ${root.objective}`,
1064
+ isSideTask ? `You are in a side task: ${t.title}. Its goal: ${t.objective}` : null,
1065
+ t.state.currentState ? `Where it stands: ${t.state.currentState}` : null,
1066
+ next ? `Next: ${next}` : null,
1067
+ ]
1068
+ .filter(Boolean)
1069
+ .join("\n"),
1070
+ };
1071
+ }
1072
+
1073
+ function addFinding(t: TaskData, body: Record<string, unknown>, sourceTaskId: string | null = null): TaskFinding {
1074
+ const kind = (body.kind as TaskFinding["kind"] | undefined) ?? "finding";
1075
+ const finding: TaskFinding = {
1076
+ id: `fnd_dev_${++counter}`,
1077
+ taskId: t.id,
1078
+ kind,
1079
+ title: String(body.title ?? "Untitled"),
1080
+ body: String(body.body ?? ""),
1081
+ evidence: strings(body.evidence),
1082
+ decisionStatus: kind === "decision" ? "suggested" : null,
1083
+ decidedBy: null,
1084
+ decidedAt: null,
1085
+ approvalId: null,
1086
+ approvalStatus: null,
1087
+ sourceTaskId,
1088
+ createdBy: "You (development mode)",
1089
+ createdAt: new Date().toISOString(),
1090
+ };
1091
+ findings.set(t.id, [finding, ...(findings.get(t.id) ?? [])]);
1092
+ return finding;
1093
+ }
1094
+
1095
+ return {
1096
+ create(body: Record<string, unknown>): { task: TaskData; resumed: boolean } {
1097
+ const externalId = body.externalId as string | undefined;
1098
+ if (externalId) {
1099
+ const existing = [...store.values()].find(
1100
+ (t) => t.kind === "objective" && t.externalId === externalId && active(t)
1101
+ );
1102
+ if (existing) return { task: listed(existing), resumed: true };
1103
+ }
1104
+ const task = make(body, null);
1105
+ store.set(task.id, task);
1106
+ if (options.log !== false) console.log(`\n ▸ Objective: ${task.title}\n ${task.url}\n`);
1107
+ return { task: listed(task), resumed: false };
1108
+ },
1109
+
1110
+ list(query: URLSearchParams): TaskData[] {
1111
+ const status = query.get("status");
1112
+ const externalId = query.get("externalId");
1113
+ const q = query.get("q")?.toLowerCase();
1114
+ return [...store.values()]
1115
+ .filter((t) => t.kind === "objective")
1116
+ .filter((t) => !status || (status === "active" ? active(t) : t.status === status))
1117
+ .filter((t) => !externalId || t.externalId === externalId)
1118
+ .filter((t) => !q || `${t.title} ${t.objective}`.toLowerCase().includes(q))
1119
+ .map((t) => {
1120
+ const below = [...store.values()].filter((s) => s.rootTaskId === t.id && s.id !== t.id);
1121
+ return {
1122
+ ...listed(t),
1123
+ sideTasks: {
1124
+ open: below.filter(active).length,
1125
+ done: below.filter((s) => s.status === "completed" && s.outcome !== null).length,
1126
+ awaiting: below.filter((s) => s.status === "completed" && s.outcome === null).length,
1127
+ },
1128
+ };
1129
+ });
1130
+ },
1131
+
1132
+ act(method: string, id: string, action: string | null, body: Record<string, unknown>): TaskReply {
1133
+ const t = store.get(id);
1134
+ if (!t) return notFound("task");
1135
+
1136
+ if (method === "GET" && action === null) {
1137
+ return [
1138
+ 200,
1139
+ {
1140
+ ...listed(t),
1141
+ path: pathTo(t),
1142
+ children: childrenOf(t.id).map(node),
1143
+ findings: findings.get(t.id) ?? [],
1144
+ links: links.filter((l) => l.sourceTaskId === t.id || l.targetTaskId === t.id),
1145
+ },
1146
+ ];
1147
+ }
1148
+ if (method === "GET" && action === "context") return [200, context(t)];
1149
+ if (method === "GET" && action === "graph") {
1150
+ const root = store.get(t.rootTaskId) ?? t;
1151
+ const tree = [...store.values()].filter((n) => n.rootTaskId === root.id);
1152
+ const ids = new Set(tree.map((n) => n.id));
1153
+ return [
1154
+ 200,
1155
+ {
1156
+ root: listed(root),
1157
+ nodes: tree.map(node),
1158
+ links: links.filter((l) => ids.has(l.sourceTaskId) || ids.has(l.targetTaskId)),
1159
+ },
1160
+ ];
1161
+ }
1162
+
1163
+ if (method === "PATCH" && action === null) {
1164
+ if (typeof body.expectedVersion === "number" && body.expectedVersion !== t.version) {
1165
+ return refused("version_conflict", "The task changed since you read it. Read it again and retry.");
1166
+ }
1167
+ if (typeof body.title === "string") t.title = body.title;
1168
+ if (typeof body.objective === "string") t.objective = body.objective;
1169
+ if (typeof body.status === "string") t.status = body.status as TaskData["status"];
1170
+ if ("sessionUrl" in body) t.sessionUrl = (body.sessionUrl as string | null) ?? null;
1171
+ t.state = mergeState(t.state, body.state as Record<string, unknown> | undefined);
1172
+ bump(t);
1173
+ return [200, listed(t)];
1174
+ }
1175
+
1176
+ if (method !== "POST") return refused("not_in_development_mode", `${method} ${action ?? ""} is not simulated.`, 501);
1177
+
1178
+ switch (action) {
1179
+ case "side-tasks": {
1180
+ if (!active(t)) return refused("not_open", "The task this belongs to is finished. Reopen it first.");
1181
+ if (t.depth >= 3) {
1182
+ return refused("invalid", "Side tasks nest at most three deep. Branch from a task higher up instead.", 400);
1183
+ }
1184
+ const side = make(body, t);
1185
+ store.set(side.id, side);
1186
+ if (options.log !== false) console.log(`\n ↳ Side task: ${side.title}\n ${side.url}\n`);
1187
+ return [201, listed(side)];
1188
+ }
1189
+ case "findings":
1190
+ return [201, addFinding(t, body)];
1191
+ case "complete": {
1192
+ if (!active(t)) return refused("not_open", "This task is already complete or cancelled.");
1193
+ t.result = {
1194
+ summary: String(body.summary ?? ""),
1195
+ findings: (body.findings as NonNullable<TaskData["result"]>["findings"] | undefined) ?? [],
1196
+ decisions: (body.decisions as NonNullable<TaskData["result"]>["decisions"] | undefined) ?? [],
1197
+ recommendations: strings(body.recommendations),
1198
+ unresolvedQuestions: strings(body.unresolvedQuestions),
1199
+ parentImpact: (body.parentImpact as string | undefined) ?? null,
1200
+ suggestedNextAction: (body.suggestedNextAction as string | undefined) ?? null,
1201
+ };
1202
+ for (const f of t.result.findings) addFinding(t, { kind: "finding", title: f.title, body: f.description, evidence: f.evidence });
1203
+ for (const d of t.result.decisions) addFinding(t, { kind: "decision", title: d.title, body: d.rationale });
1204
+ t.status = "completed";
1205
+ t.completedAt = new Date().toISOString();
1206
+ bump(t);
1207
+ return [200, listed(t)];
1208
+ }
1209
+ case "apply": {
1210
+ const parent = t.parentTaskId ? store.get(t.parentTaskId) : undefined;
1211
+ if (!parent) return refused("invalid", "An objective has no parent to apply to.", 400);
1212
+ if (t.status !== "completed" || !t.result) {
1213
+ return refused("not_completed", "This side task has not been completed yet, so there is no result to use.");
1214
+ }
1215
+ if (t.outcome !== null) {
1216
+ return refused("already_applied", "This result has already been applied to the main task. Reopen the side task to change it.");
1217
+ }
1218
+ const outcome = (body.outcome as TaskData["outcome"] | undefined) ?? "applied";
1219
+ t.outcome = outcome;
1220
+ bump(t);
1221
+ if (outcome === "applied") {
1222
+ for (const f of findings.get(t.id) ?? []) {
1223
+ addFinding(parent, { kind: f.kind, title: f.title, body: f.body, evidence: f.evidence }, t.id);
1224
+ }
1225
+ const resolves = t.snapshot?.resolvesQuestion;
1226
+ parent.state = mergeState(parent.state, {
1227
+ addOpenQuestions: t.result.unresolvedQuestions,
1228
+ ...(resolves ? { resolveOpenQuestions: [resolves] } : {}),
1229
+ ...(t.result.suggestedNextAction ? { nextAction: t.result.suggestedNextAction } : {}),
1230
+ });
1231
+ bump(parent);
1232
+ }
1233
+ const message =
1234
+ outcome === "applied"
1235
+ ? `The result of "${t.title}" is now part of "${parent.title}".`
1236
+ : outcome === "kept"
1237
+ ? `"${t.title}" is kept for reference; nothing in "${parent.title}" changed.`
1238
+ : `"${t.title}" was discarded; nothing in "${parent.title}" changed.`;
1239
+ return [200, { sideTask: listed(t), parent: listed(parent), message, context: context(parent) }];
1240
+ }
1241
+ case "reopen": {
1242
+ if (t.status !== "completed" && t.status !== "cancelled") {
1243
+ return refused("not_open", "Only a completed or cancelled task can be reopened.");
1244
+ }
1245
+ if (t.result) t.previousResults = [t.result, ...t.previousResults];
1246
+ t.result = null;
1247
+ t.outcome = null;
1248
+ t.status = "open";
1249
+ t.completedAt = null;
1250
+ bump(t);
1251
+ return [200, listed(t)];
1252
+ }
1253
+ case "cancel": {
1254
+ if (!active(t)) return refused("not_open", "This task is already complete or cancelled.");
1255
+ t.status = "cancelled";
1256
+ t.completedAt = new Date().toISOString();
1257
+ bump(t);
1258
+ return [200, listed(t)];
1259
+ }
1260
+ case "links": {
1261
+ const targetTaskId = String(body.targetTaskId ?? "");
1262
+ if (targetTaskId === t.id) return refused("invalid", "A task cannot be linked to itself.", 400);
1263
+ if (!store.has(targetTaskId)) return notFound("task");
1264
+ const kind = body.kind as TaskLink["kind"];
1265
+ const exists = links.some((l) => l.sourceTaskId === t.id && l.targetTaskId === targetTaskId && l.kind === kind);
1266
+ if (!exists) links.push({ sourceTaskId: t.id, targetTaskId, kind });
1267
+ return [201, { linked: true, sourceTaskId: t.id, targetTaskId, kind, created: !exists }];
1268
+ }
1269
+ default:
1270
+ return refused("not_in_development_mode", `POST /tasks/${id}/${action ?? ""} is not simulated.`, 501);
1271
+ }
1272
+ },
1273
+ };
1274
+ }