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.
package/lib/commands.js CHANGED
@@ -32,10 +32,13 @@ export const SHA_RE = /^[0-9a-f]{7,64}$/;
32
32
  export const BIN_PACKAGES = Object.freeze({
33
33
  tasks: Object.freeze(['hive-tasks']),
34
34
  hive: Object.freeze(['hive-consensus']),
35
+ // `hive roles ...` belongs to the umbrella router (@d86e/hive); the
36
+ // consensus package only owns board/mode/lesson/recall.
37
+ roles: Object.freeze(['@d86e/hive']),
35
38
  });
36
39
 
37
40
  /** The executable name inside each published package. */
38
- const BIN_EXECUTABLES = Object.freeze({ tasks: 'hive-tasks', hive: 'hive' });
41
+ const BIN_EXECUTABLES = Object.freeze({ tasks: 'hive-tasks', hive: 'hive', roles: 'hive' });
39
42
 
40
43
  /** Which Hive bin a verb uses; null verbs (git, the card's own acceptance) cap no fallback. */
41
44
  const VERB_BINS = Object.freeze({
@@ -44,16 +47,42 @@ const VERB_BINS = Object.freeze({
44
47
  show: 'tasks',
45
48
  done: 'tasks',
46
49
  fail: 'tasks',
50
+ list: 'tasks',
51
+ add: 'tasks',
52
+ reopen: 'tasks',
53
+ retry: 'tasks',
54
+ remove: 'tasks',
47
55
  board: 'hive',
48
56
  guard: 'hive',
49
57
  release: 'hive',
50
58
  renew: 'hive',
51
59
  mode: 'hive',
52
60
  recall: 'hive',
61
+ lessonAdd: 'hive',
62
+ rolesList: 'roles',
63
+ rolesAdd: 'roles',
64
+ rolesRemove: 'roles',
53
65
  head: null,
54
66
  acceptance: null,
55
67
  });
56
68
 
69
+ /** Card states accepted by `hive-tasks list --state`. */
70
+ export const TASK_STATES = Object.freeze(['pending', 'claimed', 'done', 'failed']);
71
+ /** Role names accepted by `hive roles add` / `--role`. */
72
+ export const CARD_ROLE_RE = /^[a-z][a-z0-9-]{1,31}$/;
73
+ /** Adapters accepted by `hive roles add --adapter`. */
74
+ export const ROLE_ADAPTERS = Object.freeze(['dsh', 'claude', 'codex']);
75
+ /** Model ids accepted by `hive roles add --model`. */
76
+ export const MODEL_RE = /^[A-Za-z0-9._:-]{1,64}$/;
77
+ /** Lesson statuses accepted by `hive lesson add --status`. */
78
+ export const LESSON_STATUSES = Object.freeze(['hypothesis', 'confirmed', 'superseded']);
79
+ /** Maximum length of a free-text argument (title, goal, acceptance, lesson text). */
80
+ export const TEXT_MAX = 4000;
81
+ /** Maximum length of one scope / evidence token. */
82
+ export const TOKEN_MAX = 512;
83
+ /** Upper bound on repeated flags (scope/after/tag). */
84
+ const LIST_MAX = 64;
85
+
57
86
  /** POSIX single-quote one argv token. */
58
87
  export function quote(value) {
59
88
  return "'" + String(value).replaceAll("'", "'\\''") + "'";
@@ -72,6 +101,53 @@ function needMatch(re, value, name) {
72
101
  return value;
73
102
  }
74
103
 
104
+ /** One required free-text argument, trimmed and bounded; never empty, never NUL-containing. */
105
+ function textArg(value, name, max = TEXT_MAX) {
106
+ if (typeof value !== 'string') {
107
+ throw new HiveCommandError('hive/invalid-argument', name + ' must be a string');
108
+ }
109
+ if (value.includes('\u0000')) {
110
+ throw new HiveCommandError('hive/invalid-argument', name + ' must not contain NUL bytes');
111
+ }
112
+ const text = value.trim();
113
+ if (text === '') throw new HiveCommandError('hive/invalid-argument', name + ' must not be empty');
114
+ if (text.length > max) {
115
+ throw new HiveCommandError('hive/invalid-argument', name + ' must be at most ' + max + ' characters');
116
+ }
117
+ return text;
118
+ }
119
+
120
+ /** One optional free-text argument; undefined/null/empty -> null. */
121
+ function optionalText(value, name, max = TEXT_MAX) {
122
+ if (value === undefined || value === null || value === '') return null;
123
+ return textArg(value, name, max);
124
+ }
125
+
126
+ /** Repeated string flags (--scope/--after/--tag): trimmed, bounded, deduplicated. */
127
+ function listArg(value, name, { max = TOKEN_MAX, items = LIST_MAX } = {}) {
128
+ if (value === undefined || value === null) return [];
129
+ if (!Array.isArray(value)) {
130
+ throw new HiveCommandError('hive/invalid-argument', name + ' must be an array of strings');
131
+ }
132
+ if (value.length > items) {
133
+ throw new HiveCommandError('hive/invalid-argument', name + ' must have at most ' + items + ' entries');
134
+ }
135
+ const out = [];
136
+ for (const entry of value) {
137
+ const token = textArg(entry, name + ' entry', max);
138
+ if (!out.includes(token)) out.push(token);
139
+ }
140
+ return out;
141
+ }
142
+
143
+ /** One integer argument inside an inclusive range. */
144
+ function intArg(value, name, min, max) {
145
+ if (!Number.isInteger(value) || value < min || value > max) {
146
+ throw new HiveCommandError('hive/invalid-argument', name + ' must be an integer in ' + min + '..' + max);
147
+ }
148
+ return value;
149
+ }
150
+
75
151
  /** Non-empty, shell-quoted path / scope-key list for hive-consensus verbs. */
76
152
  function scopeArgs(paths, name) {
77
153
  if (!Array.isArray(paths) || paths.length === 0) {
@@ -94,6 +170,9 @@ function scopeArgs(paths, name) {
94
170
  export function buildCommand(verb, args = {}, bins = {}) {
95
171
  const tasks = bins.tasks ?? 'hive-tasks';
96
172
  const hive = bins.hive ?? 'hive';
173
+ // The umbrella router owns `hive roles`; fall back to the board bin so an
174
+ // operator who configured only one `hive` path still gets the right binary.
175
+ const roles = bins.roles ?? hive;
97
176
  const git = bins.git ?? 'git';
98
177
  switch (verb) {
99
178
  case 'ready': {
@@ -129,6 +208,60 @@ export function buildCommand(verb, args = {}, bins = {}) {
129
208
  const reason = args.reason === undefined || args.reason === null ? 'runner failure' : String(args.reason);
130
209
  return tasks + ' fail ' + quote(id) + ' --reason ' + quote(reason.slice(0, 1000));
131
210
  }
211
+ case 'list': {
212
+ const state = args.state === undefined || args.state === null
213
+ ? null
214
+ : needMatch(new RegExp('^(?:' + TASK_STATES.join('|') + ')$'), args.state, 'list.state');
215
+ const role = args.role === undefined || args.role === null ? null : needMatch(CARD_ROLE_RE, args.role, 'list.role');
216
+ return tasks + ' list --json'
217
+ + (state === null ? '' : ' --state ' + quote(state))
218
+ + (role === null ? '' : ' --role ' + quote(role));
219
+ }
220
+ case 'add': {
221
+ const title = textArg(args.title, 'add.title', 300);
222
+ const parts = [tasks, 'add', '--json', '--title', quote(title)];
223
+ const role = args.role === undefined || args.role === null || args.role === ''
224
+ ? null
225
+ : needMatch(CARD_ROLE_RE, args.role, 'add.role');
226
+ if (role !== null) parts.push('--role', quote(role));
227
+ for (const path of listArg(args.scope, 'add.scope')) parts.push('--scope', quote(path));
228
+ for (const dep of listArg(args.after, 'add.after', { max: 128 })) {
229
+ parts.push('--after', quote(needMatch(ID_RE, dep, 'add.after entry')));
230
+ }
231
+ if (args.priority !== undefined && args.priority !== null) {
232
+ parts.push('--priority', String(intArg(args.priority, 'add.priority', -1000, 1000)));
233
+ }
234
+ const goal = optionalText(args.goal, 'add.goal');
235
+ if (goal !== null) parts.push('--goal', quote(goal));
236
+ const acceptance = optionalText(args.acceptance, 'add.acceptance');
237
+ if (acceptance !== null) parts.push('--acceptance', quote(acceptance));
238
+ for (const tag of listArg(args.tags, 'add.tags', { max: 64 })) parts.push('--tag', quote(tag));
239
+ const reviewOf = args.reviewOf === undefined || args.reviewOf === null || args.reviewOf === ''
240
+ ? null
241
+ : needMatch(ID_RE, args.reviewOf, 'add.reviewOf');
242
+ if (reviewOf !== null) parts.push('--review-of', quote(reviewOf));
243
+ // A draft card is a note, not dispatchable work: hive-tasks excludes it
244
+ // from ready/next and it carries no acceptance requirement yet.
245
+ if (args.draft === true) parts.push('--draft');
246
+ return parts.join(' ');
247
+ }
248
+ case 'reopen': {
249
+ const id = needMatch(ID_RE, args.id, 'reopen.id');
250
+ const reason = args.reason === undefined || args.reason === null || args.reason === ''
251
+ ? null
252
+ : textArg(args.reason, 'reopen.reason', 1000);
253
+ return tasks + ' reopen ' + quote(id) + ' --json' + (reason === null ? '' : ' --reason ' + quote(reason));
254
+ }
255
+ case 'retry': {
256
+ const id = needMatch(ID_RE, args.id, 'retry.id');
257
+ return tasks + ' retry ' + quote(id) + ' --json';
258
+ }
259
+ case 'remove': {
260
+ const id = needMatch(ID_RE, args.id, 'remove.id');
261
+ // No --force: a claimed card must be released by its owner (or expire)
262
+ // before the queen may delete it; the CLI refuses instead of destroying work.
263
+ return tasks + ' rm ' + quote(id);
264
+ }
132
265
  case 'board':
133
266
  return hive + ' board --json';
134
267
  case 'guard': {
@@ -153,6 +286,50 @@ export function buildCommand(verb, args = {}, bins = {}) {
153
286
  }
154
287
  return hive + ' recall ' + quote(args.query.trim()) + ' --json';
155
288
  }
289
+ case 'lessonAdd': {
290
+ const text = textArg(args.text, 'lessonAdd.text');
291
+ const scope = args.scope === undefined || args.scope === null || args.scope === ''
292
+ ? null
293
+ : textArg(args.scope, 'lessonAdd.scope', TOKEN_MAX);
294
+ const evidence = args.evidence === undefined || args.evidence === null || args.evidence === ''
295
+ ? null
296
+ : textArg(args.evidence, 'lessonAdd.evidence', TOKEN_MAX);
297
+ const status = args.status === undefined || args.status === null || args.status === ''
298
+ ? null
299
+ : needMatch(new RegExp('^(?:' + LESSON_STATUSES.join('|') + ')$'), args.status, 'lessonAdd.status');
300
+ const parts = [hive, 'lesson', 'add'];
301
+ if (scope !== null) parts.push('--scope', quote(scope));
302
+ if (evidence !== null) parts.push('--evidence', quote(evidence));
303
+ if (status !== null) parts.push('--status', quote(status));
304
+ parts.push(quote(text));
305
+ return parts.join(' ');
306
+ }
307
+ case 'rolesList':
308
+ return roles + ' roles list --json';
309
+ case 'rolesAdd': {
310
+ const name = needMatch(CARD_ROLE_RE, args.name, 'rolesAdd.name');
311
+ const parts = [roles, 'roles', 'add', quote(name)];
312
+ const adapter = args.adapter === undefined || args.adapter === null || args.adapter === ''
313
+ ? null
314
+ : needMatch(new RegExp('^(?:' + ROLE_ADAPTERS.join('|') + ')$'), args.adapter, 'rolesAdd.adapter');
315
+ if (adapter !== null) parts.push('--adapter', quote(adapter));
316
+ const model = args.model === undefined || args.model === null || args.model === ''
317
+ ? null
318
+ : needMatch(MODEL_RE, args.model, 'rolesAdd.model');
319
+ if (model !== null) parts.push('--model', quote(model));
320
+ const prompt = args.prompt === undefined || args.prompt === null || args.prompt === ''
321
+ ? null
322
+ : textArg(args.prompt, 'rolesAdd.prompt', TOKEN_MAX);
323
+ if (prompt !== null) parts.push('--prompt', quote(prompt));
324
+ const description = optionalText(args.description, 'rolesAdd.description', 2000);
325
+ if (description !== null) parts.push('--description', quote(description));
326
+ if (args.force === true) parts.push('--force');
327
+ return parts.join(' ');
328
+ }
329
+ case 'rolesRemove': {
330
+ const name = needMatch(CARD_ROLE_RE, args.name, 'rolesRemove.name');
331
+ return roles + ' roles rm ' + quote(name);
332
+ }
156
333
  case 'head':
157
334
  return git + ' rev-parse HEAD';
158
335
  case 'acceptance': {
@@ -200,7 +377,7 @@ export function missingBinaryHint(verb, bins = {}) {
200
377
  if (key === undefined || key === null) return null;
201
378
  const configured = typeof bins[key] === 'string' && bins[key] !== '' ? bins[key] : BIN_EXECUTABLES[key];
202
379
  const packages = BIN_PACKAGES[key];
203
- const configKey = key === 'tasks' ? 'tasksBin' : 'hiveBin';
380
+ const configKey = key === 'tasks' ? 'tasksBin' : key === 'roles' ? 'rolesBin' : 'hiveBin';
204
381
  return '[hive-runner] ' + configured + ' was not found on the shell PATH and the npx fallback did not run it; '
205
382
  + 'install it with "npm i -g ' + packages.join(' ') + '" or set ' + configKey + '.';
206
383
  }
@@ -236,7 +413,12 @@ function failure(result, label) {
236
413
  */
237
414
  export function createCommands({ ctx, config }) {
238
415
  const run = createShellRunner({ ctx, config });
239
- const bins = { tasks: config.tasksBin, hive: config.hiveBin, git: config.gitBin };
416
+ const bins = {
417
+ tasks: config.tasksBin,
418
+ hive: config.hiveBin,
419
+ roles: config.rolesBin ?? config.hiveBin,
420
+ git: config.gitBin,
421
+ };
240
422
 
241
423
  /** Execute one allowlisted verb. @returns {Promise<object>} the raw shell result */
242
424
  async function execute(verb, args, options = {}) {
@@ -366,6 +548,87 @@ export function createCommands({ ctx, config }) {
366
548
  const value = parseJson(result.stdout, 'hive recall');
367
549
  return Array.isArray(value) ? value : [];
368
550
  },
551
+ /** `hive-tasks list --json [--state S] [--role R]` -> parsed card array. */
552
+ async list(repo, options = {}) {
553
+ const result = await execute('list', { state: options.state, role: options.role }, { ...options, repo });
554
+ if (result.exitCode !== 0) throw failure(result, 'hive-tasks list');
555
+ const value = parseJson(result.stdout, 'hive-tasks list');
556
+ return Array.isArray(value) ? value : [];
557
+ },
558
+ /** `hive-tasks add ...` -> the created card (parsed from --json output). */
559
+ async add(repo, card, options = {}) {
560
+ const args = {
561
+ title: card.title,
562
+ role: card.role,
563
+ scope: card.scope,
564
+ after: card.after,
565
+ priority: card.priority,
566
+ goal: card.goal,
567
+ acceptance: card.acceptance,
568
+ tags: card.tags,
569
+ reviewOf: card.reviewOf,
570
+ draft: card.draft,
571
+ };
572
+ const result = await execute('add', args, { ...options, repo });
573
+ if (result.exitCode !== 0) throw failure(result, 'hive-tasks add');
574
+ const value = parseJson(result.stdout, 'hive-tasks add');
575
+ return value !== null && typeof value === 'object' ? value : null;
576
+ },
577
+ /** `hive-tasks reopen <id> [--reason R]` -> the reopened card. */
578
+ async reopen(repo, id, options = {}) {
579
+ const result = await execute('reopen', { id, reason: options.reason }, { ...options, repo });
580
+ if (result.exitCode !== 0) throw failure(result, 'hive-tasks reopen ' + id);
581
+ return parseJson(result.stdout, 'hive-tasks reopen');
582
+ },
583
+ /** `hive-tasks retry <id>` -> the retried card. */
584
+ async retry(repo, id, options = {}) {
585
+ const result = await execute('retry', { id }, { ...options, repo });
586
+ if (result.exitCode !== 0) throw failure(result, 'hive-tasks retry ' + id);
587
+ return parseJson(result.stdout, 'hive-tasks retry');
588
+ },
589
+ /** `hive-tasks rm <id>`: delete a card; the CLI refuses a claimed card. */
590
+ async remove(repo, id, options = {}) {
591
+ const result = await execute('remove', { id }, { ...options, repo });
592
+ if (result.exitCode !== 0) throw failure(result, 'hive-tasks rm ' + id);
593
+ return result.stdout.trim();
594
+ },
595
+ /** `hive lesson add [--scope G] [--evidence E] [--status S] <text>`. */
596
+ async lessonAdd(repo, lesson, options = {}) {
597
+ const result = await execute('lessonAdd', {
598
+ text: lesson.text,
599
+ scope: lesson.scope,
600
+ evidence: lesson.evidence,
601
+ status: lesson.status,
602
+ }, { ...options, repo });
603
+ if (result.exitCode !== 0) throw failure(result, 'hive lesson add');
604
+ return result.stdout.trim();
605
+ },
606
+ /** `hive roles list --json` -> parsed role rows. */
607
+ async rolesList(repo, options = {}) {
608
+ const result = await execute('rolesList', {}, { ...options, repo });
609
+ if (result.exitCode !== 0) throw failure(result, 'hive roles list');
610
+ const value = parseJson(result.stdout, 'hive roles list');
611
+ return Array.isArray(value) ? value : [];
612
+ },
613
+ /** `hive roles add <name> [...]`; returns the CLI output. */
614
+ async rolesAdd(repo, role, options = {}) {
615
+ const result = await execute('rolesAdd', {
616
+ name: role.name,
617
+ adapter: role.adapter,
618
+ model: role.model,
619
+ prompt: role.prompt,
620
+ description: role.description,
621
+ force: role.force,
622
+ }, { ...options, repo });
623
+ if (result.exitCode !== 0) throw failure(result, 'hive roles add');
624
+ return result.stdout.trim();
625
+ },
626
+ /** `hive roles rm <name>`; returns the CLI output. */
627
+ async rolesRemove(repo, name, options = {}) {
628
+ const result = await execute('rolesRemove', { name }, { ...options, repo });
629
+ if (result.exitCode !== 0) throw failure(result, 'hive roles rm');
630
+ return result.stdout.trim();
631
+ },
369
632
  };
370
633
  }
371
634
 
package/lib/config.js CHANGED
@@ -24,6 +24,14 @@ export const DEFAULT_CARD_TIMEOUT_MS = 15 * 60_000;
24
24
  export const DEFAULT_HEARTBEAT_WARN_MS = 5 * 60_000;
25
25
  /** How often heartbeat/liveness is checked while a worker runs. */
26
26
  export const DEFAULT_HEARTBEAT_INTERVAL_MS = 30_000;
27
+ /** Queen patrol period: the supervisor checks for anomalies and only then nudges the queen. */
28
+ export const DEFAULT_PATROL_MS = 5 * 60_000;
29
+ /** How long anomaly events coalesce before one digest is delivered to the queen. */
30
+ export const DEFAULT_ANOMALY_DEBOUNCE_MS = 3_000;
31
+ /** Maximum number of undelivered anomaly entries kept for the queen's pending list. */
32
+ export const DEFAULT_ANOMALY_MAX = 50;
33
+ /** Grace before a done card without an arch_review event is flagged. */
34
+ export const DEFAULT_ARCH_REVIEW_GRACE_MS = 10 * 60_000;
27
35
  /** Default role -> concurrent live-worker cap, per repository. */
28
36
  export const DEFAULT_ROLE_CONCURRENCY = Object.freeze({ coder: 5, tester: 5 });
29
37
  /** Fallback cap for roles not listed in `roleConcurrency` (also finite). */
@@ -58,6 +66,16 @@ const DEFAULTS = Object.freeze({
58
66
  cardTimeoutMs: DEFAULT_CARD_TIMEOUT_MS,
59
67
  heartbeatWarnMs: DEFAULT_HEARTBEAT_WARN_MS,
60
68
  heartbeatIntervalMs: DEFAULT_HEARTBEAT_INTERVAL_MS,
69
+ // Queen coordination: the supervisor patrols every patrolMs and delivers ONE
70
+ // digest to the registered queen Session only when something needs attention.
71
+ // Until a live queen Session exists the entries stay in the pending list.
72
+ patrolMs: DEFAULT_PATROL_MS,
73
+ notifyQueen: true,
74
+ anomalyDebounceMs: DEFAULT_ANOMALY_DEBOUNCE_MS,
75
+ anomalyMax: DEFAULT_ANOMALY_MAX,
76
+ // A done card must carry an arch_review event; flag it after this grace (the
77
+ // queen reviews finished cards at the next patrol).
78
+ archReviewGraceMs: DEFAULT_ARCH_REVIEW_GRACE_MS,
61
79
  provider: 'spawn',
62
80
  parentSession: null,
63
81
  cwd: null,
@@ -278,8 +296,14 @@ export function resolveConfig(config = {}) {
278
296
  if (cfg.parentSession !== null && cfg.parentSession !== undefined) cfg.parentSession = nonEmptyString(cfg.parentSession, 'parentSession');
279
297
  else cfg.parentSession = null;
280
298
  cfg.cwd = cfg.cwd === null || cfg.cwd === undefined ? process.cwd() : absolutePath(cfg.cwd, 'cwd');
299
+ cfg.patrolMs = positiveNumber(cfg.patrolMs, 'patrolMs');
300
+ cfg.notifyQueen = boolean(cfg.notifyQueen, 'notifyQueen');
301
+ cfg.anomalyDebounceMs = positiveNumber(cfg.anomalyDebounceMs, 'anomalyDebounceMs');
302
+ cfg.anomalyMax = positiveInteger(cfg.anomalyMax, 'anomalyMax', 1000);
303
+ cfg.archReviewGraceMs = positiveNumber(cfg.archReviewGraceMs, 'archReviewGraceMs');
281
304
  cfg.tasksBin = bin(cfg.tasksBin, 'tasksBin', 'HIVE_TASKS_BIN', 'hive-tasks');
282
305
  cfg.hiveBin = bin(cfg.hiveBin, 'hiveBin', 'HIVE_BIN', 'hive');
306
+ cfg.rolesBin = bin(cfg.rolesBin, 'rolesBin', 'HIVE_ROLES_BIN', cfg.hiveBin);
283
307
  cfg.gitBin = bin(cfg.gitBin, 'gitBin', 'HIVE_GIT_BIN', 'git');
284
308
 
285
309
  // Auto-discovery without explicit roots scans the parent of each configured
package/lib/events.js ADDED
@@ -0,0 +1,249 @@
1
+ /**
2
+ * Queen action log: appends review decisions to `<repo>/.hive/events.jsonl`.
3
+ *
4
+ * The queen is a coordinator, not a worker: when it reviews an accepted card it
5
+ * records a durable `arch_review` event `{ card, verdict, findings }` instead of
6
+ * editing the card (the four card states stay untouched). The panel already
7
+ * tails `.hive/events.jsonl`, so the review is visible there and to every later
8
+ * patrol; `hive events` (read side) exposes the same file to the model.
9
+ *
10
+ * Append-only: records are never rewritten. A rejected review is a fact; the
11
+ * remediation is one or more new cards plus a `reopen --reason`.
12
+ *
13
+ * @module dsh-hive-runner/events
14
+ */
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+
18
+ import { ID_RE } from './commands.js';
19
+
20
+ /** Repository-relative event log. */
21
+ export const EVENTS_FILE = path.join('.hive', 'events.jsonl');
22
+ /** Event kind written by the architecture-review gate. */
23
+ export const ARCH_REVIEW_KIND = 'arch_review';
24
+ /** Review verdicts. */
25
+ export const ARCH_VERDICTS = Object.freeze(['pass', 'reject']);
26
+ /** Maximum findings per review. */
27
+ export const FINDINGS_MAX = 20;
28
+ /** Maximum length of one finding. */
29
+ export const FINDING_MAX = 500;
30
+ /** Default read limit. */
31
+ export const EVENTS_READ_MAX = 200;
32
+
33
+ function text(value, max) {
34
+ return String(value ?? '').replace(/\s+/g, ' ').trim().slice(0, max);
35
+ }
36
+
37
+ /** Resolve the event log path, rejecting a repo that is not a usable directory path. */
38
+ export function eventsPath(repo) {
39
+ if (typeof repo !== 'string' || repo.trim() === '') throw new TypeError('eventsPath: repo is required');
40
+ return path.resolve(repo, EVENTS_FILE);
41
+ }
42
+
43
+ /**
44
+ * Normalize the review findings: an array of actionable strings.
45
+ * Reject decisions must have at least one finding — "不符合架构" is not a review.
46
+ * @param {unknown} value
47
+ * @param {string} verdict
48
+ * @returns {string[]}
49
+ */
50
+ export function normalizeFindings(value, verdict) {
51
+ if (!Array.isArray(value)) throw new TypeError('findings must be an array of strings');
52
+ if (value.length > FINDINGS_MAX) throw new TypeError('findings must have at most ' + FINDINGS_MAX + ' entries');
53
+ const findings = [];
54
+ for (const entry of value) {
55
+ if (typeof entry !== 'string') throw new TypeError('every finding must be a string');
56
+ if (entry.includes('\u0000')) throw new TypeError('a finding must not contain NUL bytes');
57
+ const finding = text(entry, FINDING_MAX + 1);
58
+ if (finding.length > FINDING_MAX) throw new TypeError('a finding must be at most ' + FINDING_MAX + ' characters');
59
+ if (finding === '') continue;
60
+ findings.push(finding);
61
+ }
62
+ if (verdict === 'reject' && findings.length === 0) {
63
+ throw new TypeError('a reject review needs at least one actionable finding (file + what to change)');
64
+ }
65
+ return findings;
66
+ }
67
+
68
+ /** Append one validated event; returns the stored record. */
69
+ export function appendEvent(repo, event) {
70
+ if (event === null || typeof event !== 'object' || Array.isArray(event)) {
71
+ throw new TypeError('appendEvent: event must be an object');
72
+ }
73
+ const file = eventsPath(repo);
74
+ fs.mkdirSync(path.dirname(file), { recursive: true });
75
+ fs.appendFileSync(file, JSON.stringify(event) + '\n');
76
+ return event;
77
+ }
78
+
79
+ /**
80
+ * Build and append one architecture-review event.
81
+ * @param {string} repo
82
+ * @param {{ card: string, verdict: string, findings?: string[], summary?: string, actor?: string, at?: number }} review
83
+ * @returns {{ ts: string, actor: string, kind: string, task: string, verdict: string, findings: string[], summary?: string }}
84
+ */
85
+ export function appendArchReview(repo, review = {}) {
86
+ const card = typeof review.card === 'string' ? review.card.trim() : '';
87
+ if (!ID_RE.test(card)) throw new TypeError('card must be a task id matching ' + String(ID_RE));
88
+ const verdict = typeof review.verdict === 'string' ? review.verdict.trim() : '';
89
+ if (!ARCH_VERDICTS.includes(verdict)) throw new TypeError('verdict must be pass or reject');
90
+ const findings = normalizeFindings(review.findings ?? [], verdict);
91
+ const event = {
92
+ ts: new Date(Number.isFinite(review.at) ? review.at : Date.now()).toISOString(),
93
+ actor: text(review.actor ?? 'queen', 64) || 'queen',
94
+ kind: ARCH_REVIEW_KIND,
95
+ task: card,
96
+ verdict,
97
+ findings,
98
+ };
99
+ const summary = text(review.summary ?? '', 300);
100
+ if (summary !== '') event.summary = summary;
101
+ return appendEvent(repo, event);
102
+ }
103
+
104
+ /** Event kind written by every queen intervention. */
105
+ export const INTERVENTION_KIND = 'queen_intervention';
106
+ /** Event kind written when a card needs a human decision. */
107
+ export const ESCALATION_KIND = 'queen_escalation';
108
+ /** Intervention actions the queen may record. */
109
+ export const INTERVENTION_ACTIONS = Object.freeze([
110
+ 'reopen', 'split', 'reassign', 'pause', 'fail', 'guide', 'remove', 'rebuild', 'escalate',
111
+ ]);
112
+ /** A card is escalated after this many recorded interventions without progress. */
113
+ export const INTERVENTION_ESCALATE_AFTER = 3;
114
+ /** The same card may be rebuilt (deleted + recreated) at most this many times. */
115
+ export const REBUILD_LIMIT = 2;
116
+
117
+ /**
118
+ * Append one `queen_intervention` event: `{ card, action, reason }` plus the
119
+ * extra action-specific fields (for example `newCards` for a split).
120
+ * @param {string} repo
121
+ * @param {{ card: string, action: string, reason?: string, actor?: string, at?: number } & Record<string, unknown>} intervention
122
+ * @returns {object} the stored event
123
+ */
124
+ export function appendIntervention(repo, intervention = {}) {
125
+ const card = typeof intervention.card === 'string' ? intervention.card.trim() : '';
126
+ if (!ID_RE.test(card)) throw new TypeError('card must be a task id matching ' + String(ID_RE));
127
+ const action = typeof intervention.action === 'string' ? intervention.action.trim() : '';
128
+ if (!INTERVENTION_ACTIONS.includes(action)) {
129
+ throw new TypeError('action must be one of ' + INTERVENTION_ACTIONS.join(', '));
130
+ }
131
+ const reason = typeof intervention.reason === 'string' ? intervention.reason.trim() : '';
132
+ if (reason === '') throw new TypeError('a queen intervention must record a reason (the guidance for the next attempt)');
133
+ const event = {
134
+ ts: new Date(Number.isFinite(intervention.at) ? intervention.at : Date.now()).toISOString(),
135
+ actor: text(intervention.actor ?? 'queen', 64) || 'queen',
136
+ kind: INTERVENTION_KIND,
137
+ task: card,
138
+ action,
139
+ reason: reason.slice(0, 2000),
140
+ };
141
+ if (Array.isArray(intervention.newCards) && intervention.newCards.length > 0) {
142
+ event.newCards = intervention.newCards.filter((id) => typeof id === 'string' && ID_RE.test(id));
143
+ }
144
+ if (typeof intervention.sessionId === 'string' && intervention.sessionId !== '') {
145
+ event.sessionId = intervention.sessionId;
146
+ }
147
+ // Deleting a card must never make it disappear silently: the event carries
148
+ // the card's title, state and scope so the panel's event tail (and the queen's
149
+ // later report) still show what was removed and why.
150
+ const removed = intervention.removed;
151
+ if (removed !== null && typeof removed === 'object' && !Array.isArray(removed)) {
152
+ const snapshot = {};
153
+ if (typeof removed.title === 'string') snapshot.title = text(removed.title, 300);
154
+ if (typeof removed.state === 'string') snapshot.state = text(removed.state, 32);
155
+ if (Array.isArray(removed.scope)) {
156
+ snapshot.scope = removed.scope.filter((entry) => typeof entry === 'string').slice(0, 64).map((entry) => text(entry, 512));
157
+ }
158
+ if (typeof removed.reason === 'string' && removed.reason !== '') snapshot.reason = text(removed.reason, 600);
159
+ if (Object.keys(snapshot).length > 0) event.removed = snapshot;
160
+ }
161
+ return appendEvent(repo, event);
162
+ }
163
+
164
+ /**
165
+ * Append one `queen_escalation` event: the card needs a human decision.
166
+ * @param {string} repo
167
+ * @param {{ card: string, reason: string, interventions?: number, actor?: string, at?: number }} escalation
168
+ * @returns {object}
169
+ */
170
+ export function appendEscalation(repo, escalation = {}) {
171
+ const card = typeof escalation.card === 'string' ? escalation.card.trim() : '';
172
+ if (!ID_RE.test(card)) throw new TypeError('card must be a task id matching ' + String(ID_RE));
173
+ const reason = text(escalation.reason ?? '', 2000);
174
+ if (reason === '') throw new TypeError('an escalation must explain where the card is stuck');
175
+ const event = {
176
+ ts: new Date(Number.isFinite(escalation.at) ? escalation.at : Date.now()).toISOString(),
177
+ actor: text(escalation.actor ?? 'queen', 64) || 'queen',
178
+ kind: ESCALATION_KIND,
179
+ task: card,
180
+ reason,
181
+ };
182
+ if (Number.isInteger(escalation.interventions) && escalation.interventions > 0) {
183
+ event.interventions = escalation.interventions;
184
+ }
185
+ return appendEvent(repo, event);
186
+ }
187
+
188
+ /** Count queen_intervention events per card id. */
189
+ export function interventionCounts(events) {
190
+ const counts = new Map();
191
+ for (const event of Array.isArray(events) ? events : []) {
192
+ if (event === null || typeof event !== 'object' || event.kind !== INTERVENTION_KIND) continue;
193
+ if (typeof event.task !== 'string') continue;
194
+ counts.set(event.task, (counts.get(event.task) ?? 0) + 1);
195
+ }
196
+ return counts;
197
+ }
198
+
199
+ /** Count `rebuild` interventions per card id (the same-card rebuild budget). */
200
+ export function rebuildCounts(events) {
201
+ const counts = new Map();
202
+ for (const event of Array.isArray(events) ? events : []) {
203
+ if (event === null || typeof event !== 'object' || event.kind !== INTERVENTION_KIND) continue;
204
+ if (event.action !== 'rebuild' || typeof event.task !== 'string') continue;
205
+ counts.set(event.task, (counts.get(event.task) ?? 0) + 1);
206
+ }
207
+ return counts;
208
+ }
209
+
210
+ /** Set of card ids that already have a queen_escalation event. */
211
+ export function escalatedCards(events) {
212
+ const cards = new Set();
213
+ for (const event of Array.isArray(events) ? events : []) {
214
+ if (event === null || typeof event !== 'object' || event.kind !== ESCALATION_KIND) continue;
215
+ if (typeof event.task === 'string') cards.add(event.task);
216
+ }
217
+ return cards;
218
+ }
219
+
220
+ /**
221
+ * Read the tail of the event log, newest first.
222
+ * @param {string} repo
223
+ * @param {{ limit?: number, kind?: string, task?: string }} [options]
224
+ * @returns {object[]}
225
+ */
226
+ export function readEvents(repo, options = {}) {
227
+ const limit = Number.isInteger(options.limit) && options.limit > 0 ? options.limit : EVENTS_READ_MAX;
228
+ let text;
229
+ try {
230
+ text = fs.readFileSync(eventsPath(repo), 'utf8');
231
+ } catch {
232
+ return [];
233
+ }
234
+ const events = [];
235
+ for (const line of text.split('\n')) {
236
+ if (line === '') continue;
237
+ let parsed;
238
+ try {
239
+ parsed = JSON.parse(line);
240
+ } catch {
241
+ continue;
242
+ }
243
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) continue;
244
+ if (typeof options.kind === 'string' && parsed.kind !== options.kind) continue;
245
+ if (typeof options.task === 'string' && parsed.task !== options.task) continue;
246
+ events.push(parsed);
247
+ }
248
+ return events.slice(-limit).reverse();
249
+ }