@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
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+ var _chunk4XF6LQSUcjs = require('./chunk-4XF6LQSU.cjs');
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+ var _chunk4KF7KUAIcjs = require('./chunk-4KF7KUAI.cjs');
23
+
24
+
25
+ var _chunk2YFPV5GFcjs = require('./chunk-2YFPV5GF.cjs');
26
+
27
+
28
+
29
+
30
+
31
+ var _chunkKYNYPKKHcjs = require('./chunk-KYNYPKKH.cjs');
32
+
33
+
34
+
35
+ var _chunkPSKQAFDFcjs = require('./chunk-PSKQAFDF.cjs');
36
+
37
+
38
+
39
+ var _chunk6MN3H3YFcjs = require('./chunk-6MN3H3YF.cjs');
40
+
41
+
42
+ var _chunkLSE6JG5Icjs = require('./chunk-LSE6JG5I.cjs');
43
+
44
+ // src/planning.ts
45
+ function plan(item) {
46
+ return _nullishCoalesce(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: _optionalChain([item, 'access', _ => _.origin, 'optionalAccess', _2 => _2.fingerprint]),
63
+ pendingAmendments: _optionalChain([item, 'access', _3 => _3.amendments, 'optionalAccess', _4 => _4.filter, 'call', _5 => _5((proposal) => proposal.status === "pending"), 'access', _6 => _6.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), ..._nullishCoalesce(state.archiveIndex, () => ( []))];
75
+ }
76
+ function limits(state) {
77
+ const p = state.board.policy;
78
+ return { ready: _nullishCoalesce(p.maxReady, () => ( 20)), inProgress: _nullishCoalesce(p.maxInProgress, () => ( 3)), perAgent: _nullishCoalesce(_nullishCoalesce(p.maxInProgressPerAssignee, () => ( p.maxInProgressPerAgent)), () => ( 1)), perAssignee: _nullishCoalesce(_nullishCoalesce(p.maxInProgressPerAssignee, () => ( p.maxInProgressPerAgent)), () => ( 1)) };
79
+ }
80
+ function validatePlan(state, item, value) {
81
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, typeof value.kind === "string" && Number.isInteger(value.priority) && value.priority >= 0 && value.priority <= 4, "INVALID_PLANNING");
82
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, Array.isArray(value.dependencies) && value.dependencies.length <= 100 && Array.isArray(value.references) && value.references.length <= 100, "PLANNING_LIMIT");
83
+ value.dependencies.forEach(_chunk4KF7KUAIcjs.identity);
84
+ value.references.forEach(_chunk4KF7KUAIcjs.text);
85
+ if (value.area !== void 0) _chunk4KF7KUAIcjs.identity.call(void 0, value.area);
86
+ if (value.milestone !== void 0) _chunk4KF7KUAIcjs.identity.call(void 0, value.milestone);
87
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, value.execution === void 0 || ["direct", "children"].includes(value.execution), "INVALID_EXECUTION_MODE");
88
+ const type = _chunk4KF7KUAIcjs.workType.call(void 0, state.board, value.kind);
89
+ if (value.dueAt !== void 0) _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.identity.call(void 0, value.parentId);
93
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, parent && !parent.archivedAt && !terminal(parent) && !["claimed", "review"].includes(parent.status), "PARENT_UNAVAILABLE");
94
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, parent.id !== item.id && _chunk4KF7KUAIcjs.workType.call(void 0, state.board, parent.planning.kind).rank < type.rank, "INVALID_PARENT_KIND");
95
+ }
96
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, value.execution === "children" || !all.some((child) => child.planning.parentId === item.id), "CHILDREN_REQUIRE_AGGREGATION");
97
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !all.some((child) => child.planning.parentId === item.id && _chunk4KF7KUAIcjs.workType.call(void 0, state.board, child.planning.kind).rank <= type.rank), "INVALID_CHILD_KIND");
98
+ for (const id of value.dependencies) _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, id !== item.id, "DEPENDENCY_CYCLE");
103
+ if (visited.has(id)) continue;
104
+ visited.add(id);
105
+ pending.push(..._nullishCoalesce(_optionalChain([all, 'access', _7 => _7.find, 'call', _8 => _8((i) => i.id === id), 'optionalAccess', _9 => _9.planning, 'access', _10 => _10.dependencies]), () => ( [])));
106
+ }
107
+ }
108
+ function assertReady(state, item) {
109
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _chunk4KF7KUAIcjs.executable.call(void 0, state.board, item), "PLAN_NOT_EXECUTABLE");
110
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !item.blocked, "ITEM_BLOCKED");
111
+ const all = catalog(state);
112
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, plan(item).dependencies.every((id) => _optionalChain([all, 'access', _11 => _11.find, 'call', _12 => _12((i) => i.id === id), 'optionalAccess', _13 => _13.status]) === "completed"), "DEPENDENCIES_UNFINISHED");
113
+ }
114
+ function setStage(state, item, stage, now) {
115
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, ["proposed", "backlog", "open"].includes(item.status), "ITEM_NOT_PLANNABLE");
116
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, stage === "backlog" || stage === "open", "INVALID_STAGE");
117
+ if (stage === "open") {
118
+ assertReady(state, item);
119
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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) => _optionalChain([all, 'access', _14 => _14.find, 'call', _15 => _15((i) => i.id === id), 'optionalAccess', _16 => _16.status]) === "completed");
129
+ return _chunk4KF7KUAIcjs.executable.call(void 0, 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) => _chunk6MN3H3YFcjs.sha256HexSync.call(void 0, JSON.stringify(textOf(item)));
135
+ function workFingerprint(item) {
136
+ const planning = plan(item);
137
+ return _chunk6MN3H3YFcjs.sha256HexSync.call(void 0, JSON.stringify({
138
+ text: textOf(item),
139
+ kind: planning.kind,
140
+ parentId: _nullishCoalesce(planning.parentId, () => ( null)),
141
+ area: _nullishCoalesce(planning.area, () => ( null)),
142
+ milestone: _nullishCoalesce(planning.milestone, () => ( null)),
143
+ priority: planning.priority,
144
+ dependencies: [...planning.dependencies].sort(),
145
+ dueAt: _nullishCoalesce(planning.dueAt, () => ( null))
146
+ }));
147
+ }
148
+ function validateSources(sources) {
149
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, Array.isArray(sources) && sources.length <= 100, "SOURCE_LIMIT");
150
+ for (const source of sources) {
151
+ _chunk4KF7KUAIcjs.identity.call(void 0, source.sessionId);
152
+ _chunk4KF7KUAIcjs.identity.call(void 0, source.messageId);
153
+ _chunk4KF7KUAIcjs.identity.call(void 0, source.revision);
154
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, source.role === "user" || source.role === "assistant", "INVALID_SOURCE");
155
+ }
156
+ }
157
+ function proposeAmendment(item, change, actor, now, runId) {
158
+ _chunk4KF7KUAIcjs.text.call(void 0, change.title);
159
+ _chunk4KF7KUAIcjs.text.call(void 0, change.responsibility);
160
+ _chunk4KF7KUAIcjs.text.call(void 0, change.acceptance);
161
+ validateSources(change.sources);
162
+ const proposed = textOf(change), fingerprint = textDigest(proposed);
163
+ if (textDigest(item) === fingerprint || _optionalChain([item, 'access', _17 => _17.amendments, 'optionalAccess', _18 => _18.some, 'call', _19 => _19((p) => p.fingerprint === fingerprint)])) return;
164
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, (_nullishCoalesce(_optionalChain([item, 'access', _20 => _20.amendments, 'optionalAccess', _21 => _21.length]), () => ( 0))) < 20, "AMENDMENT_LIMIT");
165
+ (item.amendments ??= []).push({
166
+ runId,
167
+ id: `amendment-${_chunk6MN3H3YFcjs.sha256HexSync.call(void 0, JSON.stringify([runId, item.id, fingerprint]))}`,
168
+ fingerprint,
169
+ baseRevision: item.revision,
170
+ baseDigest: textDigest(item),
171
+ proposed,
172
+ proposedBy: _chunk4KF7KUAIcjs.principal.call(void 0, actor),
173
+ sources: structuredClone(change.sources),
174
+ createdAt: now,
175
+ status: "pending"
176
+ });
177
+ }
178
+ function requireReviewer(board, actor) {
179
+ const key = _chunk4KF7KUAIcjs.principalKey.call(void 0, _chunk4KF7KUAIcjs.principal.call(void 0, actor));
180
+ _chunk4KF7KUAIcjs.requireValue.call(void 0,
181
+ _optionalChain([board, 'access', _22 => _22.members, 'optionalAccess', _23 => _23.some, 'call', _24 => _24((m) => _chunk4KF7KUAIcjs.principalKey.call(void 0, m) === key && _optionalChain([m, 'access', _25 => _25.roles, 'optionalAccess', _26 => _26.some, 'call', _27 => _27((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 = _optionalChain([item, 'optionalAccess', _28 => _28.amendments, 'optionalAccess', _29 => _29.find, 'call', _30 => _30((p) => p.id === command.amendmentId)]);
188
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, item && _optionalChain([proposal, 'optionalAccess', _31 => _31.status]) === "pending", "AMENDMENT_NOT_PENDING");
189
+ if (command.accept) {
190
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _chunk4KF7KUAIcjs.principal.call(void 0, actor).kind === "human" || _chunk4KF7KUAIcjs.principalKey.call(void 0, proposal.proposedBy) !== _chunk4KF7KUAIcjs.principalKey.call(void 0, _chunk4KF7KUAIcjs.principal.call(void 0, actor)), "INDEPENDENT_REVIEW_REQUIRED");
191
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, ["proposed", "backlog", "open"].includes(item.status), "ITEM_NOT_PLANNABLE");
192
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !!_optionalChain([command, 'access', _32 => _32.reason, 'optionalAccess', _33 => _33.trim, 'call', _34 => _34()]), "AMENDMENT_REASON_REQUIRED");
200
+ _chunk4KF7KUAIcjs.text.call(void 0, command.reason);
201
+ }
202
+ proposal.status = command.accept ? "accepted" : "rejected";
203
+ proposal.reviewedAt = now;
204
+ proposal.reviewedBy = _chunk4KF7KUAIcjs.principal.call(void 0, 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 = _optionalChain([state, 'access', _35 => _35.records, 'optionalAccess', _36 => _36.find, 'call', _37 => _37((record2) => record2.id === command.recordId)]);
220
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, record, "RECORD_NOT_FOUND");
221
+ if (command.type === "link-record") {
222
+ validateItems(state, [command.itemId]);
223
+ if (!record.itemIds.includes(command.itemId)) {
224
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, record.itemIds.length < 100, "RECORD_LINK_LIMIT");
225
+ record.itemIds.push(command.itemId);
226
+ }
227
+ } else {
228
+ requireReviewer(state.board, actor);
229
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, record.status === "draft", "RECORD_NOT_DRAFT");
230
+ if (command.accept) {
231
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _chunk4KF7KUAIcjs.principal.call(void 0, actor).kind === "human" || _chunk4KF7KUAIcjs.principalKey.call(void 0, record.author) !== _chunk4KF7KUAIcjs.principalKey.call(void 0, _chunk4KF7KUAIcjs.principal.call(void 0, actor)), "INDEPENDENT_REVIEW_REQUIRED");
232
+ supersede(state, record, now);
233
+ record.status = "confirmed";
234
+ } else record.status = "rejected";
235
+ record.reviewedBy = _chunk4KF7KUAIcjs.principal.call(void 0, 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
+ _chunk4KF7KUAIcjs.identity.call(void 0, input.id);
245
+ _chunk4KF7KUAIcjs.text.call(void 0, input.title);
246
+ _chunk4KF7KUAIcjs.text.call(void 0, input.content);
247
+ validateRecordReferences(externalRefs);
248
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, input.kind === "log" || input.kind === "decision", "INVALID_RECORD_KIND");
249
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !_optionalChain([state, 'access', _38 => _38.records, 'optionalAccess', _39 => _39.some, 'call', _40 => _40((record) => record.id === input.id)]), "RECORD_EXISTS");
250
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, (_nullishCoalesce(_optionalChain([state, 'access', _41 => _41.records, 'optionalAccess', _42 => _42.length]), () => ( 0))) < 200, "RECORD_LIMIT");
251
+ validateItems(state, input.itemIds);
252
+ validateSources(input.sources);
253
+ if (input.rationale !== void 0) _chunk4KF7KUAIcjs.text.call(void 0, input.rationale);
254
+ if (input.kind === "decision") _chunk4KF7KUAIcjs.text.call(void 0, _nullishCoalesce(input.rationale, () => ( "")));
255
+ if (coordination) validateCoordination(state, input);
256
+ if (input.supersedes) {
257
+ _chunk4KF7KUAIcjs.identity.call(void 0, input.supersedes);
258
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, input.kind === "decision" && input.supersedes !== input.id && _optionalChain([state, 'access', _43 => _43.records, 'optionalAccess', _44 => _44.some, 'call', _45 => _45((record) => record.id === input.supersedes && record.kind === "decision" && record.status === "confirmed")]), "INVALID_SUPERSEDED_RECORD");
259
+ }
260
+ const author = _chunk4KF7KUAIcjs.principal.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, input.kind === "decision", "DECISION_COORDINATION_ONLY");
273
+ for (const owner of [input.coordination.manager, input.coordination.executor].filter(Boolean)) {
274
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, owner && ["agent", "human", "service"].includes(owner.kind), "INVALID_PRINCIPAL");
275
+ _chunk4KF7KUAIcjs.identity.call(void 0, owner.id);
276
+ const member = _optionalChain([state, 'access', _46 => _46.board, 'access', _47 => _47.members, 'optionalAccess', _48 => _48.find, 'call', _49 => _49((member2) => _chunk4KF7KUAIcjs.principalKey.call(void 0, member2) === _chunk4KF7KUAIcjs.principalKey.call(void 0, owner))]);
277
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, member, "ASSIGNEE_NOT_REGISTERED");
278
+ if (owner === input.coordination.manager) _chunk4KF7KUAIcjs.requireValue.call(void 0, _optionalChain([member, 'access', _50 => _50.roles, 'optionalAccess', _51 => _51.includes, 'call', _52 => _52("coordinator")]), "COORDINATOR_REQUIRED");
279
+ }
280
+ }
281
+ function validateItems(state, ids) {
282
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, Array.isArray(ids) && ids.length <= 100 && new Set(ids).size === ids.length, "RECORD_LINK_LIMIT");
283
+ for (const id of ids) {
284
+ _chunk4KF7KUAIcjs.identity.call(void 0, id);
285
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, state.board.items.some((item) => item.id === id) || _optionalChain([state, 'access', _53 => _53.archiveIndex, 'optionalAccess', _54 => _54.some, 'call', _55 => _55((item) => item.id === id)]), "ITEM_NOT_FOUND");
286
+ }
287
+ }
288
+ function supersede(state, record, now) {
289
+ if (!record.supersedes) return;
290
+ const previous = _optionalChain([state, 'access', _56 => _56.records, 'optionalAccess', _57 => _57.find, 'call', _58 => _58((entry) => entry.id === record.supersedes)]);
291
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _optionalChain([previous, 'optionalAccess', _59 => _59.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 = (_nullishCoalesce(state.records, () => ( []))).map(recordSummary)) {
298
+ const { cursor, ...filter } = query, limit = _nullishCoalesce(query.limit, () => ( 50));
299
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, Number.isSafeInteger(limit) && limit > 0 && limit <= 200, "INVALID_LIMIT");
300
+ if (query.kind) _chunk4KF7KUAIcjs.requireValue.call(void 0, ["log", "decision"].includes(query.kind), "INVALID_RECORD_KIND");
301
+ if (query.itemId !== void 0) _chunk4KF7KUAIcjs.identity.call(void 0, query.itemId);
302
+ if (query.status) _chunk4KF7KUAIcjs.requireValue.call(void 0, ["draft", "confirmed", "rejected", "superseded"].includes(query.status), "INVALID_RECORD_STATUS");
303
+ const digest = _chunk6MN3H3YFcjs.sha256HexSync.call(void 0, JSON.stringify(filter));
304
+ let offset = 0;
305
+ if (cursor) {
306
+ let decoded;
307
+ try {
308
+ decoded = JSON.parse(decodeURIComponent(cursor));
309
+ } catch (e) {
310
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, false, "INVALID_CURSOR");
311
+ }
312
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, decoded && typeof decoded === "object" && !Array.isArray(decoded) && typeof decoded.filter === "string" && typeof decoded.revision === "number", "INVALID_CURSOR");
313
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, decoded.revision === state.board.revision && decoded.filter === digest, "CURSOR_STALE");
314
+ offset = decoded.offset;
315
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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 _chunk6MN3H3YFcjs.sha256HexSync.call(void 0, JSON.stringify({
323
+ kind: record.kind,
324
+ title: record.title,
325
+ content: record.content,
326
+ rationale: _nullishCoalesce(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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, Array.isArray(refs) && refs.length <= 100, "REFERENCE_LIMIT");
336
+ const keys = /* @__PURE__ */ new Set();
337
+ for (const ref of refs) {
338
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, ref && typeof ref === "object", "INVALID_REFERENCE");
339
+ _chunk4KF7KUAIcjs.identity.call(void 0, ref.system);
340
+ _chunk4KF7KUAIcjs.identity.call(void 0, ref.id);
341
+ if (ref.revision !== void 0) _chunk4KF7KUAIcjs.text.call(void 0, ref.revision);
342
+ const key = JSON.stringify([ref.system, ref.id]);
343
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !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: _chunk4KF7KUAIcjs.policy.call(void 0, input.policy), revision: 1, items: [], participants: [] };
355
+ _chunk4KF7KUAIcjs.validateBoard.call(void 0, board);
356
+ if (actor.sessionId) _chunk4KF7KUAIcjs.participant.call(void 0, board.participants, actor.sessionId, actor.agentId, "creator", true, now);
357
+ for (const session of board.policy.escalationSessionIds) _chunk4KF7KUAIcjs.participant.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, Array.isArray(saved.itemIds) && Array.isArray(saved.recordIds) && _optionalChain([saved, 'access', _60 => _60.state, 'optionalAccess', _61 => _61.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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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 _nullishCoalesce(state.records, () => ( []))) rows[rowKey("record", id, record.id)] = await encodeRow(record, bodies);
393
+ const manifest = {
394
+ itemIndex: state.board.items.map(summary),
395
+ recordIndex: (_nullishCoalesce(state.records, () => ( []))).map(recordSummary),
396
+ layout: 2,
397
+ generation: _chunk6MN3H3YFcjs.randomUUID.call(void 0, ),
398
+ state: { ...state, board: { ...state.board, items: [] }, records: [] },
399
+ itemIds: state.board.items.map((item) => item.id),
400
+ recordIds: (_nullishCoalesce(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:${_chunk6MN3H3YFcjs.sha256HexSync.call(void 0, fingerprint)}`;
411
+ }
412
+ function verifyReceipt(saved, fingerprint) {
413
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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: _chunk6MN3H3YFcjs.sha256HexSync.call(void 0, 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 _nullishCoalesce(failure, () => ( new (0, _chunk2YFPV5GFcjs.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 (_optionalChain([parsed, 'optionalAccess', _62 => _62.body]) !== "kanban-body/v1") return parsed;
437
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, /^[a-f0-9]{64}$/.test(parsed.sha256) && Number.isSafeInteger(parsed.bytes) && parsed.bytes > 8192, "INVALID_BODY_REFERENCE");
438
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, bodies, "BODY_STORE_REQUIRED");
439
+ const bytes = await bodies.read(parsed.sha256);
440
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, bytes instanceof ArrayBuffer && bytes.byteLength === ref.bytes && _chunk6MN3H3YFcjs.sha256HexSync.call(void 0, bytes) === ref.sha256, "BODY_INTEGRITY");
446
+ }
447
+ function requiredRow(saved, key) {
448
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, typeof saved.rows[key] === "string", "MISSING_STORAGE_ROW");
449
+ return saved.rows[key];
450
+ }
451
+ function validateState(state) {
452
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _optionalChain([state, 'optionalAccess', _63 => _63.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: (_nullishCoalesce(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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, raw === null || /^(0|[1-9]\d*)$/.test(raw), "INVALID_NUMBER_COUNTER");
471
+ const value = raw === null ? 0 : Number(raw);
472
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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 = _optionalChain([(parsed.layout === 2 ? _optionalChain([parsed, 'access', _64 => _64.state, 'optionalAccess', _65 => _65.board]) : parsed.board), 'optionalAccess', _66 => _66.number]);
478
+ if (number !== void 0) _chunk4KF7KUAIcjs.requireValue.call(void 0, 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, ..._nullishCoalesce(state.archiveIndex, () => ( [])), ...(_nullishCoalesce(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((_nullishCoalesce(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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.text.call(void 0, reason);
520
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _optionalChain([record, 'optionalAccess', _67 => _67.item, 'access', _68 => _68.id]) === id && _optionalChain([state, 'access', _69 => _69.archiveIndex, 'optionalAccess', _70 => _70.some, 'call', _71 => _71((i) => i.id === id)]), "ARCHIVED_ITEM_NOT_FOUND");
534
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !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(_nullishCoalesce(i.closedAt, () => ( i.updatedAt)), _nullishCoalesce(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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, ["claimed", "review"].includes(item.status) && _optionalChain([item, 'access', _72 => _72.owner, 'optionalAccess', _73 => _73.token]) === command.token, "OWNER_MISMATCH");
572
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, ["backlog", "cancelled"].includes(command.next), "INVALID_STAGE");
573
+ _chunk4KF7KUAIcjs.text.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !terminal(item), "ITEM_COMPLETED");
585
+ if (item.status === "claimed") _chunk4KF7KUAIcjs.owned.call(void 0, item, actor, _nullishCoalesce(command.token, () => ( "")), now);
586
+ if (command.type === "block-item") {
587
+ _chunk4KF7KUAIcjs.text.call(void 0, 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") _chunk4KF7KUAIcjs.requireValue.call(void 0, _optionalChain([item, 'access', _74 => _74.launch, 'optionalAccess', _75 => _75.admittedAt]) === void 0, "TASK_CONTROL_REQUIRED");
596
+ if (command.type === "publish-proposal") {
597
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, item.status === "proposed", "NOT_PROPOSED");
598
+ return setStage(state, item, _nullishCoalesce(command.stage, () => ( "backlog")), now);
599
+ }
600
+ if (command.type === "set-stage") return setStage(state, item, command.stage, now);
601
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, ["proposed", "backlog", "open"].includes(item.status), "ITEM_NOT_PLANNABLE");
602
+ if (command.type === "edit-item") {
603
+ _chunk4KF7KUAIcjs.text.call(void 0, command.title);
604
+ _chunk4KF7KUAIcjs.text.call(void 0, command.responsibility);
605
+ _chunk4KF7KUAIcjs.text.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, catalog(state).filter((i) => i.planning.parentId === item.id).every(terminal), "CHILDREN_UNFINISHED");
616
+ if (command.type === "close-plan") {
617
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !_chunk4KF7KUAIcjs.executable.call(void 0, state.board, item), "TASK_REQUIRES_REVIEW");
618
+ _chunk4KF7KUAIcjs.text.call(void 0, command.resultRef);
619
+ const children = catalog(state).filter((child) => child.planning.parentId === item.id);
620
+ if (_optionalChain([item, 'access', _76 => _76.planning, 'optionalAccess', _77 => _77.execution]) === "children") _chunk4KF7KUAIcjs.requireValue.call(void 0, children.length > 0 && children.every((child) => child.status === "completed"), "CHILDREN_UNFINISHED");
621
+ item.status = "completed";
622
+ item.resultRef = command.resultRef;
623
+ } else {
624
+ _chunk4KF7KUAIcjs.text.call(void 0, 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
+ _chunk4KF7KUAIcjs.identity.call(void 0, reference.system);
635
+ _chunk4KF7KUAIcjs.identity.call(void 0, reference.id);
636
+ if (reference.revision !== void 0) _chunk4KF7KUAIcjs.text.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, item.externalRefs.length < 100, "REFERENCE_LIMIT");
640
+ item.externalRefs.push(reference);
641
+ }
642
+
643
+ // src/workflow-plans.ts
644
+ function requireCoordinator(state, actor) {
645
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _optionalChain([state, 'access', _78 => _78.board, 'access', _79 => _79.members, 'optionalAccess', _80 => _80.some, 'call', _81 => _81((member) => _chunk4KF7KUAIcjs.principalKey.call(void 0, member) === _chunk4KF7KUAIcjs.principalKey.call(void 0, _chunk4KF7KUAIcjs.principal.call(void 0, actor)) && _optionalChain([member, 'access', _82 => _82.roles, 'optionalAccess', _83 => _83.includes, 'call', _84 => _84("coordinator")]))]), "COORDINATOR_REQUIRED");
646
+ }
647
+ function publishPlan(state, plan2, actor, apply) {
648
+ requireCoordinator(state, actor);
649
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, plan2 && typeof plan2 === "object", "INVALID_WORK_PLAN");
650
+ _chunk4KF7KUAIcjs.identity.call(void 0, plan2.id);
651
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, Number.isSafeInteger(plan2.revision) && plan2.revision === (_nullishCoalesce(_optionalChain([previous, 'optionalAccess', _85 => _85.revision]), () => ( 0))) + 1, "PLAN_REVISION_CONFLICT");
654
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !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 = _optionalChain([state, 'access', _86 => _86.records, 'optionalAccess', _87 => _87.find, 'call', _88 => _88((record) => record.id === plan2.decisionId && record.kind === "decision" && record.status === "confirmed")]);
657
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, decision, "DECISION_NOT_CONFIRMED");
658
+ if (decision.coordination) _chunk4KF7KUAIcjs.requireValue.call(void 0, _chunk4KF7KUAIcjs.principalKey.call(void 0, decision.coordination.manager) === _chunk4KF7KUAIcjs.principalKey.call(void 0, _chunk4KF7KUAIcjs.principal.call(void 0, actor)), "DECISION_MANAGER_REQUIRED");
659
+ }
660
+ if (plan2.rootItemId) {
661
+ const root = state.board.items.find((item) => item.id === plan2.rootItemId);
662
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, root && !root.owner && ["backlog", "open"].includes(root.status), "PLAN_ROOT_UNAVAILABLE");
663
+ if (_optionalChain([root, 'access', _89 => _89.planning, 'optionalAccess', _90 => _90.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 = _chunk6MN3H3YFcjs.sha256HexSync.call(void 0, JSON.stringify(item));
668
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !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) || _optionalChain([state, 'access', _91 => _91.archiveIndex, 'optionalAccess', _92 => _92.some, 'call', _93 => _93((old) => old.id === item.id)]);
670
+ if (exists && _optionalChain([previous, 'optionalAccess', _94 => _94.definitions, 'access', _95 => _95[item.id], 'optionalAccess', _96 => _96.digest]) !== digest) {
671
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !_optionalChain([previous, 'optionalAccess', _97 => _97.definitions, 'access', _98 => _98[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: _nullishCoalesce(_nullishCoalesce(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: _nullishCoalesce(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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, item && definition.expectedRevision === item.revision && ["backlog", "open"].includes(item.status) && !item.owner && !item.blocked, "PLAN_ITEM_CHANGED_REQUIRES_NEW_ID");
686
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !definition.workType || definition.workType === _optionalChain([item, 'access', _99 => _99.planning, 'optionalAccess', _100 => _100.kind]), "PLAN_ITEM_CHANGED_REQUIRES_NEW_ID");
687
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !definition.externalRefs || definition.externalRefs.every((ref) => _optionalChain([item, 'access', _101 => _101.externalRefs, 'optionalAccess', _102 => _102.some, 'call', _103 => _103((existing) => JSON.stringify(existing) === JSON.stringify(ref))])), "PLAN_RESOURCE_MISMATCH");
688
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, item.title === definition.title && item.responsibility === definition.responsibility && item.acceptance === definition.acceptance, "PLAN_ITEM_CHANGED_REQUIRES_NEW_ID");
689
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.validateCandidates.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, ids.size === items.length, "DUPLICATE_PLAN_ITEM");
699
+ for (const item of items) {
700
+ _chunk4KF7KUAIcjs.identity.call(void 0, item.id);
701
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, Array.isArray(item.dependsOn) && item.dependsOn.length <= 100 && new Set(item.dependsOn).size === item.dependsOn.length, "INVALID_DEPENDENCIES");
702
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, Object.keys(_nullishCoalesce(item.inputs, () => ( {}))).length <= 100 && Array.isArray(_nullishCoalesce(item.outputs, () => ( []))) && (_nullishCoalesce(item.outputs, () => ( []))).length <= 100 && new Set(_nullishCoalesce(item.outputs, () => ( []))).size === (_nullishCoalesce(item.outputs, () => ( []))).length, "PLAN_BINDING_LIMIT");
703
+ for (const name of [...Object.keys(_nullishCoalesce(item.inputs, () => ( {}))), ..._nullishCoalesce(item.outputs, () => ( []))]) _chunk4KF7KUAIcjs.requireValue.call(void 0, /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(name), "INVALID_OUTPUT_NAME");
704
+ for (const binding of Object.values(_nullishCoalesce(item.inputs, () => ( {})))) {
705
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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" && _optionalChain([dispatch, 'access', _104 => _104.outputs, 'optionalAccess', _105 => _105.some, 'call', _106 => _106((output) => output.name === binding.output)]));
707
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, producer ? _optionalChain([producer, 'access', _107 => _107.outputs, 'optionalAccess', _108 => _108.includes, 'call', _109 => _109(binding.output)]) : existing, "OUTPUT_NOT_DECLARED");
708
+ }
709
+ for (const dependency of item.dependsOn) _chunk4KF7KUAIcjs.requireValue.call(void 0, ids.has(dependency) || [...state.board.items, ..._nullishCoalesce(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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, item && typeof item === "object" && !Array.isArray(item), "INVALID_WORK_DEFINITION");
723
+ const assignee = item.assignee;
724
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, assignee && ["agent", "human", "service"].includes(assignee.kind), "INVALID_PRINCIPAL");
725
+ _chunk4KF7KUAIcjs.identity.call(void 0, assignee.id);
726
+ if (item.inputs !== void 0) _chunk4KF7KUAIcjs.requireValue.call(void 0, item.inputs && typeof item.inputs === "object" && !Array.isArray(item.inputs), "INVALID_INPUT_BINDINGS");
727
+ if (item.outputs !== void 0) _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, ["proposed", "backlog", "open"].includes(item.status) && !item.owner && _optionalChain([item, 'access', _110 => _110.launch, 'optionalAccess', _111 => _111.admittedAt]) === void 0, "TASK_DEFINITION_FROZEN");
737
+ if (_chunkKYNYPKKHcjs.taskEditing.call(void 0, item, now)) _chunk4KF7KUAIcjs.requireValue.call(void 0, item.launch.editing.id === editId && !!actor && _chunk4KF7KUAIcjs.principalKey.call(void 0, item.launch.editing.principal) === _chunk4KF7KUAIcjs.principalKey.call(void 0, _chunk4KF7KUAIcjs.principal.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, item, "ITEM_NOT_FOUND");
742
+ item.launch ??= { startAt: _chunkKYNYPKKHcjs.taskStartAt.call(void 0, 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
+ _chunk4KF7KUAIcjs.identity.call(void 0, command.retryId);
746
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, ["failed", "clarification"].includes(_nullishCoalesce(_optionalChain([item, 'access', _112 => _112.analysis, 'optionalAccess', _113 => _113.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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _chunkLSE6JG5Icjs.boardAllowsStart.call(void 0, state.board, item), "BOARD_EXECUTION_PAUSED");
759
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, command.trigger === "manual" ? item.launch.requestedAt !== void 0 : _chunkKYNYPKKHcjs.taskDue.call(void 0, item, now), "START_NOT_DUE");
760
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !item.blocked && _optionalChain([item, 'access', _114 => _114.control, 'optionalAccess', _115 => _115.action]) !== "pause", "ITEM_BLOCKED");
761
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _nullishCoalesce(_optionalChain([item, 'access', _116 => _116.planning, 'optionalAccess', _117 => _117.dependencies, 'access', _118 => _118.every, 'call', _119 => _119((id) => _optionalChain([catalog, 'call', _120 => _120(state), 'access', _121 => _121.find, 'call', _122 => _122((i) => i.id === id), 'optionalAccess', _123 => _123.status]) === "completed")]), () => ( true)), "DEPENDENCIES_UNFINISHED");
762
+ item.launch.admittedAt = now;
763
+ } else if (command.type === "report-analysis") {
764
+ requireCoordinator(state, actor);
765
+ _chunk4KF7KUAIcjs.identity.call(void 0, command.operationId);
766
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _optionalChain([item, 'access', _124 => _124.control, 'optionalAccess', _125 => _125.id]) === command.controlId, "STALE_CONTROL_RECEIPT");
772
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, ["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
+ _chunk4KF7KUAIcjs.identity.call(void 0, command.editId);
783
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, Number.isSafeInteger(command.leaseMs) && command.leaseMs >= 1e3 && command.leaseMs <= 3e5, "INVALID_EDIT_LEASE");
784
+ item.launch.editing = { id: command.editId, principal: _chunk4KF7KUAIcjs.principal.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _chunkKYNYPKKHcjs.taskEditing.call(void 0, item, now) && item.launch.editing.id === command.editId, "EDIT_LEASE_EXPIRED");
790
+ if (command.type === "save-edit") {
791
+ _chunk4KF7KUAIcjs.text.call(void 0, command.title);
792
+ _chunk4KF7KUAIcjs.text.call(void 0, command.responsibility);
793
+ _chunk4KF7KUAIcjs.text.call(void 0, 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(_nullishCoalesce(_optionalChain([state, 'access', _126 => _126.workflow, 'optionalAccess', _127 => _127.plans]), () => ( {})))) {
803
+ const definition = plan2.definitions[item.id];
804
+ if (!definition) continue;
805
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, Object.values(_nullishCoalesce(definition.inputs, () => ( {}))).every((binding) => _optionalChain([item, 'access', _128 => _128.planning, 'optionalAccess', _129 => _129.dependencies, 'access', _130 => _130.includes, 'call', _131 => _131(binding.fromItemId)])), "EXISTING_DEPENDENCY_REQUIRED");
806
+ definition.digest = _chunk6MN3H3YFcjs.sha256HexSync.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !["completed", "cancelled", "review"].includes(item.status), "ITEM_COMPLETED");
812
+ _chunk4KF7KUAIcjs.identity.call(void 0, command.controlId);
813
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, ["pause", "resume"].includes(command.action), "INVALID_CONTROL_ACTION");
814
+ if (_optionalChain([item, 'access', _132 => _132.control, 'optionalAccess', _133 => _133.id]) === command.controlId) {
815
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, item.control.action === command.action, "IDEMPOTENCY_CONFLICT");
816
+ return;
817
+ }
818
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !item.control || !["requested", "unknown"].includes(item.control.state), "CONTROL_UNSETTLED");
819
+ const dispatch = Object.values(_nullishCoalesce(_optionalChain([state, 'access', _134 => _134.workflow, 'optionalAccess', _135 => _135.dispatches]), () => ( {}))).find((d) => d.itemId === item.id && ["prepared", "running", "unknown"].includes(d.outcome));
820
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, dispatch || _optionalChain([item, 'access', _136 => _136.launch, 'optionalAccess', _137 => _137.admittedAt]) === void 0, "TASK_CONTROL_UNSUPPORTED");
821
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, command.action === "pause" || _optionalChain([item, 'access', _138 => _138.control, 'optionalAccess', _139 => _139.action]) === "pause", "TASK_NOT_PAUSED");
822
+ item.control = { id: command.controlId, dispatchId: _optionalChain([dispatch, 'optionalAccess', _140 => _140.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
+ _chunk4KF7KUAIcjs.identity.call(void 0, issue.id);
829
+ _chunk4KF7KUAIcjs.identity.call(void 0, issue.attemptId);
830
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !issue.resolvedBy && ["clarification", "error"].includes(issue.type), "INVALID_ISSUE");
831
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _optionalChain([state, 'access', _141 => _141.workflow, 'optionalAccess', _142 => _142.dispatches, 'access', _143 => _143[issue.attemptId], 'optionalAccess', _144 => _144.itemId]) === item.id && _optionalChain([item, 'access', _145 => _145.owner, 'optionalAccess', _146 => _146.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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, item.issues.length < 200, "ISSUE_LIMIT");
836
+ item.issues.push(structuredClone(issue));
837
+ }
838
+ } else if (command.type === "resolve-issue") {
839
+ const issue = _optionalChain([item, 'access', _147 => _147.issues, 'optionalAccess', _148 => _148.find, 'call', _149 => _149((i) => i.id === command.issueId && i.attemptId === command.attemptId)]);
840
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, issue, "ISSUE_NOT_FOUND");
841
+ _chunk4KF7KUAIcjs.identity.call(void 0, command.resolvedBy);
842
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !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(_nullishCoalesce(_optionalChain([state, 'access', _150 => _150.workflow, 'optionalAccess', _151 => _151.dispatches]), () => ( {}))).filter((d) => d.itemId === item.id).sort((a, b) => a.attempt - b.attempt)[0];
849
+ const admittedAt = _nullishCoalesce(_optionalChain([first, 'optionalAccess', _152 => _152.preparedAt]), () => ( _optionalChain([item, 'access', _153 => _153.owner, 'optionalAccess', _154 => _154.claimedAt])));
850
+ item.launch = { startAt: _chunkKYNYPKKHcjs.taskStartAt.call(void 0, item), ...admittedAt === void 0 ? {} : { admittedAt } };
851
+ item.revision++;
852
+ return true;
853
+ }
854
+ function setMode(item, mode) {
855
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, ["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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, actor.kind === "human", "FORBIDDEN");
863
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, command.mode !== void 0 || command.paused !== void 0, "INVALID_BOARD_CONTROL");
864
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, command.mode === void 0 || ["automatic", "manual"].includes(command.mode), "INVALID_LAUNCH_MODE");
865
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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) _chunk4KF7KUAIcjs.requireValue.call(void 0, !state.board.items.some((item) => policy2.controls[item.id] === _optionalChain([item, 'access', _155 => _155.control, 'optionalAccess', _156 => _156.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(_nullishCoalesce(_optionalChain([state, 'access', _157 => _157.workflow, 'optionalAccess', _158 => _158.dispatches]), () => ( {}))).some((d) => d.itemId === item.id && ["prepared", "running", "unknown"].includes(d.outcome));
875
+ const managed = policy2.controls[item.id] === _optionalChain([item, 'access', _159 => _159.control, 'optionalAccess', _160 => _160.id]);
876
+ if (policy2.paused ? !active || _optionalChain([item, 'access', _161 => _161.control, 'optionalAccess', _162 => _162.action]) === "pause" : !managed || _optionalChain([item, 'access', _163 => _163.control, 'optionalAccess', _164 => _164.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 = _chunk4KF7KUAIcjs.discoveryState.call(void 0, state), pending = _optionalChain([discovery, 'optionalAccess', _165 => _165.pending]);
887
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, pending && pending.runId === batch.runId && pending.token === batch.leaseToken && pending.leaseUntil > now, "SCAN_LEASE_EXPIRED");
888
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _optionalChain([pending, 'access', _166 => _166.request, 'optionalAccess', _167 => _167.command, 'access', _168 => _168.type]) === "apply-discovery" && JSON.stringify(pending.request.command.batch) === JSON.stringify(batch), "SCAN_BATCH_MISMATCH");
889
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, batch.changes.length <= 50, "SCAN_CHANGE_LIMIT");
890
+ for (const change of batch.changes) {
891
+ _chunk4KF7KUAIcjs.identity.call(void 0, change.itemId);
892
+ validateSources(change.sources);
893
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, (_nullishCoalesce(_optionalChain([batch, 'access', _169 => _169.records, 'optionalAccess', _170 => _170.length]), () => ( 0))) <= 20, "SCAN_RECORD_LIMIT");
898
+ for (const record of _nullishCoalesce(batch.records, () => ( []))) {
899
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, record.sources.some((source) => source.role === "user"), "USER_EVIDENCE_REQUIRED");
900
+ const duplicate = _optionalChain([state, 'access', _171 => _171.records, 'optionalAccess', _172 => _172.some, 'call', _173 => _173((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
+ _chunk4KF7KUAIcjs.text.call(void 0, change.title);
912
+ _chunk4KF7KUAIcjs.text.call(void 0, change.responsibility);
913
+ _chunk4KF7KUAIcjs.text.call(void 0, change.acceptance);
914
+ const item = {
915
+ origin: { kind: "discovery", principal: _chunk4KF7KUAIcjs.principal.call(void 0, 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 + _chunkKYNYPKKHcjs.TASK_START_DELAY_MS };
932
+ item.planning = _nullishCoalesce(change.planning, () => ( { ...plan(item), kind: _nullishCoalesce(state.board.defaultWorkType, () => ( "task")) }));
933
+ const fingerprint = workFingerprint(item);
934
+ item.origin.fingerprint = fingerprint;
935
+ _chunk4KF7KUAIcjs.validateCandidates.call(void 0, state.board, item, _chunk4KF7KUAIcjs.executable.call(void 0, state.board, item));
936
+ if (_optionalChain([state, 'access', _174 => _174.archiveIndex, 'optionalAccess', _175 => _175.some, 'call', _176 => _176((old) => old.discoveryFingerprint === fingerprint)])) return void 0;
937
+ const existing = state.board.items.find((old) => workFingerprint(old) === fingerprint || _optionalChain([old, 'access', _177 => _177.origin, 'optionalAccess', _178 => _178.fingerprint]) === fingerprint);
938
+ if (existing) {
939
+ existing.revision++;
940
+ existing.updatedAt = now;
941
+ return existing;
942
+ }
943
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !state.board.items.some((old) => old.id === change.itemId) && !_optionalChain([state, 'access', _179 => _179.archiveIndex, 'optionalAccess', _180 => _180.some, 'call', _181 => _181((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) _chunk4KF7KUAIcjs.participant.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, item, "ITEM_NOT_FOUND");
953
+ if (change.action === "update") {
954
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !change.planning, "SCAN_PLANNING_REQUIRES_REVIEW");
955
+ const ownDraft = item.status === "proposed" && _optionalChain([item, 'access', _182 => _182.origin, 'optionalAccess', _183 => _183.kind]) === "discovery" && _chunk4KF7KUAIcjs.principalKey.call(void 0, item.origin.principal) === _chunk4KF7KUAIcjs.principalKey.call(void 0, _chunk4KF7KUAIcjs.principal.call(void 0, actor));
956
+ if (ownDraft) {
957
+ _chunk4KF7KUAIcjs.text.call(void 0, change.title);
958
+ _chunk4KF7KUAIcjs.text.call(void 0, change.responsibility);
959
+ _chunk4KF7KUAIcjs.text.call(void 0, 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 _chunk4KF7KUAIcjs.requireValue.call(void 0, 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 = _nullishCoalesce(_optionalChain([item, 'access', _184 => _184.participants, 'access', _185 => _185.find, 'call', _186 => _186((p) => p.sessionId === source.sessionId), 'optionalAccess', _187 => _187.subscribed]), () => ( false));
972
+ _chunk4KF7KUAIcjs.participant.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, ref && typeof ref === "object", "INVALID_AUTOMATION_TARGET");
983
+ _chunk4KF7KUAIcjs.identity.call(void 0, ref.system);
984
+ _chunk4KF7KUAIcjs.identity.call(void 0, ref.id);
985
+ _chunk4KF7KUAIcjs.identity.call(void 0, _nullishCoalesce(ref.revision, () => ( "")));
986
+ }
987
+ validateOptions(settings.preparationOptions);
988
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, settings.preparation || !Object.keys(_nullishCoalesce(settings.preparationOptions, () => ( {}))).length, "PREPARATION_REQUIRED");
989
+ const members = [..._nullishCoalesce(board.members, () => ( [])), ...(_nullishCoalesce(board.agents, () => ( []))).filter((agent) => !_optionalChain([board, 'access', _188 => _188.members, 'optionalAccess', _189 => _189.some, 'call', _190 => _190((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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, principal2 && ["agent", "human", "service"].includes(principal2.kind), "INVALID_PRINCIPAL");
992
+ _chunk4KF7KUAIcjs.identity.call(void 0, principal2.id);
993
+ const existing = members.find((member) => member.kind === principal2.kind && member.id === principal2.id);
994
+ if (existing) existing.roles = [.../* @__PURE__ */ new Set([..._nullishCoalesce(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
+ _chunk4KF7KUAIcjs.validateBoard.call(void 0, 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([..._nullishCoalesce(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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, /^[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
+ _chunk4KF7KUAIcjs.identity.call(void 0, command.dispatchId);
1022
+ const workflow = state.workflow, previous = workflow.dispatches[command.previousDispatchId];
1023
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, previous && ["failed", "cancelled"].includes(previous.outcome), "EXECUTION_NOT_CONTINUABLE");
1024
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !workflow.dispatches[command.dispatchId], "DISPATCH_EXISTS");
1025
+ const item = state.board.items.find((item2) => item2.id === previous.itemId), plan2 = workflow.plans[previous.planId];
1026
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, attempts.every((row) => row.attempt <= previous.attempt), "STALE_CONTINUATION");
1029
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !attempts.some((row) => ["prepared", "running", "unknown", "succeeded"].includes(row.outcome)), "EXECUTION_UNSETTLED");
1030
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _optionalChain([plan2, 'optionalAccess', _191 => _191.revision]) === previous.planRevision && _optionalChain([plan2, 'access', _192 => _192.definitions, 'access', _193 => _193[item.id], 'optionalAccess', _194 => _194.digest]) === previous.definitionDigest, "PLAN_CHANGED");
1031
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, command.instruction === void 0 || typeof command.instruction === "string" && command.instruction.trim().length > 0 && command.instruction.length <= 8e3, "INVALID_CONTINUATION_INSTRUCTION");
1032
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !item.blocked || item.blocked.reason === (_nullishCoalesce(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(_nullishCoalesce(_optionalChain([state, 'access', _195 => _195.workflow, 'optionalAccess', _196 => _196.dispatches]), () => ( {}))).some((dispatch) => ["prepared", "running", "unknown", "succeeded"].includes(dispatch.outcome))) {
1059
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _chunkPSKQAFDFcjs.sameAutomationBinding.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !["edit-item", "plan-item", "review-amendment"].includes(command.type), "PLAN_ITEM_CHANGED_REQUIRES_NEW_ID");
1065
+ if (plan2.sealed) _chunk4KF7KUAIcjs.requireValue.call(void 0, !["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) _chunk4KF7KUAIcjs.requireValue.call(void 0, !["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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !_optionalChain([state, 'access', _197 => _197.board, 'access', _198 => _198.executionControl, 'optionalAccess', _199 => _199.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
+ _chunk4KF7KUAIcjs.identity.call(void 0, command.dispatchId);
1084
+ const workflow = state.workflow;
1085
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !workflow.dispatches[command.dispatchId], "DISPATCH_EXISTS");
1086
+ refreshReady(state);
1087
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, workflow.ready.includes(command.itemId), "WORK_NOT_READY");
1088
+ const plan2 = Object.values(workflow.plans).find((plan3) => plan3.itemIds.includes(command.itemId));
1089
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !_chunkKYNYPKKHcjs.taskEditing.call(void 0, item, now), "EDIT_LEASE_ACTIVE");
1093
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !_optionalChain([state, 'access', _200 => _200.board, 'access', _201 => _201.executionControl, 'optionalAccess', _202 => _202.paused]), "BOARD_EXECUTION_PAUSED");
1094
+ if (command.trigger === "automatic") _chunk4KF7KUAIcjs.requireValue.call(void 0, _chunkLSE6JG5Icjs.boardAllowsStart.call(void 0, state.board, item) && _chunkKYNYPKKHcjs.taskDue.call(void 0, item, now), "START_NOT_DUE");
1095
+ item.launch ??= { startAt: _chunkKYNYPKKHcjs.taskStartAt.call(void 0, 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(_nullishCoalesce(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 = _optionalChain([producer, 'optionalAccess', _203 => _203.outputs, 'optionalAccess', _204 => _204.find, 'call', _205 => _205((output2) => output2.name === binding.output)]);
1102
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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: _chunk4KF7KUAIcjs.principal.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, command.fence === dispatch.fence && ["prepared", "running", "unknown"].includes(dispatch.outcome), "STALE_EXECUTION_RESULT");
1112
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, ["running", "unknown", "succeeded", "failed", "cancelled"].includes(command.outcome), "INVALID_EXECUTION_OUTCOME");
1113
+ if (command.code !== void 0) _chunk4KF7KUAIcjs.requireValue.call(void 0, /^[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
+ _chunk4KF7KUAIcjs.identity.call(void 0, command.executionSessionId);
1117
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !dispatch.executionSessionId || dispatch.executionSessionId === command.executionSessionId, "EXECUTION_SESSION_LOCKED");
1118
+ dispatch.executionSessionId = command.executionSessionId;
1119
+ }
1120
+ if (command.controlCapabilities) {
1121
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, ["boundary", "none"].includes(command.controlCapabilities.pause) && typeof command.controlCapabilities.resume === "boolean", "INVALID_CONTROL_CAPABILITIES");
1122
+ dispatch.controlCapabilities = structuredClone(command.controlCapabilities);
1123
+ }
1124
+ const outputs = _nullishCoalesce(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 (!_chunk4XF6LQSUcjs.executionObservationChanged.call(void 0, dispatch, command)) return false;
1128
+ if (command.outcome === "succeeded") {
1129
+ const required = state.workflow.plans[dispatch.planId].definitions[item.id].outputs;
1130
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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: _nullishCoalesce(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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, dispatch, "DISPATCH_NOT_FOUND");
1162
+ const item = state.board.items.find((item2) => item2.id === dispatch.itemId), plan2 = state.workflow.plans[dispatch.planId];
1163
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _optionalChain([plan2, 'optionalAccess', _206 => _206.revision]) === dispatch.planRevision && _optionalChain([item, 'optionalAccess', _207 => _207.owner, 'optionalAccess', _208 => _208.token]) === dispatch.fence && _optionalChain([plan2, 'access', _209 => _209.definitions, 'access', _210 => _210[dispatch.itemId], 'optionalAccess', _211 => _211.digest]) === dispatch.definitionDigest, "STALE_EXECUTION_RESULT");
1164
+ return dispatch;
1165
+ }
1166
+ function validateOutputs(outputs) {
1167
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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) _chunk4KF7KUAIcjs.requireValue.call(void 0, /^[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) => _optionalChain([all, 'access', _212 => _212.find, 'call', _213 => _213((item) => item.id === id), 'optionalAccess', _214 => _214.status]) === "completed")).map((plan2) => plan2.id);
1174
+ state.workflow.ready = state.board.items.filter((item) => included.has(item.id) && _chunkPSKQAFDFcjs.executableWorkItem.call(void 0, state.board, item) && ["backlog", "open"].includes(item.status) && !item.owner && !item.blocked && _optionalChain([item, 'access', _215 => _215.control, 'optionalAccess', _216 => _216.action]) !== "pause" && (_nullishCoalesce(_optionalChain([item, 'access', _217 => _217.planning, 'optionalAccess', _218 => _218.dependencies]), () => ( []))).every((id) => _optionalChain([all, 'access', _219 => _219.find, 'call', _220 => _220((other) => other.id === id), 'optionalAccess', _221 => _221.status]) === "completed")).map((item) => item.id);
1175
+ }
1176
+
1177
+ // src/transitions.ts
1178
+ function transition(state, item, command, actor, now, token) {
1179
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.owned.call(void 0, item, actor, command.token, now);
1184
+ if (command.type === "submit") _chunk4KF7KUAIcjs.requireValue.call(void 0, 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 = _chunk4KF7KUAIcjs.principalKey.call(void 0, _chunk4KF7KUAIcjs.principal.call(void 0, actor));
1194
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !_chunkKYNYPKKHcjs.taskEditing.call(void 0, item, now), "EDIT_LEASE_ACTIVE");
1195
+ _chunk4KF7KUAIcjs.eligible.call(void 0, board, item, actor);
1196
+ assertReady(state, item);
1197
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, command.estimate || board.policy.requireEstimate === false, "ESTIMATE_REQUIRED");
1198
+ if (command.estimate) _chunk4KF7KUAIcjs.validateEstimate.call(void 0, command.estimate);
1199
+ const wip = board.items.filter((i) => i.status === "claimed" || i.status === "review");
1200
+ if (command.type === "claim") _chunk4KF7KUAIcjs.requireValue.call(void 0, wip.length < limits(state).inProgress, "WIP_LIMIT");
1201
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, wip.filter((i) => i.id !== item.id && i.owner && _chunk4KF7KUAIcjs.assigneeKey.call(void 0, i.owner) === key).length < limits(state).perAssignee, _chunk4KF7KUAIcjs.principal.call(void 0, actor).kind === "agent" ? "AGENT_WIP_LIMIT" : "ASSIGNEE_WIP_LIMIT");
1202
+ if (command.type === "claim") _chunk4KF7KUAIcjs.requireValue.call(void 0, item.status === "open" && !item.owner, "ALREADY_OWNED");
1203
+ else {
1204
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, item.status === "claimed" && item.transfer && _chunk4KF7KUAIcjs.principalKey.call(void 0, transferTarget(item.transfer)) === key, "TRANSFER_NOT_OFFERED");
1205
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, item.transfer.expiresAt > now && item.owner && item.owner.leaseUntil > now, "TRANSFER_EXPIRED");
1206
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _chunk4KF7KUAIcjs.assigneeKey.call(void 0, 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) _chunk4KF7KUAIcjs.participant.call(void 0, item.participants, actor.sessionId, actor.agentId, "owner", true, now);
1214
+ }
1215
+ function review(state, item, accept2, actor, now) {
1216
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, item.status === "review", "NOT_IN_REVIEW");
1217
+ const key = _chunk4KF7KUAIcjs.principalKey.call(void 0, _chunk4KF7KUAIcjs.principal.call(void 0, actor));
1218
+ const registered = actor.sessionId && item.participants.some((p) => p.sessionId === actor.sessionId && p.roles.includes("reviewer")) || _optionalChain([state, 'access', _222 => _222.board, 'access', _223 => _223.members, 'optionalAccess', _224 => _224.some, 'call', _225 => _225((m) => _chunk4KF7KUAIcjs.principalKey.call(void 0, m) === key && _optionalChain([m, 'access', _226 => _226.roles, 'optionalAccess', _227 => _227.includes, 'call', _228 => _228("reviewer")]))]);
1219
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, registered, "REVIEWER_REQUIRED");
1220
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !item.owner || _chunk4KF7KUAIcjs.assigneeKey.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.validateEstimate.call(void 0, 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
+ _chunk4KF7KUAIcjs.text.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, Boolean(command.target) !== Boolean(command.agentId), "TRANSFER_TARGET_REQUIRED");
1258
+ const target = _nullishCoalesce(command.target, () => ( { kind: "agent", id: command.agentId })), key = _chunk4KF7KUAIcjs.principalKey.call(void 0, target);
1259
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _chunk4KF7KUAIcjs.candidates.call(void 0, board, item).some((p) => _chunk4KF7KUAIcjs.principalKey.call(void 0, p) === key), "AGENT_NOT_ELIGIBLE");
1260
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _chunk4KF7KUAIcjs.assigneeKey.call(void 0, item.owner) !== key, "SELF_TRANSFER");
1261
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !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 _nullishCoalesce(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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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
+ _chunk4KF7KUAIcjs.participant.call(void 0, list, command.sessionId, command.agentId, command.role, command.subscribed, now);
1298
+ if (item) item.revision++;
1299
+ } else if (command.type === "message") {
1300
+ _chunk4KF7KUAIcjs.text.call(void 0, command.message);
1301
+ command.recipientSessionIds.forEach(_chunk4KF7KUAIcjs.identity);
1302
+ if (command.itemId) itemFor(board, command.itemId);
1303
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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 ? _optionalChain([state, 'access', _229 => _229.workflow, 'optionalAccess', _230 => _230.dispatches, 'access', _231 => _231[command.dispatchId], 'optionalAccess', _232 => _232.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
+ _chunk4KF7KUAIcjs.identity.call(void 0, input.id);
1325
+ _chunk4KF7KUAIcjs.text.call(void 0, input.title);
1326
+ _chunk4KF7KUAIcjs.text.call(void 0, input.responsibility);
1327
+ _chunk4KF7KUAIcjs.text.call(void 0, input.acceptance);
1328
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !board.items.some((i) => i.id === input.id) && !_optionalChain([state, 'access', _233 => _233.archiveIndex, 'optionalAccess', _234 => _234.some, 'call', _235 => _235((i) => i.id === input.id)]), "ITEM_EXISTS");
1329
+ const item = { ...input, origin: { kind: "direct", principal: _chunk4KF7KUAIcjs.principal.call(void 0, actor) }, status: "backlog", revision: 1, createdAt: now, readyAt: now, updatedAt: now, workUnits: 0, participants: [] };
1330
+ item.launch = { startAt: now + _chunkKYNYPKKHcjs.TASK_START_DELAY_MS };
1331
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _optionalChain([command, 'access', _236 => _236.launch, 'optionalAccess', _237 => _237.mode]) === void 0 || ["automatic", "manual"].includes(command.launch.mode), "INVALID_LAUNCH_MODE");
1332
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, _optionalChain([command, 'access', _238 => _238.launch, 'optionalAccess', _239 => _239.paused]) === void 0 || typeof command.launch.paused === "boolean", "INVALID_TASK_PAUSE");
1333
+ if (_optionalChain([command, 'access', _240 => _240.launch, 'optionalAccess', _241 => _241.mode])) item.launch.mode = command.launch.mode;
1334
+ if (_optionalChain([command, 'access', _242 => _242.launch, 'optionalAccess', _243 => _243.paused])) item.control = { id: "initial-" + token, action: "pause", state: "paused" };
1335
+ item.planning = _nullishCoalesce(command.planning, () => ( { ...plan(item), kind: _nullishCoalesce(board.defaultWorkType, () => ( "task")) }));
1336
+ const references = _nullishCoalesce(item.externalRefs, () => ( []));
1337
+ item.externalRefs = [];
1338
+ for (const reference of references) attachReference(item, reference);
1339
+ _chunk4KF7KUAIcjs.validateCandidates.call(void 0, board, item, _chunk4KF7KUAIcjs.executable.call(void 0, 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 (_optionalChain([parent, 'access', _244 => _244.planning, 'optionalAccess', _245 => _245.execution]) !== "children") {
1344
+ parent.planning = { ...plan(parent), execution: "children" };
1345
+ parent.updatedAt = now;
1346
+ parent.revision++;
1347
+ }
1348
+ }
1349
+ if (actor.sessionId) _chunk4KF7KUAIcjs.participant.call(void 0, 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
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, 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 = _nullishCoalesce(_optionalChain([state, 'access', _246 => _246.archiveWrites, 'optionalAccess', _247 => _247.flatMap, 'call', _248 => _248((write) => _nullishCoalesce(_optionalChain([write, 'access', _249 => _249.value, 'optionalAccess', _250 => _250.item, 'access', _251 => _251.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(_nullishCoalesce(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" ? _optionalChain([item, 'access', _252 => _252.transfer, 'optionalAccess', _253 => _253.id]) : reason === "backlog-review" ? item.updatedAt : _nullishCoalesce(_optionalChain([item, 'access', _254 => _254.owner, 'optionalAccess', _255 => _255.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 (_optionalChain([item, 'access', _256 => _256.planning, 'optionalAccess', _257 => _257.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 - (_nullishCoalesce(item.progressAt, () => ( item.owner.claimedAt))) >= p.progressTimeoutMs) result.push("no-progress");
1415
+ if (now - item.owner.claimedAt >= Math.min(_nullishCoalesce(_optionalChain([item, 'access', _258 => _258.estimate, 'optionalAccess', _259 => _259.durationMs]), () => ( p.maxDurationMs)), p.maxDurationMs)) result.push("execution-timeout");
1416
+ if ((_nullishCoalesce(_optionalChain([item, 'access', _260 => _260.estimate, 'optionalAccess', _261 => _261.complexity]), () => ( 0))) >= p.maxComplexity) result.push("complexity-threshold");
1417
+ if (Math.max(item.workUnits, _nullishCoalesce(_optionalChain([item, 'access', _262 => _262.estimate, 'optionalAccess', _263 => _263.workUnits]), () => ( 0))) >= p.maxWorkUnits) result.push("work-threshold");
1418
+ if ((_nullishCoalesce(_optionalChain([item, 'access', _264 => _264.estimate, 'optionalAccess', _265 => _265.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_" + (_optionalChain([state, 'access', _266 => _266.board, 'access', _267 => _267.executionControl, 'optionalAccess', _268 => _268.paused]) ? "PAUSE_REQUESTED" : _optionalChain([state, 'access', _269 => _269.board, 'access', _270 => _270.executionControl, 'optionalAccess', _271 => _271.mode, 'optionalAccess', _272 => _272.toUpperCase, 'call', _273 => _273()])) };
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: _optionalChain([state, 'access', _274 => _274.workflow, 'optionalAccess', _275 => _275.ready]), ..."dispatchId" in command ? { dispatchId: command.dispatchId } : { planId: command.plan.id }, ..."outcome" in command ? { reason: `execution-${command.outcome}`, code: command.code, status: _optionalChain([state, 'access', _276 => _276.board, 'access', _277 => _277.items, 'access', _278 => _278.find, 'call', _279 => _279((item) => item.id === _optionalChain([state, 'access', _280 => _280.workflow, 'optionalAccess', _281 => _281.dispatches, 'access', _282 => _282[command.dispatchId], 'optionalAccess', _283 => _283.itemId])), 'optionalAccess', _284 => _284.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: _optionalChain([Object, 'access', _285 => _285.values, 'call', _286 => _286(_nullishCoalesce(_optionalChain([state, 'access', _287 => _287.workflow, 'optionalAccess', _288 => _288.dispatches]), () => ( {}))), 'access', _289 => _289.find, 'call', _290 => _290((dispatch) => dispatch.itemId === command.itemId && dispatch.outcome === "succeeded"), 'optionalAccess', _291 => _291.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: _optionalChain([batch, 'access', _292 => _292.records, 'optionalAccess', _293 => _293.filter, 'call', _294 => _294((record) => _optionalChain([state, 'access', _295 => _295.records, 'optionalAccess', _296 => _296.some, 'call', _297 => _297((entry) => entry.id === record.id && entry.originRunId === batch.runId)])), 'access', _298 => _298.map, 'call', _299 => _299((record) => record.id)]),
1450
+ ...state.board.items.some((item) => _optionalChain([item, 'access', _300 => _300.amendments, 'optionalAccess', _301 => _301.some, 'call', _302 => _302((proposal) => proposal.runId === batch.runId && proposal.status === "pending")])) ? { reason: "amendment-proposed" } : state.board.items.some((item) => item.status === "proposed" && _optionalChain([item, 'access', _303 => _303.origin, 'optionalAccess', _304 => _304.runId]) === batch.runId) ? { reason: "proposal-created" } : {}
1451
+ };
1452
+ }
1453
+ function deleteBoard(state, actor, operationId, now) {
1454
+ const owner = _chunk4KF7KUAIcjs.principal.call(void 0, actor), board = state.board;
1455
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, owner.kind === "human" && _optionalChain([board, 'access', _305 => _305.members, 'optionalAccess', _306 => _306.some, 'call', _307 => _307((member) => member.kind === owner.kind && member.id === owner.id && _optionalChain([member, 'access', _308 => _308.roles, 'optionalAccess', _309 => _309.includes, 'call', _310 => _310("coordinator")]))]), "COORDINATOR_REQUIRED");
1456
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !board.items.some((item) => item.owner || item.transfer || item.status === "claimed"), "BOARD_EXECUTION_ACTIVE");
1457
+ _chunk4KF7KUAIcjs.requireValue.call(void 0, !Object.values(_nullishCoalesce(_optionalChain([state, 'access', _311 => _311.workflow, 'optionalAccess', _312 => _312.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
+
1467
+
1468
+
1469
+
1470
+
1471
+
1472
+
1473
+
1474
+
1475
+
1476
+
1477
+
1478
+
1479
+
1480
+
1481
+
1482
+
1483
+
1484
+
1485
+
1486
+
1487
+
1488
+
1489
+
1490
+
1491
+
1492
+
1493
+
1494
+
1495
+
1496
+
1497
+ exports.summary = summary; exports.terminal = terminal; exports.catalog = catalog; exports.limits = limits; exports.proposeAmendment = proposeAmendment; exports.queryRecords = queryRecords; exports.recordSummary = recordSummary; exports.createBoardState = createBoardState; exports.boardKey = boardKey; exports.archiveKey = archiveKey; exports.rowKeys = rowKeys; exports.hydrate = hydrate; exports.encodeBoard = encodeBoard; exports.rowChanges = rowChanges; exports.receiptDigest = receiptDigest; exports.verifyReceipt = verifyReceipt; exports.encodeRow = encodeRow; exports.decodeRow = decodeRow; exports.indexedView = indexedView; exports.viewFromState = viewFromState; exports.boardCounterKey = boardCounterKey; exports.boardNumberKey = boardNumberKey; exports.counter = counter; exports.storedBoardNumber = storedBoardNumber; exports.patchBoardNumber = patchBoardNumber; exports.numberEntities = numberEntities; exports.allocateBoardNumber = allocateBoardNumber; exports.reduce = reduce; exports.related = related; exports.escalationReasons = escalationReasons;
1498
+ //# sourceMappingURL=chunk-L44TM4EE.cjs.map