ai-agentmanager 1.68.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
@@ -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'),
@@ -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
  }