ai-agentmanager 1.21.0 → 1.23.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/cli.js CHANGED
@@ -6,6 +6,9 @@ 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';
11
+ import { VERDICT_LABEL } from './reviews.js';
9
12
 
10
13
  const tty = process.stdout.isTTY;
11
14
  const c = (code) => (s) => (tty ? `\x1b[${code}m${s}\x1b[0m` : String(s));
@@ -661,6 +664,252 @@ export async function main(argv) {
661
664
  }
662
665
  });
663
666
 
667
+ 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');
668
+ issuesCmd
669
+ .command('ls', { isDefault: true })
670
+ .description('Issues not started and waiting for your review (--all for the rest)')
671
+ .option('--all', 'also the ones agents are still on and the finished ones')
672
+ .option('--markdown', 'print a Markdown table, to paste')
673
+ .option('--json', 'print JSON')
674
+ .action(async (opts) => {
675
+ await daemon();
676
+ const v = await api('GET', '/issues');
677
+ const rows = opts.all ? v.rows : v.rows.filter((r) => r.group === 'you' || r.group === 'new');
678
+ if (opts.json) return console.log(JSON.stringify({ ...v, rows }, null, 2));
679
+ if (opts.markdown) return console.log(issuesMarkdown(rows));
680
+ 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.'));
681
+ for (const r of rows) {
682
+ const pr = r.pr ? ` PR #${r.pr.number ?? '?'}` : '';
683
+ console.log(`${bold(r.key.padEnd(10))} ${r.jira?.status ? dim(`[${r.jira.status}] `) : ''}${truncate(r.title ?? '', 60)}`);
684
+ 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}`)}`);
685
+ }
686
+ const others = v.rows.length - rows.length;
687
+ if (others) console.log(dim(`\n${others} more with agents still on them or finished: --all`));
688
+ if (!v.jira.signedIn) console.log(dim('Jira status needs your site, email and API token: Settings → Jira.'));
689
+ });
690
+ issuesCmd
691
+ .command('propose')
692
+ .description('Propose an issue for an agent, to start when ticked (the assistant does this when you pick)')
693
+ .argument('<request...>', '[@project] "<issue link> <what to do>"')
694
+ .option('-r, --repo <url>', 'the repository, when no project fits')
695
+ .action(async (words, opts) => {
696
+ await daemon();
697
+ const project = words[0]?.startsWith('@') ? words.shift().slice(1) : null;
698
+ const p = await api('POST', '/issues/proposed', { intent: words.join(' '), project, repo: opts.repo });
699
+ console.log(`${green('+')} ${bold(p.key)} proposed${p.project ? ` in @${p.project}` : ''}: start it under Jira, Not started, or agentmgr issues start ${p.key}`);
700
+ });
701
+ issuesCmd
702
+ .command('start')
703
+ .description('Start agents for proposed issues')
704
+ .argument('<keys...>', 'issue keys, e.g. OPS-7 OPS-9')
705
+ .action(async (keys) => {
706
+ await daemon();
707
+ const r = await api('POST', '/issues/start', { keys });
708
+ for (const x of r.started) console.log(`${green('✓')} ${bold(x.key)} → agent ${x.agent.name} (${x.agent.id})`);
709
+ for (const x of r.failed) console.log(`${red('!')} ${bold(x.key)}: ${x.reason}`);
710
+ });
711
+ issuesCmd
712
+ .command('dismiss')
713
+ .description('Take proposed issues off the list; they are not proposed again')
714
+ .argument('<keys...>')
715
+ .action(async (keys) => {
716
+ await daemon();
717
+ const r = await api('POST', '/issues/dismiss', { keys });
718
+ console.log(`${r.dismissed} dismissed`);
719
+ });
720
+
721
+ program
722
+ .command('designs')
723
+ .description("Agents' design docs: name, summary and links, the ones waiting for your review first")
724
+ .option('--waiting', 'only the ones waiting for your review')
725
+ .option('--markdown', 'print a Markdown list, to paste')
726
+ .option('--json', 'print JSON')
727
+ .action(async (opts) => {
728
+ await daemon();
729
+ const { rows: all } = await api('GET', '/designs');
730
+ const rows = opts.waiting ? all.filter((r) => r.group === 'you') : all;
731
+ if (opts.json) return console.log(JSON.stringify(rows, null, 2));
732
+ if (opts.markdown) return console.log(designsMarkdown(rows));
733
+ if (!rows.length) return console.log(dim(opts.waiting ? 'No design docs waiting for your review.' : 'No design docs yet.'));
734
+ for (const r of rows) {
735
+ console.log(`${bold(r.title)}${r.issue ? dim(` ${r.issue.key}`) : ''} ${r.group === 'you' ? yellow(r.note) : dim(r.note)}`);
736
+ if (r.summary) console.log(` ${truncate(r.summary, 200)}`);
737
+ const links = [r.page?.url && `page ${r.page.url}`, r.google && `doc ${r.google}`].filter(Boolean);
738
+ console.log(dim(` agent ${r.agent.name} (${r.agent.id})${links.length ? ` ${links.join(' ')}` : r.page?.note ? ` page: ${r.page.note}` : ''}`));
739
+ }
740
+ });
741
+
742
+ program
743
+ .command('review')
744
+ .description("Start a reviewer agent on someone else's pull request: it asks the critical questions and finds what blocks approval; nothing is posted")
745
+ .argument('<pr>', 'the pull request link')
746
+ .option('-p, --project <project>', 'the project to check it out in (default: the one whose repository it is)')
747
+ .option('--notes <text>', 'what to look at closely')
748
+ .action(async (url, o) => {
749
+ await daemon();
750
+ const a = await api('POST', '/reviews', { url, project: o.project, notes: o.notes });
751
+ console.log(`${green('✓')} reviewer ${bold(a.name)} (${a.id}) started; see it with agentmgr reviews show ${a.id}`);
752
+ });
753
+ const reviewsCmd = program.command('reviews').description('Pull requests you review: reviewer agents and their verdicts, and requests with no reviewer yet');
754
+ const verdictText = (r) => {
755
+ if (!r.agent) return yellow('requested, no reviewer');
756
+ if (!r.review?.verdict) return dim(r.status);
757
+ const label = VERDICT_LABEL[r.review.verdict];
758
+ const text = r.review.openBlockers ? `${label}: ${r.review.openBlockers} blocker${r.review.openBlockers === 1 ? '' : 's'}` : label;
759
+ return r.review.verdict === 'blocked' ? red(text) : green(text);
760
+ };
761
+ reviewsCmd
762
+ .command('ls', { isDefault: true })
763
+ .description('The list, stale and blocked ones first')
764
+ .option('--markdown', 'print every review as Markdown')
765
+ .option('--json', 'print JSON')
766
+ .action(async (opts) => {
767
+ await daemon();
768
+ if (opts.markdown) return console.log((await api('GET', '/reviews?format=markdown')).markdown);
769
+ const { rows } = await api('GET', '/reviews');
770
+ if (opts.json) return console.log(JSON.stringify(rows, null, 2));
771
+ if (!rows.length) return console.log(dim('No reviews, and no pull requests waiting for your review.'));
772
+ for (const r of rows) {
773
+ console.log(`${bold(`${r.pr.repo ?? ''}#${r.pr.number}`)} ${truncate(r.pr.title ?? '', 60)} ${verdictText(r)}${r.stale ? yellow(' (author pushed since)') : ''}${r.posted ? dim(' posted') : ''}`);
774
+ console.log(dim(` ${r.pr.url}${r.agent ? ` agent ${r.agent.name} (${r.agent.id})` : ''}`));
775
+ }
776
+ });
777
+ reviewsCmd
778
+ .command('show')
779
+ .description("A reviewer's review: verdict, blockers, questions for the author, risks")
780
+ .argument('<agent>')
781
+ .action(async (ref) => {
782
+ await daemon();
783
+ const a = await resolveAgent(ref);
784
+ const r = await api('GET', `/reviews/${a.id}`);
785
+ console.log(r.markdown);
786
+ if (r.review) console.log(dim(`\nIds to post: ${[...r.review.blockers.filter((b) => b.status === 'open'), ...r.review.questions, ...r.review.nits].map((x) => x.id).join(' ') || 'none'}`));
787
+ });
788
+ reviewsCmd
789
+ .command('post')
790
+ .description('Post a pending review on GitHub, under your name, with the picked items (default: open blockers and questions); you submit it there')
791
+ .argument('<agent>')
792
+ .argument('[ids...]', 'items to send, e.g. b1 q2 n1')
793
+ .action(async (ref, ids) => {
794
+ await daemon();
795
+ const a = await resolveAgent(ref);
796
+ const r = await api('POST', `/reviews/${a.id}/post`, { ids: ids.length ? ids : null });
797
+ console.log(`${green('✓')} pending review with ${r.ids.length} item${r.ids.length === 1 ? '' : 's'}: finish and submit it at ${r.url}${r.moved ? dim(`\n ${r.moved} line comment(s) went in the body: their lines aren't in the diff`) : ''}`);
798
+ });
799
+ reviewsCmd
800
+ .command('dismiss')
801
+ .description("Take requested pull requests off the list (you won't have an agent review them)")
802
+ .argument('<prs...>')
803
+ .action(async (urls) => {
804
+ await daemon();
805
+ const r = await api('POST', '/reviews/dismiss', { urls });
806
+ console.log(`${r.dismissed} dismissed`);
807
+ });
808
+
809
+ 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');
810
+ const money = (n, cur = 'USD') => (n == null ? '—' : new Intl.NumberFormat('en-US', { style: 'currency', currency: cur, maximumFractionDigits: 0 }).format(n));
811
+ valueCmd
812
+ .command('show', { isDefault: true })
813
+ .description('Totals for the last periods and the items in the current one')
814
+ .option('-p, --period <period>', 'day, week, month or quarter', 'week')
815
+ .option('--json', 'print JSON')
816
+ .action(async (opts) => {
817
+ await daemon();
818
+ const v = await api('GET', `/value?period=${encodeURIComponent(opts.period)}`);
819
+ if (opts.json) return console.log(JSON.stringify(v, null, 2));
820
+ const cur = v.settings.currency;
821
+ for (const p of v.periods.slice(0, 6)) {
822
+ const t = p.totals;
823
+ 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)') : ''}`);
824
+ }
825
+ const now = v.periods[0];
826
+ const items = v.items.filter((it) => now.items.includes(it.agentId));
827
+ if (items.length) console.log('');
828
+ 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}`)}`);
829
+ if (v.pending) console.log(dim(`\n${v.pending} waiting for an estimate`));
830
+ });
831
+ valueCmd
832
+ .command('edit')
833
+ .description("Correct an item's figures (\"\" puts one back to the AI's estimate)")
834
+ .argument('<agent>')
835
+ .option('--hours <n>', 'engineering hours it saved')
836
+ .option('--savings <usd>', 'other savings, first year')
837
+ .option('--revenue <usd>', 'potential revenue, first year')
838
+ .option('--strategic <0-5>', 'strategic weight')
839
+ .option('--your-hours <n>', 'your own time on it')
840
+ .option('--category <name>', 'cost savings, revenue, risk reduction, quality, customer experience, strategic or maintenance')
841
+ .option('--summary <text>', 'one sentence for management')
842
+ .option('--exclude', "don't count it")
843
+ .option('--include', 'count it again')
844
+ .action(async (ref, o) => {
845
+ await daemon();
846
+ const a = await resolveAgent(ref);
847
+ const val = (x, n = true) => (x === undefined ? undefined : x === '' ? null : n ? Number(x) : x);
848
+ const patch = Object.fromEntries(
849
+ 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),
850
+ );
851
+ let it = Object.keys(patch).length ? await api('PATCH', `/value/items/${a.id}`, patch) : null;
852
+ if (o.exclude || o.include) it = await api('POST', `/value/items/${a.id}/exclude`, { excluded: Boolean(o.exclude) });
853
+ if (!it) throw new Error('Nothing to change: give --hours, --revenue, … or --exclude');
854
+ 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)') : ''}`);
855
+ });
856
+ valueCmd
857
+ .command('estimate')
858
+ .description('Estimate an item now (again)')
859
+ .argument('<agent>')
860
+ .action(async (ref) => {
861
+ await daemon();
862
+ const a = await resolveAgent(ref);
863
+ const it = await api('POST', `/value/items/${a.id}/estimate`);
864
+ if (it.estError) throw new Error(it.estError);
865
+ console.log(`${green('✓')} ${bold(it.title)}: ${it.est.humanHours} h, ${it.est.category}. ${it.est.summary}`);
866
+ });
867
+ valueCmd
868
+ .command('report')
869
+ .description('The report for the period just ended (or --current), as Markdown; --send to Slack and Google Drive as set')
870
+ .option('-k, --kind <kind>', 'day, week, month or quarter', 'week')
871
+ .option('--current', 'the current period so far')
872
+ .option('--send', 'send it now')
873
+ .action(async (o) => {
874
+ await daemon();
875
+ if (!o.send) return console.log((await api('GET', `/value/report?kind=${encodeURIComponent(o.kind)}${o.current ? '&current=1' : ''}`)).markdown);
876
+ const r = await api('POST', '/value/report', { kind: o.kind, current: Boolean(o.current) });
877
+ 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}`) : ''}`);
878
+ });
879
+ valueCmd
880
+ .command('set')
881
+ .description('Settings: your rates, the estimates, and when reports go out')
882
+ .option('--rate <usd>', 'a loaded engineering hour')
883
+ .option('--currency <code>', 'e.g. USD, EUR')
884
+ .option('--your-minutes <n>', 'your time per item unless set on it')
885
+ .option('--ai <on|off>', 'estimate delivered work with AI')
886
+ .option('--notes <text>', 'context for the estimates: your company, customers, what revenue means')
887
+ .option('--reports <list>', 'which reports, comma separated: daily,weekly,monthly,quarterly (or none)')
888
+ .option('--at <HH:MM>', 'when reports go out')
889
+ .option('--slack <on|off>', 'send reports to Slack')
890
+ .option('--drive <on|off>', 'save reports as Google Docs')
891
+ .action(async (o) => {
892
+ await daemon();
893
+ const on = (x) => (x === undefined ? undefined : /^(on|yes|true|1)$/i.test(x));
894
+ const kinds = o.reports === undefined ? null : o.reports.split(',').map((x) => x.trim());
895
+ const report = Object.fromEntries(
896
+ Object.entries({
897
+ ...(kinds ? { daily: kinds.includes('daily'), weekly: kinds.includes('weekly'), monthly: kinds.includes('monthly'), quarterly: kinds.includes('quarterly') } : {}),
898
+ at: o.at,
899
+ slack: on(o.slack),
900
+ drive: on(o.drive),
901
+ }).filter(([, x]) => x !== undefined),
902
+ );
903
+ const patch = Object.fromEntries(
904
+ 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),
905
+ );
906
+ const v = await api('PUT', '/value', patch);
907
+ const s = v.settings;
908
+ const r = s.report;
909
+ 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'}`);
910
+ console.log(`reports: ${['daily', 'weekly', 'monthly', 'quarterly'].filter((k) => r[k]).join(', ') || 'none'} at ${r.at}${r.slack ? ' · Slack' : ''}${r.drive ? ' · Google Drive' : ''}`);
911
+ });
912
+
664
913
  program
665
914
  .command('spend')
666
915
  .description('What agents cost today and lately, and spending limits')
@@ -1613,7 +1862,7 @@ export async function main(argv) {
1613
1862
  const showAssistant = (a) => {
1614
1863
  const state = !a.agentId ? dim('not set up (agentmgr assistant start)') : a.on ? green(a.busy ? 'on, checking now' : 'on') : yellow('paused');
1615
1864
  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`);
1865
+ 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
1866
  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
1867
  for (const x of a.started.slice(0, 10)) console.log(` ${green('+')} ${bold(x.name)} ${dim(x.id)} ${truncate(x.intent, 70)}`);
1619
1868
  };
@@ -1658,6 +1907,7 @@ export async function main(argv) {
1658
1907
  .option('--max-running <n>', 'of its agents running at once, at most')
1659
1908
  .option('--permission-mode <mode>', 'its own permission mode (default auto, so it can run agentmgr and gh without asking)')
1660
1909
  .option('--notes <text>', 'standing notes, e.g. which Jira project goes to which repo')
1910
+ .option('--pick-issues <on|off>', 'on: propose new Jira and Linear issues for you to tick, instead of starting agents for them')
1661
1911
  .action(async (opts) => {
1662
1912
  await daemon();
1663
1913
  const patch = {
@@ -1667,6 +1917,7 @@ export async function main(argv) {
1667
1917
  ...(opts.maxRunning ? { maxRunning: Number(opts.maxRunning) } : {}),
1668
1918
  ...(opts.permissionMode ? { permissionMode: opts.permissionMode } : {}),
1669
1919
  ...(opts.notes !== undefined ? { notes: opts.notes } : {}),
1920
+ ...(opts.pickIssues !== undefined ? { pickIssues: /^(on|yes|true|1)$/i.test(opts.pickIssues) } : {}),
1670
1921
  };
1671
1922
  showAssistant(await api('PUT', '/assistant', patch));
1672
1923
  });
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
+ }
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
+ }