dsh-hive-runner 1.0.16 → 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 CHANGED
@@ -7,6 +7,32 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
  Version 0.6.0 is the first public snapshot; 0.1.0-0.5.0 were local development
8
8
  iterations of the plugin before this repository was published.
9
9
 
10
+ ## [1.0.17] - 2026-12-05
11
+
12
+ ### Added
13
+
14
+ - Queen-only `hive_ops` with an explicit action enum (`status`, `pause`, `resume`,
15
+ `limits`, `run-round`, `health`, `services`, `diagnose`, `test`, `typecheck`, `build`)
16
+ instead of an open shell. `diagnose` accepts only `git status/log/diff/show`, `ls`,
17
+ `curl 127.0.0.1` and `lsof` (plus `.hive/ops.yaml` extensions); `test/typecheck/build`
18
+ run only the fixed pnpm script. Shell actions use the sandboxed shell seam with a
19
+ 120 s timeout and 64 KiB output cap; all actions/denials write a `hive_ops` event.
20
+ Repository isolation is enforced by the common hive_* wrapper and queen-only callers.
21
+ - Long-running services are agent work, not a human step: `.hive/services.yaml` declares
22
+ name/command/port/health; a service-role card starts the declared command detached
23
+ (`setsid nohup … >> .hive/services/<name>.log 2>&1 &`) and records PID/port in
24
+ `.hive/services/<name>.json`; acceptance is the local health check. The patrol probes
25
+ declared ports, emits `service_down`/`service_started`, and creates/reopens a service
26
+ card when a service is down. `hive_ops action=services` lists them; undeclared
27
+ commands/ports are rejected.
28
+
29
+ ### Tests
30
+
31
+ - Action enum mapping, diagnose allow/deny/extension, long-running rejection, 120 s
32
+ timeout/64 KiB truncation and `hive_ops` events; service declaration validation,
33
+ detached start/PID record, health acceptance, down/recovery redispatch and failed-card
34
+ reopen. 271 tests pass.
35
+
10
36
  ## [1.0.16] - 2026-12-05
11
37
 
12
38
  ### Fixed — hard repository isolation (release blocker)
@@ -37,6 +63,10 @@ iterations of the plugin before this repository was published.
37
63
  `hive_tasks`/`hive_intervene`/`hive_arch_review`/`hive_board`/`hive_events`,
38
64
  event-path symlink escape, recovery, and grouped status. 258 tests pass.
39
65
 
66
+ ### Published
67
+
68
+ - npm: `dsh-hive-runner@1.0.16` on 2026-12-05.
69
+
40
70
  ## [1.0.15] - 2026-12-05
41
71
 
42
72
  ### Fixed
package/README.md CHANGED
@@ -98,6 +98,7 @@ she must act on. The authoritative contract is `<repo>/.hive/roles/queen.md` (wr
98
98
  | `hive_anomalies` | `list`/`ack` the pending anomaly digest, `patrol` runs one audit tick now |
99
99
  | `hive_intervene` | act on a stuck task (reopen/split/reassign/remove/rebuild/pause/fail/guide/escalate) and record it as an event |
100
100
  | `hive_run_round` | run one round on demand (a registered queen Session is required) |
101
+ | `hive_ops` | queen-only operational actions: `status`/`pause`/`resume`/`limits`/`run-round`/`health`/`services` plus the whitelisted `diagnose` and fixed `test`/`typecheck`/`build`; no shell escape, 120 s timeout, 64 KiB cap |
101
102
 
102
103
  The tool surface keeps the boundary: none of the queen's tools claims or finishes a task
103
104
  (`hive-tasks claim` / `done` belong to agents and the supervisor), and none edits or
@@ -164,6 +165,19 @@ confirm release. The same state is sent once; a state change re-arms it. With no
164
165
  queen Session the checkpoint stays pending (`pendingCheckpoints` in status) and is
165
166
  flushed on the next patrol/registration.
166
167
 
168
+ ### Long-running services
169
+
170
+ Long-running processes are agent work, not a human step. A repository can declare
171
+ its services in `.hive/services.yaml` (`name`, `command`, `port`, optional 127.0.0.1
172
+ `health`). A `service`-role card starts one with a detached
173
+ `setsid nohup <command> >> .hive/services/<name>.log 2>&1 &` and records
174
+ `.hive/services/<name>.json` (PID/port). The acceptance command is a local health
175
+ check, so the card can be done while the service keeps running. The patrol reads the
176
+ records, probes the declared ports, and creates/reopens a service card when a service
177
+ is down, recording `service_down` / `service_started` events. `hive_ops action=services`
178
+ shows declared/running state; commands and ports outside `.hive/services.yaml` are
179
+ rejected.
180
+
167
181
  ### The gates the queen orchestrates
168
182
 
169
183
  1. **Single task**: the agent commits and the task acceptance command must pass.
package/SPEC.md CHANGED
@@ -252,7 +252,18 @@ repository unless it is that default.
252
252
  | `hive_supervisor_control` | `action` = `status`/`pause`/`resume`/`limits`, `repo`, `reason`, `roleLimits` | Supervisor/repository snapshot |
253
253
  | `hive_anomalies` | `action` = `list`/`ack`/`patrol`, `ids`, `all`, `limit` | Pending digest queue or one patrol result |
254
254
  | `hive_intervene` | `repo`, `action: reopen|split|reassign|pause|abort|fail|guide|supersede|remove|rebuild|escalate`, `card`, `reason`, `cards[]`, `role`, `sessionId` | The intervention event, created tasks, intervention count and escalation flag |
255
-
255
+ | `hive_ops` | `repo`, `action: status|pause|resume|limits|run-round|health|diagnose|test|typecheck|build|services`, `args?` | Queen-only operational action result; `diagnose` is restricted to the read-only whitelist, shell actions have a 120 s timeout and 64 KiB cap, and every action/denial appends a `hive_ops` event |
256
+
257
+ ### 7.1 Long-running services
258
+
259
+ `.hive/services.yaml` is the only service allowlist: each entry declares `name`,
260
+ `command`, `port` and an optional 127.0.0.1 `health`. A `service`-role card starts the
261
+ declared command detached (`setsid nohup <command> >> .hive/services/<name>.log 2>&1 &`),
262
+ writes `.hive/services/<name>.json` with pointer/PID/port, and its acceptance is the local
263
+ health check; the card can be done while the service keeps running. The patrol reads the
264
+ records, probes the declared ports, and creates or reopens a service card when a service
265
+ is down, emitting `service_down`/`service_started` events. Commands or ports outside the
266
+ YAML are rejected. `hive_ops action=services` lists declared/running state.
256
267
  The queen's tools never claim or finish a task: `hive-tasks claim`/`done` stay with the
257
268
  supervisor. `hive tasks rm` is forwarded without `--force`, so a claimed task is refused
258
269
  by the CLI instead of being deleted under a live agent. `hive_run_round` refuses to run
package/docs/DESIGN.md CHANGED
@@ -291,6 +291,8 @@ auto-pause failure budget; status exposes `claimedButOrphaned`,
291
291
  | `lib/config.js` | Config defaults/validation (`patrolIntervalMs`, `notifyQueen`, `anomaly*`, `checkpoint*`, `rolesBin`), role map parsing, effective-limit helpers |
292
292
  | `lib/commands.js` | Allowlisted `hive-tasks` / `hive` / `git` / acceptance commands with shell quoting; queen verbs list/add/edit/split/supersede/reopen/retry/rm/lesson/roles |
293
293
  | `lib/shell.js` | `ctx.shell.resolve/execute` adapter (sandbox policy per call) |
294
+ | `lib/ops.js` | Queen-only `hive_ops` action enum and `diagnose` whitelist: action plan, read-only command validation, 64-KiB truncation, 120-s timeout, `hive_ops` events |
295
+ | `lib/services.js` | `.hive/services.yaml` allowlist + `.hive/services/<name>.json` records: detached start command/health acceptance, port probes, patrol `service_down`/`service_started` and service-card redispatch |
294
296
  | `lib/discover.js` | `refs/hive/v1` repository discovery |
295
297
  | `lib/http.js` | `/api/hive-runner` Fetch route (status/pending/ack/pause/resume/limits/queen) |
296
298
 
@@ -385,6 +387,25 @@ writes the same durable `arch_review` event through the shared host writer. The
385
387
  `hive_events` tool remains read-only and can verify the event; a host/panel caller can
386
388
  also invoke the service method directly.
387
389
 
390
+ ### Queen operations and services
391
+
392
+ `hive_ops` is an action enum, not a shell: `status`, `pause`, `resume`, `limits`,
393
+ `run-round`, `health`, `services`, `diagnose`, `test`, `typecheck`, `build`. Only
394
+ `diagnose` executes a command, restricted to `git status/log/diff/show`, `ls`,
395
+ `curl 127.0.0.1`, `lsof` plus `.hive/ops.yaml` extensions; `test`/`typecheck`/`build`
396
+ run only the fixed pnpm script. Shell actions use the DSH shell seam with a 120-second
397
+ timeout and 64-KiB output cap. `hive_ops` is queen-only and the common tool wrapper
398
+ enforces the repo=cwd rule before the body; every action/denial appends a `hive_ops`
399
+ event.
400
+
401
+ Long-running services are agent work: `.hive/services.yaml` declares name/command/port
402
+ and health. A service-role worker starts `setsid nohup <command> >>
403
+ .hive/services/<name>.log 2>&1 &`, writes `.hive/services/<name>.json` (PID/port), and
404
+ uses the local health URL as acceptance. The patrol probes declared ports, records
405
+ `service_down`/`service_started`, and creates or reopens a `service` card when a
406
+ service disappears; `hive_ops action=services` reports the declared/running state.
407
+ Commands or ports not in the YAML are rejected.
408
+
388
409
  ### Repository isolation (hard, mechanical)
389
410
 
390
411
  Every layer is scoped by repository; the model is never trusted for this:
package/index.js CHANGED
@@ -52,6 +52,9 @@ import {
52
52
  recordQueenBoundaryViolation as recordQueenBoundaryAttempt,
53
53
  } from './lib/queen-boundary.js';
54
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';
55
58
  import { createRoundRunner } from './lib/round.js';
56
59
  import { readRunRecord } from './lib/runs.js';
57
60
  import { HiveSupervisor } from './lib/supervisor.js';
@@ -149,6 +152,8 @@ export function apply(ctx, config = {}) {
149
152
  let patrol;
150
153
  /** @type {ReturnType<typeof createCheckpointController> | undefined} */
151
154
  let checkpoint;
155
+ /** Per-repo set of currently-down services (patrol event/dedup state). */
156
+ const serviceOutages = new Map();
152
157
  function recordAnomaly(event) {
153
158
  try {
154
159
  anomalies.push(event);
@@ -264,6 +269,8 @@ export function apply(ctx, config = {}) {
264
269
  resolveSessionId: (repo) => supervisor.queenFor(repo),
265
270
  log,
266
271
  });
272
+ // hive_ops uses the same sandboxed shell seam as the rest of the plugin.
273
+ const opsRun = createShellRunner({ ctx, config: resolved });
267
274
  // Done cards must carry an arch_review event; the patrol audits the board and
268
275
  // turns a missing review into an arch-review-missing anomaly.
269
276
  const archReviewAudit = createArchReviewAudit({
@@ -342,6 +349,16 @@ export function apply(ctx, config = {}) {
342
349
  } catch (error) {
343
350
  log('warn', 'arch review audit failed for ' + repo + ': ' + (error instanceof Error ? error.message : String(error)));
344
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
+ }
345
362
  }
346
363
  // Retry the one-shot tool listing if the panel registered before the agent
347
364
  // was live (status/queenTools then contains an error until this succeeds).
@@ -440,6 +457,43 @@ export function apply(ctx, config = {}) {
440
457
  }));
441
458
  }
442
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
+ }
443
497
  const repoParameter = {
444
498
  type: 'string',
445
499
  description: 'Repository path. Default: the configured cwd.',
@@ -457,44 +511,7 @@ export function apply(ctx, config = {}) {
457
511
  ttl: { type: 'string', description: 'Claim TTL, for example 5m.' },
458
512
  agent: { type: 'string', description: 'Identity used for claims. Default: config.agent.' },
459
513
  },
460
- execute: async (args = {}, exec) => {
461
- const repo = repoOf(args);
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
- // The manual round obeys the same gate order as the resident supervisor.
470
- const gateResult = await supervisor.filterDispatchable(repo, cards, { signal });
471
- const dispatchable = gateResult.cards;
472
- const outcome = await drainQueue({
473
- queue: dispatchable.map((card) => ({ role: card.role, card, claimed: false })),
474
- roleNames: limits.rolesFor(repo, cards.map((card) => card.role)),
475
- limitFor: (role) => limits.limitFor(repo, role),
476
- runCard: (item) => runner.runCard({
477
- repo,
478
- card: item.card,
479
- claimed: item.claimed === true,
480
- signal,
481
- session,
482
- parent: exec?.agent,
483
- agent: args.agent,
484
- ttl: args.ttl,
485
- }),
486
- capacityRetryMs: resolved.capacityRetryMs,
487
- signal,
488
- });
489
- if (outcome.error !== undefined) throw outcome.error;
490
- return jsonText({
491
- repo,
492
- gate: gateResult.gate,
493
- results: outcome.results,
494
- state: outcome.state,
495
- queued: outcome.queue.length,
496
- });
497
- },
514
+ execute: async (args = {}, exec) => jsonText(await runRoundForRepo(repoOf(args), args, exec)),
498
515
  });
499
516
 
500
517
  registerTextTool({
@@ -736,6 +753,114 @@ export function apply(ctx, config = {}) {
736
753
  },
737
754
  });
738
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
+ });
739
864
  registerTextTool({
740
865
  name: 'hive_events',
741
866
  description:
package/lib/ops.js ADDED
@@ -0,0 +1,387 @@
1
+ /**
2
+ * Queen-only operational commands (`hive_ops`).
3
+ *
4
+ * Commands are parsed into argv and checked against a read-only default policy
5
+ * plus optional `<repo>/.hive/ops.yaml` extensions. They run through the DSH
6
+ * shell seam (sandbox + cancellation), never child_process, with a hard timeout,
7
+ * 64 KiB output cap, and a durable `hive_ops` event per execution.
8
+ *
9
+ * @module dsh-hive-runner/ops
10
+ */
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+
14
+ import { appendEvent } from './events.js';
15
+
16
+ /** Hard output cap for one hive_ops result (stdout + stderr). */
17
+ export const OPS_MAX_OUTPUT_BYTES = 64 * 1024;
18
+ /** Hard timeout for one hive_ops command. */
19
+ export const OPS_TIMEOUT_MS = 120_000;
20
+ /** Exact message for dev/serve/watch attempts. */
21
+ export const OPS_LONG_RUNNING_MESSAGE = '长驻服务由面板/宿主启动或建 ops 任务';
22
+
23
+ /** The complete action enum. Nothing outside this list is callable. */
24
+ export const OPS_ACTIONS = Object.freeze([
25
+ 'status', 'pause', 'resume', 'limits', 'run-round', 'health',
26
+ 'diagnose', 'test', 'typecheck', 'build', 'services',
27
+ ]);
28
+
29
+ const GIT_DIAGNOSE = new Set(['status', 'log', 'diff', 'show']);
30
+ const GIT_MUTATING = new Set(['add', 'am', 'apply', 'checkout', 'cherry-pick', 'clean', 'commit', 'config', 'merge', 'mv', 'pull', 'push', 'rebase', 'reset', 'restore', 'revert', 'rm', 'stash', 'switch', 'tag', 'update-index', 'update-ref', 'fetch', 'gc', 'prune']);
31
+
32
+ const LONG_RUNNING_TOKENS = new Set(['dev', 'serve', 'watch']);
33
+ const DENIED_COMMANDS = new Set([
34
+ 'rm', 'rmdir', 'mv', 'cp', 'touch', 'mkdir', 'chmod', 'chown', 'ln', 'tee',
35
+ 'dd', 'truncate', 'shred', 'bash', 'sh', 'zsh', 'fish', 'node', 'python',
36
+ 'python3', 'ruby', 'perl', 'env', 'nohup', 'sudo', 'su', 'kill', 'pkill',
37
+ ]);
38
+ const CURL_WRITE_FLAGS = new Set(['-o', '--output', '-O', '--remote-name', '-T', '--upload-file', '-d', '--data', '--data-raw', '--data-binary', '-F', '--form']);
39
+ const SHELL_META = /[;&|<>$`\n\r]/;
40
+ const OPS_YAML_KEYS = new Set(['allow', 'allowed', 'commands', 'allowed_commands', 'ops']);
41
+
42
+ function bad(message, code = 'denied') {
43
+ const error = new Error(message);
44
+ error.code = code;
45
+ return error;
46
+ }
47
+
48
+ /** Tokenize a command into argv, rejecting shell metacharacters. */
49
+ export function tokenizeOpsCommand(command) {
50
+ if (typeof command !== 'string' || command.trim() === '') throw bad('hive_ops needs command');
51
+ if (SHELL_META.test(command)) throw bad('运维命令不允许 shell 元字符(; | & < > $ \` 换行)');
52
+ const argv = [];
53
+ let current = '';
54
+ let quote = null;
55
+ for (const ch of command.trim()) {
56
+ if (quote !== null) {
57
+ if (ch === quote) quote = null;
58
+ else current += ch;
59
+ continue;
60
+ }
61
+ if (ch === '"' || ch === "'") {
62
+ quote = ch;
63
+ continue;
64
+ }
65
+ if (/\s/.test(ch)) {
66
+ if (current !== '') {
67
+ argv.push(current);
68
+ current = '';
69
+ }
70
+ continue;
71
+ }
72
+ current += ch;
73
+ }
74
+ if (quote !== null) throw bad('运维命令引号未闭合');
75
+ if (current !== '') argv.push(current);
76
+ if (argv.length === 0) throw bad('hive_ops needs command');
77
+ return argv;
78
+ }
79
+
80
+ /** Shell-quote argv so the shell seam receives exactly the validated tokens. */
81
+ export function quoteOpsArgv(argv) {
82
+ return argv.map((arg) => {
83
+ if (/^[A-Za-z0-9_./:=@%+,-]+$/.test(arg)) return arg;
84
+ return "'" + arg.replace(/'/g, "'\\''") + "'";
85
+ }).join(' ');
86
+ }
87
+
88
+ /** Parse the small YAML subset accepted in .hive/ops.yaml. */
89
+ export function parseOpsYaml(text) {
90
+ if (typeof text !== 'string' || text.trim() === '') return [];
91
+ const entries = [];
92
+ let section = false;
93
+ for (const rawLine of text.split(/\r?\n/)) {
94
+ const line = rawLine.replace(/^\s*#.*$/, '');
95
+ if (line.trim() === '') continue;
96
+ const item = line.match(/^\s*-\s*(.*)$/);
97
+ if (item !== null) {
98
+ if (!section) continue;
99
+ let value = item[1].trim();
100
+ if (value === '') continue;
101
+ const commandMatch = value.match(/^command\s*:\s*(.*)$/);
102
+ if (commandMatch !== null) value = commandMatch[1].trim();
103
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
104
+ value = value.slice(1, -1);
105
+ }
106
+ if (value !== '') entries.push(value);
107
+ continue;
108
+ }
109
+ const header = line.match(/^\s*([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/);
110
+ if (header !== null) {
111
+ const key = header[1];
112
+ const rest = header[2].trim();
113
+ section = OPS_YAML_KEYS.has(key);
114
+ if (section && rest.startsWith('[') && rest.endsWith(']')) {
115
+ for (const part of rest.slice(1, -1).split(',')) {
116
+ const value = part.trim().replace(/^["']|["']$/g, '');
117
+ if (value !== '') entries.push(value);
118
+ }
119
+ }
120
+ continue;
121
+ }
122
+ }
123
+ return entries;
124
+ }
125
+
126
+ /** Load the optional per-repository extension entries (absolute repo path). */
127
+ export function loadOpsPolicy(repo, options = {}) {
128
+ const readFileSync = options.readFileSync ?? fs.readFileSync;
129
+ const existsSync = options.existsSync ?? fs.existsSync;
130
+ const file = path.join(repo, '.hive', 'ops.yaml');
131
+ let text = '';
132
+ try {
133
+ if (!existsSync(file)) return { entries: [], file: null };
134
+ text = String(readFileSync(file, 'utf8'));
135
+ } catch (error) {
136
+ throw new Error('cannot read .hive/ops.yaml: ' + (error instanceof Error ? error.message : String(error)));
137
+ }
138
+ const entries = [];
139
+ for (const value of parseOpsYaml(text)) {
140
+ const argv = tokenizeOpsCommand(value);
141
+ entries.push({ command: value, argv });
142
+ }
143
+ return { entries, file };
144
+ }
145
+
146
+ function withinRepo(repo, value) {
147
+ if (typeof value !== 'string' || value === '') return false;
148
+ if (path.isAbsolute(value)) return false;
149
+ const resolved = path.resolve(repo, value);
150
+ return resolved === repo || resolved.startsWith(repo + path.sep);
151
+ }
152
+
153
+ function validateCurl(argv) {
154
+ const urls = [];
155
+ for (let i = 1; i < argv.length; i += 1) {
156
+ const token = argv[i];
157
+ if (CURL_WRITE_FLAGS.has(token)) throw bad('curl 只允许只读 GET 请求');
158
+ if (token === '-X' || token === '--request') {
159
+ const method = argv[i + 1];
160
+ if (typeof method !== 'string' || method.toUpperCase() !== 'GET') throw bad('curl 只允许只读 GET 请求');
161
+ i += 1;
162
+ continue;
163
+ }
164
+ if (token.startsWith('-')) continue;
165
+ urls.push(token);
166
+ }
167
+ if (urls.length === 0) throw bad('curl 需要 127.0.0.1 地址');
168
+ for (const url of urls) {
169
+ if (!/^https?:\/\/127\.0\.0\.1(?::\d+)?(?:\/|$)/i.test(url)) {
170
+ throw bad('curl 只允许访问 127.0.0.1');
171
+ }
172
+ }
173
+ }
174
+
175
+ function validatePaths(repo, argv) {
176
+ for (const token of argv.slice(1)) {
177
+ if (token.startsWith('-')) continue;
178
+ if (!withinRepo(repo, token)) throw bad('路径必须位于当前仓库内:' + token);
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Validate one argv against the default policy + ops.yaml extensions.
184
+ * @param {string[]} argv
185
+ * @param {{ repo: string, policy?: { entries?: Array<{ argv: string[] }> } }} options
186
+ * @returns {string} the command name
187
+ */
188
+ export function validateOpsCommand(argv, { repo, policy = { entries: [] } } = {}) {
189
+ if (!Array.isArray(argv) || argv.length === 0) throw bad('hive_ops needs command');
190
+ if (typeof repo !== 'string' || repo === '') throw bad('hive_ops needs repo');
191
+ for (const token of argv) {
192
+ if (LONG_RUNNING_TOKENS.has(token)) throw bad(OPS_LONG_RUNNING_MESSAGE, 'long-running');
193
+ }
194
+ const command = argv[0];
195
+ if (DENIED_COMMANDS.has(command)) throw bad('禁止修改源码或启动交互命令:' + command);
196
+ if (command === 'git') {
197
+ const sub = argv[1];
198
+ if (argv.some((token) => token.startsWith('--output') || token === '--ext-diff' || token === '--textconv')) {
199
+ throw bad('git 运维命令不允许写文件或执行外部 diff 程序');
200
+ }
201
+ if (sub !== undefined && GIT_MUTATING.has(sub)) throw bad('diagnose 的 git 只允许 status/log/diff/show');
202
+ if (sub === undefined || !GIT_DIAGNOSE.has(sub)) {
203
+ if (!matchesExtension(argv, policy)) throw bad('diagnose 的 git 只允许 status/log/diff/show');
204
+ }
205
+ return command;
206
+ }
207
+ if (command === 'curl') {
208
+ validateCurl(argv);
209
+ return command;
210
+ }
211
+ if (command === 'ls') {
212
+ validatePaths(repo, argv);
213
+ return command;
214
+ }
215
+ if (command === 'lsof') return command;
216
+ if (matchesExtension(argv, policy)) return command;
217
+ throw bad('diagnose 命令不在白名单:' + argv.join(' '));
218
+ }
219
+
220
+ /** Normalize the free-form args field into shell tokens + host payload. */
221
+ function parseActionArgs(args) {
222
+ if (args === undefined || args === null || args === '') return { tokens: [], data: {} };
223
+ if (Array.isArray(args)) return { tokens: args.map((token) => String(token)), data: {} };
224
+ if (typeof args === 'string') return { tokens: tokenizeOpsCommand(args), data: {} };
225
+ if (typeof args === 'object') {
226
+ const command = args.command ?? args.cmd;
227
+ const tokens = Array.isArray(command)
228
+ ? command.map((token) => String(token))
229
+ : (typeof command === 'string' ? tokenizeOpsCommand(command) : []);
230
+ return { tokens, data: args };
231
+ }
232
+ throw bad('hive_ops args must be an array, string or object');
233
+ }
234
+
235
+ /**
236
+ * Turn one enum action into a host plan or a validated shell argv. This is the
237
+ * single gate between the model-facing action enum and host capabilities.
238
+ * @param {string} action
239
+ * @param {unknown} [args]
240
+ * @param {{ repo: string, policy?: object }} [options]
241
+ */
242
+ export function planOpsAction(action, args, { repo, policy = { entries: [] } } = {}) {
243
+ if (!OPS_ACTIONS.includes(action)) throw bad('unknown hive_ops action: ' + String(action));
244
+ const parsed = parseActionArgs(args);
245
+ for (const token of parsed.tokens) {
246
+ if (LONG_RUNNING_TOKENS.has(token)) throw bad(OPS_LONG_RUNNING_MESSAGE, 'long-running');
247
+ }
248
+ if (action === 'diagnose') {
249
+ const argv = parsed.tokens.length > 0 ? parsed.tokens : ['git', 'status'];
250
+ validateOpsCommand(argv, { repo, policy });
251
+ return { kind: 'shell', action, argv };
252
+ }
253
+ if (action === 'test' || action === 'typecheck' || action === 'build') {
254
+ if (parsed.tokens.length > 0) throw bad(action + ' does not accept args');
255
+ return { kind: 'shell', action, argv: ['pnpm', action] };
256
+ }
257
+ return { kind: 'host', action, args, tokens: parsed.tokens, data: parsed.data };
258
+ }
259
+ function matchesExtension(argv, policy) {
260
+ const entries = Array.isArray(policy?.entries) ? policy.entries : [];
261
+ return entries.some((entry) => Array.isArray(entry.argv)
262
+ && entry.argv.length > 0
263
+ && entry.argv.length <= argv.length
264
+ && entry.argv.every((token, index) => argv[index] === token));
265
+ }
266
+
267
+ /** UTF-8 byte-aware truncation with an explicit marker. */
268
+ export function truncateOpsOutput(text, maxBytes = OPS_MAX_OUTPUT_BYTES) {
269
+ const value = String(text ?? '');
270
+ if (Buffer.byteLength(value, 'utf8') <= maxBytes) return { text: value, truncated: false };
271
+ let out = '';
272
+ let bytes = 0;
273
+ for (const ch of value) {
274
+ const next = Buffer.byteLength(ch, 'utf8');
275
+ if (bytes + next > maxBytes) break;
276
+ out += ch;
277
+ bytes += next;
278
+ }
279
+ return { text: out + '\n…[truncated at ' + String(maxBytes) + ' bytes]', truncated: true };
280
+ }
281
+
282
+ /**
283
+ * Execute one validated command and append a hive_ops event.
284
+ * @param {{
285
+ * repo: string,
286
+ * command?: string,
287
+ * argv?: string[],
288
+ * action?: string,
289
+ * validate?: boolean,
290
+ * run: Function,
291
+ * session?: object,
292
+ * signal?: AbortSignal,
293
+ * policy?: object,
294
+ * timeoutMs?: number,
295
+ * append?: Function,
296
+ * now?: () => number,
297
+ * }} options
298
+ */
299
+ export async function runOpsCommand({
300
+ repo,
301
+ command,
302
+ argv: inputArgv,
303
+ action = 'diagnose',
304
+ validate = true,
305
+ run,
306
+ session,
307
+ signal,
308
+ policy,
309
+ timeoutMs = OPS_TIMEOUT_MS,
310
+ append = appendEvent,
311
+ now = () => Date.now(),
312
+ } = {}) {
313
+ if (typeof run !== 'function') throw new TypeError('runOpsCommand: run is required');
314
+ const argv = Array.isArray(inputArgv) ? inputArgv : tokenizeOpsCommand(command);
315
+ for (const token of argv) {
316
+ if (LONG_RUNNING_TOKENS.has(token)) throw bad(OPS_LONG_RUNNING_MESSAGE, 'long-running');
317
+ }
318
+ if (validate) validateOpsCommand(argv, { repo, policy });
319
+ const startedAt = now();
320
+ let result;
321
+ try {
322
+ result = await run(quoteOpsArgv(argv), {
323
+ workdir: repo,
324
+ session,
325
+ signal,
326
+ timeoutMs,
327
+ stdoutMaxBytes: OPS_MAX_OUTPUT_BYTES,
328
+ });
329
+ } catch (error) {
330
+ const event = {
331
+ ts: new Date(startedAt).toISOString(),
332
+ actor: 'hive-runner',
333
+ kind: 'hive_ops',
334
+ action,
335
+ command: argv.join(' '),
336
+ exitCode: null,
337
+ timedOut: false,
338
+ truncated: false,
339
+ durationMs: now() - startedAt,
340
+ error: error instanceof Error ? error.message : String(error),
341
+ };
342
+ append(repo, event);
343
+ if (error !== null && typeof error === 'object') error.opsEventRecorded = true;
344
+ throw error;
345
+ }
346
+ const stdout = truncateOpsOutput(result?.stdout ?? '', OPS_MAX_OUTPUT_BYTES);
347
+ let stderrBudget = OPS_MAX_OUTPUT_BYTES - Buffer.byteLength(stdout.text, 'utf8');
348
+ if (stderrBudget < 0) stderrBudget = 0;
349
+ const stderr = truncateOpsOutput(result?.stderr ?? '', stderrBudget);
350
+ const event = {
351
+ ts: new Date(startedAt).toISOString(),
352
+ actor: 'hive-runner',
353
+ kind: 'hive_ops',
354
+ action,
355
+ command: argv.join(' '),
356
+ exitCode: result?.exitCode ?? null,
357
+ signal: result?.signal ?? null,
358
+ timedOut: result?.timedOut === true,
359
+ truncated: stdout.truncated || stderr.truncated,
360
+ durationMs: now() - startedAt,
361
+ };
362
+ append(repo, event);
363
+ return {
364
+ command: argv.join(' '),
365
+ exitCode: result?.exitCode ?? null,
366
+ signal: result?.signal ?? null,
367
+ timedOut: result?.timedOut === true,
368
+ stdout: stdout.text,
369
+ stderr: stderr.text,
370
+ truncated: stdout.truncated || stderr.truncated,
371
+ event,
372
+ };
373
+ }
374
+
375
+ /** Short deny helper used by the tool layer to record denied attempts. */
376
+ export function opsDeniedEvent(repo, action, args, error, sessionId = null) {
377
+ return {
378
+ ts: new Date().toISOString(),
379
+ actor: 'hive-runner',
380
+ kind: 'hive_ops',
381
+ action: typeof action === 'string' ? action : null,
382
+ args: args ?? null,
383
+ allowed: false,
384
+ reason: error instanceof Error ? error.message : String(error),
385
+ sessionId,
386
+ };
387
+ }
@@ -0,0 +1,274 @@
1
+ /**
2
+ * Declared long-running services for a repository.
3
+ *
4
+ * `.hive/services.yaml` is the single allowlist: only declared name/command/port
5
+ * pairs may be started, inspected or re-dispatched. Service workers start them as
6
+ * detached processes and persist `.hive/services/<name>.json`; the patrol probes
7
+ * the declared port and creates/reopens a `service` card when it is down.
8
+ *
9
+ * @module dsh-hive-runner/services
10
+ */
11
+ import fs from 'node:fs';
12
+ import net from 'node:net';
13
+ import path from 'node:path';
14
+
15
+ import { appendEvent } from './events.js';
16
+
17
+ export const SERVICES_FILE = path.join('.hive', 'services.yaml');
18
+ export const SERVICES_DIR = path.join('.hive', 'services');
19
+ export const SERVICE_ROLE = 'service';
20
+ export const SERVICE_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
21
+ const SHELL_META = /[;&|<>$`\n\r]/;
22
+ const SERVICE_DENIED_COMMANDS = new Set(['rm', 'rmdir', 'mv', 'cp', 'touch', 'mkdir', 'chmod', 'chown', 'tee', 'dd', 'truncate', 'shred']);
23
+
24
+ function bad(message) {
25
+ const error = new Error(message);
26
+ error.code = 'service-denied';
27
+ return error;
28
+ }
29
+
30
+ function unquote(value) {
31
+ const trimmed = String(value ?? '').trim();
32
+ if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
33
+ return trimmed.slice(1, -1);
34
+ }
35
+ return trimmed;
36
+ }
37
+
38
+ /** Parse the small services.yaml subset: a list of name/command/port objects. */
39
+ export function parseServicesYaml(text) {
40
+ if (typeof text !== 'string' || text.trim() === '') return [];
41
+ const declarations = [];
42
+ let current = null;
43
+ for (const rawLine of text.split(/\r?\n/)) {
44
+ const line = rawLine.replace(/^\s*#.*$/, '');
45
+ if (line.trim() === '') continue;
46
+ const item = line.match(/^\s*-\s*(.*)$/);
47
+ if (item !== null) {
48
+ if (current !== null) declarations.push(current);
49
+ current = {};
50
+ const pair = item[1].match(/^([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/);
51
+ if (pair !== null) current[pair[1]] = unquote(pair[2]);
52
+ continue;
53
+ }
54
+ const pair = line.match(/^\s*([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/);
55
+ if (pair !== null && current !== null) current[pair[1]] = unquote(pair[2]);
56
+ }
57
+ if (current !== null) declarations.push(current);
58
+ return declarations;
59
+ }
60
+
61
+ function normalizeDeclaration(raw) {
62
+ const name = typeof raw?.name === 'string' ? raw.name.trim() : '';
63
+ if (!SERVICE_NAME_RE.test(name)) throw bad('services.yaml: invalid service name ' + JSON.stringify(name));
64
+ const command = typeof raw?.command === 'string' ? raw.command.trim() : '';
65
+ if (command === '') throw bad('services.yaml: service ' + name + ' needs command');
66
+ if (SHELL_META.test(command)) throw bad('services.yaml: service ' + name + ' command contains shell metacharacters');
67
+ const executable = command.split(/\s+/)[0];
68
+ if (SERVICE_DENIED_COMMANDS.has(executable)) throw bad('services.yaml: service ' + name + ' command would modify source files');
69
+ if (executable === 'git' && command.split(/\s+/)[1] !== undefined && !['status', 'log', 'diff', 'show', 'branch'].includes(command.split(/\s+/)[1])) {
70
+ throw bad('services.yaml: service ' + name + ' git command is not read-only');
71
+ }
72
+ const port = Number(raw?.port);
73
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw bad('services.yaml: service ' + name + ' needs port 1..65535');
74
+ const health = typeof raw?.health === 'string' && raw.health.trim() !== ''
75
+ ? raw.health.trim()
76
+ : 'http://127.0.0.1:' + String(port);
77
+ if (!/^https?:\/\/127\.0\.0\.1(?::\d+)?(?:\/|$)/i.test(health)) {
78
+ throw bad('services.yaml: service ' + name + ' health must target 127.0.0.1');
79
+ }
80
+ return { name, command, port, health };
81
+ }
82
+
83
+ /** Load and validate declared services; an empty/missing file allows none. */
84
+ export function loadServiceDeclarations(repo, options = {}) {
85
+ const readFileSync = options.readFileSync ?? fs.readFileSync;
86
+ const existsSync = options.existsSync ?? fs.existsSync;
87
+ const file = path.join(repo, SERVICES_FILE);
88
+ try {
89
+ if (!existsSync(file)) return [];
90
+ const raw = parseServicesYaml(String(readFileSync(file, 'utf8')));
91
+ const declarations = raw.map(normalizeDeclaration);
92
+ const names = new Set();
93
+ for (const declaration of declarations) {
94
+ if (names.has(declaration.name)) throw bad('services.yaml: duplicate service ' + declaration.name);
95
+ names.add(declaration.name);
96
+ }
97
+ return declarations;
98
+ } catch (error) {
99
+ if (error?.code === 'service-denied') throw error;
100
+ throw new Error('cannot read .hive/services.yaml: ' + (error instanceof Error ? error.message : String(error)));
101
+ }
102
+ }
103
+
104
+ /** Find one declared service; anything else is outside the allowlist. */
105
+ export function findService(repo, name) {
106
+ const declarations = loadServiceDeclarations(repo);
107
+ const declaration = declarations.find((entry) => entry.name === name);
108
+ if (declaration === undefined) throw bad('service not declared in .hive/services.yaml: ' + String(name));
109
+ return declaration;
110
+ }
111
+
112
+ /** Detached start command required for service workers. */
113
+ export function serviceStartCommand(declaration) {
114
+ const log = path.join(SERVICES_DIR, declaration.name + '.log');
115
+ return 'setsid nohup ' + declaration.command + ' >> ' + log + ' 2>&1 & echo $!';
116
+ }
117
+
118
+ /** Acceptance command: health check through the declared local URL. */
119
+ export function serviceAcceptance(declaration) {
120
+ return 'curl -sf ' + declaration.health + ' >/dev/null';
121
+ }
122
+
123
+ function recordPath(repo, name) {
124
+ return path.join(repo, SERVICES_DIR, name + '.json');
125
+ }
126
+
127
+ /** Read all service runtime records, ignoring unreadable files. */
128
+ export function readServiceRecords(repo) {
129
+ const dir = path.join(repo, SERVICES_DIR);
130
+ let names = [];
131
+ try { names = fs.readdirSync(dir); } catch { return []; }
132
+ const records = [];
133
+ for (const file of names) {
134
+ if (!file.endsWith('.json')) continue;
135
+ try {
136
+ const record = JSON.parse(fs.readFileSync(path.join(dir, file), 'utf8'));
137
+ if (record !== null && typeof record === 'object' && typeof record.name === 'string') records.push(record);
138
+ } catch {
139
+ // A half-written record is ignored; the next start rewrites it.
140
+ }
141
+ }
142
+ return records;
143
+ }
144
+
145
+ /** Probe a local TCP port; injectable for tests. */
146
+ export function probePort(port, options = {}) {
147
+ const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 1_000;
148
+ if (typeof options.connect === 'function') return options.connect(port, timeoutMs);
149
+ return new Promise((resolve) => {
150
+ const socket = net.connect({ host: options.host ?? '127.0.0.1', port });
151
+ let settled = false;
152
+ const finish = (up) => {
153
+ if (settled) return;
154
+ settled = true;
155
+ socket.destroy();
156
+ resolve(up);
157
+ };
158
+ socket.setTimeout(timeoutMs);
159
+ socket.once('connect', () => finish(true));
160
+ socket.once('timeout', () => finish(false));
161
+ socket.once('error', () => finish(false));
162
+ });
163
+ }
164
+
165
+ /**
166
+ * Start one declared service as a detached process and persist its runtime record.
167
+ * Used by a service-role worker/test; the plugin never invents a command outside
168
+ * the declarations.
169
+ */
170
+ export async function startService({ repo, name, run, now = () => Date.now(), append = appendEvent } = {}) {
171
+ if (typeof run !== 'function') throw new TypeError('startService: run is required');
172
+ const declaration = findService(repo, name);
173
+ const command = serviceStartCommand(declaration);
174
+ const result = await run(command, { workdir: repo });
175
+ if (result?.timedOut === true) throw new Error('service start timed out: ' + name);
176
+ const pid = Number.parseInt(String(result?.stdout ?? '').trim(), 10);
177
+ const dir = path.join(repo, SERVICES_DIR);
178
+ fs.mkdirSync(dir, { recursive: true });
179
+ const record = {
180
+ name: declaration.name,
181
+ command: declaration.command,
182
+ port: declaration.port,
183
+ health: declaration.health,
184
+ pid: Number.isInteger(pid) && pid > 0 ? pid : null,
185
+ log: path.join(SERVICES_DIR, declaration.name + '.log'),
186
+ startedAt: new Date(now()).toISOString(),
187
+ };
188
+ fs.writeFileSync(recordPath(repo, name), JSON.stringify(record) + '\n');
189
+ append(repo, { ts: record.startedAt, actor: 'hive-runner', kind: 'service_started', service: name, port: declaration.port, pid: record.pid });
190
+ return record;
191
+ }
192
+
193
+ /** Status rows for hive_ops action=services. */
194
+ export async function serviceStatus(repo, { probe = probePort } = {}) {
195
+ const declarations = loadServiceDeclarations(repo);
196
+ const records = readServiceRecords(repo);
197
+ const rows = [];
198
+ for (const declaration of declarations) {
199
+ const record = records.find((entry) => entry.name === declaration.name) ?? null;
200
+ const running = await probe(declaration.port);
201
+ rows.push({ name: declaration.name, command: declaration.command, port: declaration.port, health: declaration.health, declared: true, recorded: record !== null, pid: record?.pid ?? null, running });
202
+ }
203
+ return rows;
204
+ }
205
+
206
+ function serviceTag(name) { return 'service:' + name; }
207
+
208
+ /** Find the latest service card for one declaration. */
209
+ async function serviceTask(commands, repo, name) {
210
+ if (typeof commands?.list !== 'function') return null;
211
+ const tasks = await commands.list(repo, {});
212
+ if (!Array.isArray(tasks)) return null;
213
+ const matches = tasks.filter((task) => Array.isArray(task?.tags) && task.tags.includes(serviceTag(name)));
214
+ return matches.length === 0 ? null : matches[matches.length - 1];
215
+ }
216
+
217
+ /**
218
+ * Probe declared services, create/reopen a service card for each down service,
219
+ * and append service_down once per outage. Healthy services with a previous
220
+ * outage append service_started once.
221
+ */
222
+ export async function auditServices({ repo, commands, probe = probePort, append = appendEvent, state = new Set(), now = () => Date.now(), log = () => {} } = {}) {
223
+ const declarations = loadServiceDeclarations(repo);
224
+ if (declarations.length === 0) return { checked: 0, down: [], started: [] };
225
+ const down = [];
226
+ const started = [];
227
+ for (const declaration of declarations) {
228
+ const key = declaration.name;
229
+ const up = await probe(declaration.port);
230
+ if (up) {
231
+ if (state.has(key)) {
232
+ state.delete(key);
233
+ started.push(key);
234
+ append(repo, { ts: new Date(now()).toISOString(), actor: 'hive-runner', kind: 'service_started', service: key, port: declaration.port });
235
+ }
236
+ continue;
237
+ }
238
+ down.push(key);
239
+ if (state.has(key)) {
240
+ // The outage was already reported; still reopen a failed service card so a
241
+ // later patrol retries the restart instead of staying silent forever.
242
+ try {
243
+ const existing = await serviceTask(commands, repo, key);
244
+ if (existing !== null && existing.state === 'failed') {
245
+ await commands.reopen(repo, existing.id, { reason: 'service still down: port ' + String(declaration.port) + ' did not answer' });
246
+ }
247
+ } catch (error) {
248
+ log('warn', 'service retry failed for ' + key, error);
249
+ }
250
+ continue;
251
+ }
252
+ state.add(key);
253
+ append(repo, { ts: new Date(now()).toISOString(), actor: 'hive-runner', kind: 'service_down', service: key, port: declaration.port });
254
+ try {
255
+ const existing = await serviceTask(commands, repo, key);
256
+ if (existing !== null && existing.state === 'failed') {
257
+ await commands.reopen(repo, existing.id, { reason: 'service down: port ' + String(declaration.port) + ' did not answer' });
258
+ } else if (existing === null || existing.state === 'done') {
259
+ await commands.add(repo, {
260
+ title: 'Restart service ' + key,
261
+ role: SERVICE_ROLE,
262
+ tags: ['service', serviceTag(key)],
263
+ acceptance: serviceAcceptance(declaration),
264
+ goal: 'Restart ' + key + ' from .hive/services.yaml; health check ' + declaration.health,
265
+ });
266
+ }
267
+ } catch (error) {
268
+ log('warn', 'service redispatch failed for ' + key, error);
269
+ }
270
+ }
271
+ return { checked: declarations.length, down, started };
272
+ }
273
+
274
+ export default { loadServiceDeclarations, startService, serviceStatus, auditServices };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-hive-runner",
3
- "version": "1.0.16",
3
+ "version": "1.0.17",
4
4
  "description": "DSH host plugin for Hive: a resident supervisor that runs one DSH subagent per ready task card, with per-role worker limits, pause/resume and Hive tools.",
5
5
  "type": "module",
6
6
  "main": "./index.js",