ai-agentmanager 1.68.0 → 1.70.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/record.js CHANGED
@@ -5,12 +5,32 @@
5
5
  // "said 85% on average, 6 of 10 held up". Per project it also says what level of "Without you"
6
6
  // the record supports. The level stays the person's to set; this only suggests. No model is called.
7
7
 
8
+ import { costOf } from './budgets.js';
9
+
8
10
  export const MIN_TO_SAY = 5; // fewer settled pull requests than this say nothing
9
11
  const LEVELS = ['ask', 'run', 'pr', 'merge'];
10
12
  const LEVEL_LABEL = { ask: 'Ask me', run: 'Agree, then run', pr: 'Run to pull request', merge: 'Run to merge' };
11
- const PROBLEMS = new Set(['reverted', 'fixed', 'broke', 'problem']);
13
+ const PROBLEMS = new Set(['incident', 'reverted', 'fixed', 'broke', 'problem']);
12
14
  const round = (n) => (Number.isFinite(n) ? Math.round(n) : null);
13
15
 
16
+ // Kinds of work, read from the request's words (first match wins). No model: a rough sort that is
17
+ // stable and can be checked; work it cannot place is a feature.
18
+ export const KINDS = [
19
+ ['docs', 'Documentation', /\b(docs?|readme|documentation|changelog|comments?)\b/i],
20
+ ['tests', 'Tests', /\b(tests?|test cases?|coverage|e2e|unit tests?)\b/i],
21
+ ['upgrade', 'Upgrades and migrations', /\b(upgrade|bump|migrat(e|ion)|dependenc(y|ies)|deprecat)/i],
22
+ ['fix', 'Bug fixes', /\b(fix(es|ed)?|bugs?|crash(es)?|errors?|broken|regression|fails?|failing|exception)\b/i],
23
+ ['refactor', 'Refactoring', /\b(refactor|clean ?up|rename|simplif(y|ies)|restructure|dedupe)\b/i],
24
+ ['investigate', 'Investigation', /\b(investigate|explore|analy[sz]e|research|look into|find out|why)\b/i],
25
+ ];
26
+ export const KIND_LABEL = { ...Object.fromEntries(KINDS.map(([k, l]) => [k, l])), feature: 'Features' };
27
+
28
+ /** The kind of a piece of work from its request or title. */
29
+ export function kindOf(text) {
30
+ const t = String(text ?? '').split('\n')[0].replace(/^<?https?:\/\/\S+>?\s*/, '');
31
+ return KINDS.find(([, , re]) => re.test(t))?.[0] ?? 'feature';
32
+ }
33
+
14
34
  /** What is said about an agent's work now, kept when its pull request merges. */
15
35
  export function saidOf(agent, { engine = null } = {}) {
16
36
  const sc = agent.docs?.scorecard?.data;
@@ -26,6 +46,9 @@ export function saidOf(agent, { engine = null } = {}) {
26
46
  engine: engine ?? agent.engine ?? 'claude',
27
47
  model: agent.model ?? null,
28
48
  level: LEVELS.includes(agent.autonomy?.level) ? agent.autonomy.level : 'ask',
49
+ // What the AI work cost as it merged, kept only to compare models with each other (never shown as money).
50
+ cost: costOf(agent) || null,
51
+ kind: kindOf(agent.intent ?? agent.name),
29
52
  };
30
53
  }
31
54
 
@@ -78,6 +101,62 @@ export function suggestLevel(settled, current = 'ask') {
78
101
  return null;
79
102
  }
80
103
 
104
+ const modelKey = (it) => `${it.said?.engine ?? 'unknown'}${it.said?.model ? ` · ${it.said.model}` : ''}`;
105
+
106
+ /**
107
+ * Model fit: which model held up as well as the most used one at a lower cost. Per model: how many
108
+ * settled pieces, the share that held up, the average review scorecard, and the cost per piece
109
+ * against the most used model's (a ratio, not money). A suggestion needs MIN_TO_SAY settled pieces
110
+ * for both, a share that held up within 5 points of the most used model's, and a cost at most
111
+ * three quarters of it. `settled`: the settled pull requests.
112
+ */
113
+ export function modelFit(settled) {
114
+ const keys = [...new Set(settled.map(modelKey))];
115
+ const rows = keys.map((k) => {
116
+ const list = settled.filter((it) => modelKey(it) === k);
117
+ const held = list.filter((it) => it.held).length;
118
+ const costs = list.map((it) => it.said?.cost).filter((c) => Number.isFinite(c) && c > 0);
119
+ const scores = list.map((it) => it.said?.score).filter(Number.isFinite);
120
+ return { model: k, n: list.length, held, heldPct: round((held / list.length) * 100), avgCost: costs.length ? costs.reduce((a, c) => a + c, 0) / costs.length : null, costed: costs.length, score: scores.length ? round(scores.reduce((a, c) => a + c, 0) / scores.length) : null };
121
+ }).sort((a, b) => b.n - a.n);
122
+ const base = rows[0] ?? null;
123
+ const out = rows.map((r) => ({ ...r, costVsMain: base?.avgCost && r.avgCost ? Math.round((r.avgCost / base.avgCost) * 100) / 100 : null, avgCost: undefined }));
124
+ let suggestion = null;
125
+ if (base && base.n >= MIN_TO_SAY && base.avgCost) {
126
+ const better = out
127
+ .slice(1)
128
+ .filter((r) => r.n >= MIN_TO_SAY && r.costed >= MIN_TO_SAY && r.costVsMain != null && r.costVsMain <= 0.75 && r.heldPct >= base.heldPct - 5)
129
+ .sort((a, b) => a.costVsMain - b.costVsMain)[0];
130
+ if (better) suggestion = { model: better.model, main: base.model, costVsMain: better.costVsMain, heldPct: better.heldPct, mainHeldPct: base.heldPct, n: better.n };
131
+ }
132
+ return { rows: out, suggestion };
133
+ }
134
+
135
+ /**
136
+ * Delegation map: by kind of work, how much went to agents, how far it ran without the person,
137
+ * and how it held up. A kind that held up at 9 in 10 over 5 settled pull requests while most of it
138
+ * still asked the person is the next worth handing over more of; one under 7 in 10 is worth
139
+ * keeping close. `settled`: the settled pull requests.
140
+ */
141
+ export function delegationMap(settled) {
142
+ const kindOfItem = (it) => it.said?.kind ?? kindOf(it.title);
143
+ const rows = Object.keys(KIND_LABEL)
144
+ .map((k) => {
145
+ const list = settled.filter((it) => kindOfItem(it) === k);
146
+ if (!list.length) return null;
147
+ const held = list.filter((it) => it.held).length;
148
+ const asked = list.filter((it) => (it.said?.level ?? 'ask') === 'ask').length;
149
+ const heldPct = round((held / list.length) * 100);
150
+ const advice =
151
+ list.length < MIN_TO_SAY ? null : heldPct >= 90 && asked * 2 > list.length ? 'hand over more' : heldPct < 70 ? 'keep close' : null;
152
+ return { kind: k, label: KIND_LABEL[k], n: list.length, held, heldPct, withoutYou: list.length - asked, advice };
153
+ })
154
+ .filter(Boolean)
155
+ .sort((a, b) => b.n - a.n);
156
+ const next = rows.filter((r) => r.advice === 'hand over more').sort((a, b) => b.heldPct - a.heldPct || b.n - a.n)[0] ?? null;
157
+ return { rows, next: next ? { kind: next.kind, label: next.label, heldPct: next.heldPct, n: next.n } : null };
158
+ }
159
+
81
160
  /**
82
161
  * The record from Quality's items. `verdict(it)` is quality.js's verdictOf; a pull request counts
83
162
  * once it is settled: held up after the watch days, or a problem. `levels`: { default, projects }.
@@ -116,6 +195,8 @@ export function trackRecord(items, verdict, { levels = {} } = {}) {
116
195
  ]),
117
196
  models: rowsOf(settled, uniq((it) => `${it.said?.engine ?? 'unknown'}${it.said?.model ? ` · ${it.said.model}` : ''}`).map((k) => [k, k, (it) => `${it.said?.engine ?? 'unknown'}${it.said?.model ? ` · ${it.said.model}` : ''}` === k])),
118
197
  levels: rowsOf(settled, LEVELS.map((l) => [l, LEVEL_LABEL[l], (it) => (it.said?.level ?? 'ask') === l])),
198
+ fit: modelFit(settled),
199
+ delegation: delegationMap(settled),
119
200
  projects: projects.sort((a, b) => b.n - a.n),
120
201
  defaultLevel: levels.default ?? 'ask',
121
202
  };
@@ -136,6 +217,16 @@ export function recordMarkdown(r) {
136
217
  part('Tests tested', r.tests);
137
218
  part('Model', r.models);
138
219
  part('Without you', r.levels);
220
+ if (r.delegation.rows.length) {
221
+ out.push('## Delegation map', '', ...r.delegation.rows.map((d) => `- ${d.label}: ${d.held} of ${d.n} held up (${d.heldPct}%), ${d.withoutYou} ran without you${d.advice ? `: ${d.advice}` : ''}`));
222
+ if (r.delegation.next) out.push('', `Next to hand over more of: **${r.delegation.next.label}** (${r.delegation.next.heldPct}% held up over ${r.delegation.next.n}, most of it still asking you).`);
223
+ out.push('');
224
+ }
225
+ if (r.fit.rows.length > 1) {
226
+ out.push('## Model fit', '', ...r.fit.rows.map((m) => `- ${m.model}: ${m.held} of ${m.n} held up (${m.heldPct}%)${m.score != null ? `, scorecard ${m.score} on average` : ''}${m.costVsMain != null && m !== r.fit.rows[0] ? `, ${m.costVsMain} times the cost of ${r.fit.rows[0].model}` : ''}`));
227
+ if (r.fit.suggestion) out.push('', `**${r.fit.suggestion.model}** held up as well as ${r.fit.suggestion.main} (${r.fit.suggestion.heldPct}% against ${r.fit.suggestion.mainHeldPct}%) at ${r.fit.suggestion.costVsMain} times the cost, over ${r.fit.suggestion.n} settled pull requests: worth trying for more of the work.`);
228
+ out.push('');
229
+ }
139
230
  if (r.projects.length) {
140
231
  out.push('## Projects', '');
141
232
  for (const p of r.projects) {
package/src/server.js CHANGED
@@ -59,6 +59,8 @@ import { Value, valueSlack } from './value.js';
59
59
  import { Quality } from './quality.js';
60
60
  import { recordMarkdown } from './record.js';
61
61
  import { Weekly } from './weekly.js';
62
+ import { queueMarkdown, readQueue } from './readfirst.js';
63
+ import { traceMarkdown, traceOf } from './trace.js';
62
64
  import { PRIVATE_MESSAGE, keptPrivate, mustBeShareable } from './private.js';
63
65
  import { Standards, runCheck } from './standards.js';
64
66
  import { Proof, proofMarkdown } from './proof.js';
@@ -643,6 +645,11 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
643
645
  if (![true, false, null].includes(b.private ?? null)) throw fail(400, 'private is true (keep it private), false (allow sharing) or null (what was read)');
644
646
  return manager.setPrivate(req.params.id, { private: b.private ?? null, note: b.note ?? '' });
645
647
  }));
648
+ // Understanding check: whether you knew the answer. Yours to say, not the agent's.
649
+ api.post('/agents/:id/understanding/knew', wrap((req) => {
650
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'Whether you knew an answer is said by the person, not by an agent');
651
+ return manager.understandingKnew(req.params.id, req.body?.question, req.body?.knew ?? null);
652
+ }));
646
653
  const DOC_LIST = ['analysis', 'design', 'flow', 'proposal', 'humanai', 'estimate', 'documentation'];
647
654
  api.post('/agents/:id/humanai/answers', wrap((req) => manager.humanAiAnswers(req.params.id, req.body?.answers, { send: req.body?.send === true })));
648
655
  api.post(
@@ -731,6 +738,13 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
731
738
  if (req.headers['x-agentmgr-agent']) throw fail(403, 'Running the proof again is asked by the person, not by an agent');
732
739
  return manager.proof.rerun(req.params.id);
733
740
  }));
741
+ // Requirement trace (trace.js): each point of what done means, followed to the scorecard's finding and the recorded checks.
742
+ api.get('/agents/:id/trace', wrap((req) => {
743
+ const a = manager.mustGet(req.params.id);
744
+ const p = manager.proof.forScore(a);
745
+ const t = traceOf(a, p.entries, p.rerun);
746
+ return req.query.format === 'md' ? { markdown: traceMarkdown(a.name, t) } : t;
747
+ }));
734
748
  // Test the tests (mutate.js): changed lines broken one at a time, the tests run on each. The
735
749
  // person's call only: it runs commands here and changes the agent's files for a moment.
736
750
  api.get('/agents/:id/breaks', wrap(async (req) => {
@@ -1260,9 +1274,26 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1260
1274
  api.get('/repeats', wrap(() => repeats.view()));
1261
1275
  api.post('/repeats/dismiss', wrap((req) => repeats.dismiss(String(req.body?.key ?? ''))));
1262
1276
  api.post('/playbooks/:id/run', wrap((req) => playbooks.run(req.params.id, { vars: req.body?.vars ?? {} })));
1277
+ // Read first (readfirst.js): finished work waiting for review, the pieces that need reading most first.
1278
+ api.get('/read-first', wrap((req) => {
1279
+ const items = readQueue(store.list(), (a) => manager.view(a));
1280
+ return req.query.format === 'md' ? { markdown: queueMarkdown(items) } : { items };
1281
+ }));
1282
+ // Reviewed: the person has read it, so it leaves the queue until the agent changes its brief again. `olderThanDays` marks every one finished longer ago.
1283
+ api.post('/read-first/reviewed', wrap((req) => {
1284
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'Whether work was reviewed is said by the person, not by an agent');
1285
+ const b = req.body ?? {};
1286
+ const at = new Date().toISOString();
1287
+ let ids = [];
1288
+ if (b.agent) ids = [manager.mustGet(b.agent).id];
1289
+ else if (Number(b.olderThanDays) > 0) ids = readQueue(store.list(), (a) => manager.view(a)).filter((i) => Date.parse(i.finishedAt) < Date.now() - Number(b.olderThanDays) * 86_400_000).map((i) => i.agentId);
1290
+ else throw fail(400, 'Give agent, or olderThanDays');
1291
+ for (const id of ids) manager.patch(id, { reviewed: b.reviewed === false ? null : { at } });
1292
+ return { marked: ids.length, items: readQueue(store.list(), (a) => manager.view(a)) };
1293
+ }));
1263
1294
  // Weekly summary (weekly.js): a week's work and achievements on one page, for management. A draft: nothing is sent.
1264
- api.get('/weekly', wrap((req) => weekly.report({ current: req.query.current === '1' })));
1265
- api.post('/weekly/save', wrap((req) => weekly.save({ current: req.body?.current === true })));
1295
+ api.get('/weekly', wrap((req) => weekly.report({ kind: String(req.query.kind ?? 'week'), current: req.query.current === '1' })));
1296
+ api.post('/weekly/save', wrap((req) => weekly.save({ kind: String(req.body?.kind ?? 'week'), current: req.body?.current === true })));
1266
1297
  api.get('/worklog', wrap(async (req) => (await worklog.record(), worklog.view({ days: Number(req.query.days ?? 30) || 0 }))));
1267
1298
  api.get('/worklog/summary', wrap(async (req) => {
1268
1299
  await worklog.record();
@@ -1390,6 +1421,12 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1390
1421
  const r = quality.record();
1391
1422
  return req.query.format === 'md' ? { markdown: recordMarkdown(r) } : r;
1392
1423
  }));
1424
+ // Production signal: an incident from any monitoring tool, a script or you, linked to the merged pull request it belongs to.
1425
+ api.post('/quality/incident', wrap((req) => {
1426
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'Incidents are reported by the person or their tools, not by an agent');
1427
+ return quality.incident({ ...(req.body ?? {}), source: req.body?.source ?? 'api' });
1428
+ }));
1429
+ api.post('/quality/incident/drop', wrap((req) => quality.dropIncident(String(req.body?.url ?? ''), String(req.body?.key ?? ''))));
1393
1430
  api.post('/quality/mark', wrap((req) => quality.mark(String(req.body?.url ?? ''), { verdict: req.body?.verdict ?? null, note: req.body?.note ?? '' })));
1394
1431
  api.post('/quality/check', wrap((req) => quality.check(String(req.body?.url ?? ''), { fresh: true })));
1395
1432
  // Standards are the person's to set: an agent's own calls can read them, not change them.
package/src/standards.js CHANGED
@@ -197,6 +197,7 @@ export function builtInChecks(bar, { files = [], diff = '' } = {}) {
197
197
  // ---------------------------------------------------------------- lessons
198
198
 
199
199
  const SOURCE_TEXT = {
200
+ incident: 'caused an incident in production',
200
201
  reverted: 'was reverted',
201
202
  fixed: 'needed a fix afterwards',
202
203
  broke: 'failed its checks once merged',
@@ -216,6 +217,7 @@ export function cleanLesson(text) {
216
217
  export function lessonSource(it) {
217
218
  const a = it.after ?? {};
218
219
  const name = (x) => clip(`${x?.number ? `#${x.number} ` : ''}${x?.title ?? ''}`, 140);
220
+ if (it.verdict === 'incident') return { kind: 'incident', detail: `Seen in production: ${(it.incidents ?? []).map((x) => clip(x.title, 100)).join('; ')}` };
219
221
  if (it.verdict === 'reverted') return { kind: 'reverted', detail: a.reverted ? `Reverted by ${name(a.reverted)}` : 'Reverted' };
220
222
  if (it.verdict === 'fixed') return { kind: 'fixed', detail: `Fixed afterwards by ${(a.fixes ?? []).map(name).join('; ')}` };
221
223
  if (it.verdict === 'broke') return { kind: 'broke', detail: `Checks failed on the commit it merged as: ${(a.checks?.failed ?? []).join(', ')}` };
package/src/trace.js ADDED
@@ -0,0 +1,69 @@
1
+ // Requirement trace: each point of what done means, followed to what shows it. For every agreed
2
+ // acceptance point (acceptance.js), or the scorecard's criteria when none were agreed: whether the
3
+ // review scorecard found it met, with its evidence; the checks the agent recorded for it in its
4
+ // proof (the command, its exit code, and whether it gave the same result when the app ran it
5
+ // again); and what is missing. A point with nothing behind it stands out. No model is called: it
6
+ // joins what the scorecard and the proof already hold.
7
+
8
+ const STATUS = { met: 'Met', not_met: 'Not met', unverified: 'Not verified', unscored: 'Not scored yet' };
9
+ const plain = (s) => String(s ?? '').toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim();
10
+ const clip = (s, n = 200) => {
11
+ const t = String(s ?? '').replace(/\s+/g, ' ').trim();
12
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
13
+ };
14
+
15
+ /** What is missing behind a point, in a few words, or null when it is shown by a run that held. */
16
+ export function gapOf(row) {
17
+ if (row.status === 'not_met') return 'the scorecard found it not met';
18
+ const runs = row.proof.filter((p) => p.command);
19
+ if (runs.some((p) => p.rerun === 'differs')) return 'its recorded command gave a different result when run again';
20
+ if (!row.proof.length) return row.status === 'met' ? 'met by the scorecard, with no check recorded for it' : 'nothing recorded for it';
21
+ if (!runs.length) return 'checked by reading only: no command was run';
22
+ if (runs.some((p) => p.exit !== null && p.exit !== 0 && !/fail|error|reject|invalid|usage|throw/i.test(`${row.text} ${p.title}`))) return 'its recorded command did not exit with success';
23
+ if (row.status === 'unverified') return 'the scorecard could not verify it';
24
+ return null;
25
+ }
26
+
27
+ /**
28
+ * The trace of an agent's points. `entries`: its proof (proof.js parseProof), `rerun`: the app's
29
+ * last run of it ({ results, stale }). Returns { source, rows, counts }.
30
+ */
31
+ export function traceOf(agent, entries = [], rerun = null) {
32
+ const agreed = agent.acceptance?.status === 'agreed' ? agent.acceptance.points ?? [] : [];
33
+ const criteria = agent.docs?.scorecard?.data?.criteria ?? [];
34
+ const points = agreed.length ? agreed.map((p) => ({ id: p.id, text: p.text })) : criteria.map((c, i) => ({ id: c.id || `C${i + 1}`, text: c.criterion }));
35
+ const again = new Map((rerun && !rerun.stale ? rerun.results ?? [] : []).map((r) => [`${r.title}\n${r.command}`, r.status]));
36
+ const rows = points.map((p) => {
37
+ const c = criteria.find((x) => x.id && x.id === p.id) ?? criteria.find((x) => plain(x.criterion) === plain(p.text));
38
+ // Its proof: sections that start with its id ("A2 …"), or whose title says the same as the point.
39
+ const proof = entries
40
+ .filter((e) => (e.point && e.point === String(p.id).toUpperCase()) || plain(e.title) === plain(p.text))
41
+ .map((e) => ({ title: e.title, command: e.command, exit: e.exit, note: e.command ? '' : clip(e.note, 160), rerun: again.get(`${e.title}\n${e.command}`) ?? null }));
42
+ const row = { id: p.id, text: p.text, status: c?.status ?? 'unscored', evidence: clip(c?.evidence, 240), proof };
43
+ return { ...row, gap: gapOf(row) };
44
+ });
45
+ const n = (f) => rows.filter(f).length;
46
+ return {
47
+ source: agreed.length ? 'agreed' : criteria.length ? 'scorecard' : 'none',
48
+ rows,
49
+ counts: { points: rows.length, met: n((r) => r.status === 'met'), notMet: n((r) => r.status === 'not_met'), shown: n((r) => !r.gap), gaps: n((r) => r.gap) },
50
+ };
51
+ }
52
+
53
+ /** "4 of 5 points shown by a check that held; 1 with a gap" */
54
+ export function traceLine(t) {
55
+ if (!t?.rows.length) return '';
56
+ return `${t.counts.shown} of ${t.counts.points} point${t.counts.points === 1 ? '' : 's'} shown by a recorded run${t.counts.gaps ? `; ${t.counts.gaps} with a gap` : ''}`;
57
+ }
58
+
59
+ export function traceMarkdown(name, t) {
60
+ const out = [`# Requirement trace: ${name}`, ''];
61
+ if (!t.rows.length) return [...out, 'No points to trace: nothing was agreed as what done means, and the scorecard holds no criteria.'].join('\n');
62
+ out.push(t.source === 'agreed' ? 'The points agreed with you as what done means.' : "The scorecard's criteria (no points were agreed).", '', `${traceLine(t)}.`, '');
63
+ for (const r of t.rows) {
64
+ out.push(`## ${r.id} ${r.text}`, '', `- Scorecard: ${STATUS[r.status]}${r.evidence ? `: ${r.evidence}` : ''}`);
65
+ for (const p of r.proof) out.push(`- Check: ${p.command ? `\`${p.command}\`${p.exit === null ? '' : ` (exit ${p.exit})`}${p.rerun ? `, ${p.rerun === 'same' ? 'the same result when run again' : p.rerun === 'differs' ? 'a different result when run again' : 'not run again'}` : ''}` : `by reading${p.note ? `: ${p.note}` : ''}`}`);
66
+ out.push(r.gap ? `- **Gap:** ${r.gap}` : '- Shown by a recorded run.', '');
67
+ }
68
+ return out.join('\n').trimEnd();
69
+ }
package/src/weekly.js CHANGED
@@ -14,8 +14,8 @@ import { paths } from './config.js';
14
14
  import { dayKey } from './budgets.js';
15
15
  import { keptPrivate } from './private.js';
16
16
  import { totals as qualityTotals } from './quality.js';
17
- import { itemValue } from './value.js';
18
- import { weekRow, weekStart } from './worklog.js';
17
+ import { PERIODS, itemValue } from './value.js';
18
+ import { weekStart } from './worklog.js';
19
19
 
20
20
  const DAY = 86_400_000;
21
21
  const PRIVATE = '(kept private)';
@@ -89,12 +89,45 @@ export function checkedLine(t) {
89
89
  /** The Monday a week's summary starts on: the week before `t`, or the one `t` is in. */
90
90
  export const weekOf = (t = Date.now(), { current = false } = {}) => (current ? weekStart(t) : weekStart(weekStart(t) - DAY));
91
91
 
92
+ export const KINDS = { week: 'Weekly', month: 'Monthly', quarter: 'Quarterly' };
93
+
94
+ /**
95
+ * The period a summary covers: a week (Monday to Sunday), a calendar month or a quarter; the one
96
+ * that just ended, or the one `t` is in. { kind, start, end, prevStart, label, key }.
97
+ */
98
+ export function periodOf(kind = 'week', t = Date.now(), { current = false } = {}) {
99
+ if (!KINDS[kind]) throw Object.assign(new Error(`kind is one of ${Object.keys(KINDS).join(', ')}`), { status: 400 });
100
+ if (kind === 'week') {
101
+ const start = weekOf(t, { current });
102
+ const end = start + 7 * DAY;
103
+ return { kind, start, end: weekStart(end + DAY), prevStart: weekStart(start - DAY), label: `${dayLabel(start)} to ${dayLabel(end - DAY)}, ${new Date(end - DAY).getFullYear()}`, key: dayKey(start) };
104
+ }
105
+ const P = PERIODS[kind];
106
+ const here = P.start(t);
107
+ const start = current ? here : P.start(here - DAY);
108
+ return { kind, start, end: P.next(start), prevStart: P.start(start - DAY), label: P.label(start), key: P.key(start) };
109
+ }
110
+
111
+ const median = (list) => {
112
+ const a = list.filter(Number.isFinite).sort((x, y) => x - y);
113
+ if (!a.length) return null;
114
+ const m = a.length >> 1;
115
+ return a.length % 2 ? a[m] : (a[m - 1] + a[m]) / 2;
116
+ };
117
+
118
+ /** The work record's counts between two moments. */
119
+ export function countRow(start, end, events) {
120
+ const mine = events.filter((e) => Date.parse(e.date) >= start && Date.parse(e.date) < end);
121
+ const n = (k) => mine.filter((e) => e.event === k).length;
122
+ const hours = median(mine.filter((e) => e.event === 'pr_merged' && e.hours !== '' && e.hours != null).map((e) => Number(e.hours)));
123
+ return { prs_opened: n('pr_opened'), prs_merged: n('pr_merged'), bugs_fixed: n('bug_fixed'), issues_filed: n('issue_filed'), agents_finished: n('agent_finished'), median_hours_to_merge: hours == null ? '' : Math.round(hours * 10) / 10 };
124
+ }
125
+
92
126
  /**
93
127
  * A week's facts. `events`: the work record's rows; `spend`: the spend ledger's days; `value` and
94
128
  * `quality`: { items, settings } of those modules; `agents`: [{ agent, view }] as they are now.
95
129
  */
96
- export function weeklyFacts({ start, events = [], spend = {}, value = null, quality = null, agents = [], t = Date.now() }) {
97
- const end = start + 7 * DAY;
130
+ export function weeklyFacts({ start, end = start + 7 * DAY, prevStart = start - 7 * DAY, kind = 'week', label = null, events = [], value = null, quality = null, agents = [], t = Date.now() }) {
98
131
  const inWeek = (iso) => Date.parse(iso) >= start && Date.parse(iso) < end;
99
132
  const hidden = new Set(agents.filter((x) => keptPrivate(x.agent)).map((x) => x.agent.id));
100
133
  const mine = events.filter((e) => inWeek(e.date));
@@ -160,7 +193,7 @@ export function weeklyFacts({ start, events = [], spend = {}, value = null, qual
160
193
  const highlights = [...merged, ...finished]
161
194
  .filter((e) => !e.private && e.hours != null)
162
195
  .sort((a, b) => b.hours - a.hours)
163
- .slice(0, 3);
196
+ .slice(0, kind === 'week' ? 3 : 5);
164
197
 
165
198
  const qItems = (quality?.items ?? []).filter((it) => inWeek(it.mergedAt));
166
199
  const held = quality && qItems.length ? qualityTotals(qItems, quality.settings, t) : null;
@@ -183,10 +216,11 @@ export function weeklyFacts({ start, events = [], spend = {}, value = null, qual
183
216
  return {
184
217
  start: dayKey(start),
185
218
  end: dayKey(end - DAY),
186
- label: `${dayLabel(start)} to ${dayLabel(end - DAY)}, ${new Date(end - DAY).getFullYear()}`,
219
+ kind,
220
+ label: label ?? `${dayLabel(start)} to ${dayLabel(end - DAY)}, ${new Date(end - DAY).getFullYear()}`,
187
221
  complete: t >= end,
188
- row: weekRow(start, events, spend),
189
- prev: weekRow(start - 7 * DAY, events, spend),
222
+ row: countRow(start, end, events),
223
+ prev: countRow(prevStart, start, events),
190
224
  merged,
191
225
  finished,
192
226
  bugs: of('bug_fixed'),
@@ -195,7 +229,7 @@ export function weeklyFacts({ start, events = [], spend = {}, value = null, qual
195
229
  technical,
196
230
  size,
197
231
  quality: held,
198
- problems: qItems.filter((it) => it.after?.reverted || it.after?.fixes?.length).map((it) => ({ title: hidden.has(it.agentId) ? PRIVATE : clip(it.title), link: hidden.has(it.agentId) ? null : it.url, what: it.after?.reverted ? 'reverted' : 'fixed afterwards' })),
232
+ problems: qItems.filter((it) => it.incidents?.length || it.after?.reverted || it.after?.fixes?.length).map((it) => ({ title: hidden.has(it.agentId) ? PRIVATE : clip(it.title), link: hidden.has(it.agentId) ? null : it.url, what: it.incidents?.length ? `caused ${it.incidents.length === 1 ? 'an incident' : `${it.incidents.length} incidents`} in production` : it.after?.reverted ? 'reverted' : 'fixed afterwards' })),
199
233
  blocked: open.filter((o) => o.state === 'blocked'),
200
234
  open: open.filter((o) => o.state !== 'blocked'),
201
235
  keptPrivate: [...merged, ...finished, ...open].filter((e) => e.private).length,
@@ -223,9 +257,10 @@ const byProject = (list, each) => {
223
257
  /** The summary as Markdown: the week in a line, achievements, numbers, quality, what is next, and what is in the way. */
224
258
  export function weeklyMarkdown(f, { who = '' } = {}) {
225
259
  const r = f.row;
226
- const out = [`# Weekly summary: ${f.label}`, '', `${who ? `${who} · ` : ''}${f.complete ? 'the week as it ended' : 'the week so far'}`, ''];
260
+ const word = f.kind ?? 'week';
261
+ const out = [`# ${KINDS[word]} summary: ${f.label}`, '', `${who ? `${who} · ` : ''}${f.complete ? `the ${word} as it ended` : `the ${word} so far`}`, ''];
227
262
  const done = f.merged.length + f.finished.length;
228
- if (!done && !f.bugs.length && !r.prs_opened && !f.open.length && !f.blocked.length) return [...out, 'Nothing was recorded this week.'].join('\n');
263
+ if (!done && !f.bugs.length && !r.prs_opened && !f.open.length && !f.blocked.length) return [...out, `Nothing was recorded this ${word}.`].join('\n');
229
264
 
230
265
  // One line a manager can repeat.
231
266
  const parts = [];
@@ -233,7 +268,7 @@ export function weeklyMarkdown(f, { who = '' } = {}) {
233
268
  if (f.finished.length) parts.push(`${plural(f.finished.length, 'more task')} finished`);
234
269
  if (r.bugs_fixed) parts.push(`${plural(r.bugs_fixed, 'bug')} fixed`);
235
270
  if (f.size) parts.push(`about ${f.size.hours} hours of engineering work delivered (an estimate)`);
236
- out.push('## The week in one line', '', parts.length ? `${parts.join('; ')}.` : 'Work is in progress; nothing was delivered yet.', '');
271
+ out.push(`## The ${word} in one line`, '', parts.length ? `${parts.join('; ')}.` : 'Work is in progress; nothing was delivered yet.', '');
237
272
 
238
273
  if (f.highlights.length) out.push('## Highlights', '', ...f.highlights.map((e) => `- **${e.title}** (${e.project})${e.summary ? `: ${e.summary}` : ''}${e.tech?.how ? ` ${e.tech.how}` : ''}`), '');
239
274
 
@@ -247,7 +282,7 @@ export function weeklyMarkdown(f, { who = '' } = {}) {
247
282
 
248
283
  const p = f.prev;
249
284
  const num = (label, a, b) => `| ${label} | ${a === '' || a == null ? '—' : a} | ${b === '' || b == null ? '—' : b} |`;
250
- out.push('## Numbers', '', '| | This week | Week before |', '| --- | --- | --- |');
285
+ out.push('## Numbers', '', `| | This ${word} | The ${word} before |`, '| --- | --- | --- |');
251
286
  out.push(num('Pull requests merged', r.prs_merged, p.prs_merged), num('Pull requests opened', r.prs_opened, p.prs_opened), num('Bugs fixed', r.bugs_fixed, p.bugs_fixed), num('Issues filed', r.issues_filed, p.issues_filed), num('Tasks finished', r.agents_finished, p.agents_finished), num('Hours from opened to merged (median)', r.median_hours_to_merge, p.median_hours_to_merge), '');
252
287
  if (f.size) out.push(`Estimated size: about ${f.size.hours} hours of engineering work for ${f.size.estimated} of the ${plural(f.size.pieces, 'piece')} listed. An estimate of what a person would have needed, not a measurement.`, '');
253
288
 
@@ -289,24 +324,24 @@ export class Weekly {
289
324
  clearInterval(this.timer);
290
325
  }
291
326
 
292
- fileFor(start) {
293
- return path.join(this.dir, `weekly-${dayKey(start)}.md`);
327
+ fileFor(p) {
328
+ return path.join(this.dir, `${KINDS[p.kind].toLowerCase()}-${String(p.key).replace(/[^\w-]+/g, '-')}.md`);
294
329
  }
295
330
 
296
- async report({ current = false, t = Date.now() } = {}) {
331
+ /** A week's, a month's or a quarter's summary: the one just ended, or the current one so far. */
332
+ async report({ kind = 'week', current = false, t = Date.now() } = {}) {
297
333
  await this.worklog.record(t).catch(() => {});
298
- const start = weekOf(t, { current });
334
+ const p = periodOf(kind, t, { current });
299
335
  const facts = weeklyFacts({
300
- start,
336
+ ...p,
301
337
  events: this.worklog.state.events,
302
- spend: this.store.data.spend?.days ?? {},
303
338
  value: this.value ? { items: Object.values(this.value.state.items), settings: this.value.settings } : null,
304
339
  quality: this.quality ? { items: Object.values(this.quality.state.items), settings: this.quality.settings } : null,
305
340
  agents: this.store.list().map((agent) => ({ agent, view: this.manager.view(agent) })),
306
341
  t,
307
342
  });
308
- const file = this.fileFor(start);
309
- return { week: { start: facts.start, end: facts.end, label: facts.label, complete: facts.complete }, facts, markdown: weeklyMarkdown(facts, { who: (await this.who) ?? '' }), file, saved: fs.existsSync(file) };
343
+ const file = this.fileFor(p);
344
+ return { week: { kind, start: facts.start, end: facts.end, label: facts.label, complete: facts.complete }, facts, markdown: weeklyMarkdown(facts, { who: (await this.who) ?? '' }), file, saved: fs.existsSync(file) };
310
345
  }
311
346
 
312
347
  /** Write the summary to its file (again: replaced). Nothing is sent. */
@@ -317,15 +352,20 @@ export class Weekly {
317
352
  return { ...r, saved: true };
318
353
  }
319
354
 
320
- /** Once a week is over, its summary is written as a draft file, once. */
355
+ /** Once a week, a month or a quarter is over, its summary is written as a draft file, once. */
321
356
  async rollOver(t = Date.now()) {
322
357
  if (this.config.weekly?.auto === false) return null;
323
- const start = weekOf(t);
324
358
  const st = (this.store.data.weekly ??= {});
325
- if (st.drafted === dayKey(start) || fs.existsSync(this.fileFor(start))) return null;
326
- const r = await this.save({ t });
327
- st.drafted = dayKey(start);
328
- this.store.save();
329
- return r;
359
+ st.draftedBy ??= {};
360
+ let first = null;
361
+ for (const kind of Object.keys(KINDS)) {
362
+ const p = periodOf(kind, t);
363
+ if (st.draftedBy[kind] === p.key || fs.existsSync(this.fileFor(p))) continue;
364
+ const r = await this.save({ kind, t });
365
+ st.draftedBy[kind] = p.key;
366
+ first ??= r;
367
+ }
368
+ if (first) this.store.save();
369
+ return first;
330
370
  }
331
371
  }