ai-agentmanager 1.67.0 → 1.69.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/weekly.js CHANGED
@@ -1,9 +1,11 @@
1
1
  // Weekly summary: one page on a week's work and achievements, written for management. It is put
2
2
  // together from what is already recorded, with no model call:
3
3
  // the work record (worklog.js) - pull requests merged and opened, bugs fixed, issues filed
4
- // Value (value.js) - what each delivered piece is, and the hours and money estimated
4
+ // Value (value.js) - what each delivered piece is, and the engineering hours estimated
5
+ // the agents' own briefs - how each piece was done, how it was checked, the risks named
5
6
  // Quality (quality.js) - how the week's merged pull requests held up
6
7
  // the agents as they are now - what is in progress, and what is blocked
8
+ // It is a technical summary: what was built and how it was verified. No money amounts are shown.
7
9
  // Work that is kept private (private.js) is counted but not described: no title and no link.
8
10
  // It is a draft for you: shown, copied or saved as a file. Nothing is sent to anyone.
9
11
  import fs from 'node:fs';
@@ -12,8 +14,8 @@ import { paths } from './config.js';
12
14
  import { dayKey } from './budgets.js';
13
15
  import { keptPrivate } from './private.js';
14
16
  import { totals as qualityTotals } from './quality.js';
15
- import { itemValue, totals as valueTotals } from './value.js';
16
- import { weekRow, weekStart } from './worklog.js';
17
+ import { PERIODS, itemValue } from './value.js';
18
+ import { weekStart } from './worklog.js';
17
19
 
18
20
  const DAY = 86_400_000;
19
21
  const PRIVATE = '(kept private)';
@@ -22,18 +24,110 @@ const clip = (s, n = 140) => {
22
24
  return t.length > n ? `${t.slice(0, n - 1)}…` : t;
23
25
  };
24
26
  const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
25
- const money = (n) => (n == null ? '—' : `$${Math.round(n).toLocaleString('en-US')}`);
26
27
  const dayLabel = (t) => new Date(t).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
27
28
 
29
+ /** The first sentence or two of a text, cut to size: how a piece of work was done, from its brief's Solution. */
30
+ export function gist(text, max = 240) {
31
+ const t = String(text ?? '').replace(/```[\s\S]*?```/g, ' ').replace(/^\s*#.*$/gm, ' ').replace(/^[>*\-\s]+/gm, '').replace(/\s+/g, ' ').trim();
32
+ if (!t) return '';
33
+ const two = /^(.+?[.!?])(\s+.+?[.!?])?(?=\s|$)/.exec(t);
34
+ return clip(two ? two[0] : t, max);
35
+ }
36
+
37
+ /** The part of the code a file is in: its first two folders ("src/engines"), or "(top level)". */
38
+ export const areaOf = (file) => {
39
+ const parts = String(file).split('/');
40
+ return parts.length > 1 ? parts.slice(0, Math.min(2, parts.length - 1)).join('/') : '(top level)';
41
+ };
42
+
43
+ /**
44
+ * The technical side of one piece of work, from the agent as it is now and from Quality's record
45
+ * of its merged pull request: how it was done, what it touched, and how it was checked.
46
+ */
47
+ export function techOf(agent, q = null) {
48
+ const b = agent?.brief ?? {};
49
+ const checks = b.checks ?? [];
50
+ const sc = agent?.docs?.scorecard?.data;
51
+ const br = agent?.breaks?.baseline?.ok ? agent.breaks.breaks ?? [] : null;
52
+ const n = (st) => br.filter((x) => x.status === st).length;
53
+ const risks = b.risks ?? [];
54
+ const files = q?.facts?.files ?? [];
55
+ const areas = {};
56
+ for (const f of files) areas[areaOf(f)] = (areas[areaOf(f)] ?? 0) + 1;
57
+ return {
58
+ how: gist(b.solution),
59
+ files: files.length || null,
60
+ lines: q?.facts?.lines ?? null,
61
+ areas: Object.entries(areas).sort((x, y) => y[1] - x[1]).slice(0, 3).map(([k]) => k),
62
+ testFiles: files.filter((f) => /(^|\/)(tests?|__tests__|spec|specs)\/|[._-](test|spec)\.[a-z]+$|_test\.go$/i.test(f)).length,
63
+ checksPassed: checks.filter((c) => c.state === 'passed').length,
64
+ checksFailed: checks.filter((c) => c.state === 'failed').length,
65
+ proof: agent?.proofDoc?.commands ?? 0,
66
+ breaks: br && n('caught') + n('missed') ? { caught: n('caught'), tried: n('caught') + n('missed') } : q?.said?.breaks ?? null,
67
+ score: Number.isFinite(sc?.overall) ? sc.overall : q?.said?.score ?? null,
68
+ risks: risks.length ? { named: risks.length, avoided: risks.filter((r) => r.state === 'avoided').length, happened: risks.filter((r) => r.state === 'happened').length } : null,
69
+ reviews: q?.facts?.reviews ?? null,
70
+ changesRequested: q?.facts?.changesRequested ?? null,
71
+ engine: agent?.engine ?? q?.said?.engine ?? null,
72
+ model: agent?.model ?? q?.said?.model ?? null,
73
+ };
74
+ }
75
+
76
+ /** How one piece was checked, in a line: "4 checks passed, 3 with recorded runs; tests tested: 5 of 6 breaks caught; scorecard 86". */
77
+ export function checkedLine(t) {
78
+ if (!t) return '';
79
+ const out = [];
80
+ if (t.checksPassed || t.checksFailed) out.push(`${plural(t.checksPassed, 'check')} passed${t.checksFailed ? `, ${t.checksFailed} failed` : ''}`);
81
+ if (t.proof) out.push(`${plural(t.proof, 'command')} recorded with ${t.proof === 1 ? 'its' : 'their'} output`);
82
+ if (t.breaks) out.push(`tests tested: ${t.breaks.caught} of ${plural(t.breaks.tried, 'break')} caught`);
83
+ if (t.score != null) out.push(`scorecard ${t.score}`);
84
+ if (t.risks) out.push(`${t.risks.avoided} of ${plural(t.risks.named, 'named risk')} avoided${t.risks.happened ? `, ${t.risks.happened} happened` : ''}`);
85
+ if (t.reviews) out.push(`${plural(t.reviews, 'review')}${t.changesRequested ? `, ${plural(t.changesRequested, 'change request')}` : ''}`);
86
+ return out.join('; ');
87
+ }
88
+
28
89
  /** The Monday a week's summary starts on: the week before `t`, or the one `t` is in. */
29
90
  export const weekOf = (t = Date.now(), { current = false } = {}) => (current ? weekStart(t) : weekStart(weekStart(t) - DAY));
30
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
+
31
126
  /**
32
127
  * A week's facts. `events`: the work record's rows; `spend`: the spend ledger's days; `value` and
33
128
  * `quality`: { items, settings } of those modules; `agents`: [{ agent, view }] as they are now.
34
129
  */
35
- export function weeklyFacts({ start, events = [], spend = {}, value = null, quality = null, agents = [], t = Date.now() }) {
36
- 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() }) {
37
131
  const inWeek = (iso) => Date.parse(iso) >= start && Date.parse(iso) < end;
38
132
  const hidden = new Set(agents.filter((x) => keptPrivate(x.agent)).map((x) => x.agent.id));
39
133
  const mine = events.filter((e) => inWeek(e.date));
@@ -46,18 +140,60 @@ export function weeklyFacts({ start, events = [], spend = {}, value = null, qual
46
140
 
47
141
  // What each delivered piece is, in Value's words, with its estimate.
48
142
  const vItems = (value?.items ?? []).filter((it) => !it.excluded && inWeek(it.deliveredAt));
49
- const worth = value ? valueTotals(vItems, value.settings) : null;
50
143
  const said = new Map(vItems.map((it) => [it.agentId, itemValue(it, value.settings)]));
51
144
  for (const e of [...merged, ...finished]) {
52
145
  const v = e.agentId && said.get(e.agentId);
53
146
  if (v?.summary) e.summary = clip(v.summary, 200);
54
147
  if (v?.humanHours != null) e.hours = v.humanHours;
55
148
  }
149
+ // The technical side of each: how it was done, what it touched, how it was checked.
150
+ const byId = new Map(agents.map((x) => [x.agent.id, x.agent]));
151
+ const qBy = new Map((quality?.items ?? []).map((it) => [it.url, it]));
152
+ for (const e of [...merged, ...finished]) {
153
+ if (e.private || !e.agentId) continue;
154
+ const q = (e.link && qBy.get(e.link)) || null;
155
+ if (byId.get(e.agentId) || q) e.tech = techOf(byId.get(e.agentId), q);
156
+ }
157
+ const techs = [...merged, ...finished].map((e) => e.tech).filter(Boolean);
158
+ const sum = (f) => techs.reduce((n, t) => n + (f(t) || 0), 0);
159
+ const areaCount = {};
160
+ for (const e of merged) for (const f of (e.link && qBy.get(e.link)?.facts?.files) || []) if (!e.private) areaCount[areaOf(f)] = (areaCount[areaOf(f)] ?? 0) + 1;
161
+ const scores = techs.map((t) => t.score).filter(Number.isFinite);
162
+ const tested = techs.filter((t) => t.breaks);
163
+ const models = {};
164
+ for (const t of techs) if (t.engine) models[`${t.engine}${t.model ? ` · ${t.model}` : ''}`] = (models[`${t.engine}${t.model ? ` · ${t.model}` : ''}`] ?? 0) + 1;
165
+ const technical = techs.length
166
+ ? {
167
+ pieces: techs.length,
168
+ files: sum((t) => t.files),
169
+ lines: sum((t) => t.lines),
170
+ testFiles: sum((t) => t.testFiles),
171
+ areas: Object.entries(areaCount).sort((x, y) => y[1] - x[1]).slice(0, 6).map(([area, files]) => ({ area, files })),
172
+ checksPassed: sum((t) => t.checksPassed),
173
+ checksFailed: sum((t) => t.checksFailed),
174
+ proof: sum((t) => t.proof),
175
+ tested: tested.length,
176
+ breaksCaught: tested.reduce((n, t) => n + t.breaks.caught, 0),
177
+ breaksTried: tested.reduce((n, t) => n + t.breaks.tried, 0),
178
+ score: scores.length ? Math.round(scores.reduce((a, b) => a + b, 0) / scores.length) : null,
179
+ scored: scores.length,
180
+ risksNamed: sum((t) => t.risks?.named),
181
+ risksAvoided: sum((t) => t.risks?.avoided),
182
+ risksHappened: sum((t) => t.risks?.happened),
183
+ changesRequested: sum((t) => t.changesRequested),
184
+ models: Object.entries(models).sort((x, y) => y[1] - x[1]).map(([name, n]) => ({ name, n })),
185
+ }
186
+ : null;
187
+
188
+ // The size of the week, over the pieces listed: the hours a person would have needed, as Value estimates them.
189
+ const listed = [...merged, ...finished].filter((e) => !e.private);
190
+ const sized = listed.filter((e) => e.hours != null);
191
+ const size = sized.length ? { hours: Math.round(sized.reduce((n, e) => n + e.hours, 0) * 10) / 10, estimated: sized.length, pieces: listed.length } : null;
56
192
  // The three worth the most, as the week's highlights.
57
193
  const highlights = [...merged, ...finished]
58
194
  .filter((e) => !e.private && e.hours != null)
59
195
  .sort((a, b) => b.hours - a.hours)
60
- .slice(0, 3);
196
+ .slice(0, kind === 'week' ? 3 : 5);
61
197
 
62
198
  const qItems = (quality?.items ?? []).filter((it) => inWeek(it.mergedAt));
63
199
  const held = quality && qItems.length ? qualityTotals(qItems, quality.settings, t) : null;
@@ -80,16 +216,18 @@ export function weeklyFacts({ start, events = [], spend = {}, value = null, qual
80
216
  return {
81
217
  start: dayKey(start),
82
218
  end: dayKey(end - DAY),
83
- 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()}`,
84
221
  complete: t >= end,
85
- row: weekRow(start, events, spend),
86
- prev: weekRow(start - 7 * DAY, events, spend),
222
+ row: countRow(start, end, events),
223
+ prev: countRow(prevStart, start, events),
87
224
  merged,
88
225
  finished,
89
226
  bugs: of('bug_fixed'),
90
227
  filed: of('issue_filed'),
91
228
  highlights,
92
- worth,
229
+ technical,
230
+ size,
93
231
  quality: held,
94
232
  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' })),
95
233
  blocked: open.filter((o) => o.state === 'blocked'),
@@ -100,6 +238,14 @@ export function weeklyFacts({ start, events = [], spend = {}, value = null, qual
100
238
  }
101
239
 
102
240
  const item = (e) => `${e.link ? `[${e.title}](${e.link})` : e.title}${e.bugs ? ` (${e.bugs})` : ''}${e.summary ? `: ${e.summary}` : ''}`;
241
+ /** A delivered piece with its technical side under it: how it was done, what it touched, how it was checked. */
242
+ const piece = (e) => {
243
+ const t = e.tech;
244
+ if (!t) return item(e);
245
+ const touched = t.files ? `${plural(t.files, 'file')}${t.lines ? `, ${plural(t.lines, 'line')}` : ''}${t.areas.length ? ` in ${t.areas.join(', ')}` : ''}${t.testFiles ? `; ${plural(t.testFiles, 'test file')}` : ''}` : '';
246
+ const checked = checkedLine(t);
247
+ return [item(e), ...(t.how ? [` - How: ${t.how}`] : []), ...(touched ? [` - Changed: ${touched}`] : []), ...(checked ? [` - Checked: ${checked}`] : [])].join('\n');
248
+ };
103
249
  const byProject = (list, each) => {
104
250
  const out = [];
105
251
  for (const p of [...new Set(list.map((e) => e.project))]) {
@@ -111,34 +257,47 @@ const byProject = (list, each) => {
111
257
  /** The summary as Markdown: the week in a line, achievements, numbers, quality, what is next, and what is in the way. */
112
258
  export function weeklyMarkdown(f, { who = '' } = {}) {
113
259
  const r = f.row;
114
- 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`}`, ''];
115
262
  const done = f.merged.length + f.finished.length;
116
- 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');
117
264
 
118
265
  // One line a manager can repeat.
119
266
  const parts = [];
120
267
  if (r.prs_merged) parts.push(`${plural(r.prs_merged, 'pull request')} merged${f.projects.length > 1 ? ` across ${f.projects.length} projects` : f.projects.length === 1 ? ` in ${f.projects[0]}` : ''}`);
121
268
  if (f.finished.length) parts.push(`${plural(f.finished.length, 'more task')} finished`);
122
269
  if (r.bugs_fixed) parts.push(`${plural(r.bugs_fixed, 'bug')} fixed`);
123
- if (f.worth?.humanHours) parts.push(`about ${f.worth.humanHours} hours of engineering delivered${f.worth.yourHours ? ` for ${f.worth.yourHours} of mine` : ''}`);
124
- out.push('## The week in one line', '', parts.length ? `${parts.join('; ')}.` : 'Work is in progress; nothing was delivered yet.', '');
270
+ if (f.size) parts.push(`about ${f.size.hours} hours of engineering work delivered (an estimate)`);
271
+ out.push(`## The ${word} in one line`, '', parts.length ? `${parts.join('; ')}.` : 'Work is in progress; nothing was delivered yet.', '');
125
272
 
126
- if (f.highlights.length) out.push('## Highlights', '', ...f.highlights.map((e) => `- **${e.title}** (${e.project})${e.summary ? `: ${e.summary}` : ''}`), '');
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}` : ''}`), '');
127
274
 
128
275
  if (done) {
129
276
  out.push('## Achievements', '');
130
- if (f.merged.length) out.push('### Merged', '', ...byProject(f.merged, item));
131
- if (f.finished.length) out.push('### Finished, not merged yet or with no pull request', '', ...byProject(f.finished, item));
277
+ if (f.merged.length) out.push('### Merged', '', ...byProject(f.merged, piece));
278
+ if (f.finished.length) out.push('### Finished, not merged yet or with no pull request', '', ...byProject(f.finished, piece));
132
279
  }
133
280
  if (f.bugs.length) out.push('### Bugs fixed', '', ...f.bugs.map((e) => `- ${item(e)}`), '');
134
281
  if (f.filed.length) out.push('### Issues filed', '', ...f.filed.map((e) => `- ${item(e)}`), '');
135
282
 
136
283
  const p = f.prev;
137
284
  const num = (label, a, b) => `| ${label} | ${a === '' || a == null ? '—' : a} | ${b === '' || b == null ? '—' : b} |`;
138
- out.push('## Numbers', '', '| | This week | Week before |', '| --- | --- | --- |');
139
- 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), num('AI cost', money(r.cost_usd), money(p.cost_usd)), '');
140
- if (f.worth?.estimated) {
141
- out.push(`Estimated value: about ${f.worth.humanHours} engineering hours (${money(f.worth.laborUsd)})${f.worth.savingsUsd ? `, ${money(f.worth.savingsUsd)} saved beyond that` : ''}${f.worth.roi ? `; ${f.worth.roi} times the AI cost` : ''}. These are estimates for ${f.worth.estimated} of ${plural(f.worth.items, 'delivered piece')}, not measurements.`, '');
285
+ out.push('## Numbers', '', `| | This ${word} | The ${word} before |`, '| --- | --- | --- |');
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), '');
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.`, '');
288
+
289
+ const k = f.technical;
290
+ if (k) {
291
+ out.push('## Technical summary', '');
292
+ if (k.files) out.push(`- **Code:** ${plural(k.files, 'file')} and ${plural(k.lines, 'line')} changed in merged pull requests${k.testFiles ? `, ${plural(k.testFiles, 'test file')} among them` : ''}.`);
293
+ if (k.areas.length) out.push(`- **Areas touched:** ${k.areas.map((a) => `${a.area} (${a.files})`).join(', ')}.`);
294
+ if (k.checksPassed || k.checksFailed) out.push(`- **Verification:** ${plural(k.checksPassed, 'check')} passed${k.checksFailed ? `, ${k.checksFailed} failed` : ''} across ${plural(k.pieces, 'piece')} of work${k.proof ? `; ${plural(k.proof, 'command')} recorded with ${k.proof === 1 ? 'its' : 'their'} output, so ${k.proof === 1 ? 'it' : 'they'} can be run again` : ''}.`);
295
+ if (k.tested) out.push(`- **Tests tested:** on ${plural(k.tested, 'piece')}, ${k.breaksCaught} of ${plural(k.breaksTried, 'deliberate break')} in the changed code ${k.breaksCaught === 1 ? 'was' : 'were'} caught by the tests.`);
296
+ if (k.scored) out.push(`- **Review scorecard:** ${k.score} of 100 on average over ${plural(k.scored, 'piece')}.`);
297
+ if (k.risksNamed) out.push(`- **Risks named before starting:** ${k.risksNamed}; ${k.risksAvoided} avoided${k.risksHappened ? `, ${k.risksHappened} happened` : ''}${k.risksNamed - k.risksAvoided - k.risksHappened ? `, ${k.risksNamed - k.risksAvoided - k.risksHappened} not checked` : ''}.`);
298
+ if (k.changesRequested) out.push(`- **Review:** changes were requested ${plural(k.changesRequested, 'time')} before merging.`);
299
+ if (k.models.length) out.push(`- **Done with:** ${k.models.map((m) => `${m.name} (${m.n})`).join(', ')}.`);
300
+ out.push('');
142
301
  }
143
302
 
144
303
  if (f.quality) {
@@ -165,24 +324,24 @@ export class Weekly {
165
324
  clearInterval(this.timer);
166
325
  }
167
326
 
168
- fileFor(start) {
169
- 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`);
170
329
  }
171
330
 
172
- 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() } = {}) {
173
333
  await this.worklog.record(t).catch(() => {});
174
- const start = weekOf(t, { current });
334
+ const p = periodOf(kind, t, { current });
175
335
  const facts = weeklyFacts({
176
- start,
336
+ ...p,
177
337
  events: this.worklog.state.events,
178
- spend: this.store.data.spend?.days ?? {},
179
338
  value: this.value ? { items: Object.values(this.value.state.items), settings: this.value.settings } : null,
180
339
  quality: this.quality ? { items: Object.values(this.quality.state.items), settings: this.quality.settings } : null,
181
340
  agents: this.store.list().map((agent) => ({ agent, view: this.manager.view(agent) })),
182
341
  t,
183
342
  });
184
- const file = this.fileFor(start);
185
- 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) };
186
345
  }
187
346
 
188
347
  /** Write the summary to its file (again: replaced). Nothing is sent. */
@@ -193,15 +352,20 @@ export class Weekly {
193
352
  return { ...r, saved: true };
194
353
  }
195
354
 
196
- /** 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. */
197
356
  async rollOver(t = Date.now()) {
198
357
  if (this.config.weekly?.auto === false) return null;
199
- const start = weekOf(t);
200
358
  const st = (this.store.data.weekly ??= {});
201
- if (st.drafted === dayKey(start) || fs.existsSync(this.fileFor(start))) return null;
202
- const r = await this.save({ t });
203
- st.drafted = dayKey(start);
204
- this.store.save();
205
- 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;
206
370
  }
207
371
  }