ai-agentmanager 1.21.0 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/issues.js ADDED
@@ -0,0 +1,272 @@
1
+ // Issues: every Jira (or Linear) issue an agent works on, one row per agent, with where it stands
2
+ // for you: waiting for your review (an open pull request, a finished agent, a question), with the
3
+ // agent still on it, or done. The issue's own workflow status comes from Jira when it can be had.
4
+
5
+ import { leadingJiraKey, landState } from './tracker.js';
6
+ import { wordsAfterLink } from './jira.js';
7
+ import { designOutline } from './designs.js';
8
+ import { needsOf } from './standup.js';
9
+
10
+ const ISSUE_KEY = /^[A-Z][A-Z0-9_]+-\d+$/;
11
+ const MAX_PROPOSED = 200;
12
+ const err = (status, message) => Object.assign(new Error(message), { status });
13
+ const NEEDS = new Set(['prompt', 'waiting', 'plan', 'question']);
14
+
15
+ /** Where each stage goes in the summary's filters. */
16
+ // In the order they're listed.
17
+ export const GROUPS = {
18
+ proposed: 'new',
19
+ needs: 'you',
20
+ review: 'you',
21
+ blocked: 'you',
22
+ approved: 'you',
23
+ working: 'agent',
24
+ fixing: 'agent',
25
+ merged: 'done',
26
+ closed: 'done',
27
+ };
28
+
29
+ /** The issue an agent works on: { key, url }, from the link its request starts with or one in it. */
30
+ export function issueOf(v) {
31
+ const lead = leadingJiraKey(v.intent);
32
+ const bugs = (v.bugs ?? []).filter((b) => b.source === 'intent' && ISSUE_KEY.test(b.key));
33
+ const key = v.synopsis?.key ?? lead ?? bugs[0]?.key ?? null;
34
+ if (!key) return null;
35
+ const bug = bugs.find((b) => b.key === key) ?? (v.bugs ?? []).find((b) => b.key === key);
36
+ const url = bug?.url ?? String(v.intent ?? '').trimStart().match(/^<?(https?:\/\/\S+)/)?.[1]?.replace(/>$/, '') ?? null;
37
+ return { key, url, title: (v.synopsis?.key === key ? v.synopsis.text : null) ?? bug?.title ?? null };
38
+ }
39
+
40
+ /** Where the work stands for you: { stage, note, pr }. */
41
+ export function stageOf(v) {
42
+ const prs = (v.prs ?? []).filter((p) => p.source !== 'mentioned' && p.state);
43
+ const open = prs.filter((p) => p.state === 'OPEN');
44
+ // The newest PR the agent is on.
45
+ const pr = open.at(-1) ?? prs.at(-1) ?? null;
46
+ const needs = needsOf(v).filter((n) => NEEDS.has(n.kind));
47
+ if (needs.length) return { stage: 'needs', note: `Needs your answer: ${needs[0].text}`, pr };
48
+ if (open.length) {
49
+ const land = landState(pr);
50
+ if (pr.isDraft) return { stage: 'working', note: 'Draft pull request', pr };
51
+ if (pr.review === 'APPROVED') return { stage: 'approved', note: 'Approved, not merged yet', pr };
52
+ if (pr.review === 'CHANGES_REQUESTED') return { stage: 'fixing', note: v.runtime?.busy ? 'Working on your review comments' : 'Changes requested', pr };
53
+ if (land === 'fix') return { stage: 'fixing', note: pr.checks?.state === 'failed' ? 'Checks failing' : 'Merge conflict', pr };
54
+ return { stage: 'review', note: pr.checks?.state === 'running' ? 'Ready for your review (checks running)' : 'Ready for your review', pr };
55
+ }
56
+ if (prs.some((p) => p.state === 'MERGED')) return { stage: 'merged', note: 'Merged', pr };
57
+ if (prs.length) return { stage: 'closed', note: 'Pull request closed', pr };
58
+ const outcome = v.results?.outcome;
59
+ if (outcome === 'blocked') return { stage: 'blocked', note: `Blocked${v.results.blockers?.[0]?.text ? `: ${v.results.blockers[0].text}` : ''}`, pr };
60
+ if (outcome === 'done') return { stage: 'review', note: 'Done, no pull request: review it in the session', pr };
61
+ return { stage: 'working', note: v.runtime?.busy ? 'Agent working' : v.runtime?.running ? 'Agent idle' : 'Agent not running', pr };
62
+ }
63
+
64
+ /** A plan's steps: { done, total } from its "- [x]" and "- [ ]" items. */
65
+ export function planSteps(markdown) {
66
+ const items = String(markdown ?? '').match(/^\s*[-*]\s+\[[ xX]\]/gm) ?? [];
67
+ return { done: items.filter((i) => /\[[xX]\]/.test(i)).length, total: items.length };
68
+ }
69
+
70
+ /** The agent's plan: written or not, its steps, and its review when plans are reviewed. */
71
+ function planOf(v, read) {
72
+ const written = Boolean(v.specDocs?.plan);
73
+ const review = v.planReview?.status ?? null;
74
+ if (!written && !review) return null;
75
+ const steps = written ? planSteps(read(v.id, 'plan')) : { done: 0, total: 0 };
76
+ return { written, review, ...steps };
77
+ }
78
+
79
+ /** The agent's design doc: written or not, its summary, and where it's published. */
80
+ function designOf(v, read) {
81
+ const written = Boolean(v.specDocs?.designdoc);
82
+ const ref = (v.brief?.references ?? []).find((r) => /design page/i.test(r.label));
83
+ const google = v.drive?.files?.designdoc?.url ?? null;
84
+ if (!written && !ref && !google && !v.designDoc) return null;
85
+ const summary = written ? designOutline(read(v.id, 'designdoc')).summary : null;
86
+ return { written, page: ref?.url ?? null, google, ...(summary ? { summary } : {}) };
87
+ }
88
+
89
+ /**
90
+ * The summary's rows from agent views, those waiting for you first.
91
+ * `read(agentId, name)` gives one of the agent's documents ('plan'), or null.
92
+ */
93
+ export function issueRows(views, jira = new Map(), read = () => null, proposed = []) {
94
+ const rank = Object.fromEntries(Object.keys(GROUPS).map((k, i) => [k, i]));
95
+ const rows = [];
96
+ // Issues proposed for agents, not started yet: they wait for you to tick them.
97
+ for (const p of proposed) {
98
+ const j = jira.get(p.key) ?? null;
99
+ rows.push({
100
+ key: p.key,
101
+ url: p.url,
102
+ title: j?.summary ?? p.title,
103
+ jira: j ? { status: j.status, category: j.category } : null,
104
+ stage: 'proposed',
105
+ group: 'new',
106
+ note: `Not started${p.project ? ` (@${p.project})` : ''}: tick it to start an agent`,
107
+ agent: null,
108
+ proposal: { project: p.project ?? null, repo: p.repo ?? null, by: p.by ?? null, intent: p.intent },
109
+ pr: null,
110
+ aiReview: null,
111
+ plan: null,
112
+ design: null,
113
+ updatedAt: p.at,
114
+ });
115
+ }
116
+ for (const v of views) {
117
+ if (v.kind === 'assistant') continue;
118
+ const issue = issueOf(v);
119
+ if (!issue) continue;
120
+ const { stage, note, pr } = stageOf(v);
121
+ const j = jira.get(issue.key) ?? null;
122
+ rows.push({
123
+ key: issue.key,
124
+ url: issue.url,
125
+ title: j?.summary ?? issue.title,
126
+ jira: j ? { status: j.status, category: j.category } : null,
127
+ stage,
128
+ group: GROUPS[stage],
129
+ note: note.length > 200 ? `${note.slice(0, 199)}…` : note,
130
+ agent: { id: v.id, name: v.name, project: v.projectInfo?.name ?? null, running: Boolean(v.runtime?.running), busy: Boolean(v.runtime?.busy), from: v.startedBy ? 'assistant' : v.trigger?.source ?? null },
131
+ pr: pr ? { url: pr.url, number: pr.number ?? null, title: pr.title ?? null, state: pr.state, checks: pr.checks?.state ?? null, review: pr.review ?? null } : null,
132
+ aiReview: v.aiReview?.verdict ?? null,
133
+ plan: planOf(v, read),
134
+ design: designOf(v, read),
135
+ updatedAt: v.activeAt ?? v.createdAt ?? null,
136
+ });
137
+ }
138
+ return rows.sort((a, b) => rank[a.stage] - rank[b.stage] || String(b.updatedAt ?? '').localeCompare(String(a.updatedAt ?? '')));
139
+ }
140
+
141
+ const REVIEW = { writing: 'being written', review: 'waiting for your approval', approved: 'approved', changes: 'changes asked' };
142
+
143
+ /** A plan in a few words: "3/5 steps, approved". */
144
+ export function planText(p) {
145
+ if (!p) return '';
146
+ const steps = p.total ? `${p.done}/${p.total} steps` : p.written ? 'written' : '';
147
+ return [steps, p.review ? REVIEW[p.review] ?? p.review : null].filter(Boolean).join(', ');
148
+ }
149
+
150
+ /** A design doc in a few words, with its links. */
151
+ function designText(d) {
152
+ if (!d) return '';
153
+ const links = [d.page && `[page](${d.page})`, d.google && `[doc](${d.google})`].filter(Boolean);
154
+ return links.length ? links.join(' ') : d.written ? 'written' : 'not yet';
155
+ }
156
+
157
+ /** The rows as a Markdown table, to paste into Slack, Jira or a doc. */
158
+ export function issuesMarkdown(rows) {
159
+ const cell = (s) => String(s ?? '').replace(/\|/g, '\\|').replace(/\s+/g, ' ').trim();
160
+ const lines = ['| Issue | Jira status | Where it stands | Plan | Design | Pull request | Agent |', '|---|---|---|---|---|---|---|'];
161
+ for (const r of rows) {
162
+ const issue = r.url ? `[${r.key}](${r.url})` : r.key;
163
+ const pr = r.pr ? (r.pr.url ? `[#${r.pr.number ?? '?'}](${r.pr.url})` : `#${r.pr.number}`) : '';
164
+ lines.push(`| ${issue}${r.title ? ` ${cell(r.title)}` : ''} | ${cell(r.jira?.status ?? '')} | ${cell(r.note)} | ${planText(r.plan)} | ${designText(r.design)} | ${pr} | ${cell(r.agent?.name ?? '')} |`);
165
+ }
166
+ return lines.join('\n');
167
+ }
168
+
169
+ /**
170
+ * Issues proposed for agents (by the assistant, when you pick), waiting for you to tick the ones
171
+ * to start. Kept in state.json; dismissed ones are remembered so they aren't proposed again.
172
+ */
173
+ export class ProposedIssues {
174
+ constructor({ store, manager }) {
175
+ this.store = store;
176
+ this.manager = manager;
177
+ }
178
+
179
+ get all() {
180
+ return (this.store.data.proposedIssues ??= []);
181
+ }
182
+
183
+ /** The ones waiting for you, without those an agent has taken up meanwhile. */
184
+ waiting() {
185
+ return this.all.filter((p) => p.status === 'waiting' && !this.agentFor(p.key));
186
+ }
187
+
188
+ agentFor(key) {
189
+ const k = key.toLowerCase();
190
+ return this.store.list().find((a) => a.kind === 'task' && (a.name.toLowerCase() === k || leadingJiraKey(a.intent)?.toLowerCase() === k)) ?? null;
191
+ }
192
+
193
+ /** Propose an issue: the request starts with its link. */
194
+ add({ intent, project = null, repo = null, by = null } = {}) {
195
+ const text = String(intent ?? '').trim();
196
+ const key = leadingJiraKey(text);
197
+ if (!key) throw err(400, 'Start the request with the issue link (a Jira /browse/KEY-1 or Linear /issue/KEY-1 link)');
198
+ const agent = this.agentFor(key);
199
+ if (agent) throw err(409, `An agent for ${key} already exists: ${agent.name} (${agent.id})`);
200
+ const prev = this.all.find((p) => p.key === key);
201
+ if (prev?.status === 'dismissed') throw err(409, `${key} was dismissed; not proposed again`);
202
+ if (prev?.status === 'started') throw err(409, `${key} was started already`);
203
+ project = project ? String(project).trim().replace(/^@/, '') || null : null;
204
+ if (project && !this.manager.resolveProject(project)) throw err(400, `No project @${project}; see agentmgr project ls`);
205
+ const item = {
206
+ key,
207
+ url: text.match(/^<?(https?:\/\/\S+)/)[1].replace(/>$/, ''),
208
+ title: wordsAfterLink(text),
209
+ intent: text.slice(0, 4000),
210
+ project,
211
+ repo: repo || null,
212
+ by: by || null,
213
+ status: 'waiting',
214
+ at: prev?.at ?? new Date().toISOString(),
215
+ };
216
+ if (prev) Object.assign(prev, item);
217
+ else this.all.push(item);
218
+ // Old decisions go first when the list grows long.
219
+ while (this.all.length > MAX_PROPOSED) {
220
+ const i = this.all.findIndex((p) => p.status !== 'waiting');
221
+ this.all.splice(i < 0 ? 0 : i, 1);
222
+ }
223
+ this.store.save();
224
+ return item;
225
+ }
226
+
227
+ /** Start agents for the ticked issues: { started: [{ key, agent }], failed: [{ key, reason }] }. */
228
+ start(keys = []) {
229
+ const started = [];
230
+ const failed = [];
231
+ for (const key of new Set(keys)) {
232
+ const p = this.all.find((x) => x.key === key && x.status === 'waiting');
233
+ if (!p) {
234
+ failed.push({ key, reason: 'not waiting to be started' });
235
+ continue;
236
+ }
237
+ const agent = this.agentFor(key);
238
+ if (agent) {
239
+ p.status = 'started';
240
+ p.agentId = agent.id;
241
+ failed.push({ key, reason: `${agent.name} (${agent.id}) already works on it` });
242
+ continue;
243
+ }
244
+ try {
245
+ const [a] = this.manager.createMany([p.intent], { ...(p.project ? { project: p.project } : {}), ...(p.repo ? { repo: p.repo } : {}) });
246
+ p.status = 'started';
247
+ p.agentId = a.id;
248
+ p.startedAt = new Date().toISOString();
249
+ started.push({ key, agent: { id: a.id, name: a.name } });
250
+ } catch (e) {
251
+ failed.push({ key, reason: e.message });
252
+ }
253
+ }
254
+ this.store.save();
255
+ return { started, failed };
256
+ }
257
+
258
+ /** Not for an agent: off the list, and not proposed again. */
259
+ dismiss(keys = []) {
260
+ const want = new Set(keys);
261
+ let n = 0;
262
+ for (const p of this.all) {
263
+ if (want.has(p.key) && p.status === 'waiting') {
264
+ p.status = 'dismissed';
265
+ p.dismissedAt = new Date().toISOString();
266
+ n++;
267
+ }
268
+ }
269
+ this.store.save();
270
+ return { dismissed: n };
271
+ }
272
+ }
package/src/jira.js CHANGED
@@ -76,7 +76,15 @@ export function wordsAfterLink(text) {
76
76
  * The issue's summary, or null when it can't be had (not a site we contact, no access, offline).
77
77
  * `fetchImpl` and `allow` are for tests.
78
78
  */
79
- export async function issueSummary({ key, site }, { jira = loadJira(), fetchImpl = fetch, timeoutMs = 6000, allow = null } = {}) {
79
+ export async function issueSummary(issue, opts = {}) {
80
+ return (await issueFields(issue, opts))?.summary ?? null;
81
+ }
82
+
83
+ /**
84
+ * The issue's summary and workflow status ({ summary, status, category }: category is Jira's
85
+ * "new", "indeterminate" or "done"), or null when it can't be had.
86
+ */
87
+ export async function issueFields({ key, site }, { jira = loadJira(), fetchImpl = fetch, timeoutMs = 6000, allow = null } = {}) {
80
88
  const host = (() => {
81
89
  try {
82
90
  return new URL(site).host;
@@ -90,10 +98,13 @@ export async function issueSummary({ key, site }, { jira = loadJira(), fetchImpl
90
98
  const headers = { accept: 'application/json' };
91
99
  if (configured && jira.email && jira.token) headers.authorization = `Basic ${Buffer.from(`${jira.email}:${jira.token}`).toString('base64')}`;
92
100
  try {
93
- const res = await fetchImpl(`${site}/rest/api/3/issue/${encodeURIComponent(key)}?fields=summary`, { headers, redirect: 'error', signal: AbortSignal.timeout(timeoutMs) });
101
+ const res = await fetchImpl(`${site}/rest/api/3/issue/${encodeURIComponent(key)}?fields=summary,status`, { headers, redirect: 'error', signal: AbortSignal.timeout(timeoutMs) });
94
102
  if (!res.ok) return null;
95
- const summary = (await res.json())?.fields?.summary;
96
- return typeof summary === 'string' && summary.trim() ? summary.trim().slice(0, 300) : null;
103
+ const f = (await res.json())?.fields ?? {};
104
+ const summary = typeof f.summary === 'string' && f.summary.trim() ? f.summary.trim().slice(0, 300) : null;
105
+ const status = typeof f.status?.name === 'string' ? f.status.name.slice(0, 60) : null;
106
+ if (!summary && !status) return null;
107
+ return { summary, status, category: typeof f.status?.statusCategory?.key === 'string' ? f.status.statusCategory.key : null };
97
108
  } catch {
98
109
  return null;
99
110
  }
package/src/manager.js CHANGED
@@ -107,7 +107,9 @@ import { spawn } from 'node:child_process';
107
107
  import * as git from './git.js';
108
108
  import { buildMap, touchedFiles } from './codemap.js';
109
109
  import { parseDiff } from '../public/review.js';
110
- import { issueSummary, leadingIssue, wordsAfterLink } from './jira.js';
110
+ import { issueFields, issueSummary, leadingIssue, loadJira, wordsAfterLink } from './jira.js';
111
+ import { issueRows } from './issues.js';
112
+ import { designRows } from './designs.js';
111
113
  import { reminderFor, reminderSettings } from './reminders.js';
112
114
  import { combine, facts as scoreFacts, improveMessage, scorecardMarkdown, scorecardPrompt } from './scorecard.js';
113
115
  import { CONTAINER_ENGINES, claudeToken, containerName, containerRunning, engineMounts, gitCommonDir, removeContainer, runArgs, stopContainer } from './container.js';
@@ -817,6 +819,50 @@ export class AgentManager extends EventEmitter {
817
819
  return { project: { key: g.key, name: g.name }, projects: list, map: buildMap({ files, agents }) };
818
820
  }
819
821
 
822
+ /**
823
+ * The issues agents work on, for the summary: one row per agent, with each issue's Jira status
824
+ * (fetched a few at a time, kept five minutes).
825
+ */
826
+ async issues(proposed = []) {
827
+ const views = this.store.list().map((a) => this.view(a));
828
+ const rows = issueRows(views, new Map(), () => null, proposed);
829
+ this.jiraCache ??= new Map();
830
+ const jira = new Map();
831
+ const want = [];
832
+ for (const r of rows) {
833
+ if (jira.has(r.key)) continue;
834
+ const hit = this.jiraCache.get(r.key);
835
+ if (hit && Date.now() - hit.at < 5 * 60_000) jira.set(r.key, hit.fields);
836
+ else if (r.url && want.length < 40) {
837
+ let site = null;
838
+ try {
839
+ site = new URL(r.url).origin;
840
+ } catch {}
841
+ if (site) want.push({ key: r.key, site });
842
+ jira.set(r.key, null);
843
+ }
844
+ }
845
+ const opts = { ...this.jiraOptions };
846
+ for (let i = 0; i < want.length; i += 4) {
847
+ await Promise.all(
848
+ want.slice(i, i + 4).map(async (w) => {
849
+ const fields = await issueFields(w, opts).catch(() => null);
850
+ this.jiraCache.set(w.key, { at: Date.now(), fields });
851
+ jira.set(w.key, fields);
852
+ }),
853
+ );
854
+ }
855
+ for (const [k, v] of jira) if (!v) jira.delete(k);
856
+ const j = loadJira();
857
+ return { rows: issueRows(views, jira, (id, name) => readSpecDoc(id, name)?.markdown ?? null, proposed), jira: { site: j.site, signedIn: Boolean(j.site && j.email && j.token) } };
858
+ }
859
+
860
+ /** Every agent's design doc, for the Designs list. */
861
+ designs() {
862
+ const views = this.store.list().map((a) => this.view(a));
863
+ return { rows: designRows(views, (id) => readSpecDoc(id, 'designdoc')?.markdown ?? null) };
864
+ }
865
+
820
866
  /** A repository's tracked files, for the map (kept a few minutes). */
821
867
  async repoFiles(dir) {
822
868
  this.fileLists ??= new Map();
@@ -831,6 +877,7 @@ export class AgentManager extends EventEmitter {
831
877
 
832
878
  /** Fill in summaries still missing (after Jira settings change); returns how many it found. */
833
879
  async refreshSynopses() {
880
+ this.jiraCache?.clear();
834
881
  let found = 0;
835
882
  for (const a of this.store.list()) {
836
883
  if (a.synopsis?.source === 'jira' || !leadingIssue(a.intent)) continue;
@@ -2490,6 +2537,18 @@ export class AgentManager extends EventEmitter {
2490
2537
  return this.view(this.store.get(agent.id));
2491
2538
  }
2492
2539
 
2540
+ /**
2541
+ * One Google Doc in a Drive folder (created the first time, `folderId` after that), through the
2542
+ * Google Drive connector of the Claude account: { folderId, id, url }.
2543
+ */
2544
+ async publishDriveDoc({ folderTitle, folderId = null, title, markdown }) {
2545
+ const sent = [{ key: 'doc', title, html: driveHtml(title, markdown) }];
2546
+ const reply = await this.oneShot({ id: 'drive' }, drivePrompt({ folderTitle, folderId, docs: sent, trash: [] }), { engine: engineOf('claude'), tools: DRIVE_TOOLS, timeoutMs: 600_000 });
2547
+ const r = parseDrive(reply, ['doc']);
2548
+ if (!r.files.doc) throw new Error(r.errors[0] ?? 'Google Drive returned no document (is the Google Drive connector linked to your Claude account?)');
2549
+ return { folderId: r.folderId, id: r.files.doc, url: docUrl(r.files.doc) };
2550
+ }
2551
+
2493
2552
  /** Diagrams only: the problem and its solution drawn from the documents already written and the live context. */
2494
2553
  async runDiagrams(agent, ctx) {
2495
2554
  const cur0 = this.store.get(agent.id) ?? agent;
package/src/notify.js CHANGED
@@ -19,6 +19,7 @@ export const EVENT_DEFAULTS = {
19
19
  assistant: true, // an agent was started for new work (assistant, GitHub label, webhook)
20
20
  budget: true, // an agent neared or reached its budget, or today's spend reached the daily limit
21
21
  standup: true, // the daily standup is ready to play
22
+ value: true, // a scheduled value report (week, month, quarter)
22
23
  };
23
24
 
24
25
  // Alerts the AI judge may hold for the digest or drop; the rest are always sent at once.
package/src/server.js CHANGED
@@ -39,10 +39,13 @@ import { LiveBrowser } from './livebrowser.js';
39
39
  import * as remote from './remote.js';
40
40
  import * as service from './service.js';
41
41
  import { jiraView, saveJira } from './jira.js';
42
+ import { ProposedIssues, issuesMarkdown } from './issues.js';
43
+ import { designsMarkdown } from './designs.js';
42
44
  import { CONTAINER_ENGINES, buildImage, claudeToken, dockerStatus, isBuilding, saveSecrets } from './container.js';
43
45
  import { AgentkitReports } from './agentkit-reports.js';
44
46
  import { Builder } from './builder.js';
45
47
  import { Standup } from './standup.js';
48
+ import { Value, valueSlack } from './value.js';
46
49
  import { Store } from './store.js';
47
50
  import { about, latestRelease } from './about.js';
48
51
 
@@ -87,6 +90,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
87
90
  registerAcpEngines(config);
88
91
  const manager = new AgentManager({ store, config, plugins });
89
92
  const backlog = new Backlog({ manager, store, config });
93
+ const proposed = new ProposedIssues({ store, manager });
90
94
  const races = new Races({ manager, store });
91
95
  const review = new Review({ manager });
92
96
  // The walkthrough explains the same diff the review screen shows.
@@ -131,6 +135,30 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
131
135
  sendSlack(`:sunrise: *Standup ready*: ${what}\n<${link}|Play it>`, n, `Standup ready: ${what}\nPlay it: ${link}`).catch(() => {});
132
136
  },
133
137
  });
138
+ // Value: what delivered work is worth, by day, week, month and quarter, with scheduled reports (value.js).
139
+ let pushValue = () => {};
140
+ const value = new Value({
141
+ manager,
142
+ store,
143
+ config,
144
+ who: me,
145
+ onChange: () => pushValue(),
146
+ notify: async (period, s) => {
147
+ const n = loadNotify();
148
+ if (!n.enabled || !n.events.value) throw new Error('Slack alerts are off');
149
+ const phone = remoteServer ? remote.remoteUrls(remotePort).find((u) => !u.vpn) : null;
150
+ const link = `${phone ? phone.url : `http://127.0.0.1:${port}/`}#value`;
151
+ const msg = valueSlack(period, s, link);
152
+ await sendSlack(msg.text, n, msg.plain);
153
+ },
154
+ publishDrive: async (title, markdown) => {
155
+ const st = store.data.value;
156
+ const r = await manager.publishDriveDoc({ folderTitle: 'Value reports (AI Agent Manager)', folderId: st.driveFolderId ?? null, title, markdown });
157
+ st.driveFolderId = r.folderId ?? st.driveFolderId;
158
+ store.save();
159
+ return r;
160
+ },
161
+ });
134
162
  const triggers = new Triggers({ manager, store, config, notifier });
135
163
  const budgets = new Budgets({ manager, store, config, notifier });
136
164
  const playbooks = new Playbooks({ manager, store });
@@ -754,6 +782,46 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
754
782
  return stats(store.list(), { days, projectOf: (a) => manager.projectInfo(a)?.name ?? null });
755
783
  }));
756
784
  api.get('/codemap', wrap((req) => manager.codeMap(req.query.project ? String(req.query.project) : null)));
785
+ // Issues agents work on, for the summary; ?group=you|agent|done and ?format=markdown to paste.
786
+ api.get('/issues', wrap(async (req) => {
787
+ const v = await manager.issues(proposed.waiting());
788
+ const group = req.query.group ? String(req.query.group) : null;
789
+ const rows = group && group !== 'all' ? v.rows.filter((r) => r.group === group) : v.rows;
790
+ return req.query.format === 'markdown' ? { markdown: issuesMarkdown(rows) } : { ...v, rows };
791
+ }));
792
+ // Issues proposed for agents (the assistant, when you pick): start the ticked ones, or dismiss them.
793
+ api.post('/issues/proposed', wrap((req) => proposed.add({ ...req.body, by: req.headers['x-agentmgr-agent'] ? 'assistant' : 'you' })));
794
+ api.post('/issues/start', wrap((req) => proposed.start(Array.isArray(req.body?.keys) ? req.body.keys.map(String) : [])));
795
+ api.post('/issues/dismiss', wrap((req) => proposed.dismiss(Array.isArray(req.body?.keys) ? req.body.keys.map(String) : [])));
796
+ // Design docs of all agents; the same ?group= and ?format=markdown.
797
+ api.get('/designs', wrap((req) => {
798
+ const v = manager.designs();
799
+ const group = req.query.group ? String(req.query.group) : null;
800
+ const q = String(req.query.q ?? '').trim().toLowerCase();
801
+ const rows = v.rows
802
+ .filter((r) => !group || group === 'all' || r.group === group)
803
+ .filter((r) => !q || [r.title, r.summary, r.agent.name, r.agent.project, r.issue?.key].some((s) => String(s ?? '').toLowerCase().includes(q)));
804
+ return req.query.format === 'markdown' ? { markdown: designsMarkdown(rows) } : { rows };
805
+ }));
806
+ // Value: totals by period, items with estimates you can correct, reports.
807
+ api.get('/value', wrap((req) => value.view({ period: String(req.query.period ?? 'week') })));
808
+ api.put('/value', wrap((req) => {
809
+ const next = value.update(req.body ?? {});
810
+ saveConfig({ value: next });
811
+ return value.view({ period: String(req.query.period ?? 'week') });
812
+ }));
813
+ api.patch('/value/items/:id', wrap((req) => value.edit(req.params.id, req.body ?? {})));
814
+ api.post('/value/items/:id/estimate', wrap((req) => value.estimate(req.params.id).then((it) => value.itemView(it))));
815
+ api.post('/value/items/:id/exclude', wrap((req) => value.exclude(req.params.id, req.body?.excluded !== false)));
816
+ api.get('/value/report', wrap((req) => value.report(String(req.query.kind ?? 'week'), { current: req.query.current === '1' })));
817
+ api.post('/value/report', wrap((req) => value.sendReport(String(req.body?.kind ?? 'week'), { current: req.body?.current === true })));
818
+ api.get('/value/value.csv', (req, res) => {
819
+ try {
820
+ res.download(value.writeCsv(), 'value.csv');
821
+ } catch (e) {
822
+ res.status(500).json({ error: e.message });
823
+ }
824
+ });
757
825
  api.get('/standup', wrap(() => standup.view()));
758
826
  api.post('/standup', wrap(async () => ({ ...standup.view(), latest: await standup.make({ reason: 'asked' }) })));
759
827
  api.put('/standup', wrap((req) => {
@@ -1026,6 +1094,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
1026
1094
  };
1027
1095
  manager.on('change', (agent) => broadcast({ t: 'agent', agent }));
1028
1096
  pushStandup = (latest) => broadcast({ t: 'standup', latest });
1097
+ pushValue = () => broadcast({ t: 'value' });
1029
1098
  reports.on('change', () => broadcast({ t: 'built', reports: reports.list() }));
1030
1099
  manager.rules.on('change', (rules) => broadcast({ t: 'rules', rules }));
1031
1100
  repeats.on('change', (view) => broadcast({ t: 'repeats', repeats: view }));
@@ -1160,6 +1229,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
1160
1229
  cleanup.close();
1161
1230
  landing.close();
1162
1231
  standup.close();
1232
+ value.close();
1163
1233
  autopilot.close();
1164
1234
  goals.close();
1165
1235
  worklog.close();