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.
@@ -0,0 +1,299 @@
1
+ // Value: what the delivered work is worth, by day, week, month and quarter: the engineering time it
2
+ // saved, other savings, potential revenue and strategic weight, against the AI cost and your own
3
+ // time. Each item's figures are AI estimates you can correct; reports go out on a schedule.
4
+
5
+ const PERIODS = [
6
+ ['day', 'Day'],
7
+ ['week', 'Week'],
8
+ ['month', 'Month'],
9
+ ['quarter', 'Quarter'],
10
+ ];
11
+ const CATEGORIES = ['cost savings', 'revenue', 'risk reduction', 'quality', 'customer experience', 'strategic', 'maintenance'];
12
+ const SAVED = 'agentmgr.valuePeriod';
13
+
14
+ export function initValue({ api, $, esc, toast, openAgent }) {
15
+ const dialog = $('#value-dialog');
16
+ const body = $('#value-body');
17
+ let data = null;
18
+ let period = 'week';
19
+ let selected = null; // a period key; null is the current one
20
+ let editing = null; // an agent id
21
+ let again = null;
22
+ try {
23
+ period = localStorage.getItem(SAVED) || 'week';
24
+ } catch {}
25
+
26
+ const money = (n) => (n == null ? '—' : new Intl.NumberFormat(undefined, { style: 'currency', currency: data?.settings.currency ?? 'USD', maximumFractionDigits: 0 }).format(n));
27
+ const pct = (a, b) => (b ? Math.round(((a - b) / b) * 100) : null);
28
+
29
+ async function load() {
30
+ try {
31
+ data = await api('GET', `/value?period=${period}`);
32
+ } catch (e) {
33
+ toast?.(e.message, 5000);
34
+ }
35
+ render();
36
+ }
37
+
38
+ function card(label, value, sub, prevValue, cur) {
39
+ const d = prevValue != null && cur != null ? pct(cur, prevValue) : null;
40
+ return `<div class="value-card"><div class="hint">${esc(label)}</div><div class="value-big">${value}</div>${sub ? `<div class="hint">${sub}</div>` : ''}${d != null && Number.isFinite(d) ? `<div class="value-delta ${d >= 0 ? 'up' : 'down'}">${d >= 0 ? '▲' : '▼'} ${Math.abs(d)}% vs before</div>` : ''}</div>`;
41
+ }
42
+
43
+ function bars(periods) {
44
+ const max = Math.max(1, ...periods.map((p) => p.totals.valueUsd + p.totals.revenueUsd));
45
+ return `<div class="value-bars" role="list">${[...periods]
46
+ .reverse()
47
+ .map((p) => {
48
+ const v = (p.totals.valueUsd / max) * 100;
49
+ const r = (p.totals.revenueUsd / max) * 100;
50
+ const on = (selected ?? periods[0].key) === p.key;
51
+ return `<button class="value-bar ${on ? 'on' : ''}" role="listitem" data-value-pick="${esc(p.key)}" title="${esc(`${p.label}: ${money(p.totals.valueUsd)} value, ${money(p.totals.revenueUsd)} potential revenue, ${p.totals.items} items`)}">
52
+ <span class="stack"><span class="rev" style="height:${r}%"></span><span class="val" style="height:${v}%"></span></span>
53
+ <span class="lbl">${esc(shortLabel(p))}</span>
54
+ </button>`;
55
+ })
56
+ .join('')}</div>`;
57
+ }
58
+
59
+ const shortLabel = (p) => {
60
+ const d = new Date(p.start);
61
+ if (period === 'day') return d.toLocaleDateString(undefined, { weekday: 'narrow', day: 'numeric' });
62
+ if (period === 'week') return d.toLocaleDateString(undefined, { month: 'numeric', day: 'numeric' });
63
+ if (period === 'month') return d.toLocaleDateString(undefined, { month: 'short' });
64
+ return p.label.split(' ')[0];
65
+ };
66
+
67
+ function itemRow(it) {
68
+ const v = it.value;
69
+ const mine = (k) => (v.yours.includes(k) ? ' class="mine" title="Set by you"' : it.est ? ` title="${esc(it.est.why?.[{ humanHours: 'hours', savingsUsd: 'savings', revenueUsd: 'revenue', strategic: 'strategic' }[k]] ?? '')}"` : '');
70
+ const status = it.excluded ? 'not counted' : it.est ? (v.yours.length ? 'AI + you' : `AI${it.est.confidence != null ? ` · ${Math.round(it.est.confidence * 100)}%` : ''}`) : it.estError ? 'no estimate' : data.estimating === it.agentId ? 'estimating…' : 'waiting for estimate';
71
+ const title = it.link ? `<a href="${esc(it.link)}" target="_blank" rel="noopener">${esc(it.title)}</a>` : esc(it.title);
72
+ const row = `<tr class="${it.excluded ? 'excluded' : ''}">
73
+ <td class="hint nowrap">${esc(new Date(it.deliveredAt).toLocaleDateString())}</td>
74
+ <td>${title}${v.summary ? `<div class="hint">${esc(v.summary)}</div>` : ''}${it.project ? `<div class="hint">${esc(it.project)}</div>` : ''}</td>
75
+ <td>${esc(v.category ?? '—')}</td>
76
+ <td${mine('humanHours')}>${v.humanHours ?? '—'}</td>
77
+ <td${mine('humanHours')}>${money(v.valueUsd)}${v.savingsUsd ? `<div class="hint"${mine('savingsUsd')}>incl. ${money(v.savingsUsd)} savings</div>` : ''}</td>
78
+ <td${mine('revenueUsd')}>${money(v.revenueUsd)}</td>
79
+ <td${mine('strategic')}>${v.strategic != null ? `${v.strategic}/5` : '—'}</td>
80
+ <td class="nowrap">${v.yourHours}h<div class="hint">AI ${money(v.aiCostUsd)}</div></td>
81
+ <td class="nowrap"><span class="hint">${esc(status)}</span><div><button class="link" data-value-edit="${esc(it.agentId)}">Edit</button></div></td>
82
+ </tr>`;
83
+ if (editing !== it.agentId) return row;
84
+ const e = it.edits ?? {};
85
+ const est = it.est ?? {};
86
+ const field = (k, label, step, max) => `<label>${label}<input type="number" min="0" ${max ? `max="${max}"` : ''} step="${step}" name="${k}" value="${esc(e[k] ?? '')}" placeholder="${esc(est[k] ?? (k === 'yourHours' ? v.yourHours : ''))}" /></label>`;
87
+ return `${row}<tr class="value-edit"><td colspan="9"><form data-value-form="${esc(it.agentId)}">
88
+ <div class="row value-fields">
89
+ ${field('humanHours', 'Engineering hours saved', '0.5')}
90
+ ${field('savingsUsd', 'Other savings', '100')}
91
+ ${field('revenueUsd', 'Potential revenue', '100')}
92
+ ${field('strategic', 'Strategic (0–5)', '1', 5)}
93
+ ${field('yourHours', 'Your hours', '0.25')}
94
+ <label>Category<select name="category"><option value="">${esc(est.category ? `AI: ${est.category}` : '—')}</option>${CATEGORIES.map((c) => `<option ${e.category === c ? 'selected' : ''}>${esc(c)}</option>`).join('')}</select></label>
95
+ </div>
96
+ <label>For management <input name="summary" value="${esc(e.summary ?? '')}" placeholder="${esc(est.summary ?? 'One sentence: what it gives the business')}" /></label>
97
+ ${it.est ? `<p class="hint">AI's reasons: ${['hours', 'savings', 'revenue', 'strategic'].map((k) => (it.est.why?.[k] ? `<b>${k}</b> ${esc(it.est.why[k])}` : '')).filter(Boolean).join(' · ')}</p>` : it.estError ? `<p class="hint">No estimate: ${esc(it.estError)}</p>` : ''}
98
+ <p class="hint">Empty fields use the AI's figure (shown faint). Yours are marked and win.</p>
99
+ <div class="actions">
100
+ <button type="button" class="small" data-value-act="estimate" ${it.gone ? 'disabled title="The agent is gone"' : ''}>${it.est ? 'Estimate again' : 'Estimate now'}</button>
101
+ <button type="button" class="small" data-value-act="${it.excluded ? 'include' : 'exclude'}">${it.excluded ? 'Count it' : "Don't count it"}</button>
102
+ <button type="button" class="small" data-value-act="open">Open agent</button>
103
+ <span class="spacer"></span>
104
+ <button type="button" class="small" data-value-act="cancel">Cancel</button>
105
+ <button class="small primary">Save</button>
106
+ </div>
107
+ </form></td></tr>`;
108
+ }
109
+
110
+ function settingsHtml() {
111
+ const s = data.settings;
112
+ const r = s.report;
113
+ return `<details class="value-settings"><summary>Settings and reports</summary><form data-value-settings>
114
+ <div class="row three">
115
+ <label>Engineering hour <span class="hint">loaded cost, ${esc(s.currency)}</span><input type="number" min="0" step="5" name="hourlyRate" value="${s.hourlyRate}" /></label>
116
+ <label>Your time per item <span class="hint">minutes, unless set on it</span><input type="number" min="0" step="5" name="yourMinutes" value="${s.yourMinutes}" /></label>
117
+ <label>Currency<input name="currency" maxlength="3" value="${esc(s.currency)}" /></label>
118
+ </div>
119
+ <label class="check"><input type="checkbox" name="ai" ${s.ai ? 'checked' : ''} /> Estimate each delivered item with AI (one short model call each, at most <input type="number" class="inline" min="0" name="maxPerDay" value="${s.maxPerDay}" /> a day)</label>
120
+ <label>Notes for the estimates <span class="hint">e.g. "B2B SaaS, ~2,000 customers; checkout work affects revenue; support costs $40/ticket"</span><textarea name="notes" rows="2">${esc(s.notes)}</textarea></label>
121
+ <fieldset><legend>Reports</legend>
122
+ <div class="value-report-kinds">
123
+ <label class="check"><input type="checkbox" name="daily" ${r.daily ? 'checked' : ''} /> Daily</label>
124
+ <label class="check"><input type="checkbox" name="weekly" ${r.weekly ? 'checked' : ''} /> Weekly (Mondays)</label>
125
+ <label class="check"><input type="checkbox" name="monthly" ${r.monthly ? 'checked' : ''} /> Monthly (the 1st)</label>
126
+ <label class="check"><input type="checkbox" name="quarterly" ${r.quarterly ? 'checked' : ''} /> Quarterly</label>
127
+ <label>at <input type="time" name="at" value="${esc(r.at)}" /></label>
128
+ </div>
129
+ <label class="check"><input type="checkbox" name="slack" ${r.slack ? 'checked' : ''} /> Send to Slack (Slack alerts must be on, with "value reports")</label>
130
+ <label class="check"><input type="checkbox" name="drive" ${r.drive ? 'checked' : ''} /> Save as a Google Doc in "Value reports (AI Agent Manager)" (uses the Google Drive connector of your Claude account)</label>
131
+ <p class="hint">Each report covers the period just ended and is also saved in ${esc(data.dir)}, with value.csv.</p>
132
+ </fieldset>
133
+ <div class="actions"><span class="spacer"></span><button class="small primary">Save settings</button></div>
134
+ </form></details>`;
135
+ }
136
+
137
+ function render() {
138
+ if (!dialog.open) return;
139
+ if (!data) {
140
+ body.innerHTML = '<p class="hint">Loading…</p>';
141
+ return;
142
+ }
143
+ const ps = data.periods;
144
+ const i = Math.max(0, ps.findIndex((p) => p.key === selected));
145
+ const p = ps[i];
146
+ const prev = ps[i + 1] ?? null;
147
+ const t = p.totals;
148
+ const items = data.items.filter((it) => {
149
+ const at = Date.parse(it.deliveredAt);
150
+ return at >= Date.parse(p.start) && at < Date.parse(p.end);
151
+ });
152
+ const typing = body.contains(document.activeElement) && document.activeElement.matches('input, textarea, select');
153
+ if (typing) return;
154
+ body.innerHTML = `
155
+ <div class="issues-head">
156
+ <h2>Value</h2>
157
+ <div class="chips" role="tablist">${PERIODS.map(([k, label]) => `<button class="chip ${k === period ? 'active' : ''}" role="tab" aria-selected="${k === period}" data-value-period="${k}">${label}</button>`).join('')}</div>
158
+ <span class="spacer"></span>
159
+ <button class="small" data-value="copy" title="Copy this period's report as Markdown, for an email, doc or review">Copy report</button>
160
+ <button class="small" data-value="send" title="Send this period's report now, to Slack and Google Drive as set below">Send</button>
161
+ <button class="small" data-value="csv" title="Every item with its figures, for a spreadsheet">CSV</button>
162
+ <button class="small" data-value="close" title="Close (Esc)">Close</button>
163
+ </div>
164
+ <p class="value-period"><b>${esc(p.label)}</b>${p.current ? ' <span class="hint">so far</span>' : ''} · ${t.items} item${t.items === 1 ? '' : 's'} delivered${data.pending ? ` · <span class="hint">${data.pending} waiting for an estimate</span>` : ''}</p>
165
+ <div class="value-cards">
166
+ ${card('Value delivered', money(t.valueUsd), `${t.humanHours} engineering hours${t.savingsUsd ? ` + ${money(t.savingsUsd)} savings` : ''}`, prev?.totals.valueUsd, t.valueUsd)}
167
+ ${card('Potential revenue', money(t.revenueUsd), 'first year', prev?.totals.revenueUsd, t.revenueUsd)}
168
+ ${card('Strategic', String(t.strategicHigh), 'high-impact items (4–5 of 5)', null, null)}
169
+ ${card('Leverage', t.leverage ? `${t.leverage}×` : '—', `engineering hours per hour of yours (${t.yourHours}h)`, prev?.totals.leverage, t.leverage)}
170
+ ${card('AI cost', money(t.aiCostUsd), t.roi ? `${t.roi}× value per AI dollar` : '', null, null)}
171
+ </div>
172
+ ${bars(ps)}
173
+ <div class="value-legend hint"><span class="sw val"></span> value delivered <span class="sw rev"></span> potential revenue · pick a bar to see that ${esc(period)}</div>
174
+ ${items.length
175
+ ? `<div class="issues-scroll"><table class="issues value-items">
176
+ <thead><tr><th>Delivered</th><th>Work</th><th>Category</th><th>Hours saved</th><th>Value</th><th>Revenue</th><th>Strategic</th><th>You · AI</th><th></th></tr></thead>
177
+ <tbody>${items.map(itemRow).join('')}</tbody></table></div>`
178
+ : `<p class="hint issues-empty">${data.items.length ? `Nothing delivered in ${esc(p.label)}.` : 'Nothing delivered yet. Work counts once an agent\'s pull request merges, or it finishes without one.'}</p>`}
179
+ ${settingsHtml()}`;
180
+ }
181
+
182
+ body.addEventListener('click', async (e) => {
183
+ const per = e.target.closest('[data-value-period]');
184
+ if (per) {
185
+ period = per.dataset.valuePeriod;
186
+ selected = null;
187
+ try {
188
+ localStorage.setItem(SAVED, period);
189
+ } catch {}
190
+ return load();
191
+ }
192
+ const pick = e.target.closest('[data-value-pick]');
193
+ if (pick) {
194
+ selected = pick.dataset.valuePick;
195
+ return render();
196
+ }
197
+ const ed = e.target.closest('[data-value-edit]');
198
+ if (ed) {
199
+ editing = editing === ed.dataset.valueEdit ? null : ed.dataset.valueEdit;
200
+ return render();
201
+ }
202
+ const act = e.target.closest('[data-value-act]')?.dataset.valueAct;
203
+ if (act) {
204
+ const id = e.target.closest('[data-value-form]').dataset.valueForm;
205
+ if (act === 'cancel') {
206
+ editing = null;
207
+ document.activeElement?.blur();
208
+ return render();
209
+ }
210
+ if (act === 'open') {
211
+ dialog.close();
212
+ return openAgent(id);
213
+ }
214
+ try {
215
+ if (act === 'estimate') {
216
+ toast?.('Estimating…');
217
+ await api('POST', `/value/items/${id}/estimate`);
218
+ } else await api('POST', `/value/items/${id}/exclude`, { excluded: act === 'exclude' });
219
+ } catch (err) {
220
+ toast?.(err.message, 6000);
221
+ }
222
+ document.activeElement?.blur();
223
+ return load();
224
+ }
225
+ const b = e.target.closest('[data-value]')?.dataset.value;
226
+ if (b === 'close') return dialog.close();
227
+ if (b === 'csv') {
228
+ const res = await fetch('/api/value/value.csv', { headers: { 'x-agentmgr': '1' } });
229
+ if (!res.ok) return toast?.((await res.json().catch(() => ({}))).error || `HTTP ${res.status}`, 4000);
230
+ const url = URL.createObjectURL(await res.blob());
231
+ Object.assign(document.createElement('a'), { href: url, download: 'value.csv' }).click();
232
+ return setTimeout(() => URL.revokeObjectURL(url), 10_000);
233
+ }
234
+ const p = data?.periods.find((x) => x.key === selected) ?? data?.periods[0];
235
+ const current = Boolean(p?.current);
236
+ if (b === 'copy' || b === 'send') {
237
+ // Reports cover a whole period: the current one so far, or the one just before it.
238
+ if (p && !current && p !== data.periods[1]) return toast?.('Reports are for the current period or the one just ended: pick one of those bars', 5000);
239
+ try {
240
+ if (b === 'copy') {
241
+ const r = await api('GET', `/value/report?kind=${period}${current ? '&current=1' : ''}`);
242
+ await navigator.clipboard.writeText(r.markdown);
243
+ toast?.(`Copied the report for ${r.period.label}`);
244
+ } else {
245
+ const r = await api('POST', '/value/report', { kind: period, current });
246
+ const where = [r.sent.slack && 'Slack', r.sent.drive?.url && 'Google Drive'].filter(Boolean);
247
+ toast?.(`Report for ${r.period.label} saved${where.length ? ` and sent to ${where.join(' and ')}` : ''}${r.sent.drive?.error ? `; Google Drive: ${r.sent.drive.error}` : ''}`, 7000);
248
+ }
249
+ } catch (err) {
250
+ toast?.(err.message, 6000);
251
+ }
252
+ }
253
+ });
254
+
255
+ body.addEventListener('submit', async (e) => {
256
+ e.preventDefault();
257
+ const f = e.target;
258
+ try {
259
+ if (f.dataset.valueSettings !== undefined) {
260
+ await api('PUT', `/value?period=${period}`, {
261
+ hourlyRate: Number(f.hourlyRate.value),
262
+ yourMinutes: Number(f.yourMinutes.value),
263
+ currency: f.currency.value.trim().toUpperCase(),
264
+ ai: f.ai.checked,
265
+ maxPerDay: Number(f.maxPerDay.value),
266
+ notes: f.notes.value,
267
+ report: { daily: f.daily.checked, weekly: f.weekly.checked, monthly: f.monthly.checked, quarterly: f.quarterly.checked, at: f.at.value, slack: f.slack.checked, drive: f.drive.checked },
268
+ });
269
+ toast?.('Saved');
270
+ } else {
271
+ const id = f.dataset.valueForm;
272
+ const patch = {};
273
+ for (const k of ['humanHours', 'savingsUsd', 'revenueUsd', 'strategic', 'yourHours', 'category', 'summary']) patch[k] = f[k].value.trim() === '' ? null : k === 'category' || k === 'summary' ? f[k].value.trim() : Number(f[k].value);
274
+ await api('PATCH', `/value/items/${id}`, patch);
275
+ editing = null;
276
+ }
277
+ } catch (err) {
278
+ return toast?.(err.message, 6000);
279
+ }
280
+ document.activeElement?.blur();
281
+ load();
282
+ });
283
+
284
+ function open() {
285
+ if (dialog.open) return dialog.close();
286
+ dialog.showModal();
287
+ render();
288
+ load();
289
+ }
290
+
291
+ /** The daemon says the figures changed: look again, while open. */
292
+ function changed() {
293
+ if (!dialog.open) return;
294
+ clearTimeout(again);
295
+ again = setTimeout(load, 800);
296
+ }
297
+
298
+ return { open, changed, isOpen: () => dialog.open };
299
+ }
package/src/assistant.js CHANGED
@@ -27,6 +27,8 @@ export const ASSISTANT_DEFAULTS = {
27
27
  permissionMode: 'auto',
28
28
  model: null,
29
29
  notes: '',
30
+ // Propose Jira and Linear issues for the person to pick, instead of starting agents for them.
31
+ pickIssues: false,
30
32
  };
31
33
  const DAY = 86_400_000;
32
34
  const BIN = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'agentmgr.js');
@@ -48,6 +50,7 @@ export function assistantSettings(config = {}) {
48
50
  permissionMode: typeof c.permissionMode === 'string' && c.permissionMode ? c.permissionMode : null,
49
51
  model: typeof c.model === 'string' && c.model ? c.model : null,
50
52
  notes: typeof c.notes === 'string' ? c.notes.slice(0, 4000) : '',
53
+ pickIssues: c.pickIssues === true,
51
54
  };
52
55
  }
53
56
 
@@ -56,18 +59,27 @@ export function assistantPrompt(s, dir, bin = `node ${BIN}`) {
56
59
  const am = bin;
57
60
  const watch = s.sources.map((k) => `- ${SOURCES[k]}`).join('\n');
58
61
  const how = [];
62
+ // The person picks which issues get agents: propose them instead of starting them.
63
+ const pick =
64
+ `Don't start agents for new issues: the person picks which ones get agents. Propose each one you haven't handled instead: ${am} issues propose @<project> "<the issue link> <a one-line summary of what to do>". ` +
65
+ `It is listed for them under Jira, Not started, and an agent starts only if they tick it. Record it as "proposed". ` +
66
+ `A proposal for an issue they dismissed, or one that already has an agent, is refused: record it as skipped and don't propose it again.`;
59
67
  if (s.sources.includes('jira')) {
60
68
  how.push(
61
69
  `Jira, new assignments: with your Jira / Atlassian tools, find unresolved issues assigned to the person that were created or assigned since your last check (on the first check, the last 2 days). ` +
62
- `For each one you haven't handled, start an agent: ${am} add @<project> "<the issue link> <a one-line summary of what to do>". ` +
63
- `Start the request with the issue link: the agent is then named after the issue key, and the daemon refuses a second agent for the same key.`,
70
+ (s.pickIssues
71
+ ? pick
72
+ : `For each one you haven't handled, start an agent: ${am} add @<project> "<the issue link> <a one-line summary of what to do>". ` +
73
+ `Start the request with the issue link: the agent is then named after the issue key, and the daemon refuses a second agent for the same key.`),
64
74
  );
65
75
  }
66
76
  if (s.sources.includes('linear')) {
67
77
  how.push(
68
78
  `Linear, new assignments: with your Linear tools, find open issues assigned to the person that were created or assigned since your last check (on the first check, the last 2 days). ` +
69
- `For each one you haven't handled, start an agent: ${am} add @<project> "<the issue link> <a one-line summary of what to do>". ` +
70
- `Start the request with the issue link (https://linear.app/<team>/issue/<KEY>/…): the agent is then named after the issue key, and the daemon refuses a second agent for the same key. ` +
79
+ (s.pickIssues
80
+ ? `${pick} The link looks like https://linear.app/<team>/issue/<KEY>/…. `
81
+ : `For each one you haven't handled, start an agent: ${am} add @<project> "<the issue link> <a one-line summary of what to do>". ` +
82
+ `Start the request with the issue link (https://linear.app/<team>/issue/<KEY>/…): the agent is then named after the issue key, and the daemon refuses a second agent for the same key. `) +
71
83
  `New comments on issues that already have an agent: pass them on with ${am} tell, as for Jira.`,
72
84
  );
73
85
  }
package/src/cli.js CHANGED
@@ -6,6 +6,8 @@ import WebSocket from 'ws';
6
6
  import { HOST, PORT } from './config.js';
7
7
  import { api, BASE, ensureDaemon, health, isRunning, waitForExit } from './client.js';
8
8
  import { about, latestRelease } from './about.js';
9
+ import { issuesMarkdown } from './issues.js';
10
+ import { designsMarkdown } from './designs.js';
9
11
 
10
12
  const tty = process.stdout.isTTY;
11
13
  const c = (code) => (s) => (tty ? `\x1b[${code}m${s}\x1b[0m` : String(s));
@@ -661,6 +663,185 @@ export async function main(argv) {
661
663
  }
662
664
  });
663
665
 
666
+ const issuesCmd = program.command('issues').description('Jira and Linear issues: the ones proposed for agents, and the ones agents work on, waiting for your review first');
667
+ issuesCmd
668
+ .command('ls', { isDefault: true })
669
+ .description('Issues not started and waiting for your review (--all for the rest)')
670
+ .option('--all', 'also the ones agents are still on and the finished ones')
671
+ .option('--markdown', 'print a Markdown table, to paste')
672
+ .option('--json', 'print JSON')
673
+ .action(async (opts) => {
674
+ await daemon();
675
+ const v = await api('GET', '/issues');
676
+ const rows = opts.all ? v.rows : v.rows.filter((r) => r.group === 'you' || r.group === 'new');
677
+ if (opts.json) return console.log(JSON.stringify({ ...v, rows }, null, 2));
678
+ if (opts.markdown) return console.log(issuesMarkdown(rows));
679
+ if (!rows.length) return console.log(dim(opts.all ? 'No agents work on Jira or Linear issues.' : 'Nothing to start or review. --all shows the rest.'));
680
+ for (const r of rows) {
681
+ const pr = r.pr ? ` PR #${r.pr.number ?? '?'}` : '';
682
+ console.log(`${bold(r.key.padEnd(10))} ${r.jira?.status ? dim(`[${r.jira.status}] `) : ''}${truncate(r.title ?? '', 60)}`);
683
+ console.log(` ${r.group === 'you' || r.group === 'new' ? yellow(r.note) : r.note}${pr} ${dim(r.agent ? `agent ${r.agent.name} (${r.agent.id})` : `start: agentmgr issues start ${r.key}`)}`);
684
+ }
685
+ const others = v.rows.length - rows.length;
686
+ if (others) console.log(dim(`\n${others} more with agents still on them or finished: --all`));
687
+ if (!v.jira.signedIn) console.log(dim('Jira status needs your site, email and API token: Settings → Jira.'));
688
+ });
689
+ issuesCmd
690
+ .command('propose')
691
+ .description('Propose an issue for an agent, to start when ticked (the assistant does this when you pick)')
692
+ .argument('<request...>', '[@project] "<issue link> <what to do>"')
693
+ .option('-r, --repo <url>', 'the repository, when no project fits')
694
+ .action(async (words, opts) => {
695
+ await daemon();
696
+ const project = words[0]?.startsWith('@') ? words.shift().slice(1) : null;
697
+ const p = await api('POST', '/issues/proposed', { intent: words.join(' '), project, repo: opts.repo });
698
+ console.log(`${green('+')} ${bold(p.key)} proposed${p.project ? ` in @${p.project}` : ''}: start it under Jira, Not started, or agentmgr issues start ${p.key}`);
699
+ });
700
+ issuesCmd
701
+ .command('start')
702
+ .description('Start agents for proposed issues')
703
+ .argument('<keys...>', 'issue keys, e.g. OPS-7 OPS-9')
704
+ .action(async (keys) => {
705
+ await daemon();
706
+ const r = await api('POST', '/issues/start', { keys });
707
+ for (const x of r.started) console.log(`${green('✓')} ${bold(x.key)} → agent ${x.agent.name} (${x.agent.id})`);
708
+ for (const x of r.failed) console.log(`${red('!')} ${bold(x.key)}: ${x.reason}`);
709
+ });
710
+ issuesCmd
711
+ .command('dismiss')
712
+ .description('Take proposed issues off the list; they are not proposed again')
713
+ .argument('<keys...>')
714
+ .action(async (keys) => {
715
+ await daemon();
716
+ const r = await api('POST', '/issues/dismiss', { keys });
717
+ console.log(`${r.dismissed} dismissed`);
718
+ });
719
+
720
+ program
721
+ .command('designs')
722
+ .description("Agents' design docs: name, summary and links, the ones waiting for your review first")
723
+ .option('--waiting', 'only the ones waiting for your review')
724
+ .option('--markdown', 'print a Markdown list, to paste')
725
+ .option('--json', 'print JSON')
726
+ .action(async (opts) => {
727
+ await daemon();
728
+ const { rows: all } = await api('GET', '/designs');
729
+ const rows = opts.waiting ? all.filter((r) => r.group === 'you') : all;
730
+ if (opts.json) return console.log(JSON.stringify(rows, null, 2));
731
+ if (opts.markdown) return console.log(designsMarkdown(rows));
732
+ if (!rows.length) return console.log(dim(opts.waiting ? 'No design docs waiting for your review.' : 'No design docs yet.'));
733
+ for (const r of rows) {
734
+ console.log(`${bold(r.title)}${r.issue ? dim(` ${r.issue.key}`) : ''} ${r.group === 'you' ? yellow(r.note) : dim(r.note)}`);
735
+ if (r.summary) console.log(` ${truncate(r.summary, 200)}`);
736
+ const links = [r.page?.url && `page ${r.page.url}`, r.google && `doc ${r.google}`].filter(Boolean);
737
+ console.log(dim(` agent ${r.agent.name} (${r.agent.id})${links.length ? ` ${links.join(' ')}` : r.page?.note ? ` page: ${r.page.note}` : ''}`));
738
+ }
739
+ });
740
+
741
+ const valueCmd = program.command('value').description('What the delivered work is worth (AI estimates you can correct), by day, week, month and quarter, with reports for management');
742
+ const money = (n, cur = 'USD') => (n == null ? '—' : new Intl.NumberFormat('en-US', { style: 'currency', currency: cur, maximumFractionDigits: 0 }).format(n));
743
+ valueCmd
744
+ .command('show', { isDefault: true })
745
+ .description('Totals for the last periods and the items in the current one')
746
+ .option('-p, --period <period>', 'day, week, month or quarter', 'week')
747
+ .option('--json', 'print JSON')
748
+ .action(async (opts) => {
749
+ await daemon();
750
+ const v = await api('GET', `/value?period=${encodeURIComponent(opts.period)}`);
751
+ if (opts.json) return console.log(JSON.stringify(v, null, 2));
752
+ const cur = v.settings.currency;
753
+ for (const p of v.periods.slice(0, 6)) {
754
+ const t = p.totals;
755
+ console.log(`${bold(p.label.padEnd(22))} ${money(t.valueUsd, cur).padStart(9)} value ${money(t.revenueUsd, cur).padStart(9)} revenue ${String(t.humanHours).padStart(5)} h ${t.items} items${t.leverage ? dim(` ${t.leverage}× leverage`) : ''}${p.current ? dim(' (so far)') : ''}`);
756
+ }
757
+ const now = v.periods[0];
758
+ const items = v.items.filter((it) => now.items.includes(it.agentId));
759
+ if (items.length) console.log('');
760
+ for (const it of items) console.log(` ${truncate(it.title, 50).padEnd(50)} ${money(it.value.valueUsd, cur).padStart(9)} ${dim(`${it.value.humanHours ?? '—'} h · ${it.value.category ?? '—'}${it.value.yours.length ? ' · edited' : it.est ? '' : ' · no estimate yet'} ${it.agentId}`)}`);
761
+ if (v.pending) console.log(dim(`\n${v.pending} waiting for an estimate`));
762
+ });
763
+ valueCmd
764
+ .command('edit')
765
+ .description("Correct an item's figures (\"\" puts one back to the AI's estimate)")
766
+ .argument('<agent>')
767
+ .option('--hours <n>', 'engineering hours it saved')
768
+ .option('--savings <usd>', 'other savings, first year')
769
+ .option('--revenue <usd>', 'potential revenue, first year')
770
+ .option('--strategic <0-5>', 'strategic weight')
771
+ .option('--your-hours <n>', 'your own time on it')
772
+ .option('--category <name>', 'cost savings, revenue, risk reduction, quality, customer experience, strategic or maintenance')
773
+ .option('--summary <text>', 'one sentence for management')
774
+ .option('--exclude', "don't count it")
775
+ .option('--include', 'count it again')
776
+ .action(async (ref, o) => {
777
+ await daemon();
778
+ const a = await resolveAgent(ref);
779
+ const val = (x, n = true) => (x === undefined ? undefined : x === '' ? null : n ? Number(x) : x);
780
+ const patch = Object.fromEntries(
781
+ Object.entries({ humanHours: val(o.hours), savingsUsd: val(o.savings), revenueUsd: val(o.revenue), strategic: val(o.strategic), yourHours: val(o.yourHours), category: val(o.category, false), summary: val(o.summary, false) }).filter(([, x]) => x !== undefined),
782
+ );
783
+ let it = Object.keys(patch).length ? await api('PATCH', `/value/items/${a.id}`, patch) : null;
784
+ if (o.exclude || o.include) it = await api('POST', `/value/items/${a.id}/exclude`, { excluded: Boolean(o.exclude) });
785
+ if (!it) throw new Error('Nothing to change: give --hours, --revenue, … or --exclude');
786
+ console.log(`${green('✓')} ${bold(it.title)}: ${money(it.value.valueUsd)} value, ${money(it.value.revenueUsd)} revenue, ${it.value.humanHours ?? '—'} h${it.excluded ? dim(' (not counted)') : ''}`);
787
+ });
788
+ valueCmd
789
+ .command('estimate')
790
+ .description('Estimate an item now (again)')
791
+ .argument('<agent>')
792
+ .action(async (ref) => {
793
+ await daemon();
794
+ const a = await resolveAgent(ref);
795
+ const it = await api('POST', `/value/items/${a.id}/estimate`);
796
+ if (it.estError) throw new Error(it.estError);
797
+ console.log(`${green('✓')} ${bold(it.title)}: ${it.est.humanHours} h, ${it.est.category}. ${it.est.summary}`);
798
+ });
799
+ valueCmd
800
+ .command('report')
801
+ .description('The report for the period just ended (or --current), as Markdown; --send to Slack and Google Drive as set')
802
+ .option('-k, --kind <kind>', 'day, week, month or quarter', 'week')
803
+ .option('--current', 'the current period so far')
804
+ .option('--send', 'send it now')
805
+ .action(async (o) => {
806
+ await daemon();
807
+ if (!o.send) return console.log((await api('GET', `/value/report?kind=${encodeURIComponent(o.kind)}${o.current ? '&current=1' : ''}`)).markdown);
808
+ const r = await api('POST', '/value/report', { kind: o.kind, current: Boolean(o.current) });
809
+ console.log(`${green('✓')} ${r.period.label}: saved to ${r.sent.file}${r.sent.slack ? ', sent to Slack' : ''}${r.sent.drive?.url ? `, Google Doc ${r.sent.drive.url}` : ''}${r.sent.drive?.error ? red(`; Google Drive: ${r.sent.drive.error}`) : ''}`);
810
+ });
811
+ valueCmd
812
+ .command('set')
813
+ .description('Settings: your rates, the estimates, and when reports go out')
814
+ .option('--rate <usd>', 'a loaded engineering hour')
815
+ .option('--currency <code>', 'e.g. USD, EUR')
816
+ .option('--your-minutes <n>', 'your time per item unless set on it')
817
+ .option('--ai <on|off>', 'estimate delivered work with AI')
818
+ .option('--notes <text>', 'context for the estimates: your company, customers, what revenue means')
819
+ .option('--reports <list>', 'which reports, comma separated: daily,weekly,monthly,quarterly (or none)')
820
+ .option('--at <HH:MM>', 'when reports go out')
821
+ .option('--slack <on|off>', 'send reports to Slack')
822
+ .option('--drive <on|off>', 'save reports as Google Docs')
823
+ .action(async (o) => {
824
+ await daemon();
825
+ const on = (x) => (x === undefined ? undefined : /^(on|yes|true|1)$/i.test(x));
826
+ const kinds = o.reports === undefined ? null : o.reports.split(',').map((x) => x.trim());
827
+ const report = Object.fromEntries(
828
+ Object.entries({
829
+ ...(kinds ? { daily: kinds.includes('daily'), weekly: kinds.includes('weekly'), monthly: kinds.includes('monthly'), quarterly: kinds.includes('quarterly') } : {}),
830
+ at: o.at,
831
+ slack: on(o.slack),
832
+ drive: on(o.drive),
833
+ }).filter(([, x]) => x !== undefined),
834
+ );
835
+ const patch = Object.fromEntries(
836
+ Object.entries({ hourlyRate: o.rate === undefined ? undefined : Number(o.rate), currency: o.currency?.toUpperCase(), yourMinutes: o.yourMinutes === undefined ? undefined : Number(o.yourMinutes), ai: on(o.ai), notes: o.notes, ...(Object.keys(report).length ? { report } : {}) }).filter(([, x]) => x !== undefined),
837
+ );
838
+ const v = await api('PUT', '/value', patch);
839
+ const s = v.settings;
840
+ const r = s.report;
841
+ console.log(`engineering hour ${money(s.hourlyRate, s.currency)} · your time ${s.yourMinutes} min per item · AI estimates ${s.ai ? `on (at most ${s.maxPerDay} a day)` : 'off'}`);
842
+ console.log(`reports: ${['daily', 'weekly', 'monthly', 'quarterly'].filter((k) => r[k]).join(', ') || 'none'} at ${r.at}${r.slack ? ' · Slack' : ''}${r.drive ? ' · Google Drive' : ''}`);
843
+ });
844
+
664
845
  program
665
846
  .command('spend')
666
847
  .description('What agents cost today and lately, and spending limits')
@@ -1613,7 +1794,7 @@ export async function main(argv) {
1613
1794
  const showAssistant = (a) => {
1614
1795
  const state = !a.agentId ? dim('not set up (agentmgr assistant start)') : a.on ? green(a.busy ? 'on, checking now' : 'on') : yellow('paused');
1615
1796
  console.log(`${bold('Assistant')}: ${state}${a.agentId ? dim(` agent ${a.agentId}`) : ''}`);
1616
- console.log(`checks every ${a.everyMin} min · watches ${a.sources.join(', ') || 'nothing'} · at most ${a.maxPerDay} new agents a day, ${a.maxRunning} running`);
1797
+ console.log(`checks every ${a.everyMin} min · watches ${a.sources.join(', ') || 'nothing'} · at most ${a.maxPerDay} new agents a day, ${a.maxRunning} running${a.pickIssues ? ' · new issues proposed for you to pick (agentmgr issues)' : ''}`);
1617
1798
  if (a.lastCheckAt) console.log(dim(`last check ${new Date(a.lastCheckAt).toLocaleString()}${a.nextAt ? ` · next ${new Date(a.nextAt).toLocaleTimeString()}` : ''} · started ${a.startedToday} today, ${a.startedTotal} in all`));
1618
1799
  for (const x of a.started.slice(0, 10)) console.log(` ${green('+')} ${bold(x.name)} ${dim(x.id)} ${truncate(x.intent, 70)}`);
1619
1800
  };
@@ -1658,6 +1839,7 @@ export async function main(argv) {
1658
1839
  .option('--max-running <n>', 'of its agents running at once, at most')
1659
1840
  .option('--permission-mode <mode>', 'its own permission mode (default auto, so it can run agentmgr and gh without asking)')
1660
1841
  .option('--notes <text>', 'standing notes, e.g. which Jira project goes to which repo')
1842
+ .option('--pick-issues <on|off>', 'on: propose new Jira and Linear issues for you to tick, instead of starting agents for them')
1661
1843
  .action(async (opts) => {
1662
1844
  await daemon();
1663
1845
  const patch = {
@@ -1667,6 +1849,7 @@ export async function main(argv) {
1667
1849
  ...(opts.maxRunning ? { maxRunning: Number(opts.maxRunning) } : {}),
1668
1850
  ...(opts.permissionMode ? { permissionMode: opts.permissionMode } : {}),
1669
1851
  ...(opts.notes !== undefined ? { notes: opts.notes } : {}),
1852
+ ...(opts.pickIssues !== undefined ? { pickIssues: /^(on|yes|true|1)$/i.test(opts.pickIssues) } : {}),
1670
1853
  };
1671
1854
  showAssistant(await api('PUT', '/assistant', patch));
1672
1855
  });
package/src/designs.js ADDED
@@ -0,0 +1,72 @@
1
+ // Designs: every agent's design doc in one list: its name and summary from DESIGN.md, where it's
2
+ // published (the agent's Artifact, the Google Doc), the specs it builds on, and where the work
3
+ // stands for you, so design docs waiting for review are easy to find and read.
4
+
5
+ import { issueOf, stageOf, GROUPS } from './issues.js';
6
+
7
+ const clip = (s, n) => {
8
+ const t = String(s ?? '').replace(/\s+/g, ' ').trim();
9
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
10
+ };
11
+
12
+ /** The name ("# Design: <name>") and the Summary section's text from DESIGN.md. */
13
+ export function designOutline(markdown) {
14
+ const md = String(markdown ?? '');
15
+ const title = md.match(/^#\s+(?:Design:\s*)?(.+)$/m)?.[1]?.trim() ?? null;
16
+ const summary = md.match(/^##\s+Summary\s*\n+([\s\S]*?)(?=\n#{1,3}\s|(?![\s\S]))/m)?.[1] ?? '';
17
+ // Plain text: no Markdown emphasis, links or code fences.
18
+ const plain = summary
19
+ .replace(/```[\s\S]*?```/g, '')
20
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
21
+ .replace(/[*_`]/g, '');
22
+ return { title: title ? clip(title, 120) : null, summary: clip(plain, 400) || null };
23
+ }
24
+
25
+ /**
26
+ * The list's rows: one per agent with a design doc (written, published or asked for).
27
+ * `read(agentId)` gives the agent's DESIGN.md text, or null.
28
+ */
29
+ export function designRows(views, read) {
30
+ const rank = Object.fromEntries(Object.keys(GROUPS).map((k, i) => [k, i]));
31
+ const rows = [];
32
+ for (const v of views) {
33
+ if (v.kind === 'assistant' || v.kind === 'general') continue;
34
+ const refs = v.brief?.references ?? [];
35
+ const pageRef = refs.find((r) => /design page/i.test(r.label));
36
+ const google = v.drive?.files?.designdoc?.url ?? null;
37
+ const written = v.specDocs?.designdoc ?? null;
38
+ if (!written && !pageRef && !google) continue;
39
+ const outline = written ? designOutline(read(v.id)) : { title: null, summary: null };
40
+ const issue = issueOf(v);
41
+ const { stage, note } = stageOf(v);
42
+ rows.push({
43
+ agent: { id: v.id, name: v.name, project: v.projectInfo?.name ?? null, running: Boolean(v.runtime?.running), busy: Boolean(v.runtime?.busy) },
44
+ title: outline.title ?? v.synopsis?.text ?? v.name,
45
+ summary: outline.summary,
46
+ written: Boolean(written),
47
+ updatedAt: written ?? v.drive?.files?.designdoc?.at ?? v.activeAt ?? null,
48
+ page: pageRef?.url ? { url: pageRef.url } : pageRef?.highlight ? { note: clip(pageRef.highlight, 160) } : null,
49
+ google,
50
+ // The specs it builds on: PRDs, tech specs and other key documents in the brief.
51
+ specs: refs.filter((r) => r.key && r.url && r !== pageRef).slice(0, 4).map((r) => ({ label: r.label, title: r.title, url: r.url })),
52
+ issue: issue ? { key: issue.key, url: issue.url } : null,
53
+ stage,
54
+ group: GROUPS[stage],
55
+ note: clip(note, 200),
56
+ });
57
+ }
58
+ return rows.sort((a, b) => rank[a.stage] - rank[b.stage] || String(b.updatedAt ?? '').localeCompare(String(a.updatedAt ?? '')));
59
+ }
60
+
61
+ /** The rows as a Markdown list, to paste. */
62
+ export function designsMarkdown(rows) {
63
+ if (!rows.length) return 'No design docs.';
64
+ const link = (label, url) => (url ? `[${label}](${url})` : null);
65
+ return rows
66
+ .map((r) => {
67
+ const head = `- **${r.title}**${r.issue ? ` (${link(r.issue.key, r.issue.url) ?? r.issue.key})` : ''}: ${r.note}`;
68
+ const links = [link('Design page', r.page?.url), link('Google Doc', r.google), ...r.specs.map((s) => link(s.label, s.url))].filter(Boolean);
69
+ return [head, r.summary ? ` ${r.summary}` : null, links.length ? ` ${links.join(' · ')}` : null].filter(Boolean).join('\n');
70
+ })
71
+ .join('\n');
72
+ }