@aigile/engine 0.2.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/dist/action-item-features.d.ts +33 -0
  2. package/dist/action-item-features.d.ts.map +1 -0
  3. package/dist/action-item-features.js +113 -0
  4. package/dist/action-item-features.js.map +1 -0
  5. package/dist/action-items.d.ts +234 -0
  6. package/dist/action-items.d.ts.map +1 -0
  7. package/dist/action-items.js +722 -0
  8. package/dist/action-items.js.map +1 -0
  9. package/dist/action-sources.d.ts +44 -0
  10. package/dist/action-sources.d.ts.map +1 -0
  11. package/dist/action-sources.js +141 -0
  12. package/dist/action-sources.js.map +1 -0
  13. package/dist/agent-roles.d.ts +9 -0
  14. package/dist/agent-roles.d.ts.map +1 -0
  15. package/dist/agent-roles.js +18 -0
  16. package/dist/agent-roles.js.map +1 -0
  17. package/dist/agent-tasks.d.ts +36 -0
  18. package/dist/agent-tasks.d.ts.map +1 -0
  19. package/dist/agent-tasks.js +151 -0
  20. package/dist/agent-tasks.js.map +1 -0
  21. package/dist/agents/orchestrator.d.ts +26 -6
  22. package/dist/agents/orchestrator.d.ts.map +1 -1
  23. package/dist/agents/orchestrator.js +95 -45
  24. package/dist/agents/orchestrator.js.map +1 -1
  25. package/dist/agents/spec-analyst.d.ts +81 -13
  26. package/dist/agents/spec-analyst.d.ts.map +1 -1
  27. package/dist/agents/spec-analyst.js +350 -89
  28. package/dist/agents/spec-analyst.js.map +1 -1
  29. package/dist/ai-service.d.ts +40 -0
  30. package/dist/ai-service.d.ts.map +1 -1
  31. package/dist/ai-service.js +94 -9
  32. package/dist/ai-service.js.map +1 -1
  33. package/dist/api-tokens.d.ts +67 -0
  34. package/dist/api-tokens.d.ts.map +1 -0
  35. package/dist/api-tokens.js +89 -0
  36. package/dist/api-tokens.js.map +1 -0
  37. package/dist/attachments/extract.d.ts +26 -0
  38. package/dist/attachments/extract.d.ts.map +1 -0
  39. package/dist/attachments/extract.js +160 -0
  40. package/dist/attachments/extract.js.map +1 -0
  41. package/dist/attachments/fixtures.d.ts +9 -0
  42. package/dist/attachments/fixtures.d.ts.map +1 -0
  43. package/dist/attachments/fixtures.js +58 -0
  44. package/dist/attachments/fixtures.js.map +1 -0
  45. package/dist/attachments/service.d.ts +71 -0
  46. package/dist/attachments/service.d.ts.map +1 -0
  47. package/dist/attachments/service.js +220 -0
  48. package/dist/attachments/service.js.map +1 -0
  49. package/dist/build-service.d.ts +1 -1
  50. package/dist/build-service.d.ts.map +1 -1
  51. package/dist/build-service.js +9 -4
  52. package/dist/build-service.js.map +1 -1
  53. package/dist/change-events.d.ts +110 -0
  54. package/dist/change-events.d.ts.map +1 -0
  55. package/dist/change-events.js +238 -0
  56. package/dist/change-events.js.map +1 -0
  57. package/dist/change-sets.d.ts +110 -0
  58. package/dist/change-sets.d.ts.map +1 -0
  59. package/dist/change-sets.js +188 -0
  60. package/dist/change-sets.js.map +1 -0
  61. package/dist/command-runner.d.ts.map +1 -1
  62. package/dist/command-runner.js +2 -1
  63. package/dist/command-runner.js.map +1 -1
  64. package/dist/conversations.d.ts +2 -1
  65. package/dist/conversations.d.ts.map +1 -1
  66. package/dist/conversations.js +1 -1
  67. package/dist/conversations.js.map +1 -1
  68. package/dist/data-access.d.ts +9 -2
  69. package/dist/data-access.d.ts.map +1 -1
  70. package/dist/data-access.js +38 -6
  71. package/dist/data-access.js.map +1 -1
  72. package/dist/decisions.d.ts +56 -0
  73. package/dist/decisions.d.ts.map +1 -0
  74. package/dist/decisions.js +76 -0
  75. package/dist/decisions.js.map +1 -0
  76. package/dist/deliverables.d.ts +96 -0
  77. package/dist/deliverables.d.ts.map +1 -0
  78. package/dist/deliverables.js +344 -0
  79. package/dist/deliverables.js.map +1 -0
  80. package/dist/designs.d.ts +30 -0
  81. package/dist/designs.d.ts.map +1 -0
  82. package/dist/designs.js +154 -0
  83. package/dist/designs.js.map +1 -0
  84. package/dist/git-host.d.ts +10 -0
  85. package/dist/git-host.d.ts.map +1 -1
  86. package/dist/git-host.js +30 -2
  87. package/dist/git-host.js.map +1 -1
  88. package/dist/grounding.d.ts +9 -0
  89. package/dist/grounding.d.ts.map +1 -0
  90. package/dist/grounding.js +12 -0
  91. package/dist/grounding.js.map +1 -0
  92. package/dist/index.d.ts +35 -12
  93. package/dist/index.d.ts.map +1 -1
  94. package/dist/index.js +33 -10
  95. package/dist/index.js.map +1 -1
  96. package/dist/jira-features.d.ts +142 -0
  97. package/dist/jira-features.d.ts.map +1 -0
  98. package/dist/jira-features.js +366 -0
  99. package/dist/jira-features.js.map +1 -0
  100. package/dist/milestones.js +1 -1
  101. package/dist/milestones.js.map +1 -1
  102. package/dist/pull-request-sync.d.ts.map +1 -1
  103. package/dist/pull-request-sync.js +10 -6
  104. package/dist/pull-request-sync.js.map +1 -1
  105. package/dist/questions.d.ts +100 -10
  106. package/dist/questions.d.ts.map +1 -1
  107. package/dist/questions.js +211 -22
  108. package/dist/questions.js.map +1 -1
  109. package/dist/related.d.ts +26 -0
  110. package/dist/related.d.ts.map +1 -0
  111. package/dist/related.js +64 -0
  112. package/dist/related.js.map +1 -0
  113. package/dist/release-gates.d.ts +16 -0
  114. package/dist/release-gates.d.ts.map +1 -0
  115. package/dist/release-gates.js +47 -0
  116. package/dist/release-gates.js.map +1 -0
  117. package/dist/reviews.d.ts.map +1 -1
  118. package/dist/reviews.js +4 -3
  119. package/dist/reviews.js.map +1 -1
  120. package/dist/router.d.ts +2 -2
  121. package/dist/router.d.ts.map +1 -1
  122. package/dist/router.js.map +1 -1
  123. package/dist/scheduler.d.ts +41 -5
  124. package/dist/scheduler.d.ts.map +1 -1
  125. package/dist/scheduler.js +109 -7
  126. package/dist/scheduler.js.map +1 -1
  127. package/dist/services.d.ts +760 -15
  128. package/dist/services.d.ts.map +1 -1
  129. package/dist/services.js +402 -20
  130. package/dist/services.js.map +1 -1
  131. package/dist/source-sync.d.ts +136 -0
  132. package/dist/source-sync.d.ts.map +1 -0
  133. package/dist/source-sync.js +370 -0
  134. package/dist/source-sync.js.map +1 -0
  135. package/dist/sources/front-matter.d.ts +20 -0
  136. package/dist/sources/front-matter.d.ts.map +1 -0
  137. package/dist/sources/front-matter.js +57 -0
  138. package/dist/sources/front-matter.js.map +1 -0
  139. package/dist/sources/git.d.ts +80 -0
  140. package/dist/sources/git.d.ts.map +1 -0
  141. package/dist/sources/git.js +338 -0
  142. package/dist/sources/git.js.map +1 -0
  143. package/dist/sources/http.d.ts +54 -0
  144. package/dist/sources/http.d.ts.map +1 -0
  145. package/dist/sources/http.js +79 -0
  146. package/dist/sources/http.js.map +1 -0
  147. package/dist/spec-cache.d.ts +54 -0
  148. package/dist/spec-cache.d.ts.map +1 -0
  149. package/dist/spec-cache.js +133 -0
  150. package/dist/spec-cache.js.map +1 -0
  151. package/dist/spec-links.d.ts +68 -0
  152. package/dist/spec-links.d.ts.map +1 -0
  153. package/dist/spec-links.js +144 -0
  154. package/dist/spec-links.js.map +1 -0
  155. package/dist/spec-reader.d.ts +44 -0
  156. package/dist/spec-reader.d.ts.map +1 -0
  157. package/dist/spec-reader.js +81 -0
  158. package/dist/spec-reader.js.map +1 -0
  159. package/dist/spec-resolver.d.ts +13 -1
  160. package/dist/spec-resolver.d.ts.map +1 -1
  161. package/dist/spec-resolver.js +45 -8
  162. package/dist/spec-resolver.js.map +1 -1
  163. package/dist/spec-tools.d.ts +10 -0
  164. package/dist/spec-tools.d.ts.map +1 -0
  165. package/dist/spec-tools.js +103 -0
  166. package/dist/spec-tools.js.map +1 -0
  167. package/dist/task-scope.d.ts +11 -0
  168. package/dist/task-scope.d.ts.map +1 -0
  169. package/dist/task-scope.js +11 -0
  170. package/dist/task-scope.js.map +1 -0
  171. package/dist/telemetry.d.ts +34 -0
  172. package/dist/telemetry.d.ts.map +1 -0
  173. package/dist/telemetry.js +72 -0
  174. package/dist/telemetry.js.map +1 -0
  175. package/dist/template.d.ts +341 -0
  176. package/dist/template.d.ts.map +1 -0
  177. package/dist/template.js +142 -0
  178. package/dist/template.js.map +1 -0
  179. package/dist/tool-sandbox.d.ts.map +1 -1
  180. package/dist/tool-sandbox.js +2 -2
  181. package/dist/tool-sandbox.js.map +1 -1
  182. package/dist/tracks.d.ts +3 -3
  183. package/dist/tracks.js +1 -1
  184. package/dist/tracks.js.map +1 -1
  185. package/dist/verifier.d.ts.map +1 -1
  186. package/dist/verifier.js +8 -7
  187. package/dist/verifier.js.map +1 -1
  188. package/dist/vscode-connect.d.ts +48 -0
  189. package/dist/vscode-connect.d.ts.map +1 -0
  190. package/dist/vscode-connect.js +105 -0
  191. package/dist/vscode-connect.js.map +1 -0
  192. package/package.json +14 -3
  193. package/prompts/agent-task.contract.md +9 -0
  194. package/prompts/orchestrator.brief.md +17 -0
  195. package/prompts/orchestrator.contract.md +7 -0
  196. package/prompts/spec-analyst.brief.md +19 -0
  197. package/prompts/spec-analyst.contract.md +5 -0
  198. package/prompts/spec-analyst.sweep.md +2 -0
@@ -0,0 +1,722 @@
1
+ import { telemetry } from './telemetry.js';
2
+ import { BUILT_IN_ACTION_TYPES, COLLECTIONS, LEGACY_COLLECTIONS, newId, nowIso, actionItemSchema, parseRole, reviewLevelOf } from '@aigile/core';
3
+ import { FeatureResolver } from './action-item-features.js';
4
+ import { ConversationService } from './conversations.js';
5
+ import { DataAccess } from './data-access.js';
6
+ import { Router } from './router.js';
7
+ import { ServiceError } from './services.js';
8
+ const KIND_NAMES = { task: 'A task', question: 'A question', conflict: 'A conflict', review: 'A review', edit: 'An edit', approval: 'An approval', gate: 'A gate', publish: 'A publish gate', incident: 'An incident', signal: 'A signal' };
9
+ /** "A gate", or "A <kind>" for a type a template or a source added. */
10
+ const label = (kind) => KIND_NAMES[kind] ?? `A ${kind}`;
11
+ /** The ref of a review that asks the opener to accept an item's resolution. */
12
+ export const ACCEPTANCE_REF = 'action-item';
13
+ /**
14
+ * Action items: what waits for whom (documentation/action-items.md), shown as
15
+ * a person's queues, the Action items window and a feature's charts. Writes
16
+ * go to the datastore like everything else; reads go through the index, an
17
+ * in-memory view rebuilt from the datastore when it is stale (any write
18
+ * through this service marks it so; a process that only reads refreshes on a
19
+ * timer).
20
+ */
21
+ export class ActionItemService {
22
+ store;
23
+ maxAgeMs;
24
+ data;
25
+ conversations;
26
+ router;
27
+ index = null;
28
+ builtAt = 0;
29
+ /** Called when an agent's task is queued, so the queue can start it without waiting for a tick. */
30
+ onQueued = null;
31
+ /** The action types in use (the built-in ones, the templates'), for their review levels. */
32
+ types = BUILT_IN_ACTION_TYPES;
33
+ /** Where notices go besides a person's conversation (documentation/plugins.md: Teams); each takes the kinds it wants. */
34
+ notifiers = [];
35
+ /** The workspace's address, for the link in a notice. */
36
+ publicUrl = null;
37
+ /** Called when an item is resolved in aigile (not by its source): an action source writes it back. */
38
+ onResolved = null;
39
+ constructor(store, maxAgeMs = 5_000) {
40
+ this.store = store;
41
+ this.maxAgeMs = maxAgeMs;
42
+ this.data = new DataAccess(store);
43
+ this.conversations = new ConversationService(store);
44
+ this.router = new Router(store);
45
+ }
46
+ /** Every item, open and done, from the index. */
47
+ async all() {
48
+ if (this.index === null || Date.now() - this.builtAt >= this.maxAgeMs) {
49
+ this.index = await this.data.actionItems();
50
+ this.builtAt = Date.now();
51
+ }
52
+ return this.index;
53
+ }
54
+ invalidate() {
55
+ this.index = null;
56
+ }
57
+ /** A person's open items, newest first (one waiting for someone's acceptance is not theirs to act on). */
58
+ async openFor(userId) {
59
+ return (await this.all()).filter((i) => i.assigneeUserId === userId && i.status === 'open').sort((a, b) => b.createdAt.localeCompare(a.createdAt));
60
+ }
61
+ async get(id) {
62
+ const raw = (await this.store.get(COLLECTIONS.actionItems, id)) ?? (await this.store.get(LEGACY_COLLECTIONS.queueItems, id));
63
+ if (raw === null)
64
+ throw new ServiceError(404, `action item ${id} not found`);
65
+ return actionItemSchema.parse(raw);
66
+ }
67
+ /** Every write lands in `action-items`; a copy still in the older `queue-items` goes, so an item lives in one place. */
68
+ async save(item, message, actor) {
69
+ const opts = { message, ...(actor.author ? { author: actor.author } : {}) };
70
+ await this.store.put(COLLECTIONS.actionItems, item.id, item, opts);
71
+ if ((await this.store.get(LEGACY_COLLECTIONS.queueItems, item.id)) !== null)
72
+ await this.store.delete(LEGACY_COLLECTIONS.queueItems, item.id, { message: `Moved ${item.kind} ${item.id} to action-items`, ...(actor.author ? { author: actor.author } : {}) });
73
+ this.invalidate();
74
+ }
75
+ async notify(userId, body, actor, item) {
76
+ if (!userId || userId.startsWith('agent:'))
77
+ return;
78
+ await this.conversations.notify(userId, body, actor);
79
+ if (item)
80
+ await this.notice(item, userId, body);
81
+ }
82
+ /** The notice for the notifiers: an item waiting on someone, with a link to it. A notifier that fails is logged; nothing else stops. */
83
+ async notice(item, userId, body) {
84
+ if (this.notifiers.length === 0)
85
+ return;
86
+ const user = await this.store.get(COLLECTIONS.users, userId);
87
+ const who = [user?.firstName, user?.lastName].filter(Boolean).join(' ') || user?.email || userId;
88
+ const notice = { title: `${label(item.kind)} for ${who}: ${item.title}`, body: body.replace(/\*\*/g, ''), url: this.itemUrl(item.id), kind: item.kind, userIds: [userId], emails: user?.email ? [user.email] : [], key: item.id };
89
+ for (const n of this.notifiers.filter((x) => x.wants(notice))) {
90
+ try {
91
+ await n.send(notice);
92
+ }
93
+ catch (err) {
94
+ console.warn(`[aigile] notifier ${n.id}: ${err instanceof Error ? err.message : String(err)}`);
95
+ }
96
+ }
97
+ }
98
+ /** The item in aigile, for a link in a notice or a write-back; null without `publicUrl`. */
99
+ itemUrl(id) {
100
+ return this.publicUrl ? `${this.publicUrl.replace(/\/+$/, '')}/?w=action-item%3A${encodeURIComponent(id)}` : null;
101
+ }
102
+ /** The item is done: the notifiers that resolve what they opened (PagerDuty) hear it; the rest post nothing. */
103
+ async resolvedNotice(item) {
104
+ const resolving = this.notifiers.filter((n) => typeof n.resolve === 'function');
105
+ if (resolving.length === 0)
106
+ return;
107
+ const userIds = item.assigneeUserId ? [item.assigneeUserId] : [];
108
+ const notice = { title: `Done: ${item.title}`, body: item.resolution?.note ?? '', url: this.itemUrl(item.id), kind: item.kind, userIds, key: item.id };
109
+ for (const n of resolving.filter((x) => x.wants(notice))) {
110
+ try {
111
+ await n.resolve(notice);
112
+ }
113
+ catch (err) {
114
+ console.warn(`[aigile] notifier ${n.id}: ${err instanceof Error ? err.message : String(err)}`);
115
+ }
116
+ }
117
+ }
118
+ /**
119
+ * Whether a new item's resolution is reviewed (documentation/action-items.md
120
+ * "Reviews"): `never` and `always` types decide; within `optional` and
121
+ * `default`, the requester's say wins over the type's default.
122
+ */
123
+ reviewFor(kind, requested, byUserId) {
124
+ const level = reviewLevelOf(kind, this.types);
125
+ if (level === 'never' || level === 'always' || requested === undefined)
126
+ return { required: level === 'always' || level === 'default', decidedBy: 'type', byUserId: null, reviewers: [], acceptedBy: [] };
127
+ return { required: requested, decidedBy: 'requester', byUserId, reviewers: [], acceptedBy: [] };
128
+ }
129
+ /** An item's review as it stands (worked out from its type and requester for an older item). */
130
+ reviewOf(item) {
131
+ return item.review ?? this.reviewFor(item.kind, undefined, null);
132
+ }
133
+ /** Who reviews an item's resolution, each required or optional: the reviewers named, else the requester. */
134
+ reviewersOf(item) {
135
+ const named = this.reviewOf(item).reviewers;
136
+ if (named.length)
137
+ return named;
138
+ return item.openedByUserId ? [{ userId: item.openedByUserId, optional: false }] : [];
139
+ }
140
+ /** The reviewers who must accept before the item is done, leaving out the one resolving it (their resolution is their acceptance). */
141
+ requiredReviewers(item, actor) {
142
+ return this.reviewersOf(item).filter((r) => !r.optional && r.userId !== actor.userId).map((r) => r.userId);
143
+ }
144
+ /** Whether resolving it now (by this actor) waits for a review: required, and a required reviewer other than them. */
145
+ needsReview(item, actor) {
146
+ return this.reviewOf(item).required && this.requiredReviewers(item, actor).length > 0;
147
+ }
148
+ /**
149
+ * Change an item's review (documentation/action-items.md "Reviews"):
150
+ * - the assignee may ask for a review and add reviewers, never drop a review or a reviewer;
151
+ * - the person who asked for it may turn the review on or off within the type's level
152
+ * (not off when the assignee asked for it), and set the reviewers;
153
+ * - a required review keeps at least one required reviewer (the requester when none is named).
154
+ */
155
+ async setReview(id, input, actor) {
156
+ const item = await this.get(id);
157
+ if (item.status !== 'open')
158
+ throw new ServiceError(409, 'only an open item’s review can change');
159
+ const level = reviewLevelOf(item.kind, this.types);
160
+ const current = this.reviewOf(item);
161
+ const isAssignee = item.assigneeUserId === actor.userId;
162
+ const isRequester = !!item.openedByUserId && item.openedByUserId === actor.userId;
163
+ if (!isAssignee && !isRequester)
164
+ throw new ServiceError(403, 'only its assignee or the person who asked for it changes its review');
165
+ if (level === 'never')
166
+ throw new ServiceError(409, `a ${item.kind} is never reviewed: its decision is the review`);
167
+ const given = input.reviewers?.map((r) => ({ userId: r.userId, optional: r.optional ?? false }));
168
+ for (const r of given ?? [])
169
+ if ((await this.store.get(COLLECTIONS.users, r.userId)) === null)
170
+ throw new ServiceError(404, `user ${r.userId} not found`);
171
+ if (given && new Set(given.map((r) => r.userId)).size !== given.length)
172
+ throw new ServiceError(400, 'each reviewer once');
173
+ let reviewers = current.reviewers;
174
+ if (given) {
175
+ if (isRequester)
176
+ reviewers = given;
177
+ else {
178
+ // The assignee adds; whoever was already reviewing stays as they were.
179
+ const kept = this.reviewersOf(item);
180
+ reviewers = [...kept, ...given.filter((g) => !kept.some((k) => k.userId === g.userId))];
181
+ }
182
+ }
183
+ let next;
184
+ if (input.required) {
185
+ next = { ...current, required: true, decidedBy: isAssignee && !isRequester ? 'assignee' : current.decidedBy === 'assignee' ? 'assignee' : current.required && current.decidedBy === 'type' ? 'type' : 'requester', byUserId: current.required && !given ? current.byUserId : actor.userId, reviewers, acceptedBy: [] };
186
+ const effective = reviewers.length ? reviewers : item.openedByUserId ? [{ userId: item.openedByUserId, optional: false }] : [];
187
+ if (!effective.some((r) => !r.optional))
188
+ throw new ServiceError(400, 'a required review needs at least one required reviewer');
189
+ }
190
+ else {
191
+ if (isAssignee && !isRequester && current.required)
192
+ throw new ServiceError(409, current.decidedBy === 'type' ? `a review is required for a ${item.kind}; only the person who asked for it can waive it` : 'a review was asked for; you cannot drop it');
193
+ if (level === 'always')
194
+ throw new ServiceError(409, `a ${item.kind} is always reviewed`);
195
+ if (current.required && current.decidedBy === 'assignee')
196
+ throw new ServiceError(409, 'its assignee asked for a review; it stays');
197
+ next = { required: false, decidedBy: 'requester', byUserId: actor.userId, reviewers, acceptedBy: [] };
198
+ }
199
+ const nameOf = async (userId) => {
200
+ const u = (await this.store.get(COLLECTIONS.users, userId)) ?? {};
201
+ return [u.firstName, u.lastName].filter(Boolean).join(' ') || u.email || userId;
202
+ };
203
+ const names = await Promise.all(next.reviewers.map(async (r) => `${await nameOf(r.userId)}${r.optional ? ' (optional)' : ''}`));
204
+ const who = names.length ? names.join(', ') : 'the requester';
205
+ const saved = { ...item, review: next, notes: [...item.notes, { at: nowIso(), byUserId: actor.userId, byRoleId: null, text: next.required ? `Reviewed by ${who}.` : 'Review waived.' }], updatedAt: nowIso() };
206
+ await this.save(saved, `${item.kind} ${item.title}: review ${next.required ? `by ${who}` : 'waived'}`, actor);
207
+ return saved;
208
+ }
209
+ /** The agent key of an agent role, or null when there is no such agent role. */
210
+ async agentKeyOf(roleId) {
211
+ const raw = await this.store.get(COLLECTIONS.roles, roleId);
212
+ if (raw === null)
213
+ return null;
214
+ const role = parseRole(raw);
215
+ return role.kind === 'agent' ? (role.agentKey ?? role.id) : null;
216
+ }
217
+ queuedRun(agentKey, attempts = 0) {
218
+ return { state: 'queued', queuedAt: nowIso(), startedAt: null, finishedAt: null, detail: null, costUsd: null, agentKey, attempts };
219
+ }
220
+ /**
221
+ * Open an item. A person's goes to whom the router picks (past
222
+ * reassignments first, the given assignee otherwise), unless they already
223
+ * have an open one about the same record, and they are told in their
224
+ * conversation. An agent's is a task in the agents' queue.
225
+ */
226
+ async open(input, actor) {
227
+ const roleId = input.assigneeRoleId ?? null;
228
+ if (!roleId && !input.assigneeUserId && !input.external)
229
+ throw new ServiceError(400, 'an action item waits on a person (assigneeUserId) or an agent role (assigneeRoleId)');
230
+ const assignee = roleId || !input.assigneeUserId ? null : input.watch === 'new' || input.exact ? input.assigneeUserId : await this.router.assigneeFor(input.kind, input.projectIds ?? [], input.assigneeUserId);
231
+ if (input.ref) {
232
+ const ref = input.ref;
233
+ const existing = (await this.all()).find((i) => i.status !== 'done' && i.kind === input.kind && i.assigneeUserId === assignee && i.assigneeRoleId === roleId && i.ref.kind === ref.kind && i.ref.id === ref.id);
234
+ if (existing)
235
+ return existing;
236
+ }
237
+ let agentKey = null;
238
+ if (roleId) {
239
+ agentKey = await this.agentKeyOf(roleId);
240
+ if (!agentKey)
241
+ throw new ServiceError(404, `agent role ${roleId} not found`);
242
+ }
243
+ const blockedBy = await this.checkBlockers(null, input.blockedBy ?? []);
244
+ const ts = nowIso();
245
+ const id = newId('action-item');
246
+ const draft = {
247
+ id,
248
+ kind: input.kind,
249
+ status: 'open',
250
+ assigneeUserId: assignee,
251
+ assigneeRoleId: roleId,
252
+ openedByUserId: input.openedByUserId ?? null,
253
+ openedByRoleId: input.openedByRoleId ?? null,
254
+ title: input.title,
255
+ summary: input.summary ?? '',
256
+ ref: input.ref ?? { kind: 'task', id },
257
+ waitingOnRoleId: input.waitingOnRoleId ?? null,
258
+ projectIds: input.projectIds ?? [],
259
+ watch: input.watch ?? 'owner',
260
+ blockedBy,
261
+ deliverableIds: input.deliverableIds ?? [],
262
+ deliverablesSetBy: input.deliverableIds ? 'person' : null,
263
+ resolution: null,
264
+ doneAt: null,
265
+ run: roleId ? { ...this.queuedRun(agentKey), ...(input.held ? { state: 'held', queuedAt: null } : {}) } : null,
266
+ external: input.external ?? null,
267
+ review: this.reviewFor(input.kind, input.review, input.openedByUserId ?? null),
268
+ notes: [],
269
+ createdAt: ts,
270
+ updatedAt: ts,
271
+ };
272
+ const item = draft.deliverablesSetBy ? draft : { ...draft, deliverableIds: await new FeatureResolver(this.store).forItem(draft, await this.all()), deliverablesSetBy: 'auto' };
273
+ await this.save(item, `Queue ${item.kind}${item.watch === 'new' ? ' (cc)' : ''}${roleId ? ` for agent ${agentKey}` : ''}: ${item.title}`, actor);
274
+ telemetry.actionItem(item.kind, 'opened');
275
+ if (assignee)
276
+ await this.notify(assignee, item.watch === 'new' ? `**You are CC'd on ${label(item.kind).toLowerCase()}:** ${item.title} — follow it or dismiss it from your queue.` : `**${label(item.kind)} for you:** ${item.title}${item.summary ? ` — ${item.summary}` : ''}`, actor, item.watch === 'owner' ? item : undefined);
277
+ if (roleId && !input.held)
278
+ this.onQueued?.();
279
+ return item;
280
+ }
281
+ /**
282
+ * Ask a person or an agent role for something: a task or a question. With
283
+ * `blocks`, that item waits on the new one ("needs something first"), and
284
+ * the new one belongs to its features. The asker accepts the resolution.
285
+ */
286
+ async ask(input, actor, blocks, options = {}) {
287
+ if (!input.title.trim())
288
+ throw new ServiceError(400, 'say what is needed (title)');
289
+ if (!input.assigneeRoleId && !input.assigneeUserId)
290
+ throw new ServiceError(400, 'ask a person (assigneeUserId) or an agent role (assigneeRoleId)');
291
+ if (input.assigneeRoleId && input.kind !== 'task')
292
+ throw new ServiceError(400, 'an agent is given a task; ask a person a question');
293
+ if (input.assigneeUserId && (await this.store.get(COLLECTIONS.users, input.assigneeUserId)) === null)
294
+ throw new ServiceError(404, `user ${input.assigneeUserId} not found`);
295
+ const parent = blocks ? await this.get(blocks) : null;
296
+ if (parent && parent.status === 'done')
297
+ throw new ServiceError(409, 'that item is done; nothing waits on it any more');
298
+ // A dependency is accepted by whoever is waiting on it: the person on the blocked item, else the asker.
299
+ const opener = parent?.assigneeUserId ?? (actor.userId.startsWith('agent:') ? null : actor.userId);
300
+ const item = await this.open({
301
+ kind: input.kind,
302
+ assigneeUserId: input.assigneeRoleId ? null : (input.assigneeUserId ?? null),
303
+ assigneeRoleId: input.assigneeRoleId ?? null,
304
+ title: input.title.trim(),
305
+ summary: input.summary?.trim() ?? '',
306
+ projectIds: input.projectIds ?? parent?.projectIds ?? [],
307
+ openedByUserId: opener,
308
+ openedByRoleId: options.openedByRoleId ?? null,
309
+ ...(input.review !== undefined ? { review: input.review } : {}),
310
+ ...(input.deliverableIds ? { deliverableIds: input.deliverableIds } : {}),
311
+ }, actor);
312
+ if (!parent)
313
+ return item;
314
+ const fresh = await this.get(parent.id);
315
+ await this.save({ ...fresh, blockedBy: [...new Set([...fresh.blockedBy, item.id])], updatedAt: nowIso() }, `${parent.kind} ${parent.title} now waits on ${item.kind} ${item.title}`, actor);
316
+ // What it blocks lends it its features: worked out, not set, so they follow that item's.
317
+ if (item.deliverablesSetBy === 'person' || parent.deliverableIds.every((d) => item.deliverableIds.includes(d)))
318
+ return item;
319
+ const next = { ...item, deliverableIds: [...new Set([...item.deliverableIds, ...parent.deliverableIds])], deliverablesSetBy: 'auto' };
320
+ await this.save(next, `${item.kind} ${item.title}: features of what it blocks`, actor);
321
+ return next;
322
+ }
323
+ /** Blockers must exist, must not be the item itself, and must not wait on it (directly or further down). */
324
+ async checkBlockers(itemId, blockers) {
325
+ const all = await this.all();
326
+ const byId = new Map(all.map((i) => [i.id, i]));
327
+ const ids = [...new Set(blockers)];
328
+ for (const b of ids) {
329
+ if (b === itemId)
330
+ throw new ServiceError(400, 'an item cannot wait on itself');
331
+ if (!byId.has(b))
332
+ throw new ServiceError(404, `action item ${b} not found`);
333
+ }
334
+ if (itemId) {
335
+ const stack = [...ids];
336
+ const seen = new Set();
337
+ while (stack.length) {
338
+ const at = stack.pop();
339
+ if (at === itemId)
340
+ throw new ServiceError(409, 'that would make the items wait on each other');
341
+ if (seen.has(at))
342
+ continue;
343
+ seen.add(at);
344
+ stack.push(...(byId.get(at)?.blockedBy ?? []));
345
+ }
346
+ }
347
+ return ids;
348
+ }
349
+ /** Replace what an item waits on. */
350
+ async setBlockedBy(id, blockers, actor) {
351
+ const item = await this.get(id);
352
+ const next = { ...item, blockedBy: await this.checkBlockers(id, blockers), updatedAt: nowIso() };
353
+ await this.save(next, `${item.kind} ${item.title} waits on ${next.blockedBy.length} item(s)`, actor);
354
+ return next;
355
+ }
356
+ /** Set an item's features by hand, or (null) let aigile work them out again. */
357
+ async setDeliverables(id, deliverableIds, actor) {
358
+ const item = await this.get(id);
359
+ const next = deliverableIds === null
360
+ ? { ...item, deliverableIds: await new FeatureResolver(this.store).forItem(item, await this.all()), deliverablesSetBy: 'auto', updatedAt: nowIso() }
361
+ : { ...item, deliverableIds: [...new Set(deliverableIds)], deliverablesSetBy: 'person', updatedAt: nowIso() };
362
+ await this.save(next, `${item.kind} ${item.title}: features ${next.deliverablesSetBy === 'person' ? 'set' : 'worked out'}`, actor);
363
+ return next;
364
+ }
365
+ /**
366
+ * Work the features out again for the items aigile owns: open items it set
367
+ * and items never worked out (older records). A done item keeps what it
368
+ * had once worked out, so a feature's history does not move.
369
+ */
370
+ async refreshFeatures() {
371
+ const all = await this.all();
372
+ const resolver = new FeatureResolver(this.store);
373
+ const blocking = new Set(all.flatMap((i) => i.blockedBy));
374
+ const current = new Map(all.map((i) => [i.id, i]));
375
+ let changed = 0;
376
+ // Inheritance reads the blocked items' features, so the items that block nothing go first.
377
+ for (const item of [...all].sort((a, b) => Number(blocking.has(a.id)) - Number(blocking.has(b.id)))) {
378
+ if (item.deliverablesSetBy === 'person')
379
+ continue;
380
+ if (item.deliverablesSetBy === 'auto' && item.status === 'done')
381
+ continue;
382
+ // An action source's items take their features from the source (ActionSourceSync).
383
+ if (item.external)
384
+ continue;
385
+ const ids = await resolver.forItem(item, [...current.values()]);
386
+ if (item.deliverablesSetBy === 'auto' && sameSet(ids, item.deliverableIds))
387
+ continue;
388
+ const next = { ...item, deliverableIds: ids, deliverablesSetBy: 'auto' };
389
+ await this.store.put(COLLECTIONS.actionItems, item.id, next, { message: `${item.kind} ${item.title}: features worked out` });
390
+ current.set(item.id, next);
391
+ changed++;
392
+ }
393
+ if (changed)
394
+ this.invalidate();
395
+ return changed;
396
+ }
397
+ /** A CC keeps the item until the record is resolved. */
398
+ async follow(id, actor) {
399
+ const item = await this.get(id);
400
+ if (item.watch === 'owner')
401
+ throw new ServiceError(409, 'this item waits on you; it is not a CC');
402
+ const next = { ...item, watch: 'following', updatedAt: nowIso() };
403
+ await this.save(next, `Follow ${item.kind}: ${item.title}`, actor);
404
+ return next;
405
+ }
406
+ /** A CC lets the item go; nothing else changes. */
407
+ async dismiss(id, actor) {
408
+ const item = await this.get(id);
409
+ if (item.watch === 'owner')
410
+ throw new ServiceError(409, 'this item waits on you; hand it over instead');
411
+ const ts = nowIso();
412
+ const next = { ...item, status: 'done', doneAt: ts, updatedAt: ts };
413
+ await this.save(next, `Dismiss ${item.kind}: ${item.title}`, actor);
414
+ telemetry.actionItem(item.kind, 'closed');
415
+ return next;
416
+ }
417
+ /**
418
+ * Hand an item to someone else: a person, or (a task) an agent role. A
419
+ * hand-over between people is remembered for the next one of its kind
420
+ * (documentation/agents.md §3.7); a task handed to an agent joins the agents' queue.
421
+ */
422
+ async reassign(id, to, actor) {
423
+ const target = typeof to === 'string' ? { userId: to, roleId: null } : { userId: to.userId ?? null, roleId: to.roleId ?? null };
424
+ const item = await this.get(id);
425
+ if (item.status !== 'open')
426
+ throw new ServiceError(409, 'only an open item can be reassigned');
427
+ if (item.watch !== 'owner')
428
+ throw new ServiceError(409, 'a CC is followed or dismissed, not handed over');
429
+ const ts = nowIso();
430
+ const from = item.assigneeUserId ?? (item.run?.agentKey ? `the ${item.run.agentKey} agent` : 'nobody');
431
+ if (target.roleId) {
432
+ if (item.kind !== 'task')
433
+ throw new ServiceError(409, 'only a task can be handed to an agent');
434
+ if (target.roleId === item.assigneeRoleId)
435
+ return item;
436
+ const agentKey = await this.agentKeyOf(target.roleId);
437
+ if (!agentKey)
438
+ throw new ServiceError(404, `agent role ${target.roleId} not found`);
439
+ const next = { ...item, assigneeUserId: null, assigneeRoleId: target.roleId, run: this.queuedRun(agentKey, item.run?.attempts ?? 0), notes: [...item.notes, { at: ts, byUserId: actor.userId, byRoleId: null, text: `Handed from ${from} to the ${agentKey} agent.` }], updatedAt: ts };
440
+ await this.save(next, `${item.kind} ${item.title} now with the ${agentKey} agent`, actor);
441
+ this.onQueued?.();
442
+ return next;
443
+ }
444
+ const toUserId = target.userId;
445
+ if (!toUserId)
446
+ throw new ServiceError(400, 'hand it to a person (toUserId) or an agent role (toRoleId)');
447
+ if ((await this.store.get(COLLECTIONS.users, toUserId)) === null)
448
+ throw new ServiceError(404, `user ${toUserId} not found`);
449
+ if (toUserId === item.assigneeUserId)
450
+ return item;
451
+ if (item.assigneeUserId) {
452
+ const record = { id: newId('reassignment'), actionItemId: id, kind: item.kind, projectIds: item.projectIds, fromUserId: item.assigneeUserId, toUserId, byUserId: actor.userId, createdAt: ts, updatedAt: ts };
453
+ await this.store.put(COLLECTIONS.reassignments, record.id, record, { message: `Reassign ${item.kind} to ${toUserId}`, ...(actor.author ? { author: actor.author } : {}) });
454
+ }
455
+ const run = item.run && !['done', 'cancelled'].includes(item.run.state) ? { ...item.run, state: 'cancelled', finishedAt: ts, detail: 'handed to a person' } : item.run;
456
+ const next = { ...item, assigneeUserId: toUserId, assigneeRoleId: null, run, notes: item.assigneeUserId ? item.notes : [...item.notes, { at: ts, byUserId: actor.userId, byRoleId: null, text: `Handed from ${from} to a person.` }], updatedAt: ts };
457
+ await this.save(next, `${item.kind} ${item.title} now with ${toUserId}`, actor);
458
+ await this.notify(toUserId, `**${label(item.kind)} for you** (from ${from}): ${item.title}${item.summary ? ` — ${item.summary}` : ''}`, actor, next);
459
+ return next;
460
+ }
461
+ /**
462
+ * The assignee says what resolves the item. When its resolution is reviewed
463
+ * and the reviewer is someone else, that is a request: the item waits for
464
+ * acceptance and the reviewer gets a review (documentation/action-items.md
465
+ * "Reviews"). Otherwise it is done.
466
+ */
467
+ async requestResolution(id, note, actor, options = {}) {
468
+ const item = await this.get(id);
469
+ if (item.status !== 'open')
470
+ throw new ServiceError(409, item.status === 'resolving' ? 'its resolution is already waiting for acceptance' : 'it is done');
471
+ const isAssignee = item.assigneeUserId === actor.userId || (!!item.assigneeRoleId && !!options.byRoleId && options.byRoleId === item.assigneeRoleId);
472
+ if (!options.force && !isAssignee)
473
+ throw new ServiceError(403, 'only its assignee resolves it; hand it over first');
474
+ // The record was resolved where it lives (force): its open dependencies do not hold that back.
475
+ const waiting = options.force ? [] : (await this.all()).filter((i) => item.blockedBy.includes(i.id) && i.status !== 'done');
476
+ if (waiting.length)
477
+ throw new ServiceError(409, `it still waits on ${waiting.map((i) => `"${i.title}"`).join(', ')}`);
478
+ const ts = nowIso();
479
+ const resolution = { note: note.trim(), byUserId: options.byRoleId ? null : actor.userId, byRoleId: options.byRoleId ?? null, at: ts };
480
+ const run = item.run ? { ...item.run, state: 'done', finishedAt: item.run.finishedAt ?? ts } : null;
481
+ if (!this.needsReview(item, actor))
482
+ return this.markDone({ ...item, resolution, run }, `Resolved ${item.kind}: ${item.title}`, actor);
483
+ const review = this.reviewOf(item);
484
+ // A reviewer resolving it has accepted it by doing so.
485
+ const next = { ...item, status: 'resolving', resolution, run, review: { ...review, acceptedBy: this.reviewersOf(item).some((r) => r.userId === actor.userId) ? [actor.userId] : [] }, updatedAt: ts };
486
+ await this.save(next, `Resolution requested for ${item.kind}: ${item.title}`, actor);
487
+ for (const r of this.reviewersOf(item).filter((x) => x.userId !== actor.userId)) {
488
+ await this.open({
489
+ kind: 'review',
490
+ assigneeUserId: r.userId,
491
+ exact: true,
492
+ title: `Accept${r.optional ? ' (optional)' : ''}: ${item.title}`,
493
+ summary: resolution.note ? resolution.note.slice(0, 300) : 'Resolved without a note.',
494
+ ref: { kind: ACCEPTANCE_REF, id: item.id },
495
+ projectIds: item.projectIds,
496
+ deliverableIds: item.deliverableIds,
497
+ }, actor);
498
+ }
499
+ return next;
500
+ }
501
+ /**
502
+ * A reviewer accepts the resolution. When every required reviewer has, the
503
+ * item is done and every review of it closes; until then it waits for the rest.
504
+ */
505
+ async acceptResolution(id, actor) {
506
+ const item = await this.get(id);
507
+ if (item.status !== 'resolving')
508
+ throw new ServiceError(409, 'no resolution is waiting for acceptance');
509
+ const reviewers = this.reviewersOf(item);
510
+ if (reviewers.length && !reviewers.some((r) => r.userId === actor.userId))
511
+ throw new ServiceError(403, 'only its reviewers accept its resolution');
512
+ const review = this.reviewOf(item);
513
+ const acceptedBy = [...new Set([...review.acceptedBy, actor.userId])];
514
+ const waiting = reviewers.filter((r) => !r.optional && !acceptedBy.includes(r.userId));
515
+ if (waiting.length) {
516
+ await this.closeReviews(item.id, actor, actor.userId);
517
+ const next = { ...item, review: { ...review, acceptedBy }, updatedAt: nowIso() };
518
+ await this.save(next, `${actor.userId} accepted the resolution of ${item.kind}: ${item.title}; waiting on ${waiting.length} more`, actor);
519
+ return next;
520
+ }
521
+ await this.closeReviews(item.id, actor);
522
+ const done = await this.markDone({ ...item, review: { ...review, acceptedBy } }, `Accepted the resolution of ${item.kind}: ${item.title}`, actor);
523
+ await this.notify(item.assigneeUserId, `**Accepted:** ${item.title}`, actor);
524
+ return done;
525
+ }
526
+ /** Any of its reviewers (optional ones too) sends the resolution back: the item goes back to its assignee (an agent's to its queue) with the reason. */
527
+ async rejectResolution(id, reason, actor) {
528
+ const item = await this.get(id);
529
+ if (item.status !== 'resolving')
530
+ throw new ServiceError(409, 'no resolution is waiting for acceptance');
531
+ const reviewers = this.reviewersOf(item);
532
+ if (reviewers.length && !reviewers.some((r) => r.userId === actor.userId))
533
+ throw new ServiceError(403, 'only its reviewers send its resolution back');
534
+ if (!reason.trim())
535
+ throw new ServiceError(400, 'say why (reason)');
536
+ await this.closeReviews(item.id, actor);
537
+ const ts = nowIso();
538
+ const toAgent = !!item.assigneeRoleId && !!item.run;
539
+ const next = {
540
+ ...item,
541
+ status: 'open',
542
+ resolution: null,
543
+ review: item.review ? { ...item.review, acceptedBy: [] } : null,
544
+ notes: [...item.notes, { at: ts, byUserId: actor.userId, byRoleId: null, text: `Resolution not accepted: ${reason.trim()}${item.resolution?.note ? `\n(It said: ${item.resolution.note.slice(0, 500)})` : ''}` }],
545
+ run: toAgent ? this.queuedRun(item.run.agentKey, item.run.attempts) : item.run,
546
+ updatedAt: ts,
547
+ };
548
+ await this.save(next, `Did not accept the resolution of ${item.kind}: ${item.title}`, actor);
549
+ await this.notify(item.assigneeUserId, `**Not accepted:** ${item.title} — ${reason.trim()}`, actor);
550
+ if (toAgent)
551
+ this.onQueued?.();
552
+ return next;
553
+ }
554
+ /** Close the reviews of an item: every one, or one reviewer's. */
555
+ async closeReviews(itemId, actor, onlyFor) {
556
+ for (const r of (await this.all()).filter((i) => i.kind === 'review' && i.ref.kind === ACCEPTANCE_REF && i.ref.id === itemId && i.status !== 'done' && (!onlyFor || i.assigneeUserId === onlyFor))) {
557
+ await this.markDone(r, `Done review: ${r.title}`, actor);
558
+ }
559
+ }
560
+ /** Done: the item is closed, and anything that waited on it hears whether it can go ahead. */
561
+ async markDone(item, message, actor, options = {}) {
562
+ const ts = nowIso();
563
+ const next = { ...item, status: 'done', doneAt: ts, updatedAt: ts };
564
+ await this.save(next, message, actor);
565
+ telemetry.actionItem(item.kind, 'closed');
566
+ await this.unblockDependents(item.id, actor);
567
+ await this.resolvedNotice(next);
568
+ if (next.external && !options.fromSource && this.onResolved) {
569
+ try {
570
+ await this.onResolved(next, actor);
571
+ }
572
+ catch (err) {
573
+ console.warn(`[aigile] writing ${next.external.key} back to ${next.external.sourceId}: ${err instanceof Error ? err.message : String(err)}`);
574
+ }
575
+ }
576
+ return next;
577
+ }
578
+ /** An item its source says is done (the Jira issue was closed there): done here, nothing written back. */
579
+ async closeFromSource(id, note, actor) {
580
+ const item = await this.get(id);
581
+ if (item.status === 'done')
582
+ return item;
583
+ const next = { ...item, resolution: item.resolution ?? { note, byUserId: null, byRoleId: null, at: nowIso() } };
584
+ await this.closeReviews(item.id, actor);
585
+ return this.markDone(next, `Done at its source: ${item.title}`, actor, { fromSource: true });
586
+ }
587
+ /** Save an item as its source has it now (title, assignee, status, dependencies, features), keeping what people set here. */
588
+ async saveFromSource(item, actor) {
589
+ await this.save({ ...item, updatedAt: nowIso() }, `From ${item.external?.sourceId ?? 'its source'}: ${item.title}`, actor);
590
+ }
591
+ async unblockDependents(doneId, actor) {
592
+ const all = await this.all();
593
+ const byId = new Map(all.map((i) => [i.id, i]));
594
+ for (const dep of all.filter((i) => i.status === 'open' && i.blockedBy.includes(doneId))) {
595
+ if (dep.blockedBy.some((b) => byId.get(b)?.status !== 'done'))
596
+ continue;
597
+ if (dep.run?.state === 'waiting') {
598
+ await this.save({ ...dep, run: { ...dep.run, state: 'queued', queuedAt: nowIso() }, updatedAt: nowIso() }, `${dep.kind} ${dep.title}: what it waited on is done; queued again`, actor);
599
+ this.onQueued?.();
600
+ }
601
+ else {
602
+ await this.notify(dep.assigneeUserId, `**Ready:** ${dep.title} — what it waited on is done.`, actor);
603
+ }
604
+ }
605
+ }
606
+ /**
607
+ * Refuse to act on a record while an item about it waits on unfinished
608
+ * items (documentation/action-items.md "Dependencies"): approving a build
609
+ * whose approval still needs an answer, say. Saying no stays possible.
610
+ */
611
+ async assertReady(ref) {
612
+ const all = await this.all();
613
+ const byId = new Map(all.map((i) => [i.id, i]));
614
+ const waiting = all
615
+ .filter((i) => i.status === 'open' && i.watch === 'owner' && i.ref.kind === ref.kind && i.ref.id === ref.id)
616
+ .flatMap((i) => i.blockedBy.map((b) => byId.get(b)).filter((b) => !!b && b.status !== 'done'));
617
+ if (waiting.length)
618
+ throw new ServiceError(409, `it still waits on ${[...new Set(waiting.map((w) => `"${w.title}"`))].join(', ')}`);
619
+ }
620
+ /**
621
+ * Every open item about a record is resolved (the conflict settled, the
622
+ * question answered). A task or question someone else opened becomes a
623
+ * resolution request they accept; the rest are done.
624
+ */
625
+ async closeAbout(ref, actor) {
626
+ const open = (await this.all()).filter((i) => i.status === 'open' && i.ref.kind === ref.kind && i.ref.id === ref.id);
627
+ for (const item of open) {
628
+ const needsAcceptance = item.watch === 'owner' && this.needsReview(item, actor);
629
+ if (needsAcceptance)
630
+ await this.requestResolution(item.id, '', actor, { force: true });
631
+ else
632
+ await this.markDone(item, `Done ${item.kind}: ${item.title}`, actor);
633
+ }
634
+ return open.length;
635
+ }
636
+ // ── Agents' jobs as tasks (documentation/action-items.md "Agent tasks") ──
637
+ /** A job an agent starts on its own (a build, a review of a spec revision): a task already running. */
638
+ async beginJob(input, actor) {
639
+ const ts = nowIso();
640
+ const id = newId('action-item');
641
+ const draft = {
642
+ id,
643
+ kind: 'task',
644
+ status: 'open',
645
+ assigneeUserId: null,
646
+ assigneeRoleId: input.roleId,
647
+ openedByUserId: null,
648
+ openedByRoleId: null,
649
+ title: input.title,
650
+ summary: '',
651
+ ref: input.ref ?? { kind: 'task', id },
652
+ waitingOnRoleId: null,
653
+ projectIds: input.projectIds ?? [],
654
+ watch: 'owner',
655
+ blockedBy: [],
656
+ deliverableIds: [],
657
+ deliverablesSetBy: null,
658
+ resolution: null,
659
+ doneAt: null,
660
+ run: { state: 'running', queuedAt: ts, startedAt: ts, finishedAt: null, detail: null, costUsd: null, agentKey: input.agentKey, attempts: 1 },
661
+ external: null,
662
+ review: { required: false, decidedBy: 'type', byUserId: null, reviewers: [], acceptedBy: [] },
663
+ notes: [],
664
+ createdAt: ts,
665
+ updatedAt: ts,
666
+ };
667
+ const item = { ...draft, deliverableIds: await new FeatureResolver(this.store).forItem(draft, []), deliverablesSetBy: 'auto' };
668
+ await this.save(item, `Task for the ${input.agentKey ?? 'unknown'} agent: ${item.title}`, actor);
669
+ telemetry.actionItem('task', 'opened');
670
+ return item;
671
+ }
672
+ /** A job's task ends: done, failed or blocked (the cost cap), with what it said. */
673
+ async finishJob(id, outcome, actor) {
674
+ const item = await this.get(id);
675
+ const ts = nowIso();
676
+ const base = item.run ?? { state: 'running', queuedAt: ts, startedAt: ts, finishedAt: null, detail: null, costUsd: null, agentKey: null, attempts: 1 };
677
+ const run = { ...base, state: outcome.state, finishedAt: ts, detail: outcome.detail ?? null };
678
+ return this.markDone({ ...item, run }, `Task ${outcome.state}: ${item.title}`, actor);
679
+ }
680
+ /** Add an AI call's cost to its task's. */
681
+ async addCost(id, costUsd) {
682
+ if (!costUsd)
683
+ return;
684
+ const raw = await this.store.get(COLLECTIONS.actionItems, id);
685
+ if (raw === null)
686
+ return;
687
+ const item = actionItemSchema.parse(raw);
688
+ if (!item.run)
689
+ return;
690
+ await this.store.put(COLLECTIONS.actionItems, id, { ...item, run: { ...item.run, costUsd: (item.run.costUsd ?? 0) + costUsd } }, { message: `Task cost: ${item.title}` });
691
+ this.invalidate();
692
+ }
693
+ /** Save a task's run as the queue moves it. */
694
+ async updateRun(id, run, actor, extra = {}) {
695
+ const item = await this.get(id);
696
+ if (!item.run)
697
+ throw new ServiceError(409, 'that item is not an agent task');
698
+ const next = { ...item, ...extra, run: { ...item.run, ...run }, updatedAt: nowIso() };
699
+ await this.save(next, `Task ${next.run.state}: ${item.title}`, actor);
700
+ return next;
701
+ }
702
+ /** Stop a queued, waiting, failed or blocked task; it stays open for a person to pick up or queue again. */
703
+ async cancelRun(id, actor) {
704
+ const item = await this.get(id);
705
+ if (!item.run || !['held', 'queued', 'waiting', 'failed', 'blocked'].includes(item.run.state))
706
+ throw new ServiceError(409, 'only a held, queued, waiting, failed or blocked task can be stopped');
707
+ return this.updateRun(id, { state: 'cancelled', finishedAt: nowIso() }, actor, { notes: [...item.notes, { at: nowIso(), byUserId: actor.userId, byRoleId: null, text: 'Stopped.' }] });
708
+ }
709
+ /** Queue a failed, blocked or stopped task again. */
710
+ async retryRun(id, actor) {
711
+ const item = await this.get(id);
712
+ if (item.status !== 'open' || !item.assigneeRoleId || !item.run || !['held', 'failed', 'blocked', 'cancelled'].includes(item.run.state))
713
+ throw new ServiceError(409, 'only an open agent task that is held, failed, was blocked or was stopped can be queued');
714
+ const next = await this.updateRun(id, { state: 'queued', queuedAt: nowIso(), startedAt: null, finishedAt: null, detail: null }, actor);
715
+ this.onQueued?.();
716
+ return next;
717
+ }
718
+ }
719
+ function sameSet(a, b) {
720
+ return a.length === b.length && a.every((x) => b.includes(x));
721
+ }
722
+ //# sourceMappingURL=action-items.js.map