dsh-hive-runner 1.0.15 → 1.0.17
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/CHANGELOG.md +64 -0
- package/README.md +14 -0
- package/SPEC.md +31 -4
- package/docs/DESIGN.md +63 -7
- package/index.js +219 -54
- package/lib/checkpoint.js +15 -2
- package/lib/events.js +10 -2
- package/lib/http.js +19 -2
- package/lib/notify.js +18 -7
- package/lib/ops.js +387 -0
- package/lib/patrol.js +42 -12
- package/lib/queen-boundary.js +26 -7
- package/lib/queen-scope.js +103 -0
- package/lib/round.js +3 -3
- package/lib/services.js +274 -0
- package/lib/supervisor.js +130 -26
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -42,10 +42,19 @@ import { createHiveRunnerRoute } from './lib/http.js';
|
|
|
42
42
|
import { RepoLimits } from './lib/limits.js';
|
|
43
43
|
import { createAnomalyFeed } from './lib/anomalies.js';
|
|
44
44
|
import { createCheckpointController } from './lib/checkpoint.js';
|
|
45
|
-
import { createQueenNotifier, deliverToSession } from './lib/notify.js';
|
|
45
|
+
import { createQueenNotifier, deliverToSession, resolveAgent } from './lib/notify.js';
|
|
46
46
|
import { createPatrol } from './lib/patrol.js';
|
|
47
47
|
import { drainQueue } from './lib/queue.js';
|
|
48
|
-
import {
|
|
48
|
+
import {
|
|
49
|
+
createQueenBoundaryGuard,
|
|
50
|
+
hasQueenRole,
|
|
51
|
+
isQueenSuppressed,
|
|
52
|
+
recordQueenBoundaryViolation as recordQueenBoundaryAttempt,
|
|
53
|
+
} from './lib/queen-boundary.js';
|
|
54
|
+
import { createQueenHiveScopeEnforcer } from './lib/queen-scope.js';
|
|
55
|
+
import { loadOpsPolicy, OPS_ACTIONS, opsDeniedEvent, planOpsAction, runOpsCommand } from './lib/ops.js';
|
|
56
|
+
import { createShellRunner } from './lib/shell.js';
|
|
57
|
+
import { auditServices, probePort, serviceStatus } from './lib/services.js';
|
|
49
58
|
import { createRoundRunner } from './lib/round.js';
|
|
50
59
|
import { readRunRecord } from './lib/runs.js';
|
|
51
60
|
import { HiveSupervisor } from './lib/supervisor.js';
|
|
@@ -101,22 +110,23 @@ export function apply(ctx, config = {}) {
|
|
|
101
110
|
if (typeof write === 'function') write.call(console, '[hive-runner]', ...args);
|
|
102
111
|
else console.warn('[hive-runner]', ...args);
|
|
103
112
|
};
|
|
104
|
-
// The panel registers
|
|
105
|
-
// POST ?op=queen).
|
|
106
|
-
//
|
|
107
|
-
const queenSession = { sessionId: null };
|
|
113
|
+
// The panel registers one queen per repository (setQueenSession(sessionId, repo),
|
|
114
|
+
// also via POST ?op=queen). Workers are parented only to that repo's queen; a
|
|
115
|
+
// repository with no registered queen is unmanaged and never dispatches.
|
|
108
116
|
// One-shot diagnostic: schema names visible to the queen agent (under PTC the
|
|
109
117
|
// model sees only run_code, but tools.hive_* exist inside run_code).
|
|
110
118
|
const queenTools = { names: [], sessionId: null, listedAt: null, error: null };
|
|
111
119
|
/** Queen boundary violations observed by the tool guard (status observability). */
|
|
112
120
|
const queenBoundary = { count: 0, last: null };
|
|
121
|
+
/** Mechanical cross-repo rejections of queen hive_* calls. */
|
|
122
|
+
const crossRepoBlocked = { count: 0, last: null };
|
|
113
123
|
let parentProviderImpl;
|
|
114
124
|
const runner = createRoundRunner({
|
|
115
125
|
ctx,
|
|
116
126
|
config: resolved,
|
|
117
127
|
commands,
|
|
118
128
|
limitFor: (repo, role) => limits.limitFor(repo, role),
|
|
119
|
-
parentProvider: (explicit) => parentProviderImpl(explicit),
|
|
129
|
+
parentProvider: (explicit, repo) => parentProviderImpl(explicit, repo),
|
|
120
130
|
onAnomaly: (event) => recordAnomaly(event),
|
|
121
131
|
// A finished worker or a settled card asks for a near-real-time checkpoint
|
|
122
132
|
// check instead of waiting for the next patrol tick.
|
|
@@ -127,8 +137,10 @@ export function apply(ctx, config = {}) {
|
|
|
127
137
|
},
|
|
128
138
|
log,
|
|
129
139
|
});
|
|
130
|
-
parentProviderImpl = async (explicit) => {
|
|
131
|
-
const sessionId =
|
|
140
|
+
parentProviderImpl = async (explicit, repo) => {
|
|
141
|
+
const sessionId = typeof repo === 'string' && repo !== ''
|
|
142
|
+
? supervisor.queenFor(repo)
|
|
143
|
+
: (supervisor.queens()[0]?.sessionId ?? null);
|
|
132
144
|
const agent = sessionId === null ? undefined : ctx.get('agents')?.get?.(sessionId);
|
|
133
145
|
return { agent, source: 'queen', sessionId };
|
|
134
146
|
};
|
|
@@ -140,6 +152,8 @@ export function apply(ctx, config = {}) {
|
|
|
140
152
|
let patrol;
|
|
141
153
|
/** @type {ReturnType<typeof createCheckpointController> | undefined} */
|
|
142
154
|
let checkpoint;
|
|
155
|
+
/** Per-repo set of currently-down services (patrol event/dedup state). */
|
|
156
|
+
const serviceOutages = new Map();
|
|
143
157
|
function recordAnomaly(event) {
|
|
144
158
|
try {
|
|
145
159
|
anomalies.push(event);
|
|
@@ -193,8 +207,8 @@ export function apply(ctx, config = {}) {
|
|
|
193
207
|
/** Idempotently register a cwd-recognized queen so the panel can show it. */
|
|
194
208
|
function registerDetectedQueen(sessionId, cwd) {
|
|
195
209
|
try {
|
|
196
|
-
if (supervisor.
|
|
197
|
-
supervisor.setQueenSession(sessionId);
|
|
210
|
+
if (supervisor.queenFor(cwd) === sessionId) return;
|
|
211
|
+
supervisor.setQueenSession(sessionId, cwd);
|
|
198
212
|
log('info', 'auto-registered initialized queen session', sessionId, 'cwd', cwd);
|
|
199
213
|
} catch (error) {
|
|
200
214
|
log('warn', 'auto-registering detected queen failed', error);
|
|
@@ -240,7 +254,8 @@ export function apply(ctx, config = {}) {
|
|
|
240
254
|
// Recognition is registration OR an ordinary initialized-repo Session; a
|
|
241
255
|
// /queen off command event suppresses both paths.
|
|
242
256
|
ctx.effect(() => ctx.tools.guard(createQueenBoundaryGuard({
|
|
243
|
-
|
|
257
|
+
isRegisteredQueen: (sessionId) => supervisor.isQueenSession(sessionId),
|
|
258
|
+
queenSessionIds: () => supervisor.queenSessionIds(),
|
|
244
259
|
onViolation: recordQueenBoundaryViolation,
|
|
245
260
|
onQueenDetected: registerDetectedQueen,
|
|
246
261
|
resolveCwd: resolveQueenBoundaryCwd,
|
|
@@ -249,7 +264,13 @@ export function apply(ctx, config = {}) {
|
|
|
249
264
|
log,
|
|
250
265
|
})));
|
|
251
266
|
|
|
252
|
-
const notifier = createQueenNotifier({
|
|
267
|
+
const notifier = createQueenNotifier({
|
|
268
|
+
ctx,
|
|
269
|
+
resolveSessionId: (repo) => supervisor.queenFor(repo),
|
|
270
|
+
log,
|
|
271
|
+
});
|
|
272
|
+
// hive_ops uses the same sandboxed shell seam as the rest of the plugin.
|
|
273
|
+
const opsRun = createShellRunner({ ctx, config: resolved });
|
|
253
274
|
// Done cards must carry an arch_review event; the patrol audits the board and
|
|
254
275
|
// turns a missing review into an arch-review-missing anomaly.
|
|
255
276
|
const archReviewAudit = createArchReviewAudit({
|
|
@@ -282,9 +303,13 @@ export function apply(ctx, config = {}) {
|
|
|
282
303
|
runCard: runner.runCard,
|
|
283
304
|
preflight: runner.preflight,
|
|
284
305
|
activeRuns: (repo) => runner.activeRuns(repo),
|
|
285
|
-
|
|
306
|
+
resolveQueenRepo: (sessionId) => {
|
|
307
|
+
const agent = ctx.get('agents')?.get?.(sessionId);
|
|
308
|
+
return resolveQueenBoundaryCwd(agent, agent?.session);
|
|
309
|
+
},
|
|
286
310
|
queenBoundary,
|
|
287
311
|
queenTools: () => queenTools,
|
|
312
|
+
crossRepoBlocked: () => crossRepoBlocked,
|
|
288
313
|
archReview: (repo, review) => recordArchReviewHost(repo, review),
|
|
289
314
|
readMode: (repo) => commands.mode(repo),
|
|
290
315
|
onAnomaly: (event) => recordAnomaly(event),
|
|
@@ -324,10 +349,20 @@ export function apply(ctx, config = {}) {
|
|
|
324
349
|
} catch (error) {
|
|
325
350
|
log('warn', 'arch review audit failed for ' + repo + ': ' + (error instanceof Error ? error.message : String(error)));
|
|
326
351
|
}
|
|
352
|
+
try {
|
|
353
|
+
let outages = serviceOutages.get(repo);
|
|
354
|
+
if (outages === undefined) {
|
|
355
|
+
outages = new Set();
|
|
356
|
+
serviceOutages.set(repo, outages);
|
|
357
|
+
}
|
|
358
|
+
await auditServices({ repo, commands, probe: probePort, state: outages, log });
|
|
359
|
+
} catch (error) {
|
|
360
|
+
log('warn', 'service audit failed for ' + repo + ': ' + (error instanceof Error ? error.message : String(error)));
|
|
361
|
+
}
|
|
327
362
|
}
|
|
328
363
|
// Retry the one-shot tool listing if the panel registered before the agent
|
|
329
364
|
// was live (status/queenTools then contains an error until this succeeds).
|
|
330
|
-
|
|
365
|
+
for (const queen of supervisor.queens()) inspectQueenTools(queen.sessionId);
|
|
331
366
|
// Progress checkpoints: drained/all-done/gate-advance/idle goals. Delivery
|
|
332
367
|
// is direct; failures stay pending in the checkpoint controller.
|
|
333
368
|
try {
|
|
@@ -356,6 +391,7 @@ export function apply(ctx, config = {}) {
|
|
|
356
391
|
return { tasks, ready };
|
|
357
392
|
},
|
|
358
393
|
loadEvents: (repo) => readEvents(repo, { limit: 100 }),
|
|
394
|
+
queenForRepo: (repo) => supervisor.queenFor(repo),
|
|
359
395
|
drainMs: resolved.checkpointDrainMs,
|
|
360
396
|
idleMs: resolved.checkpointIdleMs,
|
|
361
397
|
log,
|
|
@@ -394,6 +430,22 @@ export function apply(ctx, config = {}) {
|
|
|
394
430
|
);
|
|
395
431
|
}
|
|
396
432
|
|
|
433
|
+
/**
|
|
434
|
+
* Mechanical red line: a queen may call hive_* only for her own cwd repository.
|
|
435
|
+
* Enforced before every tool body; an omitted repo defaults to the queen cwd.
|
|
436
|
+
*/
|
|
437
|
+
const enforceQueenHiveScope = createQueenHiveScopeEnforcer({
|
|
438
|
+
isQueenSession: (sessionId) => supervisor.isQueenSession(sessionId),
|
|
439
|
+
resolveCwd: (agent, session) => resolveQueenBoundaryCwd(agent, session),
|
|
440
|
+
hasQueenRole,
|
|
441
|
+
isSuppressed: isQueenSuppressed,
|
|
442
|
+
onBlocked: (info) => {
|
|
443
|
+
crossRepoBlocked.count += 1;
|
|
444
|
+
crossRepoBlocked.last = info;
|
|
445
|
+
},
|
|
446
|
+
log,
|
|
447
|
+
});
|
|
448
|
+
|
|
397
449
|
/** Register one model-facing tool whose result is rendered as one text block. */
|
|
398
450
|
function registerTextTool({ name, description, parameters = {}, execute }) {
|
|
399
451
|
ctx.tools.register(defineTool({
|
|
@@ -401,10 +453,47 @@ export function apply(ctx, config = {}) {
|
|
|
401
453
|
description,
|
|
402
454
|
parameters,
|
|
403
455
|
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
|
|
404
|
-
execute,
|
|
456
|
+
execute: async (args = {}, exec = {}) => execute(enforceQueenHiveScope(name, parameters, args, exec), exec),
|
|
405
457
|
}));
|
|
406
458
|
}
|
|
407
459
|
|
|
460
|
+
/** Run one manual round for a single repository (shared by hive_run_round/hive_ops). */
|
|
461
|
+
async function runRoundForRepo(repo, args = {}, exec = {}) {
|
|
462
|
+
const signal = exec?.signal;
|
|
463
|
+
const session = exec?.agent?.session;
|
|
464
|
+
if (supervisor.queenFor(repo) === null) {
|
|
465
|
+
throw new Error('waiting: no-queen-session for ' + repo + ' — open the Hive panel and initialise that repository first');
|
|
466
|
+
}
|
|
467
|
+
runner.preflight(repo);
|
|
468
|
+
const cards = await runner.listReady(repo, { signal, session });
|
|
469
|
+
const gateResult = await supervisor.filterDispatchable(repo, cards, { signal });
|
|
470
|
+
const dispatchable = gateResult.cards;
|
|
471
|
+
const outcome = await drainQueue({
|
|
472
|
+
queue: dispatchable.map((card) => ({ role: card.role, card, claimed: false })),
|
|
473
|
+
roleNames: limits.rolesFor(repo, cards.map((card) => card.role)),
|
|
474
|
+
limitFor: (role) => limits.limitFor(repo, role),
|
|
475
|
+
runCard: (item) => runner.runCard({
|
|
476
|
+
repo,
|
|
477
|
+
card: item.card,
|
|
478
|
+
claimed: item.claimed === true,
|
|
479
|
+
signal,
|
|
480
|
+
session,
|
|
481
|
+
parent: exec?.agent,
|
|
482
|
+
agent: args.agent,
|
|
483
|
+
ttl: args.ttl,
|
|
484
|
+
}),
|
|
485
|
+
capacityRetryMs: resolved.capacityRetryMs,
|
|
486
|
+
signal,
|
|
487
|
+
});
|
|
488
|
+
if (outcome.error !== undefined) throw outcome.error;
|
|
489
|
+
return {
|
|
490
|
+
repo,
|
|
491
|
+
gate: gateResult.gate,
|
|
492
|
+
results: outcome.results,
|
|
493
|
+
state: outcome.state,
|
|
494
|
+
queued: outcome.queue.length,
|
|
495
|
+
};
|
|
496
|
+
}
|
|
408
497
|
const repoParameter = {
|
|
409
498
|
type: 'string',
|
|
410
499
|
description: 'Repository path. Default: the configured cwd.',
|
|
@@ -422,44 +511,7 @@ export function apply(ctx, config = {}) {
|
|
|
422
511
|
ttl: { type: 'string', description: 'Claim TTL, for example 5m.' },
|
|
423
512
|
agent: { type: 'string', description: 'Identity used for claims. Default: config.agent.' },
|
|
424
513
|
},
|
|
425
|
-
execute: async (args = {}, exec) =>
|
|
426
|
-
const repo = repoOf(args);
|
|
427
|
-
const signal = exec?.signal;
|
|
428
|
-
const session = exec?.agent?.session;
|
|
429
|
-
if (supervisor.queenSession.sessionId === null) {
|
|
430
|
-
throw new Error('waiting: no-queen-session — open the Hive panel and initialise the repository first');
|
|
431
|
-
}
|
|
432
|
-
runner.preflight(repo);
|
|
433
|
-
const cards = await runner.listReady(repo, { signal, session });
|
|
434
|
-
// The manual round obeys the same gate order as the resident supervisor.
|
|
435
|
-
const gateResult = await supervisor.filterDispatchable(repo, cards, { signal });
|
|
436
|
-
const dispatchable = gateResult.cards;
|
|
437
|
-
const outcome = await drainQueue({
|
|
438
|
-
queue: dispatchable.map((card) => ({ role: card.role, card, claimed: false })),
|
|
439
|
-
roleNames: limits.rolesFor(repo, cards.map((card) => card.role)),
|
|
440
|
-
limitFor: (role) => limits.limitFor(repo, role),
|
|
441
|
-
runCard: (item) => runner.runCard({
|
|
442
|
-
repo,
|
|
443
|
-
card: item.card,
|
|
444
|
-
claimed: item.claimed === true,
|
|
445
|
-
signal,
|
|
446
|
-
session,
|
|
447
|
-
parent: exec?.agent,
|
|
448
|
-
agent: args.agent,
|
|
449
|
-
ttl: args.ttl,
|
|
450
|
-
}),
|
|
451
|
-
capacityRetryMs: resolved.capacityRetryMs,
|
|
452
|
-
signal,
|
|
453
|
-
});
|
|
454
|
-
if (outcome.error !== undefined) throw outcome.error;
|
|
455
|
-
return jsonText({
|
|
456
|
-
repo,
|
|
457
|
-
gate: gateResult.gate,
|
|
458
|
-
results: outcome.results,
|
|
459
|
-
state: outcome.state,
|
|
460
|
-
queued: outcome.queue.length,
|
|
461
|
-
});
|
|
462
|
-
},
|
|
514
|
+
execute: async (args = {}, exec) => jsonText(await runRoundForRepo(repoOf(args), args, exec)),
|
|
463
515
|
});
|
|
464
516
|
|
|
465
517
|
registerTextTool({
|
|
@@ -701,6 +753,114 @@ export function apply(ctx, config = {}) {
|
|
|
701
753
|
},
|
|
702
754
|
});
|
|
703
755
|
|
|
756
|
+
registerTextTool({
|
|
757
|
+
name: 'hive_ops',
|
|
758
|
+
description:
|
|
759
|
+
'Queen-only operational actions inside one repository. action=status|pause|resume|limits|run-round|health|'
|
|
760
|
+
+ 'diagnose|test|typecheck|build|services. Only diagnose runs a command, restricted to git status/log/diff/show, ls, '
|
|
761
|
+
+ 'curl 127.0.0.1 and lsof (plus <repo>/.hive/ops.yaml extensions); test/typecheck/build run the fixed pnpm script. '
|
|
762
|
+
+ 'Source-changing commands and long-running dev/serve/watch are rejected. Shell actions use a 120s timeout and '
|
|
763
|
+
+ '64 KiB output cap. Every action/denial appends a hive_ops event.',
|
|
764
|
+
parameters: {
|
|
765
|
+
repo: repoParameter,
|
|
766
|
+
action: { type: 'string', enum: [...OPS_ACTIONS], description: 'Action to perform.' },
|
|
767
|
+
args: { type: 'object', additionalProperties: true, description: 'diagnose: command/args; pause: {reason}; limits: {roleLimits}; run-round: {agent,ttl}; services: none.' },
|
|
768
|
+
},
|
|
769
|
+
execute: async (args = {}, exec = {}) => {
|
|
770
|
+
const session = exec?.agent?.session;
|
|
771
|
+
const sessionId = session?.id;
|
|
772
|
+
const cwd = resolveQueenBoundaryCwd(exec?.agent, session);
|
|
773
|
+
let queen = false;
|
|
774
|
+
try {
|
|
775
|
+
queen = supervisor.isQueenSession(sessionId)
|
|
776
|
+
|| (typeof cwd === 'string' && cwd !== '' && hasQueenRole(cwd));
|
|
777
|
+
} catch {
|
|
778
|
+
queen = false;
|
|
779
|
+
}
|
|
780
|
+
if (!queen) throw new Error('hive_ops 仅女王可用');
|
|
781
|
+
const repo = repoOf(args);
|
|
782
|
+
const policy = loadOpsPolicy(repo);
|
|
783
|
+
let plan;
|
|
784
|
+
try {
|
|
785
|
+
plan = planOpsAction(args.action, args.args, { repo, policy });
|
|
786
|
+
} catch (error) {
|
|
787
|
+
try { appendEvent(repo, opsDeniedEvent(repo, args.action, args.args, error, sessionId)); } catch { /* primary error wins */ }
|
|
788
|
+
throw error;
|
|
789
|
+
}
|
|
790
|
+
const appendHostEvent = (fields = {}) => {
|
|
791
|
+
try {
|
|
792
|
+
appendEvent(repo, {
|
|
793
|
+
ts: new Date().toISOString(),
|
|
794
|
+
actor: 'hive-runner',
|
|
795
|
+
kind: 'hive_ops',
|
|
796
|
+
action: plan.action,
|
|
797
|
+
args: args.args ?? null,
|
|
798
|
+
ok: true,
|
|
799
|
+
...fields,
|
|
800
|
+
});
|
|
801
|
+
} catch {
|
|
802
|
+
// Audit failure must not mask the action result.
|
|
803
|
+
}
|
|
804
|
+
};
|
|
805
|
+
try {
|
|
806
|
+
if (plan.kind === 'shell') {
|
|
807
|
+
const result = await runOpsCommand({
|
|
808
|
+
repo,
|
|
809
|
+
argv: plan.argv,
|
|
810
|
+
action: plan.action,
|
|
811
|
+
validate: false,
|
|
812
|
+
run: opsRun,
|
|
813
|
+
session,
|
|
814
|
+
signal: exec?.signal,
|
|
815
|
+
policy,
|
|
816
|
+
});
|
|
817
|
+
return jsonText({ ok: true, action: plan.action, repo, ...result });
|
|
818
|
+
}
|
|
819
|
+
const data = plan.data ?? {};
|
|
820
|
+
let result;
|
|
821
|
+
if (plan.action === 'status') {
|
|
822
|
+
const status = supervisor.status();
|
|
823
|
+
result = { status: status.repos.find((entry) => entry.repo === repo) ?? null, queens: status.queens, waiting: status.waiting };
|
|
824
|
+
} else if (plan.action === 'pause') {
|
|
825
|
+
const reason = typeof data.reason === 'string' && data.reason !== '' ? data.reason : (plan.tokens.join(' ') || 'paused via hive_ops');
|
|
826
|
+
result = supervisor.pause(repo, reason);
|
|
827
|
+
} else if (plan.action === 'resume') {
|
|
828
|
+
result = supervisor.resume(repo);
|
|
829
|
+
} else if (plan.action === 'limits') {
|
|
830
|
+
if (data.roleLimits !== null && typeof data.roleLimits === 'object') {
|
|
831
|
+
result = supervisor.setRoleLimits(repo, data.roleLimits);
|
|
832
|
+
} else {
|
|
833
|
+
result = supervisor.roleLimits(repo);
|
|
834
|
+
}
|
|
835
|
+
} else if (plan.action === 'health') {
|
|
836
|
+
const status = supervisor.status();
|
|
837
|
+
const entry = status.repos.find((item) => item.repo === repo) ?? null;
|
|
838
|
+
result = {
|
|
839
|
+
repo,
|
|
840
|
+
state: entry?.state ?? null,
|
|
841
|
+
gate: entry?.gate ?? null,
|
|
842
|
+
mode: await commands.mode(repo),
|
|
843
|
+
environmentError: entry?.environmentError ?? null,
|
|
844
|
+
lastError: entry?.lastError ?? null,
|
|
845
|
+
workers: Array.isArray(entry?.workers) ? entry.workers : [],
|
|
846
|
+
};
|
|
847
|
+
} else if (plan.action === 'run-round') {
|
|
848
|
+
result = await runRoundForRepo(repo, data, exec);
|
|
849
|
+
} else if (plan.action === 'services') {
|
|
850
|
+
result = { services: await serviceStatus(repo, { probe: probePort }) };
|
|
851
|
+
} else {
|
|
852
|
+
throw new Error('unsupported hive_ops action: ' + String(plan.action));
|
|
853
|
+
}
|
|
854
|
+
appendHostEvent();
|
|
855
|
+
return jsonText({ ok: true, action: plan.action, repo, ...result });
|
|
856
|
+
} catch (error) {
|
|
857
|
+
if (error?.opsEventRecorded !== true) {
|
|
858
|
+
try { appendEvent(repo, opsDeniedEvent(repo, args.action, args.args, error, sessionId)); } catch { /* primary error wins */ }
|
|
859
|
+
}
|
|
860
|
+
throw error;
|
|
861
|
+
}
|
|
862
|
+
},
|
|
863
|
+
});
|
|
704
864
|
registerTextTool({
|
|
705
865
|
name: 'hive_events',
|
|
706
866
|
description:
|
|
@@ -953,6 +1113,11 @@ export function apply(ctx, config = {}) {
|
|
|
953
1113
|
if (typeof args.sessionId !== 'string' || args.sessionId === '') {
|
|
954
1114
|
throw new Error('hive_intervene guide needs sessionId (see hive_tasks show lastRun.sessionId)');
|
|
955
1115
|
}
|
|
1116
|
+
const targetAgent = resolveAgent(ctx, args.sessionId);
|
|
1117
|
+
const targetCwd = resolveQueenBoundaryCwd(targetAgent, targetAgent?.session);
|
|
1118
|
+
if (typeof targetCwd !== 'string' || normalizeRepoKey(targetCwd) !== normalizeRepoKey(repo)) {
|
|
1119
|
+
throw new Error('女王只能操作自己所在的仓库');
|
|
1120
|
+
}
|
|
956
1121
|
delivery = deliverToSession({ ctx }, args.sessionId, '[hive queen guidance]' + NL + NL + args.reason, { prefer: 'steer' });
|
|
957
1122
|
if (delivery.delivered !== true) {
|
|
958
1123
|
throw new Error('cannot deliver guidance: ' + String(delivery.reason ?? 'unknown'));
|
package/lib/checkpoint.js
CHANGED
|
@@ -129,6 +129,7 @@ export function renderCheckpoint({ repo, stats, gate, recentEvents, trigger, at,
|
|
|
129
129
|
* eventWindowMs?: number,
|
|
130
130
|
* cacheMs?: number,
|
|
131
131
|
* errorBackoffMs?: number,
|
|
132
|
+
* queenForRepo?: (repo: string) => string | null,
|
|
132
133
|
* log?: (level: string, ...args: unknown[]) => void,
|
|
133
134
|
* }} options
|
|
134
135
|
*/
|
|
@@ -145,6 +146,7 @@ export function createCheckpointController({
|
|
|
145
146
|
eventWindowMs = DEFAULT_CHECKPOINT_EVENT_WINDOW_MS,
|
|
146
147
|
cacheMs = DEFAULT_CHECKPOINT_CACHE_MS,
|
|
147
148
|
errorBackoffMs = DEFAULT_CHECKPOINT_ERROR_BACKOFF_MS,
|
|
149
|
+
queenForRepo,
|
|
148
150
|
log = () => {},
|
|
149
151
|
} = {}) {
|
|
150
152
|
if (typeof loadBoard !== 'function') throw new TypeError('createCheckpointController: loadBoard is required');
|
|
@@ -176,7 +178,7 @@ export function createCheckpointController({
|
|
|
176
178
|
return { delivered: false, reason: 'no-notifier' };
|
|
177
179
|
}
|
|
178
180
|
try {
|
|
179
|
-
const result = notifier.deliver(entry.body);
|
|
181
|
+
const result = notifier.deliver(entry.body, entry.repo);
|
|
180
182
|
if (result !== undefined && result.delivered === true) {
|
|
181
183
|
return { delivered: true, via: result.via ?? null };
|
|
182
184
|
}
|
|
@@ -300,7 +302,14 @@ export function createCheckpointController({
|
|
|
300
302
|
startup: !firstCheckpointCreated,
|
|
301
303
|
});
|
|
302
304
|
const entry = { repo, body, signature, at, trigger: reasons.join('+') };
|
|
303
|
-
|
|
305
|
+
// Hard repo isolation: a checkpoint may only go to the queen registered
|
|
306
|
+
// for this repository. No match -> pending, never another repo's queen.
|
|
307
|
+
const targetQueen = typeof queenForRepo === 'function' ? queenForRepo(repo) : undefined;
|
|
308
|
+
const unmatched = typeof queenForRepo === 'function'
|
|
309
|
+
&& (typeof targetQueen !== 'string' || targetQueen === '');
|
|
310
|
+
const delivery = unmatched
|
|
311
|
+
? { delivered: false, reason: 'no-queen-for-repo' }
|
|
312
|
+
: deliver(entry);
|
|
304
313
|
state.lastSignature = signature;
|
|
305
314
|
state.lastCheckpointAt = at;
|
|
306
315
|
state.hasCheckpoint = true;
|
|
@@ -323,6 +332,10 @@ export function createCheckpointController({
|
|
|
323
332
|
function flushPending() {
|
|
324
333
|
let delivered = 0;
|
|
325
334
|
for (const entry of [...pending]) {
|
|
335
|
+
if (typeof queenForRepo === 'function') {
|
|
336
|
+
const target = queenForRepo(entry.repo);
|
|
337
|
+
if (typeof target !== 'string' || target === '') continue;
|
|
338
|
+
}
|
|
326
339
|
const result = deliver(entry);
|
|
327
340
|
if (result.delivered) {
|
|
328
341
|
pending.splice(pending.indexOf(entry), 1);
|
package/lib/events.js
CHANGED
|
@@ -37,6 +37,8 @@ function text(value, max) {
|
|
|
37
37
|
/** Resolve the event log path, rejecting a repo that is not a usable directory path. */
|
|
38
38
|
export function eventsPath(repo) {
|
|
39
39
|
if (typeof repo !== 'string' || repo.trim() === '') throw new TypeError('eventsPath: repo is required');
|
|
40
|
+
if (repo.includes('\u0000')) throw new TypeError('eventsPath: repo must not contain NUL bytes');
|
|
41
|
+
if (!path.isAbsolute(repo.trim())) throw new TypeError('eventsPath: repo must be an absolute path');
|
|
40
42
|
return path.resolve(repo, EVENTS_FILE);
|
|
41
43
|
}
|
|
42
44
|
|
|
@@ -71,8 +73,14 @@ export function appendEvent(repo, event) {
|
|
|
71
73
|
throw new TypeError('appendEvent: event must be an object');
|
|
72
74
|
}
|
|
73
75
|
const file = eventsPath(repo);
|
|
74
|
-
|
|
75
|
-
|
|
76
|
+
// Resolve symlinks before writing: a `.hive` symlink must never redirect the
|
|
77
|
+
// append outside the repository that owns the event log.
|
|
78
|
+
const root = fs.realpathSync(repo);
|
|
79
|
+
const dir = path.join(root, path.dirname(EVENTS_FILE));
|
|
80
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
81
|
+
const realDir = fs.realpathSync(dir);
|
|
82
|
+
if (realDir !== dir) throw new Error('event path escapes repository: ' + repo);
|
|
83
|
+
fs.appendFileSync(path.join(realDir, path.basename(file)), JSON.stringify(event) + '\n');
|
|
76
84
|
return event;
|
|
77
85
|
}
|
|
78
86
|
|
package/lib/http.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* POST /api/hive-runner?op=pause { repo }
|
|
12
12
|
* POST /api/hive-runner?op=resume { repo }
|
|
13
13
|
* POST /api/hive-runner?op=limits { repo, roleLimits: { role: number } }
|
|
14
|
-
* POST /api/hive-runner?op=queen { sessionId }
|
|
14
|
+
* POST /api/hive-runner?op=queen { sessionId, repo }
|
|
15
15
|
*/
|
|
16
16
|
import { normalizeRepoKey } from './config.js';
|
|
17
17
|
import { UnknownRepoError } from './supervisor.js';
|
|
@@ -117,8 +117,25 @@ export async function handleHiveRunnerRequest(request, supervisor, anomalies) {
|
|
|
117
117
|
if (typeof sessionId !== 'string' || sessionId.trim() === '') {
|
|
118
118
|
return failure(op, 'hive/missing-session-id', 'sessionId is required (JSON body field)', 400);
|
|
119
119
|
}
|
|
120
|
+
const explicitRepo = typeof payload.repo === 'string'
|
|
121
|
+
? payload.repo
|
|
122
|
+
: url.searchParams.get('repo');
|
|
123
|
+
let repo = typeof explicitRepo === 'string' && explicitRepo.trim() !== '' ? explicitRepo.trim() : null;
|
|
124
|
+
if (repo === null) {
|
|
125
|
+
// Single-repository deployments keep the old payload shape; multi-repo
|
|
126
|
+
// callers must name the repository they are registering the queen for.
|
|
127
|
+
try {
|
|
128
|
+
const status = supervisor.status();
|
|
129
|
+
if (Array.isArray(status?.repos) && status.repos.length === 1) repo = status.repos[0].repo;
|
|
130
|
+
} catch {
|
|
131
|
+
repo = null;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (repo === null) {
|
|
135
|
+
return failure(op, 'hive/missing-repo', 'repo is required with sessionId when more than one repository is configured', 400);
|
|
136
|
+
}
|
|
120
137
|
try {
|
|
121
|
-
return json({ ok: true, op: 'queen', ...supervisor.setQueenSession(sessionId) });
|
|
138
|
+
return json({ ok: true, op: 'queen', ...supervisor.setQueenSession(sessionId, repo) });
|
|
122
139
|
} catch (error) {
|
|
123
140
|
return failure(op, 'hive/invalid-session-id', error instanceof Error ? error.message : String(error), 400);
|
|
124
141
|
}
|
package/lib/notify.js
CHANGED
|
@@ -102,17 +102,28 @@ export function deliverToSession({ ctx } = {}, sessionId, body, delivery = {}) {
|
|
|
102
102
|
|
|
103
103
|
/**
|
|
104
104
|
* Create the delivery facade.
|
|
105
|
-
* @param {{ ctx: object, queenSession
|
|
106
|
-
* @returns {{ deliver: (body: string) => { delivered: boolean, via?: string, reason?: string }, hasLiveQueen: () => boolean }}
|
|
105
|
+
* @param {{ ctx: object, queenSession?: { sessionId: string|null }, resolveSessionId?: (repo: string|undefined) => string|null, log?: (level: string, ...args: unknown[]) => void }} options
|
|
106
|
+
* @returns {{ deliver: (body: string, repo?: string) => { delivered: boolean, via?: string, reason?: string }, hasLiveQueen: (repo?: string) => boolean }}
|
|
107
107
|
*/
|
|
108
|
-
export function createQueenNotifier({ ctx, queenSession, log = () => {} } = {}) {
|
|
109
|
-
|
|
108
|
+
export function createQueenNotifier({ ctx, queenSession, resolveSessionId, log = () => {} } = {}) {
|
|
109
|
+
function sessionFor(repo) {
|
|
110
|
+
if (typeof resolveSessionId === 'function') {
|
|
111
|
+
const resolved = resolveSessionId(repo);
|
|
112
|
+
return typeof resolved === 'string' && resolved !== '' ? resolved : null;
|
|
113
|
+
}
|
|
114
|
+
const legacy = queenSession?.sessionId;
|
|
115
|
+
return typeof legacy === 'string' && legacy !== '' ? legacy : null;
|
|
116
|
+
}
|
|
117
|
+
const target = (repo) => {
|
|
118
|
+
const sessionId = sessionFor(repo);
|
|
119
|
+
return sessionId === null ? undefined : resolveAgent(ctx, sessionId);
|
|
120
|
+
};
|
|
110
121
|
|
|
111
|
-
function deliver(body) {
|
|
122
|
+
function deliver(body, repo) {
|
|
112
123
|
if (typeof body !== 'string' || body.trim() === '') {
|
|
113
124
|
return { delivered: false, reason: 'empty-digest' };
|
|
114
125
|
}
|
|
115
|
-
const agent = target();
|
|
126
|
+
const agent = target(repo);
|
|
116
127
|
if (agent === undefined) return { delivered: false, reason: 'no-live-queen-session' };
|
|
117
128
|
const message = createQueenMessage(body);
|
|
118
129
|
try {
|
|
@@ -138,7 +149,7 @@ export function createQueenNotifier({ ctx, queenSession, log = () => {} } = {})
|
|
|
138
149
|
|
|
139
150
|
return {
|
|
140
151
|
deliver,
|
|
141
|
-
hasLiveQueen: () => target() !== undefined,
|
|
152
|
+
hasLiveQueen: (repo) => target(repo) !== undefined,
|
|
142
153
|
};
|
|
143
154
|
}
|
|
144
155
|
|