dsh-hive-runner 0.6.7 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Anomaly feed and digest for the queen.
3
+ *
4
+ * The supervisor and the round runner emit small, normalized supervision events
5
+ * (a card failed, a worker timed out, heartbeat stalled, a repository was
6
+ * auto-paused). They are coalesced per (kind, repo, card) so a repeating
7
+ * condition becomes ONE entry with a count instead of a flood, and a compact
8
+ * digest is delivered to the registered queen Session.
9
+ *
10
+ * When no live queen Session exists (or delivery fails) the entries stay
11
+ * `pending` and are exposed through `hive_anomalies` and the supervisor status,
12
+ * so the next patrol — or the next time the panel opens the queen — processes
13
+ * them. The feed never throws into the scheduling path.
14
+ *
15
+ * @module dsh-hive-runner/anomalies
16
+ */
17
+
18
+ /** Stable anomaly kinds. The wire strings are part of the tool/status contract. */
19
+ export const ANOMALY_KINDS = Object.freeze({
20
+ /** A card worker finished with a failed verdict (acceptance, no commit, stop reason). */
21
+ CARD_FAILED: 'card-failed',
22
+ /** A card hit the hard per-card wall-clock timeout and was aborted. */
23
+ CARD_TIMEOUT: 'card-timeout',
24
+ /** A running worker produced no new commit for heartbeatWarnMs. */
25
+ HEARTBEAT_WARN: 'heartbeat-warn',
26
+ /** A worker activation ended without a verdict (aborted/cancelled/disappeared). */
27
+ WORKER_ABORTED: 'worker-aborted',
28
+ /** A whole round threw for a non-deferrable reason. */
29
+ ROUND_FAILED: 'round-failed',
30
+ /** The repository was auto-paused after maxConsecutiveFailures. */
31
+ AUTO_PAUSED: 'auto-paused',
32
+ /** The environment is missing something (hook, CLIs); the round is deferred. */
33
+ ENVIRONMENT: 'environment-error',
34
+ /** A done card has no arch_review event; the queen must review it. */
35
+ ARCH_REVIEW_MISSING: 'arch-review-missing',
36
+ /** A card the queen intervened on repeatedly needs a human decision. */
37
+ ESCALATION: 'queen-escalation',
38
+ });
39
+
40
+ const SEVERITY = Object.freeze({
41
+ [ANOMALY_KINDS.CARD_FAILED]: 'warn',
42
+ [ANOMALY_KINDS.CARD_TIMEOUT]: 'error',
43
+ [ANOMALY_KINDS.HEARTBEAT_WARN]: 'warn',
44
+ [ANOMALY_KINDS.WORKER_ABORTED]: 'warn',
45
+ [ANOMALY_KINDS.ROUND_FAILED]: 'error',
46
+ [ANOMALY_KINDS.AUTO_PAUSED]: 'error',
47
+ [ANOMALY_KINDS.ENVIRONMENT]: 'warn',
48
+ [ANOMALY_KINDS.ARCH_REVIEW_MISSING]: 'warn',
49
+ [ANOMALY_KINDS.ESCALATION]: 'error',
50
+ });
51
+
52
+ /** Default coalescing window: the same condition inside it updates one entry. */
53
+ export const DEFAULT_COALESCE_MS = 10 * 60_000;
54
+ /** Default number of undelivered entries kept. */
55
+ export const DEFAULT_MAX_ITEMS = 50;
56
+
57
+ function text(value, max) {
58
+ const normalized = String(value ?? '').replace(/\s+/g, ' ').trim();
59
+ return normalized.length <= max ? normalized : normalized.slice(0, Math.max(0, max - 1)) + '…';
60
+ }
61
+
62
+ /**
63
+ * Build the pending-entry store.
64
+ * @param {{ now?: () => number, max?: number, coalesceMs?: number }} [options]
65
+ * @returns {{
66
+ * push: (event: object) => object|null,
67
+ * list: (options?: { pendingOnly?: boolean, limit?: number }) => object[],
68
+ * pending: () => object[],
69
+ * markDelivered: (ids: string[], at?: number) => number,
70
+ * clear: () => void,
71
+ * size: () => number,
72
+ * pendingCount: () => number,
73
+ * }}
74
+ */
75
+ export function createAnomalyFeed(options = {}) {
76
+ const now = typeof options.now === 'function' ? options.now : () => Date.now();
77
+ const max = Number.isInteger(options.max) && options.max > 0 ? options.max : DEFAULT_MAX_ITEMS;
78
+ const coalesceMs = Number.isFinite(options.coalesceMs) && options.coalesceMs >= 0
79
+ ? options.coalesceMs
80
+ : DEFAULT_COALESCE_MS;
81
+ /** @type {object[]} oldest first */
82
+ const entries = [];
83
+ let sequence = 0;
84
+
85
+ /** Normalize one pushed event; unknown/malformed kinds are ignored, never thrown. */
86
+ function normalize(event) {
87
+ if (event === null || typeof event !== 'object') return null;
88
+ const kind = typeof event.kind === 'string' ? event.kind.trim() : '';
89
+ if (kind === '') return null;
90
+ const repo = typeof event.repo === 'string' ? event.repo : '';
91
+ const cardId = typeof event.cardId === 'string' && event.cardId !== '' ? event.cardId : null;
92
+ const role = typeof event.role === 'string' && event.role !== '' ? event.role : null;
93
+ const summary = text(event.summary ?? event.detail ?? kind, 300);
94
+ const detail = text(event.detail ?? '', 600);
95
+ return { kind, repo, cardId, role, summary, detail, severity: SEVERITY[kind] ?? 'warn' };
96
+ }
97
+
98
+ function push(event) {
99
+ const input = normalize(event);
100
+ if (input === null) return null;
101
+ const at = Number.isFinite(event.at) ? event.at : now();
102
+ const existing = entries.find((entry) => entry.kind === input.kind
103
+ && entry.repo === input.repo
104
+ && entry.cardId === input.cardId
105
+ && at - entry.lastAt <= coalesceMs);
106
+ if (existing !== undefined) {
107
+ existing.count += 1;
108
+ existing.lastAt = at;
109
+ if (input.detail !== '') existing.detail = input.detail;
110
+ if (input.summary !== '') existing.summary = input.summary;
111
+ return existing;
112
+ }
113
+ const entry = {
114
+ id: 'anomaly-' + String(++sequence),
115
+ kind: input.kind,
116
+ severity: input.severity,
117
+ repo: input.repo,
118
+ cardId: input.cardId,
119
+ role: input.role,
120
+ summary: input.summary,
121
+ detail: input.detail,
122
+ count: 1,
123
+ at,
124
+ lastAt: at,
125
+ deliveredAt: null,
126
+ };
127
+ entries.push(entry);
128
+ while (entries.length > max) entries.shift();
129
+ return entry;
130
+ }
131
+
132
+ function list(listOptions = {}) {
133
+ const pendingOnly = listOptions.pendingOnly === true;
134
+ const limit = Number.isInteger(listOptions.limit) && listOptions.limit > 0 ? listOptions.limit : max;
135
+ const selected = pendingOnly ? entries.filter((entry) => entry.deliveredAt === null) : entries;
136
+ return selected.slice(-limit).reverse().map((entry) => ({ ...entry }));
137
+ }
138
+
139
+ function pending() {
140
+ return entries.filter((entry) => entry.deliveredAt === null).map((entry) => ({ ...entry }));
141
+ }
142
+
143
+ function markDelivered(ids, at = now()) {
144
+ const wanted = new Set(Array.isArray(ids) ? ids : []);
145
+ let changed = 0;
146
+ for (const entry of entries) {
147
+ if (wanted.has(entry.id) && entry.deliveredAt === null) {
148
+ entry.deliveredAt = at;
149
+ changed += 1;
150
+ }
151
+ }
152
+ return changed;
153
+ }
154
+
155
+ return {
156
+ push,
157
+ list,
158
+ pending,
159
+ markDelivered,
160
+ clear() {
161
+ entries.length = 0;
162
+ },
163
+ size() {
164
+ return entries.length;
165
+ },
166
+ pendingCount() {
167
+ return entries.reduce((count, entry) => count + (entry.deliveredAt === null ? 1 : 0), 0);
168
+ },
169
+ };
170
+ }
171
+
172
+ /** One-line label for an entry, used by the digest and by `hive_anomalies`. */
173
+ export function labelOf(entry) {
174
+ if (entry === null || typeof entry !== 'object') return '';
175
+ const parts = [String(entry.kind ?? 'anomaly')];
176
+ if (typeof entry.cardId === 'string') parts.push('card=' + entry.cardId);
177
+ if (typeof entry.role === 'string') parts.push('role=' + entry.role);
178
+ return parts.join(' ');
179
+ }
180
+
181
+ /**
182
+ * Render the compact digest injected into the queen Session.
183
+ *
184
+ * Bounded on purpose: the queen gets the facts it needs to decide, not the
185
+ * whole run log (the run records stay on disk and `hive_tasks show` reaches
186
+ * them). One digest per delivery; repeated conditions carry their count.
187
+ *
188
+ * @param {object[]} items pending anomaly entries (oldest first)
189
+ * @param {{ max?: number, now?: () => number }} [options]
190
+ * @returns {string}
191
+ */
192
+ export function renderDigest(items, options = {}) {
193
+ const list = Array.isArray(items) ? items : [];
194
+ if (list.length === 0) return '';
195
+ const max = Number.isInteger(options.max) && options.max > 0 ? options.max : 10;
196
+ const total = list.reduce((count, entry) => count + (Number.isInteger(entry.count) ? entry.count : 1), 0);
197
+ const lines = [
198
+ '[hive-runner] supervision digest — ' + String(list.length) + ' pending item(s), '
199
+ + String(total) + ' occurrence(s); act only on real problems.',
200
+ ];
201
+ const repos = [...new Set(list.map((entry) => entry.repo).filter((repo) => typeof repo === 'string' && repo !== ''))];
202
+ if (repos.length === 1) lines.push('repo: ' + repos[0]);
203
+ else if (repos.length > 1) lines.push('repos: ' + repos.join(', '));
204
+ for (const entry of list.slice(-max)) {
205
+ const tag = labelOf(entry);
206
+ const count = Number.isInteger(entry.count) && entry.count > 1 ? ' ×' + String(entry.count) : '';
207
+ const detail = typeof entry.detail === 'string' && entry.detail !== '' ? ': ' + entry.detail : '';
208
+ lines.push('- ' + tag + count + detail);
209
+ }
210
+ if (list.length > max) lines.push('- … and ' + String(list.length - max) + ' more (hive_anomalies lists all)');
211
+ lines.push('');
212
+ lines.push('Next: read the board and supervisor status, then decide — reopen/retry/split/remove a card, '
213
+ + 'pause or resume the repository, adjust role limits, add a fix card, or ask the human. '
214
+ + 'Do not edit code, do not commit, do not claim or done a card.');
215
+ return lines.join('\n');
216
+ }
package/lib/audit.js ADDED
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Architecture-review audit: a done card must carry an `arch_review` event.
3
+ *
4
+ * The queen reviews every accepted card (pass/reject) and records the decision with
5
+ * `hive_arch_review`. This audit is the mechanical half: the supervisor patrols, and
6
+ * a done card that stayed unreviewed past `archReviewGraceMs` becomes an
7
+ * `arch-review-missing` anomaly — logged as a warning and listed in the queen's
8
+ * pending digest. The grace window lets the queen review a card that just finished
9
+ * at the next patrol instead of flagging it the second it lands.
10
+ *
11
+ * @module dsh-hive-runner/audit
12
+ */
13
+ import { ANOMALY_KINDS } from './anomalies.js';
14
+ import {
15
+ ARCH_REVIEW_KIND,
16
+ appendEscalation,
17
+ escalatedCards,
18
+ INTERVENTION_ESCALATE_AFTER,
19
+ INTERVENTION_KIND,
20
+ interventionCounts,
21
+ readEvents,
22
+ } from './events.js';
23
+
24
+ /** A done card gets this long to be reviewed before it is flagged. */
25
+ export const DEFAULT_ARCH_REVIEW_GRACE_MS = 10 * 60_000;
26
+
27
+ /**
28
+ * Pure computation: done cards with no arch_review event, older than the grace.
29
+ * @param {{ tasks: object[], events: object[], now?: number, graceMs?: number }} input
30
+ * @returns {object[]} the unreviewed done cards
31
+ */
32
+ export function findMissingArchReviews({ tasks, events, now = Date.now(), graceMs = DEFAULT_ARCH_REVIEW_GRACE_MS } = {}) {
33
+ const list = Array.isArray(tasks) ? tasks : [];
34
+ const reviewed = new Set();
35
+ for (const event of Array.isArray(events) ? events : []) {
36
+ if (event !== null && typeof event === 'object' && event.kind === ARCH_REVIEW_KIND && typeof event.task === 'string') {
37
+ reviewed.add(event.task);
38
+ }
39
+ }
40
+ const missing = [];
41
+ for (const card of list) {
42
+ if (card === null || typeof card !== 'object' || card.state !== 'done') continue;
43
+ if (typeof card.id !== 'string' || reviewed.has(card.id)) continue;
44
+ const stamp = Date.parse(card.updatedAt ?? card.createdAt ?? '');
45
+ if (Number.isFinite(stamp) && now - stamp < graceMs) continue;
46
+ missing.push(card);
47
+ }
48
+ return missing;
49
+ }
50
+
51
+ /**
52
+ * Build the audit bound to the command layer and the anomaly feed.
53
+ * @param {{
54
+ * commands: { list: Function },
55
+ * feed: { push: Function },
56
+ * log?: (level: string, ...args: unknown[]) => void,
57
+ * graceMs?: number,
58
+ * now?: () => number,
59
+ * reviewLimit?: number,
60
+ * }} options
61
+ */
62
+ export function createArchReviewAudit(options = {}) {
63
+ const commands = options.commands;
64
+ if (commands === undefined || typeof commands.list !== 'function') {
65
+ throw new TypeError('createArchReviewAudit: commands.list is required');
66
+ }
67
+ const feed = options.feed;
68
+ if (feed === undefined || typeof feed.push !== 'function') {
69
+ throw new TypeError('createArchReviewAudit: an anomaly feed is required');
70
+ }
71
+ const log = typeof options.log === 'function' ? options.log : () => {};
72
+ const graceMs = Number.isFinite(options.graceMs) && options.graceMs >= 0
73
+ ? options.graceMs
74
+ : DEFAULT_ARCH_REVIEW_GRACE_MS;
75
+ const now = typeof options.now === 'function' ? options.now : () => Date.now();
76
+ const reviewLimit = Number.isInteger(options.reviewLimit) && options.reviewLimit > 0 ? options.reviewLimit : 500;
77
+
78
+ /**
79
+ * Audit one repository; returns the unreviewed done cards.
80
+ * @param {string} repo
81
+ * @param {{ signal?: AbortSignal, session?: object }} [callOptions]
82
+ */
83
+ async function audit(repo, callOptions = {}) {
84
+ const tasks = await commands.list(repo, {}, callOptions);
85
+ const events = readEvents(repo, { limit: reviewLimit });
86
+ const missing = findMissingArchReviews({ tasks, events, now: now(), graceMs });
87
+ for (const card of missing) {
88
+ feed.push({
89
+ kind: 'arch-review-missing',
90
+ repo,
91
+ cardId: card.id,
92
+ role: typeof card.role === 'string' ? card.role : null,
93
+ summary: 'done card has no arch_review event',
94
+ detail: 'card ' + card.id + ' is done but was never reviewed; run hive_arch_review or reopen it',
95
+ });
96
+ }
97
+ if (missing.length > 0) {
98
+ log('warn', 'arch review missing for ' + missing.map((card) => card.id).join(', ') + ' in ' + repo);
99
+ }
100
+ // Same-class escalation: a card the queen intervened on more than
101
+ // INTERVENTION_ESCALATE_AFTER times without progress needs a human.
102
+ const counts = interventionCounts(events);
103
+ const escalated = escalatedCards(events);
104
+ const byId = new Map(tasks.filter((card) => card !== null && typeof card === 'object' && typeof card.id === 'string')
105
+ .map((card) => [card.id, card]));
106
+ for (const [cardId, count] of counts) {
107
+ if (count <= INTERVENTION_ESCALATE_AFTER) continue;
108
+ const card = byId.get(cardId);
109
+ if (card === undefined || card.state === 'done') continue;
110
+ if (escalated.has(cardId)) continue;
111
+ const reason = 'queen intervened ' + count + ' times without progress; needs a human decision (state ' + String(card.state) + ')';
112
+ try {
113
+ appendEscalation(repo, { card: cardId, reason, interventions: count });
114
+ escalated.add(cardId);
115
+ } catch (error) {
116
+ log('warn', 'writing escalation for ' + cardId + ' failed: ' + (error instanceof Error ? error.message : String(error)));
117
+ }
118
+ feed.push({
119
+ kind: ANOMALY_KINDS.ESCALATION,
120
+ repo,
121
+ cardId,
122
+ role: typeof card.role === 'string' ? card.role : null,
123
+ summary: 'card needs a human decision',
124
+ detail: reason,
125
+ });
126
+ log('warn', 'escalated ' + cardId + ' in ' + repo + ': ' + reason);
127
+ }
128
+ return missing;
129
+ }
130
+
131
+ return { audit };
132
+ }
133
+
134
+ export default createArchReviewAudit;