@nestos/kanban 0.0.0-stage → 0.5.1

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.
Files changed (99) hide show
  1. package/README.md +121 -2
  2. package/dist/activity-C6xDM-cg.d.cts +232 -0
  3. package/dist/activity-Dw8DOw0L.d.ts +232 -0
  4. package/dist/activity.cjs +288 -0
  5. package/dist/activity.cjs.map +1 -0
  6. package/dist/activity.d.cts +34 -0
  7. package/dist/activity.d.ts +34 -0
  8. package/dist/activity.js +288 -0
  9. package/dist/activity.js.map +1 -0
  10. package/dist/chunk-2YFPV5GF.cjs +16 -0
  11. package/dist/chunk-2YFPV5GF.cjs.map +1 -0
  12. package/dist/chunk-4KF7KUAI.cjs +221 -0
  13. package/dist/chunk-4KF7KUAI.cjs.map +1 -0
  14. package/dist/chunk-4XF6LQSU.cjs +9 -0
  15. package/dist/chunk-4XF6LQSU.cjs.map +1 -0
  16. package/dist/chunk-5DLZWW5Y.js +148 -0
  17. package/dist/chunk-5DLZWW5Y.js.map +1 -0
  18. package/dist/chunk-5XKOCKY2.js +58 -0
  19. package/dist/chunk-5XKOCKY2.js.map +1 -0
  20. package/dist/chunk-6MN3H3YF.cjs +183 -0
  21. package/dist/chunk-6MN3H3YF.cjs.map +1 -0
  22. package/dist/chunk-ATUFFNLV.js +221 -0
  23. package/dist/chunk-ATUFFNLV.js.map +1 -0
  24. package/dist/chunk-DFTOTBGF.js +439 -0
  25. package/dist/chunk-DFTOTBGF.js.map +1 -0
  26. package/dist/chunk-G6FCDLDF.js +16 -0
  27. package/dist/chunk-G6FCDLDF.js.map +1 -0
  28. package/dist/chunk-IUI5CI2S.cjs +439 -0
  29. package/dist/chunk-IUI5CI2S.cjs.map +1 -0
  30. package/dist/chunk-KYNYPKKH.cjs +71 -0
  31. package/dist/chunk-KYNYPKKH.cjs.map +1 -0
  32. package/dist/chunk-L44TM4EE.cjs +1498 -0
  33. package/dist/chunk-L44TM4EE.cjs.map +1 -0
  34. package/dist/chunk-LSE6JG5I.cjs +20 -0
  35. package/dist/chunk-LSE6JG5I.cjs.map +1 -0
  36. package/dist/chunk-O4OGAAV4.js +71 -0
  37. package/dist/chunk-O4OGAAV4.js.map +1 -0
  38. package/dist/chunk-OHQTKGQN.js +1498 -0
  39. package/dist/chunk-OHQTKGQN.js.map +1 -0
  40. package/dist/chunk-PSKQAFDF.cjs +58 -0
  41. package/dist/chunk-PSKQAFDF.cjs.map +1 -0
  42. package/dist/chunk-QTMTBEBA.js +20 -0
  43. package/dist/chunk-QTMTBEBA.js.map +1 -0
  44. package/dist/chunk-RQP77ZTY.js +9 -0
  45. package/dist/chunk-RQP77ZTY.js.map +1 -0
  46. package/dist/chunk-T7P5EIC4.cjs +148 -0
  47. package/dist/chunk-T7P5EIC4.cjs.map +1 -0
  48. package/dist/chunk-TB2RZGDV.js +183 -0
  49. package/dist/chunk-TB2RZGDV.js.map +1 -0
  50. package/dist/content-CAIp1njn.d.cts +35 -0
  51. package/dist/content-CGMJdyH_.d.ts +35 -0
  52. package/dist/contracts/index.cjs +21 -0
  53. package/dist/contracts/index.cjs.map +1 -0
  54. package/dist/contracts/index.d.cts +4 -0
  55. package/dist/contracts/index.d.ts +4 -0
  56. package/dist/contracts/index.js +21 -0
  57. package/dist/contracts/index.js.map +1 -0
  58. package/dist/discovery-DxpirOz3.d.cts +61 -0
  59. package/dist/discovery-gSqWpuRm.d.ts +61 -0
  60. package/dist/discovery.cjs +379 -0
  61. package/dist/discovery.cjs.map +1 -0
  62. package/dist/discovery.d.cts +22 -0
  63. package/dist/discovery.d.ts +22 -0
  64. package/dist/discovery.js +379 -0
  65. package/dist/discovery.js.map +1 -0
  66. package/dist/execution.cjs +368 -0
  67. package/dist/execution.cjs.map +1 -0
  68. package/dist/execution.d.cts +89 -0
  69. package/dist/execution.d.ts +89 -0
  70. package/dist/execution.js +368 -0
  71. package/dist/execution.js.map +1 -0
  72. package/dist/index.cjs +76 -0
  73. package/dist/index.cjs.map +1 -0
  74. package/dist/index.d.cts +61 -0
  75. package/dist/index.d.ts +61 -0
  76. package/dist/index.js +76 -0
  77. package/dist/index.js.map +1 -0
  78. package/dist/module-BbvwdCDF.d.cts +11 -0
  79. package/dist/module-CWNK2BMj.d.ts +11 -0
  80. package/dist/planning-CcFZYdIL.d.cts +844 -0
  81. package/dist/planning-CcFZYdIL.d.ts +844 -0
  82. package/dist/ports-Bn6ro2FB.d.ts +142 -0
  83. package/dist/ports-CaL6geqR.d.cts +142 -0
  84. package/dist/storage.cjs +289 -0
  85. package/dist/storage.cjs.map +1 -0
  86. package/dist/storage.d.cts +71 -0
  87. package/dist/storage.d.ts +71 -0
  88. package/dist/storage.js +289 -0
  89. package/dist/storage.js.map +1 -0
  90. package/dist/store-Ct0gOAAg.d.ts +28 -0
  91. package/dist/store-q63eSMoT.d.cts +28 -0
  92. package/dist/ui/index.cjs +1961 -0
  93. package/dist/ui/index.cjs.map +1 -0
  94. package/dist/ui/index.d.cts +209 -0
  95. package/dist/ui/index.d.ts +209 -0
  96. package/dist/ui/index.js +1961 -0
  97. package/dist/ui/index.js.map +1 -0
  98. package/dist/ui/kanban.css +194 -0
  99. package/package.json +113 -4
@@ -0,0 +1,1498 @@
1
+ import {
2
+ executionObservationChanged
3
+ } from "./chunk-RQP77ZTY.js";
4
+ import {
5
+ assigneeKey,
6
+ candidates,
7
+ discoveryState,
8
+ eligible,
9
+ executable,
10
+ identity,
11
+ owned,
12
+ participant,
13
+ policy,
14
+ principal,
15
+ principalKey,
16
+ requireValue,
17
+ text,
18
+ validateBoard,
19
+ validateCandidates,
20
+ validateEstimate,
21
+ workType
22
+ } from "./chunk-ATUFFNLV.js";
23
+ import {
24
+ KanbanError
25
+ } from "./chunk-G6FCDLDF.js";
26
+ import {
27
+ TASK_START_DELAY_MS,
28
+ taskDue,
29
+ taskEditing,
30
+ taskStartAt
31
+ } from "./chunk-O4OGAAV4.js";
32
+ import {
33
+ executableWorkItem,
34
+ sameAutomationBinding
35
+ } from "./chunk-5XKOCKY2.js";
36
+ import {
37
+ randomUUID,
38
+ sha256HexSync
39
+ } from "./chunk-TB2RZGDV.js";
40
+ import {
41
+ boardAllowsStart
42
+ } from "./chunk-QTMTBEBA.js";
43
+
44
+ // src/planning.ts
45
+ function plan(item) {
46
+ return item.planning ?? { kind: "task", priority: 2, dependencies: [], references: [] };
47
+ }
48
+ function summary(item) {
49
+ return {
50
+ launch: item.launch,
51
+ analysis: item.analysis,
52
+ control: item.control,
53
+ issues: item.issues,
54
+ blocked: item.blocked,
55
+ id: item.id,
56
+ number: item.number,
57
+ title: item.title,
58
+ status: item.status,
59
+ revision: item.revision,
60
+ createdAt: item.createdAt,
61
+ updatedAt: item.updatedAt,
62
+ discoveryFingerprint: item.origin?.fingerprint,
63
+ pendingAmendments: item.amendments?.filter((proposal) => proposal.status === "pending").length,
64
+ externalRefs: item.externalRefs,
65
+ closedAt: item.closedAt,
66
+ planning: plan(item),
67
+ sessionIds: item.participants.map((p) => p.sessionId)
68
+ };
69
+ }
70
+ function terminal(item) {
71
+ return item.status === "completed" || item.status === "cancelled";
72
+ }
73
+ function catalog(state) {
74
+ return [...state.board.items.map(summary), ...state.archiveIndex ?? []];
75
+ }
76
+ function limits(state) {
77
+ const p = state.board.policy;
78
+ return { ready: p.maxReady ?? 20, inProgress: p.maxInProgress ?? 3, perAgent: p.maxInProgressPerAssignee ?? p.maxInProgressPerAgent ?? 1, perAssignee: p.maxInProgressPerAssignee ?? p.maxInProgressPerAgent ?? 1 };
79
+ }
80
+ function validatePlan(state, item, value) {
81
+ requireValue(typeof value.kind === "string" && Number.isInteger(value.priority) && value.priority >= 0 && value.priority <= 4, "INVALID_PLANNING");
82
+ requireValue(Array.isArray(value.dependencies) && value.dependencies.length <= 100 && Array.isArray(value.references) && value.references.length <= 100, "PLANNING_LIMIT");
83
+ value.dependencies.forEach(identity);
84
+ value.references.forEach(text);
85
+ if (value.area !== void 0) identity(value.area);
86
+ if (value.milestone !== void 0) identity(value.milestone);
87
+ requireValue(value.execution === void 0 || ["direct", "children"].includes(value.execution), "INVALID_EXECUTION_MODE");
88
+ const type = workType(state.board, value.kind);
89
+ if (value.dueAt !== void 0) requireValue(Number.isFinite(value.dueAt) && value.dueAt >= 0, "INVALID_DUE_DATE");
90
+ const all = catalog(state), parent = all.find((i) => i.id === value.parentId);
91
+ if (value.parentId) {
92
+ identity(value.parentId);
93
+ requireValue(parent && !parent.archivedAt && !terminal(parent) && !["claimed", "review"].includes(parent.status), "PARENT_UNAVAILABLE");
94
+ requireValue(parent.id !== item.id && workType(state.board, parent.planning.kind).rank < type.rank, "INVALID_PARENT_KIND");
95
+ }
96
+ requireValue(value.execution === "children" || !all.some((child) => child.planning.parentId === item.id), "CHILDREN_REQUIRE_AGGREGATION");
97
+ requireValue(!all.some((child) => child.planning.parentId === item.id && workType(state.board, child.planning.kind).rank <= type.rank), "INVALID_CHILD_KIND");
98
+ for (const id of value.dependencies) requireValue(id !== item.id && all.some((i) => i.id === id), "INVALID_DEPENDENCY");
99
+ const visited = /* @__PURE__ */ new Set(), pending = [...value.dependencies];
100
+ while (pending.length) {
101
+ const id = pending.pop();
102
+ requireValue(id !== item.id, "DEPENDENCY_CYCLE");
103
+ if (visited.has(id)) continue;
104
+ visited.add(id);
105
+ pending.push(...all.find((i) => i.id === id)?.planning.dependencies ?? []);
106
+ }
107
+ }
108
+ function assertReady(state, item) {
109
+ requireValue(executable(state.board, item), "PLAN_NOT_EXECUTABLE");
110
+ requireValue(!item.blocked, "ITEM_BLOCKED");
111
+ const all = catalog(state);
112
+ requireValue(plan(item).dependencies.every((id) => all.find((i) => i.id === id)?.status === "completed"), "DEPENDENCIES_UNFINISHED");
113
+ }
114
+ function setStage(state, item, stage, now) {
115
+ requireValue(["proposed", "backlog", "open"].includes(item.status), "ITEM_NOT_PLANNABLE");
116
+ requireValue(stage === "backlog" || stage === "open", "INVALID_STAGE");
117
+ if (stage === "open") {
118
+ assertReady(state, item);
119
+ requireValue(item.status === "open" || state.board.items.filter((i) => i.status === "open").length < limits(state).ready, "READY_LIMIT");
120
+ }
121
+ item.status = stage;
122
+ item.readyAt = now;
123
+ item.updatedAt = now;
124
+ item.revision++;
125
+ }
126
+ function automaticStage(state, item) {
127
+ const all = catalog(state);
128
+ const dependenciesComplete = plan(item).dependencies.every((id) => all.find((i) => i.id === id)?.status === "completed");
129
+ return executable(state.board, item) && !item.blocked && dependenciesComplete && state.board.items.filter((i) => i.status === "open").length < limits(state).ready ? "open" : "backlog";
130
+ }
131
+
132
+ // src/amendments.ts
133
+ var textOf = (item) => ({ title: item.title, responsibility: item.responsibility, acceptance: item.acceptance });
134
+ var textDigest = (item) => sha256HexSync(JSON.stringify(textOf(item)));
135
+ function workFingerprint(item) {
136
+ const planning = plan(item);
137
+ return sha256HexSync(JSON.stringify({
138
+ text: textOf(item),
139
+ kind: planning.kind,
140
+ parentId: planning.parentId ?? null,
141
+ area: planning.area ?? null,
142
+ milestone: planning.milestone ?? null,
143
+ priority: planning.priority,
144
+ dependencies: [...planning.dependencies].sort(),
145
+ dueAt: planning.dueAt ?? null
146
+ }));
147
+ }
148
+ function validateSources(sources) {
149
+ requireValue(Array.isArray(sources) && sources.length <= 100, "SOURCE_LIMIT");
150
+ for (const source of sources) {
151
+ identity(source.sessionId);
152
+ identity(source.messageId);
153
+ identity(source.revision);
154
+ requireValue(source.role === "user" || source.role === "assistant", "INVALID_SOURCE");
155
+ }
156
+ }
157
+ function proposeAmendment(item, change, actor, now, runId) {
158
+ text(change.title);
159
+ text(change.responsibility);
160
+ text(change.acceptance);
161
+ validateSources(change.sources);
162
+ const proposed = textOf(change), fingerprint = textDigest(proposed);
163
+ if (textDigest(item) === fingerprint || item.amendments?.some((p) => p.fingerprint === fingerprint)) return;
164
+ requireValue((item.amendments?.length ?? 0) < 20, "AMENDMENT_LIMIT");
165
+ (item.amendments ??= []).push({
166
+ runId,
167
+ id: `amendment-${sha256HexSync(JSON.stringify([runId, item.id, fingerprint]))}`,
168
+ fingerprint,
169
+ baseRevision: item.revision,
170
+ baseDigest: textDigest(item),
171
+ proposed,
172
+ proposedBy: principal(actor),
173
+ sources: structuredClone(change.sources),
174
+ createdAt: now,
175
+ status: "pending"
176
+ });
177
+ }
178
+ function requireReviewer(board, actor) {
179
+ const key = principalKey(principal(actor));
180
+ requireValue(
181
+ board.members?.some((m) => principalKey(m) === key && m.roles?.some((role) => role === "coordinator" || role === "reviewer")),
182
+ "REVIEWER_REQUIRED"
183
+ );
184
+ }
185
+ function reviewAmendment(board, command, actor, now) {
186
+ requireReviewer(board, actor);
187
+ const item = board.items.find((i) => i.id === command.itemId), proposal = item?.amendments?.find((p) => p.id === command.amendmentId);
188
+ requireValue(item && proposal?.status === "pending", "AMENDMENT_NOT_PENDING");
189
+ if (command.accept) {
190
+ requireValue(principal(actor).kind === "human" || principalKey(proposal.proposedBy) !== principalKey(principal(actor)), "INDEPENDENT_REVIEW_REQUIRED");
191
+ requireValue(["proposed", "backlog", "open"].includes(item.status), "ITEM_NOT_PLANNABLE");
192
+ requireValue(textDigest(item) === proposal.baseDigest, "AMENDMENT_STALE");
193
+ Object.assign(item, proposal.proposed);
194
+ if (item.status === "open") {
195
+ item.status = "backlog";
196
+ item.readyAt = now;
197
+ }
198
+ } else {
199
+ requireValue(!!command.reason?.trim(), "AMENDMENT_REASON_REQUIRED");
200
+ text(command.reason);
201
+ }
202
+ proposal.status = command.accept ? "accepted" : "rejected";
203
+ proposal.reviewedAt = now;
204
+ proposal.reviewedBy = principal(actor);
205
+ proposal.reason = command.reason;
206
+ item.updatedAt = now;
207
+ item.revision++;
208
+ }
209
+
210
+ // src/project-records.ts
211
+ function isRecordCommand(command) {
212
+ return ["append-record", "review-record", "link-record"].includes(command.type);
213
+ }
214
+ function applyRecord(state, command, actor, now, forceDraft = false) {
215
+ if (command.type === "append-record") {
216
+ append(state, command, actor, now, forceDraft);
217
+ return;
218
+ }
219
+ const record = state.records?.find((record2) => record2.id === command.recordId);
220
+ requireValue(record, "RECORD_NOT_FOUND");
221
+ if (command.type === "link-record") {
222
+ validateItems(state, [command.itemId]);
223
+ if (!record.itemIds.includes(command.itemId)) {
224
+ requireValue(record.itemIds.length < 100, "RECORD_LINK_LIMIT");
225
+ record.itemIds.push(command.itemId);
226
+ }
227
+ } else {
228
+ requireReviewer(state.board, actor);
229
+ requireValue(record.status === "draft", "RECORD_NOT_DRAFT");
230
+ if (command.accept) {
231
+ requireValue(principal(actor).kind === "human" || principalKey(record.author) !== principalKey(principal(actor)), "INDEPENDENT_REVIEW_REQUIRED");
232
+ supersede(state, record, now);
233
+ record.status = "confirmed";
234
+ } else record.status = "rejected";
235
+ record.reviewedBy = principal(actor);
236
+ }
237
+ record.updatedAt = now;
238
+ record.revision++;
239
+ }
240
+ function append(state, command, actor, now, forceDraft) {
241
+ validateSources(command.record.sources);
242
+ const { id, kind, title, content, rationale, itemIds, sources, supersedes, coordination, externalRefs } = command.record;
243
+ const input = structuredClone({ id, kind, title, content, rationale, itemIds, sources: sources.map((source) => ({ sessionId: source.sessionId, messageId: source.messageId, revision: source.revision, role: source.role })), supersedes, ...coordination ? { coordination } : {}, ...externalRefs ? { externalRefs } : {} });
244
+ identity(input.id);
245
+ text(input.title);
246
+ text(input.content);
247
+ validateRecordReferences(externalRefs);
248
+ requireValue(input.kind === "log" || input.kind === "decision", "INVALID_RECORD_KIND");
249
+ requireValue(!state.records?.some((record) => record.id === input.id), "RECORD_EXISTS");
250
+ requireValue((state.records?.length ?? 0) < 200, "RECORD_LIMIT");
251
+ validateItems(state, input.itemIds);
252
+ validateSources(input.sources);
253
+ if (input.rationale !== void 0) text(input.rationale);
254
+ if (input.kind === "decision") text(input.rationale ?? "");
255
+ if (coordination) validateCoordination(state, input);
256
+ if (input.supersedes) {
257
+ identity(input.supersedes);
258
+ requireValue(input.kind === "decision" && input.supersedes !== input.id && state.records?.some((record) => record.id === input.supersedes && record.kind === "decision" && record.status === "confirmed"), "INVALID_SUPERSEDED_RECORD");
259
+ }
260
+ const author = principal(actor), manual = author.kind === "human" && !forceDraft;
261
+ (state.records ??= []).push({
262
+ ...input,
263
+ author,
264
+ origin: manual ? "manual" : "flow",
265
+ status: manual && input.kind === "log" ? "confirmed" : "draft",
266
+ revision: 1,
267
+ createdAt: now,
268
+ updatedAt: now
269
+ });
270
+ }
271
+ function validateCoordination(state, input) {
272
+ requireValue(input.kind === "decision", "DECISION_COORDINATION_ONLY");
273
+ for (const owner of [input.coordination.manager, input.coordination.executor].filter(Boolean)) {
274
+ requireValue(owner && ["agent", "human", "service"].includes(owner.kind), "INVALID_PRINCIPAL");
275
+ identity(owner.id);
276
+ const member = state.board.members?.find((member2) => principalKey(member2) === principalKey(owner));
277
+ requireValue(member, "ASSIGNEE_NOT_REGISTERED");
278
+ if (owner === input.coordination.manager) requireValue(member.roles?.includes("coordinator"), "COORDINATOR_REQUIRED");
279
+ }
280
+ }
281
+ function validateItems(state, ids) {
282
+ requireValue(Array.isArray(ids) && ids.length <= 100 && new Set(ids).size === ids.length, "RECORD_LINK_LIMIT");
283
+ for (const id of ids) {
284
+ identity(id);
285
+ requireValue(state.board.items.some((item) => item.id === id) || state.archiveIndex?.some((item) => item.id === id), "ITEM_NOT_FOUND");
286
+ }
287
+ }
288
+ function supersede(state, record, now) {
289
+ if (!record.supersedes) return;
290
+ const previous = state.records?.find((entry) => entry.id === record.supersedes);
291
+ requireValue(previous?.kind === "decision" && previous.status === "confirmed", "SUPERSEDED_RECORD_CHANGED");
292
+ previous.status = "superseded";
293
+ previous.supersededBy = record.id;
294
+ previous.revision++;
295
+ previous.updatedAt = now;
296
+ }
297
+ function queryRecords(state, query = {}, summaries = (state.records ?? []).map(recordSummary)) {
298
+ const { cursor, ...filter } = query, limit = query.limit ?? 50;
299
+ requireValue(Number.isSafeInteger(limit) && limit > 0 && limit <= 200, "INVALID_LIMIT");
300
+ if (query.kind) requireValue(["log", "decision"].includes(query.kind), "INVALID_RECORD_KIND");
301
+ if (query.itemId !== void 0) identity(query.itemId);
302
+ if (query.status) requireValue(["draft", "confirmed", "rejected", "superseded"].includes(query.status), "INVALID_RECORD_STATUS");
303
+ const digest = sha256HexSync(JSON.stringify(filter));
304
+ let offset = 0;
305
+ if (cursor) {
306
+ let decoded;
307
+ try {
308
+ decoded = JSON.parse(decodeURIComponent(cursor));
309
+ } catch {
310
+ requireValue(false, "INVALID_CURSOR");
311
+ }
312
+ requireValue(decoded && typeof decoded === "object" && !Array.isArray(decoded) && typeof decoded.filter === "string" && typeof decoded.revision === "number", "INVALID_CURSOR");
313
+ requireValue(decoded.revision === state.board.revision && decoded.filter === digest, "CURSOR_STALE");
314
+ offset = decoded.offset;
315
+ requireValue(Number.isSafeInteger(offset) && offset >= 0, "INVALID_CURSOR");
316
+ }
317
+ const matched = summaries.filter((record) => (!query.kind || query.kind === record.kind) && (!query.itemId || record.itemIds.includes(query.itemId)) && (!query.status || query.status === record.status)).sort((a, b) => b.createdAt - a.createdAt || a.id.localeCompare(b.id));
318
+ const items = matched.slice(offset, offset + limit);
319
+ return { revision: state.board.revision, total: matched.length, items, ...offset + limit < matched.length ? { nextCursor: encodeURIComponent(JSON.stringify({ revision: state.board.revision, filter: digest, offset: offset + limit })) } : {} };
320
+ }
321
+ function recordFingerprint(record) {
322
+ return sha256HexSync(JSON.stringify({
323
+ kind: record.kind,
324
+ title: record.title,
325
+ content: record.content,
326
+ rationale: record.rationale ?? null,
327
+ itemIds: [...record.itemIds].sort(),
328
+ sources: record.sources.map((source) => JSON.stringify([source.sessionId, source.messageId, source.role])).sort(),
329
+ ...record.coordination ? { coordination: record.coordination } : {},
330
+ ...record.externalRefs ? { externalRefs: record.externalRefs } : {}
331
+ }));
332
+ }
333
+ function validateRecordReferences(refs) {
334
+ if (refs === void 0) return;
335
+ requireValue(Array.isArray(refs) && refs.length <= 100, "REFERENCE_LIMIT");
336
+ const keys = /* @__PURE__ */ new Set();
337
+ for (const ref of refs) {
338
+ requireValue(ref && typeof ref === "object", "INVALID_REFERENCE");
339
+ identity(ref.system);
340
+ identity(ref.id);
341
+ if (ref.revision !== void 0) text(ref.revision);
342
+ const key = JSON.stringify([ref.system, ref.id]);
343
+ requireValue(!keys.has(key), "DUPLICATE_REFERENCE");
344
+ keys.add(key);
345
+ }
346
+ }
347
+ function recordSummary(record) {
348
+ const { content: _content, rationale: _rationale, sources, ...metadata } = record;
349
+ return { ...metadata, sessionIds: [...new Set(sources.map((source) => source.sessionId))] };
350
+ }
351
+
352
+ // src/board.ts
353
+ function createBoardState(input, actor, now) {
354
+ const board = { ...structuredClone(input), policy: policy(input.policy), revision: 1, items: [], participants: [] };
355
+ validateBoard(board);
356
+ if (actor.sessionId) participant(board.participants, actor.sessionId, actor.agentId, "creator", true, now);
357
+ for (const session of board.policy.escalationSessionIds) participant(board.participants, session, void 0, "escalation", true, now);
358
+ return { schema: 1, board, sequence: 0, events: [], escalations: [] };
359
+ }
360
+
361
+ // src/storage-codec.ts
362
+ var boardKey = (id) => `board/${encodeURIComponent(id)}`;
363
+ var archiveKey = (board, item) => `archive/${encodeURIComponent(board)}/${encodeURIComponent(item)}`;
364
+ var rowKey = (kind, board, id) => `${kind}/${encodeURIComponent(board)}/${encodeURIComponent(id)}`;
365
+ function rowKeys(raw) {
366
+ if (raw === null) return [];
367
+ const saved = JSON.parse(raw);
368
+ if (saved.layout !== 2) return [];
369
+ requireValue(Array.isArray(saved.itemIds) && Array.isArray(saved.recordIds) && saved.state?.board, "INVALID_STORAGE");
370
+ return [...saved.itemIds.map((id) => rowKey("item", saved.state.board.id, id)), ...saved.recordIds.map((id) => rowKey("record", saved.state.board.id, id))];
371
+ }
372
+ async function hydrate(saved, bodies) {
373
+ if (saved.raw === null) return null;
374
+ const parsed = JSON.parse(saved.raw);
375
+ if (parsed.layout !== 2) return validateState(parsed);
376
+ const state = validateState(parsed.state), id = state.board.id;
377
+ state.board.items = await Promise.all(parsed.itemIds.map(async (itemId) => {
378
+ const item = await decodeRow(requiredRow(saved, rowKey("item", id, itemId)), bodies);
379
+ requireValue(item.id === itemId, "INVALID_STORAGE");
380
+ return item;
381
+ }));
382
+ state.records = await Promise.all(parsed.recordIds.map(async (recordId) => {
383
+ const record = await decodeRow(requiredRow(saved, rowKey("record", id, recordId)), bodies);
384
+ requireValue(record.id === recordId, "INVALID_STORAGE");
385
+ return record;
386
+ }));
387
+ return state;
388
+ }
389
+ async function encodeBoard(state, bodies) {
390
+ const rows = {}, id = state.board.id;
391
+ for (const item of state.board.items) rows[rowKey("item", id, item.id)] = await encodeRow(item, bodies);
392
+ for (const record of state.records ?? []) rows[rowKey("record", id, record.id)] = await encodeRow(record, bodies);
393
+ const manifest = {
394
+ itemIndex: state.board.items.map(summary),
395
+ recordIndex: (state.records ?? []).map(recordSummary),
396
+ layout: 2,
397
+ generation: randomUUID(),
398
+ state: { ...state, board: { ...state.board, items: [] }, records: [] },
399
+ itemIds: state.board.items.map((item) => item.id),
400
+ recordIds: (state.records ?? []).map((record) => record.id)
401
+ };
402
+ return { raw: JSON.stringify(manifest), rows };
403
+ }
404
+ function rowChanges(before, after) {
405
+ const writes = Object.entries(after.rows).filter(([key, value]) => before.rows[key] !== value).map(([key, value]) => ({ key, value }));
406
+ for (const key of Object.keys(before.rows)) if (!(key in after.rows)) writes.push({ key, value: null });
407
+ return writes;
408
+ }
409
+ function receiptDigest(fingerprint) {
410
+ return `sha256:v1:${sha256HexSync(fingerprint)}`;
411
+ }
412
+ function verifyReceipt(saved, fingerprint) {
413
+ requireValue(saved === fingerprint || saved === receiptDigest(fingerprint), "IDEMPOTENCY_CONFLICT");
414
+ }
415
+ async function encodeRow(value, bodies) {
416
+ const raw = JSON.stringify(value), bytes = new TextEncoder().encode(raw);
417
+ if (!bodies || bytes.length <= 8192) return raw;
418
+ const ref = { body: "kanban-body/v1", sha256: sha256HexSync(bytes), bytes: bytes.length };
419
+ const existing = await bodies.read(ref.sha256);
420
+ if (existing !== null) verifyBody(existing, ref);
421
+ else {
422
+ let failure;
423
+ try {
424
+ await bodies.write(ref.sha256, bytes.buffer);
425
+ } catch (error) {
426
+ failure = error;
427
+ }
428
+ const confirmed = await bodies.read(ref.sha256);
429
+ if (confirmed === null) throw failure ?? new KanbanError("BODY_WRITE_UNCONFIRMED");
430
+ verifyBody(confirmed, ref);
431
+ }
432
+ return JSON.stringify(ref);
433
+ }
434
+ async function decodeRow(raw, bodies) {
435
+ const parsed = JSON.parse(raw);
436
+ if (parsed?.body !== "kanban-body/v1") return parsed;
437
+ requireValue(/^[a-f0-9]{64}$/.test(parsed.sha256) && Number.isSafeInteger(parsed.bytes) && parsed.bytes > 8192, "INVALID_BODY_REFERENCE");
438
+ requireValue(bodies, "BODY_STORE_REQUIRED");
439
+ const bytes = await bodies.read(parsed.sha256);
440
+ requireValue(bytes !== null, "BODY_MISSING");
441
+ verifyBody(bytes, parsed);
442
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
443
+ }
444
+ function verifyBody(bytes, ref) {
445
+ requireValue(bytes instanceof ArrayBuffer && bytes.byteLength === ref.bytes && sha256HexSync(bytes) === ref.sha256, "BODY_INTEGRITY");
446
+ }
447
+ function requiredRow(saved, key) {
448
+ requireValue(typeof saved.rows[key] === "string", "MISSING_STORAGE_ROW");
449
+ return saved.rows[key];
450
+ }
451
+ function validateState(state) {
452
+ requireValue(state?.schema === 1 && state.board && Array.isArray(state.board.items) && Array.isArray(state.events), "INVALID_STORAGE");
453
+ return state;
454
+ }
455
+ function indexedView(raw) {
456
+ if (raw === null) return null;
457
+ const parsed = JSON.parse(raw);
458
+ if (parsed.layout === 2 && Array.isArray(parsed.itemIndex) && Array.isArray(parsed.recordIndex))
459
+ return { state: validateState(parsed.state), items: parsed.itemIndex, records: parsed.recordIndex };
460
+ return null;
461
+ }
462
+ function viewFromState(state) {
463
+ return { state: { ...state, board: { ...state.board, items: [] }, records: [] }, items: state.board.items.map(summary), records: (state.records ?? []).map(recordSummary) };
464
+ }
465
+
466
+ // src/numbering.ts
467
+ var boardCounterKey = "counter/board";
468
+ var boardNumberKey = (number) => `reference/board/${number}`;
469
+ function counter(raw) {
470
+ requireValue(raw === null || /^(0|[1-9]\d*)$/.test(raw), "INVALID_NUMBER_COUNTER");
471
+ const value = raw === null ? 0 : Number(raw);
472
+ requireValue(Number.isSafeInteger(value) && value >= 0 && value <= Number.MAX_SAFE_INTEGER, "INVALID_NUMBER_COUNTER");
473
+ return value;
474
+ }
475
+ function storedBoardNumber(raw) {
476
+ if (raw === null) return void 0;
477
+ const parsed = JSON.parse(raw), number = (parsed.layout === 2 ? parsed.state?.board : parsed.board)?.number;
478
+ if (number !== void 0) requireValue(Number.isSafeInteger(number) && number > 0, "INVALID_NUMBERING");
479
+ return number;
480
+ }
481
+ function patchBoardNumber(raw, number) {
482
+ const parsed = JSON.parse(raw);
483
+ parsed.state.board.number = number;
484
+ return JSON.stringify(parsed);
485
+ }
486
+ function numberEntities(state) {
487
+ const high = state.numbering ??= { item: 0, log: 0, decision: 0 };
488
+ const items = [...state.board.items, ...state.archiveIndex ?? [], ...(state.archiveWrites ?? []).flatMap((write) => write.value ? [write.value.item] : [])];
489
+ high.item = assign(items, high.item);
490
+ for (const kind of ["log", "decision"]) high[kind] = assign((state.records ?? []).filter((record) => record.kind === kind), high[kind]);
491
+ }
492
+ function assign(rows, high) {
493
+ counter(String(high));
494
+ const used = /* @__PURE__ */ new Map(), known = /* @__PURE__ */ new Map();
495
+ for (const row of rows) if (row.number !== void 0) {
496
+ requireValue(Number.isSafeInteger(row.number) && row.number > 0 && (!used.has(row.number) || used.get(row.number) === row.id) && (!known.has(row.id) || known.get(row.id) === row.number), "INVALID_NUMBERING");
497
+ used.set(row.number, row.id);
498
+ known.set(row.id, row.number);
499
+ high = Math.max(high, row.number);
500
+ }
501
+ for (const row of rows) if (row.number === void 0) {
502
+ if (!known.has(row.id)) {
503
+ requireValue(high < Number.MAX_SAFE_INTEGER, "NUMBER_COUNTER_EXHAUSTED");
504
+ known.set(row.id, ++high);
505
+ }
506
+ row.number = known.get(row.id);
507
+ }
508
+ return high;
509
+ }
510
+ function allocateBoardNumber(raw, high) {
511
+ const known = storedBoardNumber(raw);
512
+ if (known !== void 0) return known;
513
+ requireValue(high < Number.MAX_SAFE_INTEGER, "NUMBER_COUNTER_EXHAUSTED");
514
+ return high + 1;
515
+ }
516
+
517
+ // src/archives.ts
518
+ function archiveItems(state, ids, reason, now) {
519
+ text(reason);
520
+ requireValue(ids.length > 0 && ids.length <= 50 && new Set(ids).size === ids.length, "ARCHIVE_BATCH_LIMIT");
521
+ const items = ids.map((id) => state.board.items.find((i) => i.id === id));
522
+ requireValue(items.every((item) => item && terminal(item)), "ARCHIVE_REQUIRES_CLOSED_ITEM");
523
+ for (const item of items) {
524
+ const archived = { item, archivedAt: now, reason };
525
+ (state.archiveIndex ??= []).push({ ...summary(item), archivedAt: now, archiveReason: reason });
526
+ (state.archiveWrites ??= []).push({ id: item.id, value: archived });
527
+ }
528
+ const selected = new Set(ids);
529
+ state.board.items = state.board.items.filter((i) => !selected.has(i.id));
530
+ }
531
+ function restoreItem(state, id, now) {
532
+ const record = state.restore;
533
+ requireValue(record?.item.id === id && state.archiveIndex?.some((i) => i.id === id), "ARCHIVED_ITEM_NOT_FOUND");
534
+ requireValue(!state.board.items.some((i) => i.id === id), "ITEM_EXISTS");
535
+ record.item.restoredAt = now;
536
+ record.item.updatedAt = now;
537
+ record.item.revision++;
538
+ state.board.items.push(record.item);
539
+ state.archiveIndex = state.archiveIndex.filter((i) => i.id !== id);
540
+ (state.archiveWrites ??= []).push({ id, value: null });
541
+ delete state.restore;
542
+ }
543
+ function archiveExpired(state, now) {
544
+ const age = state.board.policy.archiveAfterMs;
545
+ if (age === void 0) return [];
546
+ const ids = state.board.items.filter((i) => terminal(i) && now - Math.max(i.closedAt ?? i.updatedAt, i.restoredAt ?? 0) >= age).slice(0, 50).map((i) => i.id);
547
+ if (ids.length) archiveItems(state, ids, "retention-policy", now);
548
+ return ids;
549
+ }
550
+
551
+ // src/planning-commands.ts
552
+ function planningCommand(command) {
553
+ return ["edit-item", "plan-item", "set-stage", "publish-proposal", "cancel-item", "close-plan", "archive-items", "restore-item", "block-item", "unblock-item", "link-reference", "release-item"].includes(command.type);
554
+ }
555
+ function applyPlanningCommand(state, command, now, actor, internal = false) {
556
+ if (command.type === "archive-items") return archiveItems(state, command.itemIds, command.reason, now);
557
+ if (command.type === "restore-item") return restoreItem(state, command.itemId, now);
558
+ const item = state.board.items.find((i) => i.id === command.itemId);
559
+ requireValue(item, "ITEM_NOT_FOUND");
560
+ if (isOperational(command)) operate(item, command, now, actor);
561
+ else {
562
+ if (!internal && ["edit-item", "plan-item", "review-amendment"].includes(command.type)) assertDefinitionEditable(item, now);
563
+ updatePlan(state, item, command, now);
564
+ }
565
+ }
566
+ function isOperational(command) {
567
+ return ["block-item", "unblock-item", "link-reference", "release-item"].includes(command.type);
568
+ }
569
+ function operate(item, command, now, actor) {
570
+ if (command.type === "release-item") {
571
+ requireValue(["claimed", "review"].includes(item.status) && item.owner?.token === command.token, "OWNER_MISMATCH");
572
+ requireValue(["backlog", "cancelled"].includes(command.next), "INVALID_STAGE");
573
+ text(command.reason);
574
+ item.status = command.next;
575
+ if (command.next === "cancelled") {
576
+ item.closedAt = now;
577
+ item.closureReason = command.reason;
578
+ }
579
+ delete item.owner;
580
+ delete item.transfer;
581
+ delete item.estimate;
582
+ } else if (command.type === "link-reference") attachReference(item, command.reference);
583
+ else {
584
+ requireValue(!terminal(item), "ITEM_COMPLETED");
585
+ if (item.status === "claimed") owned(item, actor, command.token ?? "", now);
586
+ if (command.type === "block-item") {
587
+ text(command.reason);
588
+ item.blocked = { reason: command.reason, at: now };
589
+ } else delete item.blocked;
590
+ }
591
+ item.updatedAt = now;
592
+ item.revision++;
593
+ }
594
+ function updatePlan(state, item, command, now) {
595
+ if (command.type === "cancel-item") requireValue(item.launch?.admittedAt === void 0, "TASK_CONTROL_REQUIRED");
596
+ if (command.type === "publish-proposal") {
597
+ requireValue(item.status === "proposed", "NOT_PROPOSED");
598
+ return setStage(state, item, command.stage ?? "backlog", now);
599
+ }
600
+ if (command.type === "set-stage") return setStage(state, item, command.stage, now);
601
+ requireValue(["proposed", "backlog", "open"].includes(item.status), "ITEM_NOT_PLANNABLE");
602
+ if (command.type === "edit-item") {
603
+ text(command.title);
604
+ text(command.responsibility);
605
+ text(command.acceptance);
606
+ item.title = command.title;
607
+ item.responsibility = command.responsibility;
608
+ item.acceptance = command.acceptance;
609
+ if (item.status === "open") return setStage(state, item, "backlog", now);
610
+ } else if (command.type === "plan-item") {
611
+ validatePlan(state, item, command.planning);
612
+ item.planning = command.planning;
613
+ if (item.status === "open") return setStage(state, item, "backlog", now);
614
+ } else {
615
+ requireValue(catalog(state).filter((i) => i.planning.parentId === item.id).every(terminal), "CHILDREN_UNFINISHED");
616
+ if (command.type === "close-plan") {
617
+ requireValue(!executable(state.board, item), "TASK_REQUIRES_REVIEW");
618
+ text(command.resultRef);
619
+ const children = catalog(state).filter((child) => child.planning.parentId === item.id);
620
+ if (item.planning?.execution === "children") requireValue(children.length > 0 && children.every((child) => child.status === "completed"), "CHILDREN_UNFINISHED");
621
+ item.status = "completed";
622
+ item.resultRef = command.resultRef;
623
+ } else {
624
+ text(command.reason);
625
+ item.status = "cancelled";
626
+ item.closureReason = command.reason;
627
+ }
628
+ item.closedAt = now;
629
+ }
630
+ item.updatedAt = now;
631
+ item.revision++;
632
+ }
633
+ function attachReference(item, reference) {
634
+ identity(reference.system);
635
+ identity(reference.id);
636
+ if (reference.revision !== void 0) text(reference.revision);
637
+ item.externalRefs ??= [];
638
+ if (item.externalRefs.some((r) => r.system === reference.system && r.id === reference.id && r.revision === reference.revision)) return;
639
+ requireValue(item.externalRefs.length < 100, "REFERENCE_LIMIT");
640
+ item.externalRefs.push(reference);
641
+ }
642
+
643
+ // src/workflow-plans.ts
644
+ function requireCoordinator(state, actor) {
645
+ requireValue(state.board.members?.some((member) => principalKey(member) === principalKey(principal(actor)) && member.roles?.includes("coordinator")), "COORDINATOR_REQUIRED");
646
+ }
647
+ function publishPlan(state, plan2, actor, apply) {
648
+ requireCoordinator(state, actor);
649
+ requireValue(plan2 && typeof plan2 === "object", "INVALID_WORK_PLAN");
650
+ identity(plan2.id);
651
+ requireValue(plan2.schema === "kanban.plan/1" && typeof plan2.sealed === "boolean" && Array.isArray(plan2.items) && plan2.items.length > 0 && plan2.items.length <= 100, "INVALID_WORK_PLAN");
652
+ const workflow = state.workflow, previous = workflow.plans[plan2.id];
653
+ requireValue(Number.isSafeInteger(plan2.revision) && plan2.revision === (previous?.revision ?? 0) + 1, "PLAN_REVISION_CONFLICT");
654
+ requireValue(!Object.values(workflow.dispatches).some((dispatch) => dispatch.planId === plan2.id && ["prepared", "running", "unknown", "succeeded"].includes(dispatch.outcome)), "PLAN_EXECUTION_UNSETTLED");
655
+ if (plan2.decisionId) {
656
+ const decision = state.records?.find((record) => record.id === plan2.decisionId && record.kind === "decision" && record.status === "confirmed");
657
+ requireValue(decision, "DECISION_NOT_CONFIRMED");
658
+ if (decision.coordination) requireValue(principalKey(decision.coordination.manager) === principalKey(principal(actor)), "DECISION_MANAGER_REQUIRED");
659
+ }
660
+ if (plan2.rootItemId) {
661
+ const root = state.board.items.find((item) => item.id === plan2.rootItemId);
662
+ requireValue(root && !root.owner && ["backlog", "open"].includes(root.status), "PLAN_ROOT_UNAVAILABLE");
663
+ if (root.planning?.execution !== "children") apply({ type: "plan-item", itemId: root.id, planning: { ...plan(root), execution: "children" } });
664
+ }
665
+ const ordered = orderWork(plan2.items, state), definitions = {};
666
+ for (const item of ordered) {
667
+ const digest = sha256HexSync(JSON.stringify(item));
668
+ requireValue(!Object.values(workflow.plans).some((other) => other.id !== plan2.id && other.itemIds.includes(item.id)), "ITEM_IN_OTHER_PLAN");
669
+ const exists = state.board.items.some((old) => old.id === item.id) || state.archiveIndex?.some((old) => old.id === item.id);
670
+ if (exists && previous?.definitions[item.id]?.digest !== digest) {
671
+ requireValue(!previous?.definitions[item.id], "PLAN_ITEM_CHANGED_REQUIRES_NEW_ID");
672
+ adoptItem(state, item, apply);
673
+ }
674
+ if (!exists) apply({
675
+ type: "create-item",
676
+ item: { id: item.id, title: item.title, responsibility: item.responsibility, acceptance: item.acceptance, eligiblePrincipals: [item.assignee], externalRefs: item.externalRefs },
677
+ planning: { kind: item.workType ?? state.board.defaultWorkType ?? "task", priority: 2, dependencies: item.dependsOn, references: [], ...plan2.rootItemId ? { parentId: plan2.rootItemId } : {} }
678
+ });
679
+ definitions[item.id] = { digest, inputs: item.inputs, outputs: item.outputs ?? [] };
680
+ }
681
+ workflow.plans[plan2.id] = { schema: plan2.schema, id: plan2.id, revision: plan2.revision, decisionId: plan2.decisionId, rootItemId: plan2.rootItemId, sealed: plan2.sealed, itemIds: ordered.map((item) => item.id), definitions };
682
+ }
683
+ function adoptItem(state, definition, apply) {
684
+ const item = state.board.items.find((item2) => item2.id === definition.id);
685
+ requireValue(item && definition.expectedRevision === item.revision && ["backlog", "open"].includes(item.status) && !item.owner && !item.blocked, "PLAN_ITEM_CHANGED_REQUIRES_NEW_ID");
686
+ requireValue(!definition.workType || definition.workType === item.planning?.kind, "PLAN_ITEM_CHANGED_REQUIRES_NEW_ID");
687
+ requireValue(!definition.externalRefs || definition.externalRefs.every((ref) => item.externalRefs?.some((existing) => JSON.stringify(existing) === JSON.stringify(ref))), "PLAN_RESOURCE_MISMATCH");
688
+ requireValue(item.title === definition.title && item.responsibility === definition.responsibility && item.acceptance === definition.acceptance, "PLAN_ITEM_CHANGED_REQUIRES_NEW_ID");
689
+ requireValue(plan(item).dependencies.every((id) => definition.dependsOn.includes(id)), "EXISTING_DEPENDENCY_REQUIRED");
690
+ apply({ type: "plan-item", itemId: item.id, planning: { ...plan(item), dependencies: definition.dependsOn } });
691
+ item.eligiblePrincipals = [definition.assignee];
692
+ delete item.eligibleAgentIds;
693
+ validateCandidates(state.board, item, true);
694
+ }
695
+ function orderWork(items, state) {
696
+ for (const item of items) validateDefinition(item);
697
+ const ids = new Set(items.map((item) => item.id));
698
+ requireValue(ids.size === items.length, "DUPLICATE_PLAN_ITEM");
699
+ for (const item of items) {
700
+ identity(item.id);
701
+ requireValue(Array.isArray(item.dependsOn) && item.dependsOn.length <= 100 && new Set(item.dependsOn).size === item.dependsOn.length, "INVALID_DEPENDENCIES");
702
+ requireValue(Object.keys(item.inputs ?? {}).length <= 100 && Array.isArray(item.outputs ?? []) && (item.outputs ?? []).length <= 100 && new Set(item.outputs ?? []).size === (item.outputs ?? []).length, "PLAN_BINDING_LIMIT");
703
+ for (const name of [...Object.keys(item.inputs ?? {}), ...item.outputs ?? []]) requireValue(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(name), "INVALID_OUTPUT_NAME");
704
+ for (const binding of Object.values(item.inputs ?? {})) {
705
+ requireValue(binding && item.dependsOn.includes(binding.fromItemId) && typeof binding.output === "string", "INPUT_DEPENDENCY_REQUIRED");
706
+ const producer = items.find((other) => other.id === binding.fromItemId), existing = Object.values(state.workflow.dispatches).some((dispatch) => dispatch.itemId === binding.fromItemId && dispatch.outcome === "accepted" && dispatch.outputs?.some((output) => output.name === binding.output));
707
+ requireValue(producer ? producer.outputs?.includes(binding.output) : existing, "OUTPUT_NOT_DECLARED");
708
+ }
709
+ for (const dependency of item.dependsOn) requireValue(ids.has(dependency) || [...state.board.items, ...state.archiveIndex ?? []].some((old) => old.id === dependency), "DEPENDENCY_NOT_FOUND");
710
+ }
711
+ const ordered = [], remaining = [...items], done = /* @__PURE__ */ new Set();
712
+ while (remaining.length) {
713
+ const next = remaining.findIndex((item2) => item2.dependsOn.every((id) => !ids.has(id) || done.has(id)));
714
+ requireValue(next >= 0, "DEPENDENCY_CYCLE");
715
+ const [item] = remaining.splice(next, 1);
716
+ ordered.push(item);
717
+ done.add(item.id);
718
+ }
719
+ return ordered;
720
+ }
721
+ function validateDefinition(item) {
722
+ requireValue(item && typeof item === "object" && !Array.isArray(item), "INVALID_WORK_DEFINITION");
723
+ const assignee = item.assignee;
724
+ requireValue(assignee && ["agent", "human", "service"].includes(assignee.kind), "INVALID_PRINCIPAL");
725
+ identity(assignee.id);
726
+ if (item.inputs !== void 0) requireValue(item.inputs && typeof item.inputs === "object" && !Array.isArray(item.inputs), "INVALID_INPUT_BINDINGS");
727
+ if (item.outputs !== void 0) requireValue(Array.isArray(item.outputs) && item.outputs.every((name) => typeof name === "string"), "INVALID_OUTPUT_NAMES");
728
+ }
729
+
730
+ // src/task-commands.ts
731
+ var types = ["set-launch-mode", "retry-analysis", "begin-edit", "end-edit", "save-edit", "request-run", "admit-item", "report-analysis", "request-control", "control-receipt", "report-issue", "resolve-issue"];
732
+ function taskCommand(command) {
733
+ return types.includes(command.type);
734
+ }
735
+ function assertDefinitionEditable(item, now, editId, actor) {
736
+ requireValue(["proposed", "backlog", "open"].includes(item.status) && !item.owner && item.launch?.admittedAt === void 0, "TASK_DEFINITION_FROZEN");
737
+ if (taskEditing(item, now)) requireValue(item.launch.editing.id === editId && !!actor && principalKey(item.launch.editing.principal) === principalKey(principal(actor)), "EDIT_LEASE_ACTIVE");
738
+ }
739
+ function applyTaskCommand(state, command, actor, now) {
740
+ const item = state.board.items.find((i) => i.id === command.itemId);
741
+ requireValue(item, "ITEM_NOT_FOUND");
742
+ item.launch ??= { startAt: taskStartAt(item) };
743
+ if (["begin-edit", "end-edit", "save-edit"].includes(command.type)) edit(state, item, command, actor, now);
744
+ else if (command.type === "retry-analysis") {
745
+ identity(command.retryId);
746
+ requireValue(["failed", "clarification"].includes(item.analysis?.state ?? "") && !item.owner, "ANALYSIS_NOT_RETRYABLE");
747
+ item.launch.analysisEpoch = command.retryId;
748
+ delete item.analysis;
749
+ } else if (command.type === "set-launch-mode") {
750
+ assertDefinitionEditable(item, now);
751
+ setMode(item, command.mode);
752
+ } else if (command.type === "request-run") {
753
+ assertDefinitionEditable(item, now);
754
+ item.launch.requestedAt ??= now;
755
+ } else if (command.type === "admit-item") {
756
+ requireCoordinator(state, actor);
757
+ assertDefinitionEditable(item, now);
758
+ requireValue(boardAllowsStart(state.board, item), "BOARD_EXECUTION_PAUSED");
759
+ requireValue(command.trigger === "manual" ? item.launch.requestedAt !== void 0 : taskDue(item, now), "START_NOT_DUE");
760
+ requireValue(!item.blocked && item.control?.action !== "pause", "ITEM_BLOCKED");
761
+ requireValue(item.planning?.dependencies.every((id) => catalog(state).find((i) => i.id === id)?.status === "completed") ?? true, "DEPENDENCIES_UNFINISHED");
762
+ item.launch.admittedAt = now;
763
+ } else if (command.type === "report-analysis") {
764
+ requireCoordinator(state, actor);
765
+ identity(command.operationId);
766
+ requireValue(command.status.itemId === item.id, "ANALYSIS_SCOPE_MISMATCH");
767
+ item.analysis = structuredClone(command.status);
768
+ } else if (command.type === "request-control") requestControl(state, item, command);
769
+ else if (command.type === "control-receipt") {
770
+ requireCoordinator(state, actor);
771
+ requireValue(item.control?.id === command.controlId, "STALE_CONTROL_RECEIPT");
772
+ requireValue(["accepted", "paused", "resumed", "failed", "unknown"].includes(command.state), "INVALID_CONTROL_STATE");
773
+ item.control.state = command.state;
774
+ item.control.code = command.code;
775
+ } else issues(state, item, command, actor);
776
+ item.updatedAt = now;
777
+ item.revision++;
778
+ }
779
+ function edit(state, item, command, actor, now) {
780
+ if (command.type === "begin-edit") {
781
+ assertDefinitionEditable(item, now, command.editId, actor);
782
+ identity(command.editId);
783
+ requireValue(Number.isSafeInteger(command.leaseMs) && command.leaseMs >= 1e3 && command.leaseMs <= 3e5, "INVALID_EDIT_LEASE");
784
+ item.launch.editing = { id: command.editId, principal: principal(actor), expiresAt: now + command.leaseMs };
785
+ return;
786
+ }
787
+ if (command.type !== "save-edit" && command.type !== "end-edit") return;
788
+ assertDefinitionEditable(item, now, command.editId, actor);
789
+ requireValue(taskEditing(item, now) && item.launch.editing.id === command.editId, "EDIT_LEASE_EXPIRED");
790
+ if (command.type === "save-edit") {
791
+ text(command.title);
792
+ text(command.responsibility);
793
+ text(command.acceptance);
794
+ validatePlan(state, item, command.planning);
795
+ if (command.launchMode !== void 0) setMode(item, command.launchMode);
796
+ Object.assign(item, { title: command.title, responsibility: command.responsibility, acceptance: command.acceptance, planning: command.planning });
797
+ if (command.externalRefs) {
798
+ item.externalRefs = [];
799
+ for (const ref of command.externalRefs) attachReference(item, ref);
800
+ }
801
+ }
802
+ if (command.type === "save-edit") for (const plan2 of Object.values(state.workflow?.plans ?? {})) {
803
+ const definition = plan2.definitions[item.id];
804
+ if (!definition) continue;
805
+ requireValue(Object.values(definition.inputs ?? {}).every((binding) => item.planning?.dependencies.includes(binding.fromItemId)), "EXISTING_DEPENDENCY_REQUIRED");
806
+ definition.digest = sha256HexSync(JSON.stringify([item.title, item.responsibility, item.acceptance, item.planning, item.externalRefs, definition.inputs, definition.outputs]));
807
+ }
808
+ delete item.launch.editing;
809
+ }
810
+ function requestControl(state, item, command) {
811
+ requireValue(!["completed", "cancelled", "review"].includes(item.status), "ITEM_COMPLETED");
812
+ identity(command.controlId);
813
+ requireValue(["pause", "resume"].includes(command.action), "INVALID_CONTROL_ACTION");
814
+ if (item.control?.id === command.controlId) {
815
+ requireValue(item.control.action === command.action, "IDEMPOTENCY_CONFLICT");
816
+ return;
817
+ }
818
+ requireValue(!item.control || !["requested", "unknown"].includes(item.control.state), "CONTROL_UNSETTLED");
819
+ const dispatch = Object.values(state.workflow?.dispatches ?? {}).find((d) => d.itemId === item.id && ["prepared", "running", "unknown"].includes(d.outcome));
820
+ requireValue(dispatch || item.launch?.admittedAt === void 0, "TASK_CONTROL_UNSUPPORTED");
821
+ requireValue(command.action === "pause" || item.control?.action === "pause", "TASK_NOT_PAUSED");
822
+ item.control = { id: command.controlId, dispatchId: dispatch?.id, action: command.action, state: "requested" };
823
+ }
824
+ function issues(state, item, command, actor) {
825
+ requireCoordinator(state, actor);
826
+ if (command.type === "report-issue") {
827
+ const issue = command.issue;
828
+ identity(issue.id);
829
+ identity(issue.attemptId);
830
+ requireValue(!issue.resolvedBy && ["clarification", "error"].includes(issue.type), "INVALID_ISSUE");
831
+ requireValue(state.workflow?.dispatches[issue.attemptId]?.itemId === item.id && item.owner?.token === state.workflow.dispatches[issue.attemptId].fence, "STALE_EXECUTION_RESULT");
832
+ item.issues ??= [];
833
+ const old = item.issues.find((i) => i.id === issue.id && i.attemptId === issue.attemptId);
834
+ if (!old) {
835
+ requireValue(item.issues.length < 200, "ISSUE_LIMIT");
836
+ item.issues.push(structuredClone(issue));
837
+ }
838
+ } else if (command.type === "resolve-issue") {
839
+ const issue = item.issues?.find((i) => i.id === command.issueId && i.attemptId === command.attemptId);
840
+ requireValue(issue, "ISSUE_NOT_FOUND");
841
+ identity(command.resolvedBy);
842
+ requireValue(!issue.resolvedBy || issue.resolvedBy === command.resolvedBy, "ISSUE_ALREADY_RESOLVED");
843
+ issue.resolvedBy = command.resolvedBy;
844
+ }
845
+ }
846
+ function initializeTaskLaunch(state, item) {
847
+ if (item.launch) return false;
848
+ const first = Object.values(state.workflow?.dispatches ?? {}).filter((d) => d.itemId === item.id).sort((a, b) => a.attempt - b.attempt)[0];
849
+ const admittedAt = first?.preparedAt ?? item.owner?.claimedAt;
850
+ item.launch = { startAt: taskStartAt(item), ...admittedAt === void 0 ? {} : { admittedAt } };
851
+ item.revision++;
852
+ return true;
853
+ }
854
+ function setMode(item, mode) {
855
+ requireValue(["automatic", "manual"].includes(mode), "INVALID_LAUNCH_MODE");
856
+ item.launch.mode = mode;
857
+ delete item.launch.requestedAt;
858
+ }
859
+
860
+ // src/board-control.ts
861
+ function setBoardControl(state, command, actor, now, token) {
862
+ requireValue(actor.kind === "human", "FORBIDDEN");
863
+ requireValue(command.mode !== void 0 || command.paused !== void 0, "INVALID_BOARD_CONTROL");
864
+ requireValue(command.mode === void 0 || ["automatic", "manual"].includes(command.mode), "INVALID_LAUNCH_MODE");
865
+ requireValue(command.paused === void 0 || typeof command.paused === "boolean", "INVALID_BOARD_CONTROL");
866
+ const policy2 = state.board.executionControl ??= { mode: "automatic", paused: false, controls: {} };
867
+ if (command.mode) policy2.mode = command.mode;
868
+ if (command.paused === void 0 || command.paused === policy2.paused) return;
869
+ if (!command.paused) requireValue(!state.board.items.some((item) => policy2.controls[item.id] === item.control?.id && ["requested", "unknown"].includes(item.control.state)), "CONTROL_UNSETTLED");
870
+ policy2.paused = command.paused;
871
+ if (policy2.paused) policy2.controls = {};
872
+ state.board.items.forEach((item, index) => {
873
+ if (["completed", "cancelled", "review"].includes(item.status)) return;
874
+ const active = Object.values(state.workflow?.dispatches ?? {}).some((d) => d.itemId === item.id && ["prepared", "running", "unknown"].includes(d.outcome));
875
+ const managed = policy2.controls[item.id] === item.control?.id;
876
+ if (policy2.paused ? !active || item.control?.action === "pause" : !managed || item.control?.action !== "pause") return;
877
+ if (item.control && ["requested", "unknown"].includes(item.control.state)) return;
878
+ const controlId = token + "-" + index;
879
+ applyTaskCommand(state, { type: "request-control", itemId: item.id, controlId, action: policy2.paused ? "pause" : "resume" }, actor, now);
880
+ policy2.controls[item.id] = controlId;
881
+ });
882
+ }
883
+
884
+ // src/scan-commit.ts
885
+ function applyDiscovery(state, batch, actor, now) {
886
+ const discovery = discoveryState(state), pending = discovery?.pending;
887
+ requireValue(pending && pending.runId === batch.runId && pending.token === batch.leaseToken && pending.leaseUntil > now, "SCAN_LEASE_EXPIRED");
888
+ requireValue(pending.request?.command.type === "apply-discovery" && JSON.stringify(pending.request.command.batch) === JSON.stringify(batch), "SCAN_BATCH_MISMATCH");
889
+ requireValue(batch.changes.length <= 50, "SCAN_CHANGE_LIMIT");
890
+ for (const change of batch.changes) {
891
+ identity(change.itemId);
892
+ validateSources(change.sources);
893
+ requireValue(change.sources.length > 0 && change.sources.some((s) => s.role === "user"), "USER_EVIDENCE_REQUIRED");
894
+ const item = change.action === "create" ? createItem(state, change, actor, now, batch.autoCreate, batch.runId) : updateItem(state, change, actor, now, batch.runId);
895
+ if (item) attachSources(item, change, now);
896
+ }
897
+ requireValue((batch.records?.length ?? 0) <= 20, "SCAN_RECORD_LIMIT");
898
+ for (const record of batch.records ?? []) {
899
+ requireValue(record.sources.some((source) => source.role === "user"), "USER_EVIDENCE_REQUIRED");
900
+ const duplicate = state.records?.some((old) => recordFingerprint(old) === recordFingerprint(record));
901
+ if (!duplicate) {
902
+ applyRecord(state, { type: "append-record", record }, actor, now, true);
903
+ state.records.find((entry) => entry.id === record.id).originRunId = batch.runId;
904
+ }
905
+ }
906
+ for (const checkpoint of batch.checkpoints) discovery.checkpoints[checkpoint.sessionId] = checkpoint.revision;
907
+ discovery.lastRun = { runId: batch.runId, outcome: "committed", at: now };
908
+ delete discovery.pending;
909
+ }
910
+ function createItem(state, change, actor, now, autoCreate, runId) {
911
+ text(change.title);
912
+ text(change.responsibility);
913
+ text(change.acceptance);
914
+ const item = {
915
+ origin: { kind: "discovery", principal: principal(actor), runId },
916
+ id: change.itemId,
917
+ title: change.title,
918
+ responsibility: change.responsibility,
919
+ acceptance: change.acceptance,
920
+ eligibleAgentIds: change.eligibleAgentIds,
921
+ eligiblePrincipals: change.eligiblePrincipals,
922
+ status: "proposed",
923
+ revision: 1,
924
+ createdAt: now,
925
+ readyAt: now,
926
+ updatedAt: now,
927
+ workUnits: 0,
928
+ participants: [],
929
+ sources: []
930
+ };
931
+ item.launch = { startAt: now + TASK_START_DELAY_MS };
932
+ item.planning = change.planning ?? { ...plan(item), kind: state.board.defaultWorkType ?? "task" };
933
+ const fingerprint = workFingerprint(item);
934
+ item.origin.fingerprint = fingerprint;
935
+ validateCandidates(state.board, item, executable(state.board, item));
936
+ if (state.archiveIndex?.some((old) => old.discoveryFingerprint === fingerprint)) return void 0;
937
+ const existing = state.board.items.find((old) => workFingerprint(old) === fingerprint || old.origin?.fingerprint === fingerprint);
938
+ if (existing) {
939
+ existing.revision++;
940
+ existing.updatedAt = now;
941
+ return existing;
942
+ }
943
+ requireValue(!state.board.items.some((old) => old.id === change.itemId) && !state.archiveIndex?.some((old) => old.id === change.itemId), "ITEM_EXISTS");
944
+ validatePlan(state, item, item.planning);
945
+ state.board.items.push(item);
946
+ if (autoCreate) setStage(state, item, automaticStage(state, item), now);
947
+ if (actor.sessionId) participant(item.participants, actor.sessionId, actor.agentId, "creator", true, now);
948
+ return item;
949
+ }
950
+ function updateItem(state, change, actor, now, runId) {
951
+ const item = state.board.items.find((i) => i.id === change.itemId);
952
+ requireValue(item, "ITEM_NOT_FOUND");
953
+ if (change.action === "update") {
954
+ requireValue(!change.planning, "SCAN_PLANNING_REQUIRES_REVIEW");
955
+ const ownDraft = item.status === "proposed" && item.origin?.kind === "discovery" && principalKey(item.origin.principal) === principalKey(principal(actor));
956
+ if (ownDraft) {
957
+ text(change.title);
958
+ text(change.responsibility);
959
+ text(change.acceptance);
960
+ item.title = change.title;
961
+ item.responsibility = change.responsibility;
962
+ item.acceptance = change.acceptance;
963
+ } else proposeAmendment(item, change, actor, now, runId);
964
+ } else requireValue(change.action === "link", "INVALID_CHANGE");
965
+ item.revision++;
966
+ item.updatedAt = now;
967
+ return item;
968
+ }
969
+ function attachSources(item, change, now) {
970
+ for (const source of change.sources) {
971
+ const subscribed = item.participants.find((p) => p.sessionId === source.sessionId)?.subscribed ?? false;
972
+ participant(item.participants, source.sessionId, void 0, source.role === "user" ? "creator" : "consultant", subscribed, now);
973
+ item.sources ??= [];
974
+ if (!item.sources.some((s) => s.sessionId === source.sessionId && s.messageId === source.messageId && s.revision === source.revision)) item.sources.push(source);
975
+ }
976
+ }
977
+
978
+ // src/automation.ts
979
+ function configureAutomation(board, settings, actor) {
980
+ requireValue(settings && typeof settings.enabled === "boolean" && typeof settings.autoAccept === "boolean", "INVALID_AUTOMATION");
981
+ for (const ref of [settings.planner, settings.executor, ...settings.preparation ? [settings.preparation] : []]) {
982
+ requireValue(ref && typeof ref === "object", "INVALID_AUTOMATION_TARGET");
983
+ identity(ref.system);
984
+ identity(ref.id);
985
+ identity(ref.revision ?? "");
986
+ }
987
+ validateOptions(settings.preparationOptions);
988
+ requireValue(settings.preparation || !Object.keys(settings.preparationOptions ?? {}).length, "PREPARATION_REQUIRED");
989
+ const members = [...board.members ?? [], ...(board.agents ?? []).filter((agent) => !board.members?.some((member) => member.kind === "agent" && member.id === agent.agentId)).map((agent) => ({ kind: "agent", id: agent.agentId, responsibility: agent.responsibility }))];
990
+ for (const [principal2, role] of [[settings.coordinator, "coordinator"], [settings.worker, "worker"]]) {
991
+ requireValue(principal2 && ["agent", "human", "service"].includes(principal2.kind), "INVALID_PRINCIPAL");
992
+ identity(principal2.id);
993
+ const existing = members.find((member) => member.kind === principal2.kind && member.id === principal2.id);
994
+ if (existing) existing.roles = [.../* @__PURE__ */ new Set([...existing.roles ?? [], role])];
995
+ else members.push({ ...principal2, responsibility: role, roles: [role] });
996
+ }
997
+ addReviewer(members, actor);
998
+ board.members = members;
999
+ delete board.agents;
1000
+ board.automation = structuredClone(settings);
1001
+ board.policy.review = settings.autoAccept ? "assignee" : "independent";
1002
+ validateBoard(board);
1003
+ }
1004
+ function addReviewer(members, actor) {
1005
+ if (actor.kind !== "human" || !actor.id) return;
1006
+ const existing = members.find((member) => member.kind === "human" && member.id === actor.id);
1007
+ if (existing) existing.roles = [.../* @__PURE__ */ new Set([...existing.roles ?? [], "reviewer", "coordinator"])];
1008
+ else members.push({ kind: "human", id: actor.id, responsibility: "Review work", roles: ["reviewer", "coordinator"] });
1009
+ }
1010
+ function validateOptions(options) {
1011
+ if (options === void 0) return;
1012
+ requireValue(options && typeof options === "object" && !Array.isArray(options) && Object.keys(options).length <= 16, "INVALID_PREPARATION_OPTIONS");
1013
+ for (const [key, value] of Object.entries(options)) {
1014
+ requireValue(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(key) && typeof value === "string" && value.length <= 4096, "INVALID_PREPARATION_OPTIONS");
1015
+ }
1016
+ }
1017
+
1018
+ // src/workflow-continuation.ts
1019
+ function continueExecution(state, command, actor, now, apply) {
1020
+ requireCoordinator(state, actor);
1021
+ identity(command.dispatchId);
1022
+ const workflow = state.workflow, previous = workflow.dispatches[command.previousDispatchId];
1023
+ requireValue(previous && ["failed", "cancelled"].includes(previous.outcome), "EXECUTION_NOT_CONTINUABLE");
1024
+ requireValue(!workflow.dispatches[command.dispatchId], "DISPATCH_EXISTS");
1025
+ const item = state.board.items.find((item2) => item2.id === previous.itemId), plan2 = workflow.plans[previous.planId];
1026
+ requireValue(item && ["backlog", "open"].includes(item.status) && !item.owner, "ITEM_NOT_CONTINUABLE");
1027
+ const attempts = Object.values(workflow.dispatches).filter((row) => row.itemId === item.id);
1028
+ requireValue(attempts.every((row) => row.attempt <= previous.attempt), "STALE_CONTINUATION");
1029
+ requireValue(!attempts.some((row) => ["prepared", "running", "unknown", "succeeded"].includes(row.outcome)), "EXECUTION_UNSETTLED");
1030
+ requireValue(plan2?.revision === previous.planRevision && plan2.definitions[item.id]?.digest === previous.definitionDigest, "PLAN_CHANGED");
1031
+ requireValue(command.instruction === void 0 || typeof command.instruction === "string" && command.instruction.trim().length > 0 && command.instruction.length <= 8e3, "INVALID_CONTINUATION_INSTRUCTION");
1032
+ requireValue(!item.blocked || item.blocked.reason === (previous.code ?? "EXECUTION_FAILED"), "ITEM_BLOCKED");
1033
+ delete item.blocked;
1034
+ if (item.status === "backlog") apply({ type: "set-stage", itemId: item.id, stage: "open" });
1035
+ apply({ type: "claim", itemId: item.id, estimate: item.estimate }, previous.principal);
1036
+ workflow.dispatches[command.dispatchId] = {
1037
+ id: command.dispatchId,
1038
+ itemId: item.id,
1039
+ itemRevision: item.revision,
1040
+ planId: previous.planId,
1041
+ planRevision: previous.planRevision,
1042
+ principal: previous.principal,
1043
+ definitionDigest: previous.definitionDigest,
1044
+ attempt: previous.attempt + 1,
1045
+ fence: item.owner.token,
1046
+ preparedAt: now,
1047
+ outcome: "prepared",
1048
+ inputs: structuredClone(previous.inputs),
1049
+ continuation: { previousDispatchId: previous.id, ...command.instruction ? { instruction: command.instruction } : {} }
1050
+ };
1051
+ }
1052
+
1053
+ // src/workflow.ts
1054
+ function isWorkflowCommand(command) {
1055
+ return ["publish-plan", "prepare-dispatch", "continue-execution", "observe-execution", "accept-execution"].includes(command.type);
1056
+ }
1057
+ function protectWorkflowItem(state, command) {
1058
+ if (command.type === "configure-automation" && Object.values(state.workflow?.dispatches ?? {}).some((dispatch) => ["prepared", "running", "unknown", "succeeded"].includes(dispatch.outcome))) {
1059
+ requireValue(sameAutomationBinding(state.board.automation, command.settings), "PLAN_EXECUTION_UNSETTLED");
1060
+ }
1061
+ if (!("itemId" in command) || !command.itemId || !state.workflow) return;
1062
+ const plan2 = Object.values(state.workflow.plans).find((plan3) => plan3.itemIds.includes(command.itemId));
1063
+ if (!plan2) return;
1064
+ requireValue(!["edit-item", "plan-item", "review-amendment"].includes(command.type), "PLAN_ITEM_CHANGED_REQUIRES_NEW_ID");
1065
+ if (plan2.sealed) requireValue(!["claim", "submit", "review", "close-plan"].includes(command.type), "WORKFLOW_COMMAND_REQUIRED");
1066
+ const live = Object.values(state.workflow.dispatches).some((dispatch) => dispatch.itemId === command.itemId && ["prepared", "running", "unknown", "succeeded"].includes(dispatch.outcome));
1067
+ if (live) requireValue(!["request-transfer", "accept-transfer", "release-item", "cancel-item"].includes(command.type), "EXECUTION_UNSETTLED");
1068
+ }
1069
+ function applyWorkflow(state, command, actor, now, apply) {
1070
+ state.workflow ??= { plans: {}, dispatches: {}, ready: [], completedPlans: [] };
1071
+ let changed = true;
1072
+ if (command.type === "publish-plan") publishPlan(state, command.plan, actor, apply);
1073
+ else if (command.type === "prepare-dispatch") prepare(state, command, actor, now, apply);
1074
+ else if (command.type === "continue-execution") {
1075
+ requireValue(!state.board.executionControl?.paused, "BOARD_EXECUTION_PAUSED");
1076
+ continueExecution(state, command, actor, now, apply);
1077
+ } else if (command.type === "observe-execution") changed = observe(state, command, actor, now);
1078
+ else accept(state, command, actor, apply);
1079
+ refreshReady(state);
1080
+ return changed;
1081
+ }
1082
+ function prepare(state, command, actor, now, apply) {
1083
+ identity(command.dispatchId);
1084
+ const workflow = state.workflow;
1085
+ requireValue(!workflow.dispatches[command.dispatchId], "DISPATCH_EXISTS");
1086
+ refreshReady(state);
1087
+ requireValue(workflow.ready.includes(command.itemId), "WORK_NOT_READY");
1088
+ const plan2 = Object.values(workflow.plans).find((plan3) => plan3.itemIds.includes(command.itemId));
1089
+ requireValue(!Object.values(workflow.dispatches).some((dispatch) => dispatch.itemId === command.itemId && ["prepared", "running", "unknown", "succeeded"].includes(dispatch.outcome)), "EXECUTION_UNSETTLED");
1090
+ const item = state.board.items.find((item2) => item2.id === command.itemId);
1091
+ if (item.status === "backlog") apply({ type: "set-stage", itemId: item.id, stage: "open" });
1092
+ requireValue(!taskEditing(item, now), "EDIT_LEASE_ACTIVE");
1093
+ requireValue(!state.board.executionControl?.paused, "BOARD_EXECUTION_PAUSED");
1094
+ if (command.trigger === "automatic") requireValue(boardAllowsStart(state.board, item) && taskDue(item, now), "START_NOT_DUE");
1095
+ item.launch ??= { startAt: taskStartAt(item) };
1096
+ item.launch.admittedAt ??= now;
1097
+ apply({ type: "claim", itemId: item.id, estimate: command.estimate });
1098
+ const inputs = {};
1099
+ for (const [name, binding] of Object.entries(plan2.definitions[item.id].inputs ?? {})) {
1100
+ const producer = Object.values(workflow.dispatches).reverse().find((dispatch) => dispatch.itemId === binding.fromItemId && dispatch.outcome === "accepted");
1101
+ const output = producer?.outputs?.find((output2) => output2.name === binding.output);
1102
+ requireValue(output, "DEPENDENCY_OUTPUT_MISSING");
1103
+ inputs[name] = structuredClone(output);
1104
+ }
1105
+ const attempt = Math.max(0, ...Object.values(workflow.dispatches).filter((dispatch) => dispatch.itemId === item.id).map((dispatch) => dispatch.attempt)) + 1;
1106
+ workflow.dispatches[command.dispatchId] = { id: command.dispatchId, itemId: item.id, itemRevision: item.revision, planId: plan2.id, planRevision: plan2.revision, principal: principal(actor), definitionDigest: plan2.definitions[item.id].digest, attempt, fence: item.owner.token, preparedAt: now, outcome: "prepared", inputs };
1107
+ }
1108
+ function observe(state, command, actor, now) {
1109
+ requireCoordinator(state, actor);
1110
+ const dispatch = activeDispatch(state, command.dispatchId);
1111
+ requireValue(command.fence === dispatch.fence && ["prepared", "running", "unknown"].includes(dispatch.outcome), "STALE_EXECUTION_RESULT");
1112
+ requireValue(["running", "unknown", "succeeded", "failed", "cancelled"].includes(command.outcome), "INVALID_EXECUTION_OUTCOME");
1113
+ if (command.code !== void 0) requireValue(/^[A-Z][A-Z0-9_]{0,79}$/.test(command.code), "INVALID_ERROR_CODE");
1114
+ const item = state.board.items.find((item2) => item2.id === dispatch.itemId);
1115
+ if (command.executionSessionId) {
1116
+ identity(command.executionSessionId);
1117
+ requireValue(!dispatch.executionSessionId || dispatch.executionSessionId === command.executionSessionId, "EXECUTION_SESSION_LOCKED");
1118
+ dispatch.executionSessionId = command.executionSessionId;
1119
+ }
1120
+ if (command.controlCapabilities) {
1121
+ requireValue(["boundary", "none"].includes(command.controlCapabilities.pause) && typeof command.controlCapabilities.resume === "boolean", "INVALID_CONTROL_CAPABILITIES");
1122
+ dispatch.controlCapabilities = structuredClone(command.controlCapabilities);
1123
+ }
1124
+ const outputs = command.outputs ?? [];
1125
+ validateOutputs(outputs);
1126
+ if (["running", "unknown"].includes(command.outcome)) item.owner.leaseUntil = Math.max(item.owner.leaseUntil, now + state.board.policy.leaseMs);
1127
+ if (!executionObservationChanged(dispatch, command)) return false;
1128
+ if (command.outcome === "succeeded") {
1129
+ const required = state.workflow.plans[dispatch.planId].definitions[item.id].outputs;
1130
+ requireValue(required.every((name) => outputs.some((output) => output.name === name)), "REQUIRED_OUTPUT_MISSING");
1131
+ item.status = state.board.policy.review === "assignee" ? "completed" : "review";
1132
+ if (item.status === "completed") item.closedAt = now;
1133
+ item.resultRef = `kanban:dispatch:${dispatch.id}`;
1134
+ dispatch.outputs = structuredClone(outputs);
1135
+ } else if (command.outcome === "failed" || command.outcome === "cancelled") {
1136
+ item.status = "backlog";
1137
+ item.blocked = { reason: command.code ?? "EXECUTION_FAILED", at: now };
1138
+ delete item.owner;
1139
+ }
1140
+ dispatch.outcome = command.outcome === "succeeded" && state.board.policy.review === "assignee" ? "accepted" : command.outcome;
1141
+ dispatch.code = command.code;
1142
+ item.updatedAt = now;
1143
+ item.revision++;
1144
+ dispatch.itemRevision = item.revision;
1145
+ return true;
1146
+ }
1147
+ function accept(state, command, actor, apply) {
1148
+ requireCoordinator(state, actor);
1149
+ const dispatch = activeDispatch(state, command.dispatchId);
1150
+ requireValue(dispatch.outcome === "succeeded", "EXECUTION_NOT_SUCCEEDED");
1151
+ apply({ type: "review", itemId: dispatch.itemId, accept: command.accept }, actor);
1152
+ dispatch.outcome = command.accept ? "accepted" : "rejected";
1153
+ if (!command.accept) {
1154
+ const item = state.board.items.find((item2) => item2.id === dispatch.itemId);
1155
+ item.status = "backlog";
1156
+ item.blocked = { reason: "EXECUTION_REJECTED", at: item.updatedAt };
1157
+ }
1158
+ }
1159
+ function activeDispatch(state, id) {
1160
+ const dispatch = state.workflow.dispatches[id];
1161
+ requireValue(dispatch, "DISPATCH_NOT_FOUND");
1162
+ const item = state.board.items.find((item2) => item2.id === dispatch.itemId), plan2 = state.workflow.plans[dispatch.planId];
1163
+ requireValue(plan2?.revision === dispatch.planRevision && item?.owner?.token === dispatch.fence && plan2.definitions[dispatch.itemId]?.digest === dispatch.definitionDigest, "STALE_EXECUTION_RESULT");
1164
+ return dispatch;
1165
+ }
1166
+ function validateOutputs(outputs) {
1167
+ requireValue(Array.isArray(outputs) && outputs.length <= 100 && outputs.every((output) => output && typeof output === "object" && typeof output.name === "string") && new Set(outputs.map((output) => output.name)).size === outputs.length, "INVALID_OUTPUTS");
1168
+ for (const output of outputs) requireValue(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(output.name) && typeof output.ref === "string" && output.ref.length > 0 && output.ref.length <= 2048 && /^[a-f0-9]{64}$/.test(output.sha256) && Number.isSafeInteger(output.bytes) && output.bytes >= 0, "INVALID_OUTPUT_REFERENCE");
1169
+ }
1170
+ function refreshReady(state) {
1171
+ if (!state.workflow) return;
1172
+ const all = catalog(state), included = new Set(Object.values(state.workflow.plans).filter((plan2) => plan2.sealed).flatMap((plan2) => plan2.itemIds));
1173
+ state.workflow.completedPlans = Object.values(state.workflow.plans).filter((plan2) => plan2.sealed && plan2.itemIds.every((id) => all.find((item) => item.id === id)?.status === "completed")).map((plan2) => plan2.id);
1174
+ state.workflow.ready = state.board.items.filter((item) => included.has(item.id) && executableWorkItem(state.board, item) && ["backlog", "open"].includes(item.status) && !item.owner && !item.blocked && item.control?.action !== "pause" && (item.planning?.dependencies ?? []).every((id) => all.find((other) => other.id === id)?.status === "completed")).map((item) => item.id);
1175
+ }
1176
+
1177
+ // src/transitions.ts
1178
+ function transition(state, item, command, actor, now, token) {
1179
+ requireValue(item.status !== "completed" && item.status !== "cancelled", "ITEM_COMPLETED");
1180
+ if (command.type === "claim" || command.type === "accept-transfer") claim(state, item, command, actor, now, token);
1181
+ else if (command.type === "review") review(state, item, command.accept, actor, now);
1182
+ else {
1183
+ owned(item, actor, command.token, now);
1184
+ if (command.type === "submit") requireValue(catalog(state).filter((i) => i.planning.parentId === item.id).every(terminal), "CHILDREN_UNFINISHED");
1185
+ ownerUpdate(state.board, item, command, now, token);
1186
+ }
1187
+ if (command.type !== "renew") {
1188
+ item.revision++;
1189
+ item.updatedAt = now;
1190
+ }
1191
+ }
1192
+ function claim(state, item, command, actor, now, token) {
1193
+ const board = state.board, key = principalKey(principal(actor));
1194
+ requireValue(!taskEditing(item, now), "EDIT_LEASE_ACTIVE");
1195
+ eligible(board, item, actor);
1196
+ assertReady(state, item);
1197
+ requireValue(command.estimate || board.policy.requireEstimate === false, "ESTIMATE_REQUIRED");
1198
+ if (command.estimate) validateEstimate(command.estimate);
1199
+ const wip = board.items.filter((i) => i.status === "claimed" || i.status === "review");
1200
+ if (command.type === "claim") requireValue(wip.length < limits(state).inProgress, "WIP_LIMIT");
1201
+ requireValue(wip.filter((i) => i.id !== item.id && i.owner && assigneeKey(i.owner) === key).length < limits(state).perAssignee, principal(actor).kind === "agent" ? "AGENT_WIP_LIMIT" : "ASSIGNEE_WIP_LIMIT");
1202
+ if (command.type === "claim") requireValue(item.status === "open" && !item.owner, "ALREADY_OWNED");
1203
+ else {
1204
+ requireValue(item.status === "claimed" && item.transfer && principalKey(transferTarget(item.transfer)) === key, "TRANSFER_NOT_OFFERED");
1205
+ requireValue(item.transfer.expiresAt > now && item.owner && item.owner.leaseUntil > now, "TRANSFER_EXPIRED");
1206
+ requireValue(assigneeKey(item.owner) !== key, "SELF_TRANSFER");
1207
+ }
1208
+ item.owner = { ...actor, principalId: key, token, claimedAt: now, leaseUntil: now + board.policy.leaseMs };
1209
+ item.estimate = command.estimate;
1210
+ item.status = "claimed";
1211
+ item.progressAt = now;
1212
+ delete item.transfer;
1213
+ if (actor.sessionId) participant(item.participants, actor.sessionId, actor.agentId, "owner", true, now);
1214
+ }
1215
+ function review(state, item, accept2, actor, now) {
1216
+ requireValue(item.status === "review", "NOT_IN_REVIEW");
1217
+ const key = principalKey(principal(actor));
1218
+ const registered = actor.sessionId && item.participants.some((p) => p.sessionId === actor.sessionId && p.roles.includes("reviewer")) || state.board.members?.some((m) => principalKey(m) === key && m.roles?.includes("reviewer"));
1219
+ requireValue(registered, "REVIEWER_REQUIRED");
1220
+ requireValue(!item.owner || assigneeKey(item.owner) !== key, "INDEPENDENT_REVIEW_REQUIRED");
1221
+ item.status = accept2 ? "completed" : state.board.items.filter((i) => i.status === "open").length < limits(state).ready ? "open" : "backlog";
1222
+ if (accept2) item.closedAt = now;
1223
+ if (!accept2) {
1224
+ delete item.owner;
1225
+ delete item.estimate;
1226
+ delete item.resultRef;
1227
+ item.readyAt = now;
1228
+ }
1229
+ }
1230
+ function ownerUpdate(board, item, command, now, token) {
1231
+ switch (command.type) {
1232
+ case "renew":
1233
+ item.owner.leaseUntil = now + board.policy.leaseMs;
1234
+ break;
1235
+ case "progress":
1236
+ requireValue(Number.isFinite(command.workUnits) && command.workUnits >= item.workUnits, "INVALID_WORK_UNITS");
1237
+ item.workUnits = command.workUnits;
1238
+ item.progressAt = now;
1239
+ if (command.estimate) {
1240
+ validateEstimate(command.estimate);
1241
+ item.estimate = command.estimate;
1242
+ }
1243
+ break;
1244
+ case "request-transfer":
1245
+ requestTransfer(board, item, command, now, token);
1246
+ break;
1247
+ case "submit":
1248
+ text(command.resultRef);
1249
+ item.resultRef = command.resultRef;
1250
+ item.status = board.policy.review === "assignee" ? "completed" : "review";
1251
+ if (item.status === "completed") item.closedAt = now;
1252
+ delete item.transfer;
1253
+ break;
1254
+ }
1255
+ }
1256
+ function requestTransfer(board, item, command, now, token) {
1257
+ requireValue(Boolean(command.target) !== Boolean(command.agentId), "TRANSFER_TARGET_REQUIRED");
1258
+ const target = command.target ?? { kind: "agent", id: command.agentId }, key = principalKey(target);
1259
+ requireValue(candidates(board, item).some((p) => principalKey(p) === key), "AGENT_NOT_ELIGIBLE");
1260
+ requireValue(assigneeKey(item.owner) !== key, "SELF_TRANSFER");
1261
+ requireValue(!item.transfer, "TRANSFER_ALREADY_PENDING");
1262
+ item.transfer = { id: token, target, ...target.kind === "agent" ? { agentId: target.id } : {}, requestedAt: now, expiresAt: now + board.policy.transferTimeoutMs };
1263
+ }
1264
+ function transferTarget(value) {
1265
+ return value.target ?? { kind: "agent", id: value.agentId };
1266
+ }
1267
+
1268
+ // src/reducer.ts
1269
+ function reduce(state, command, actor, operationId, now, token, workflowInternal = false) {
1270
+ requireValue(state.board.deletedAt === void 0, "BOARD_DELETED");
1271
+ numberEntities(state);
1272
+ if (!workflowInternal) protectWorkflowItem(state, command);
1273
+ const board = state.board;
1274
+ if (command.type === "delete-board") return deleteBoard(state, actor, operationId, now);
1275
+ if (command.type === "scan") {
1276
+ scan(state, actor, operationId, now);
1277
+ refreshReady(state);
1278
+ return state;
1279
+ }
1280
+ let recordEvent = command.type !== "renew";
1281
+ if (command.type === "set-board-control") setBoardControl(state, command, actor, now, token);
1282
+ else if (taskCommand(command)) applyTaskCommand(state, command, actor, now);
1283
+ else if (isWorkflowCommand(command)) recordEvent = applyWorkflow(state, command, actor, now, (inner, owner = actor) => {
1284
+ reduce(state, inner, owner, operationId, now, token, true);
1285
+ });
1286
+ else if (command.type === "apply-discovery") applyDiscovery(state, command.batch, actor, now);
1287
+ else if (isRecordCommand(command)) applyRecord(state, command, actor, now);
1288
+ else if (command.type === "review-amendment") {
1289
+ if (command.accept) assertDefinitionEditable(itemFor(board, command.itemId), now);
1290
+ reviewAmendment(board, command, actor, now);
1291
+ } else if (planningCommand(command)) applyPlanningCommand(state, command, now, actor, workflowInternal);
1292
+ else if (command.type === "create-item") createItem2(state, command, actor, now, token);
1293
+ else if (command.type === "configure-automation") configureAutomation(board, command.settings, actor);
1294
+ else if (command.type === "register-session") {
1295
+ const item = command.itemId ? itemFor(board, command.itemId) : void 0;
1296
+ const list = item ? item.participants : board.participants;
1297
+ participant(list, command.sessionId, command.agentId, command.role, command.subscribed, now);
1298
+ if (item) item.revision++;
1299
+ } else if (command.type === "message") {
1300
+ text(command.message);
1301
+ command.recipientSessionIds.forEach(identity);
1302
+ if (command.itemId) itemFor(board, command.itemId);
1303
+ requireValue(command.recipientSessionIds.every((id) => related(board).includes(id)), "UNKNOWN_RECIPIENT");
1304
+ } else transition(state, itemFor(board, command.itemId), command, actor, now, token);
1305
+ numberEntities(state);
1306
+ refreshReady(state);
1307
+ board.revision++;
1308
+ if (recordEvent) append2(
1309
+ state,
1310
+ actor,
1311
+ operationId,
1312
+ now,
1313
+ command.type,
1314
+ "itemId" in command ? command.itemId : command.type === "create-item" ? command.item.id : "dispatchId" in command ? state.workflow?.dispatches[command.dispatchId]?.itemId : void 0,
1315
+ eventData(command, state),
1316
+ command.type === "message" ? command.recipientSessionIds : void 0
1317
+ );
1318
+ scan(state, actor, operationId, now);
1319
+ return state;
1320
+ }
1321
+ function createItem2(state, command, actor, now, token) {
1322
+ const { id, title, responsibility, acceptance, eligibleAgentIds, eligiblePrincipals, externalRefs } = command.item;
1323
+ const input = { id, title, responsibility, acceptance, eligibleAgentIds, eligiblePrincipals, externalRefs }, board = state.board;
1324
+ identity(input.id);
1325
+ text(input.title);
1326
+ text(input.responsibility);
1327
+ text(input.acceptance);
1328
+ requireValue(!board.items.some((i) => i.id === input.id) && !state.archiveIndex?.some((i) => i.id === input.id), "ITEM_EXISTS");
1329
+ const item = { ...input, origin: { kind: "direct", principal: principal(actor) }, status: "backlog", revision: 1, createdAt: now, readyAt: now, updatedAt: now, workUnits: 0, participants: [] };
1330
+ item.launch = { startAt: now + TASK_START_DELAY_MS };
1331
+ requireValue(command.launch?.mode === void 0 || ["automatic", "manual"].includes(command.launch.mode), "INVALID_LAUNCH_MODE");
1332
+ requireValue(command.launch?.paused === void 0 || typeof command.launch.paused === "boolean", "INVALID_TASK_PAUSE");
1333
+ if (command.launch?.mode) item.launch.mode = command.launch.mode;
1334
+ if (command.launch?.paused) item.control = { id: "initial-" + token, action: "pause", state: "paused" };
1335
+ item.planning = command.planning ?? { ...plan(item), kind: board.defaultWorkType ?? "task" };
1336
+ const references = item.externalRefs ?? [];
1337
+ item.externalRefs = [];
1338
+ for (const reference of references) attachReference(item, reference);
1339
+ validateCandidates(board, item, executable(board, item));
1340
+ validatePlan(state, item, item.planning);
1341
+ if (item.planning.parentId) {
1342
+ const parent = board.items.find((parent2) => parent2.id === item.planning.parentId);
1343
+ if (parent.planning?.execution !== "children") {
1344
+ parent.planning = { ...plan(parent), execution: "children" };
1345
+ parent.updatedAt = now;
1346
+ parent.revision++;
1347
+ }
1348
+ }
1349
+ if (actor.sessionId) participant(item.participants, actor.sessionId, actor.agentId, "creator", true, now);
1350
+ board.items.push(item);
1351
+ if (command.stage === "open") setStage(state, item, "open", now);
1352
+ }
1353
+ function itemFor(board, id) {
1354
+ const item = board.items.find((value) => value.id === id);
1355
+ requireValue(item, "ITEM_NOT_FOUND");
1356
+ return item;
1357
+ }
1358
+ function related(board) {
1359
+ return [...new Set([...board.participants, ...board.items.flatMap((i) => i.participants)].map((p) => p.sessionId))];
1360
+ }
1361
+ function append2(state, actor, operationId, at, kind, itemId, data = {}, recipients) {
1362
+ const archived = state.archiveWrites?.flatMap((write) => write.value?.item.participants ?? []) ?? [];
1363
+ const members = [...archived, ...state.board.participants, ...state.board.items.filter((i) => i.id === itemId).flatMap((i) => i.participants)];
1364
+ state.events.push({
1365
+ sequence: ++state.sequence,
1366
+ boardId: state.board.id,
1367
+ itemId,
1368
+ operationId,
1369
+ at,
1370
+ kind,
1371
+ actor,
1372
+ recipients: [...new Set(recipients ?? members.filter((p) => p.subscribed).map((p) => p.sessionId))],
1373
+ data
1374
+ });
1375
+ }
1376
+ function scan(state, actor, operationId, now) {
1377
+ for (const item of state.board.items) {
1378
+ if (initializeTaskLaunch(state, item)) {
1379
+ state.board.revision++;
1380
+ append2(state, actor, operationId, now, "task-launch-initialized", item.id, { code: "LEGACY_LAUNCH_INITIALIZED" });
1381
+ }
1382
+ if (terminal(item)) continue;
1383
+ for (const reason of escalationReasons(state.board, item, now)) {
1384
+ const epoch = reason === "transfer-timeout" ? item.transfer?.id : reason === "backlog-review" ? item.updatedAt : item.owner?.token ?? item.readyAt;
1385
+ const key = JSON.stringify([item.id, epoch, reason]);
1386
+ if (state.escalations.includes(key)) continue;
1387
+ state.escalations.push(key);
1388
+ state.board.revision++;
1389
+ append2(state, actor, operationId, now, "escalated", item.id, { reason }, state.board.policy.escalationSessionIds);
1390
+ }
1391
+ if (item.transfer && item.transfer.expiresAt <= now) {
1392
+ delete item.transfer;
1393
+ item.revision++;
1394
+ item.updatedAt = now;
1395
+ state.board.revision++;
1396
+ }
1397
+ }
1398
+ const archived = archiveExpired(state, now);
1399
+ if (archived.length) {
1400
+ state.board.revision++;
1401
+ append2(state, actor, operationId, now, "items.archived", void 0, { reason: "retention-policy" });
1402
+ }
1403
+ }
1404
+ function escalationReasons(board, item, now) {
1405
+ const p = board.policy, result = [];
1406
+ if (item.status === "backlog" && p.backlogReviewMs && now - item.updatedAt >= p.backlogReviewMs) result.push("backlog-review");
1407
+ if (item.planning?.dueAt !== void 0 && now >= item.planning.dueAt) result.push("due-date");
1408
+ if (item.blocked && now - item.blocked.at >= p.progressTimeoutMs) result.push("blocked-age");
1409
+ if (!item.blocked && item.status === "open" && now - item.readyAt >= p.claimTimeoutMs) result.push("unclaimed");
1410
+ if (item.status === "review" && now - item.updatedAt >= p.progressTimeoutMs) result.push("review-timeout");
1411
+ if (item.transfer && now >= item.transfer.expiresAt) result.push("transfer-timeout");
1412
+ if (item.status !== "claimed" || !item.owner) return result;
1413
+ if (now >= item.owner.leaseUntil) result.push("lease-expired");
1414
+ if (now - (item.progressAt ?? item.owner.claimedAt) >= p.progressTimeoutMs) result.push("no-progress");
1415
+ if (now - item.owner.claimedAt >= Math.min(item.estimate?.durationMs ?? p.maxDurationMs, p.maxDurationMs)) result.push("execution-timeout");
1416
+ if ((item.estimate?.complexity ?? 0) >= p.maxComplexity) result.push("complexity-threshold");
1417
+ if (Math.max(item.workUnits, item.estimate?.workUnits ?? 0) >= p.maxWorkUnits) result.push("work-threshold");
1418
+ if ((item.estimate?.durationMs ?? 0) >= p.maxDurationMs) result.push("duration-threshold");
1419
+ return result;
1420
+ }
1421
+ function eventData(command, state) {
1422
+ if (command.type === "set-board-control") return { code: "BOARD_" + (state.board.executionControl?.paused ? "PAUSE_REQUESTED" : state.board.executionControl?.mode?.toUpperCase()) };
1423
+ if (command.type === "apply-discovery") return discoveryEvent(state, command.batch);
1424
+ if (command.type === "report-analysis") return { code: command.status.code, reason: "analysis-" + command.status.state };
1425
+ if (command.type === "control-receipt") return { code: command.code, reason: "control-" + command.state };
1426
+ if (isWorkflowCommand(command)) return { readyItemIds: state.workflow?.ready, ..."dispatchId" in command ? { dispatchId: command.dispatchId } : { planId: command.plan.id }, ..."outcome" in command ? { reason: `execution-${command.outcome}`, code: command.code, status: state.board.items.find((item) => item.id === state.workflow?.dispatches[command.dispatchId]?.itemId)?.status } : command.type === "accept-execution" ? { reason: command.accept ? "accepted" : "rejected" } : {} };
1427
+ if (command.type === "create-item") return { itemTitle: command.item.title };
1428
+ if (command.type === "link-reference") return { reference: command.reference };
1429
+ if (command.type === "block-item") return { reason: command.reason };
1430
+ if (command.type === "release-item") return { reason: command.next === "cancelled" ? "cancelled" : "released" };
1431
+ if (command.type === "review") return {
1432
+ reason: command.accept ? "accepted" : "rejected",
1433
+ dispatchId: Object.values(state.workflow?.dispatches ?? {}).find((dispatch) => dispatch.itemId === command.itemId && dispatch.outcome === "succeeded")?.id
1434
+ };
1435
+ if (command.type === "append-record") return { recordId: command.record.id, reason: command.record.kind === "decision" ? "decision-draft" : "log" };
1436
+ if (command.type === "review-record" || command.type === "link-record") return { recordId: command.recordId };
1437
+ if (command.type === "archive-items") return { itemIds: command.itemIds, reason: command.reason };
1438
+ if (command.type === "cancel-item") return { reason: command.reason };
1439
+ if (command.type === "plan-item") return { planning: command.planning };
1440
+ if (command.type === "message") return { message: command.message };
1441
+ if (command.type === "submit") return { resultRef: command.resultRef };
1442
+ if (command.type === "claim" || command.type === "accept-transfer") return { estimate: command.estimate };
1443
+ if (command.type === "progress") return { estimate: command.estimate, workUnits: command.workUnits };
1444
+ return {};
1445
+ }
1446
+ function discoveryEvent(state, batch) {
1447
+ return {
1448
+ itemIds: batch.changes.map((change) => change.itemId),
1449
+ recordIds: batch.records?.filter((record) => state.records?.some((entry) => entry.id === record.id && entry.originRunId === batch.runId)).map((record) => record.id),
1450
+ ...state.board.items.some((item) => item.amendments?.some((proposal) => proposal.runId === batch.runId && proposal.status === "pending")) ? { reason: "amendment-proposed" } : state.board.items.some((item) => item.status === "proposed" && item.origin?.runId === batch.runId) ? { reason: "proposal-created" } : {}
1451
+ };
1452
+ }
1453
+ function deleteBoard(state, actor, operationId, now) {
1454
+ const owner = principal(actor), board = state.board;
1455
+ requireValue(owner.kind === "human" && board.members?.some((member) => member.kind === owner.kind && member.id === owner.id && member.roles?.includes("coordinator")), "COORDINATOR_REQUIRED");
1456
+ requireValue(!board.items.some((item) => item.owner || item.transfer || item.status === "claimed"), "BOARD_EXECUTION_ACTIVE");
1457
+ requireValue(!Object.values(state.workflow?.dispatches ?? {}).some((dispatch) => ["prepared", "running", "unknown", "succeeded"].includes(dispatch.outcome)), "BOARD_EXECUTION_UNSETTLED");
1458
+ board.deletedAt = now;
1459
+ board.revision++;
1460
+ if (board.automation) board.automation.enabled = false;
1461
+ if (state.workflow) state.workflow.ready = [];
1462
+ append2(state, actor, operationId, now, "delete-board");
1463
+ return state;
1464
+ }
1465
+
1466
+ export {
1467
+ summary,
1468
+ terminal,
1469
+ catalog,
1470
+ limits,
1471
+ proposeAmendment,
1472
+ queryRecords,
1473
+ recordSummary,
1474
+ createBoardState,
1475
+ boardKey,
1476
+ archiveKey,
1477
+ rowKeys,
1478
+ hydrate,
1479
+ encodeBoard,
1480
+ rowChanges,
1481
+ receiptDigest,
1482
+ verifyReceipt,
1483
+ encodeRow,
1484
+ decodeRow,
1485
+ indexedView,
1486
+ viewFromState,
1487
+ boardCounterKey,
1488
+ boardNumberKey,
1489
+ counter,
1490
+ storedBoardNumber,
1491
+ patchBoardNumber,
1492
+ numberEntities,
1493
+ allocateBoardNumber,
1494
+ reduce,
1495
+ related,
1496
+ escalationReasons
1497
+ };
1498
+ //# sourceMappingURL=chunk-OHQTKGQN.js.map