dsh-hive-runner 0.6.1 → 0.6.4

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,56 @@ 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
+ ## [0.6.4] - 2026-12-04
11
+
12
+ ### Added
13
+
14
+ - A card's last-run record now carries the worker activation's `sessionId` (the
15
+ child Session id) and `agentName` (its model-facing name), so Hive UIs can
16
+ open that worker's chat like one click in the header's subagent list.
17
+ - Both keys are omitted when the attempt never started a worker (a guard denial,
18
+ a missing merge-on-commit hook, or an activation that threw); success and
19
+ failure records keep them. Records without an activation stay byte-identical
20
+ to the previous shape.
21
+
22
+ ## [0.6.3] - 2026-12-04
23
+
24
+ ### Added
25
+
26
+ - Every card attempt now leaves a last-run record at
27
+ `<repo>/.hive/runs/<cardId>.json` (`cardId`, `agent`, `startedAt`,
28
+ `endedAt`, `status: running|done|failed`, optional `exitCode`/`commit`, and
29
+ the worker `output`). The record is written as `running` when the attempt
30
+ starts and overwritten with the terminal state for done, failed, guard-denied
31
+ and exceptional endings; only the most recent attempt is kept.
32
+ - `output` stores the smaller of the worker's last 200 lines and its last
33
+ 32 KiB of UTF-8, so a chatty worker cannot grow the file without bound.
34
+ - Run records are observability only: an unwritable repository never fails a
35
+ card (the write error is swallowed).
36
+
37
+ ### Fixed
38
+
39
+ - A failed verification with no worker text now keeps the verdict as the run
40
+ record's output instead of storing a blank line.
41
+
42
+ ## [0.6.2] - 2026-12-04
43
+
44
+ ### Fixed
45
+
46
+ - Every Hive/git command now runs with an explicit `HIVE_AGENT=<claim identity>`
47
+ environment entry (including git commit), so the merge-on-commit pre-commit
48
+ hook never skips lease enforcement with "HIVE_AGENT is not set".
49
+ - Worker subagent activations inject `HIVE_AGENT` into the in-process worker
50
+ environment for their lifetime (reference-counted and restored afterwards),
51
+ because DSH's model-facing bash tool only inherits ambient environment.
52
+ - The worker prompt now requires `HIVE_AGENT` on every command, especially
53
+ `git commit`, and tells the worker that a hook warning about the missing
54
+ variable is an environment error rather than success.
55
+ - The runner detects that hook warning in the worker output and raises the
56
+ deferrable `hive/no-hive-agent-env` environment error: the repository backs
57
+ off and reports `environmentError`; the card is not marked done/failed and no
58
+ auto-pause counts.
59
+
10
60
  ## [0.6.1] - 2026-12-04
11
61
 
12
62
  ### Fixed
package/README.md CHANGED
@@ -59,39 +59,44 @@ the plugin never spawns processes outside the harness.
59
59
  - DSH 0.2.2-rc.5 with the `desktop` or `web` profile — the version the plugin is
60
60
  developed against. Node 22 or newer.
61
61
  - The [hive](https://github.com/d86e/hive) and
62
- [hive-tasks](https://github.com/d86e/hive-tasks) packages. `hive-tasks` must be
63
- reachable from the DSH host process, either on its PATH or via `tasksBin`.
62
+ [hive-tasks](https://github.com/d86e/hive-tasks) packages. `hive-tasks` and `hive`
63
+ are called by their PATH names by default and retried through `npx` when the shell
64
+ cannot find them; `tasksBin`/`hiveBin` pin an explicit executable instead.
64
65
  - Repositories already initialised with Hive (`hive init`), unless you enable discovery.
65
66
  - The [Hive panel](https://github.com/d86e/dsh-hive-panel) is not required, but it is the
66
67
  easiest way to change limits and pause/resume a repository.
67
68
 
68
69
  ## Install
69
70
 
70
- Install into the profile that boots the DSH host where the supervisor should run. The
71
- **desktop** profile is managed by the DSH Desktop app, so
72
- `dsh plugin --profile desktop ...` refuses to edit it; edit it by hand:
73
-
74
- 1. In `~/.dsh/profiles/desktop/package.json`, add the dependency and the bundle:
75
-
76
- ```diff
77
- "dependencies": {
78
- + "dsh-hive-runner": "link:/path/to/dsh-hive-runner",
79
- },
80
- "dsh": {
81
- "profile": {
82
- "bundles": [
83
- + "dsh-hive-runner"
84
- ]
85
- }
86
- }
71
+ Install into the profile that boots the DSH host where the supervisor should run. Use the
72
+ `dsh` CLI of the same version as the DSH runtime (this plugin declares compatibility with
73
+ DSH 0.2.2-rc.5):
74
+
75
+ 1. **Quit DSH Desktop completely.** The `desktop` profile belongs to the Desktop app and
76
+ is locked while it runs. If the app has never been opened, start it once so it creates
77
+ `~/.dsh/profiles/desktop/package.json`, then quit.
78
+
79
+ 2. **Install the plugin into the profile.** `dsh` and `pnpm` must be on PATH; the
80
+ command updates both `dependencies` and `dsh.profile.bundles`:
81
+
82
+ ```bash
83
+ dsh plugin --profile desktop add dsh-hive-runner
87
84
  ```
88
85
 
89
- 2. Run `cd ~/.dsh/profiles/desktop && pnpm install`.
86
+ For a CLI profile such as `web`, use
87
+ `dsh plugin --profile web add dsh-hive-runner` and restart with `dsh web`.
88
+
90
89
  3. Add your repositories to the `hive-runner` entry in that profile's
91
90
  `cordis.patch.yml`, restart DSH, and open the Hive panel's **Runner** tab.
92
91
 
93
- For a CLI profile such as `web`, `dsh plugin --profile web add /path/to/dsh-hive-runner`
94
- also works; check that `dsh.profile.bundles` lists `dsh-hive-runner`.
92
+ <details>
93
+ <summary>Manual profile edit (same result, only needed when the CLI is unavailable)</summary>
94
+
95
+ While DSH Desktop is not running, add `"dsh-hive-runner": "^0.6.4"` to the profile's
96
+ `dependencies`, add `dsh-hive-runner` to `dsh.profile.bundles`, then
97
+ `cd ~/.dsh/profiles/desktop && pnpm install`.
98
+
99
+ </details>
95
100
 
96
101
  ## Five-minute quickstart
97
102
 
@@ -176,7 +181,7 @@ accepted as plugin `config`. User-facing keys:
176
181
  | `agent` / `ttl` | `dsh` / `5m` | Identity and lease TTL for claims |
177
182
  | `provider` | `spawn` | DSH subagent provider used for workers |
178
183
  | `parentSession` | `null` | Optional live session used as the parent for workers |
179
- | `tasksBin` / `hiveBin` | `null` | Explicit `hive-tasks` / `hive` executables (PATH name or absolute path) |
184
+ | `tasksBin` / `hiveBin` | `null` | Explicit `hive-tasks` / `hive` executables (PATH name or absolute path). Default: the PATH name, retried once through `npx -y -p hive-tasks` / `npx -y -p hive-consensus` when missing |
180
185
  | `gitBin` | `git` | Git executable |
181
186
  | `cliTimeoutMs` / `headTimeoutMs` / `acceptanceTimeoutMs` | `120000` / `30000` / `900000` | Command timeouts |
182
187
  | `debug` | `false` | Verbose supervisor logging |
@@ -186,9 +191,13 @@ values in `.hive/limits.json` take precedence for the roles they contain.
186
191
  Repository-specific defaults can also be written in the config with absolute-path keys,
187
192
  for example `{ "/abs/repo": { "coder": 3 } }`.
188
193
 
189
- `hive-tasks` must be resolvable from the DSH host's `PATH` (or configured as
190
- `tasksBin`). If DSH's shell service is unavailable the plugin fails loudly instead of
191
- bypassing the sandbox.
194
+ `hive-tasks` and `hive` are resolved from the DSH shell's `PATH` by default. When a
195
+ PATH lookup misses, the supervisor retries the same command once through `npx -y -p
196
+ <hive-tasks|hive-consensus>`; if that also fails, the error carries an install hint
197
+ (`npm i -g ...` plus the `tasksBin`/`hiveBin` key to set). First use needs network
198
+ access for npx to populate its cache; on an offline machine install the CLIs globally or
199
+ pin `tasksBin`/`hiveBin` to absolute paths. If DSH's shell service is unavailable the
200
+ plugin fails loudly instead of bypassing the sandbox.
192
201
 
193
202
  ## Architecture
194
203
 
package/README.zh-CN.md CHANGED
@@ -34,35 +34,39 @@
34
34
 
35
35
  ## 环境要求
36
36
 
37
- - DSH 0.2.2-rc.5,`desktop` 或 `web` profile——插件按这个版本开发;Node 22 或更新。
37
+ - DSH 0.2.2-rc.5,`desktop` 或 `web` profile——插件按这个版本开发;Node 22.19 或更新。
38
38
  - [hive](https://github.com/d86e/hive) 与 [hive-tasks](https://github.com/d86e/hive-tasks)。
39
- `hive-tasks` 必须能被 DSH 宿主进程找到:在 PATH 上,或配置 `tasksBin`。
39
+ `hive-tasks` 和 `hive` 默认按 PATH 名调用,shell 找不到时自动用 `npx` 重试;`tasksBin`/`hiveBin` 可以显式固定可执行文件。
40
40
  - 已经用 Hive 初始化过的仓库(`hive init`),除非开启自动发现。
41
41
  - [Hive 面板](https://github.com/d86e/dsh-hive-panel)不是必须的,但它是改上限、暂停/恢复仓库最方便的方式。
42
42
 
43
43
  ## 安装
44
44
 
45
- 装到启动目标 DSH 宿主所用的 profile 里。**desktop** profile 由 DSH Desktop 应用管理,`dsh plugin --profile desktop ...` 会拒绝修改,需要手动编辑:
46
-
47
- 1. 在 `~/.dsh/profiles/desktop/package.json` 里加依赖和 bundle:
48
-
49
- ```diff
50
- "dependencies": {
51
- + "dsh-hive-runner": "link:/path/to/dsh-hive-runner",
52
- },
53
- "dsh": {
54
- "profile": {
55
- "bundles": [
56
- + "dsh-hive-runner"
57
- ]
58
- }
59
- }
45
+ 装到启动目标 DSH 宿主所用的 profile 里。请使用与 DSH 运行时同版本的 `dsh` CLI(本插件声明兼容 DSH 0.2.2-rc.5):
46
+
47
+ 1. **完全退出 DSH Desktop。** `desktop` profile 归桌面应用管理,应用运行时是锁住的。
48
+ 如果桌面应用从没打开过,先启动一次让它生成 `~/.dsh/profiles/desktop/package.json`,再退出。
49
+
50
+ 2. **把插件装进 profile。** `dsh` 和 `pnpm` 需要在 PATH 上;命令会同时更新
51
+ `dependencies` 和 `dsh.profile.bundles`:
52
+
53
+ ```bash
54
+ dsh plugin --profile desktop add dsh-hive-runner
60
55
  ```
61
56
 
62
- 2. 执行 `cd ~/.dsh/profiles/desktop && pnpm install`。
57
+ CLI profile(例如 `web`)用 `dsh plugin --profile web add dsh-hive-runner`,
58
+ 重启方式换成 `dsh web`。
59
+
63
60
  3. 在该 profile 的 `cordis.patch.yml` 的 `hive-runner` 条目里配置仓库,重启 DSH,打开 Hive 面板的 **Runner** 标签页。
64
61
 
65
- CLI profile(例如 `web`)也可以用 `dsh plugin --profile web add /path/to/dsh-hive-runner`,确认 `dsh.profile.bundles` 里列出了 `dsh-hive-runner`。
62
+ <details>
63
+ <summary>手工改 profile(效果相同,仅在 CLI 不可用时使用)</summary>
64
+
65
+ 在 DSH Desktop 退出时,把 `"dsh-hive-runner": "^0.6.4"` 加进 profile 的
66
+ `dependencies`、把 `dsh-hive-runner` 加进 `dsh.profile.bundles`,然后
67
+ `cd ~/.dsh/profiles/desktop && pnpm install`。
68
+
69
+ </details>
66
70
 
67
71
  ## 五分钟上手
68
72
 
@@ -127,14 +131,14 @@ CLI profile(例如 `web`)也可以用 `dsh plugin --profile web add /path/to
127
131
  | `agent` / `ttl` | `dsh` / `5m` | claim 身份 / 租约 TTL |
128
132
  | `provider` | `spawn` | 卡片 worker 使用的 DSH subagent provider |
129
133
  | `parentSession` | `null` | 可选的、作为 worker parent 的 live session |
130
- | `tasksBin` / `hiveBin` | `null` | 显式指定 `hive-tasks` / `hive` 可执行文件(PATH 名或绝对路径) |
134
+ | `tasksBin` / `hiveBin` | `null` | 显式指定 `hive-tasks` / `hive` 可执行文件(PATH 名或绝对路径)。默认用 PATH 名,找不到时用 `npx -y -p hive-tasks` / `npx -y -p hive-consensus` 重试一次 |
131
135
  | `gitBin` | `git` | git 可执行文件 |
132
136
  | `cliTimeoutMs` / `headTimeoutMs` / `acceptanceTimeoutMs` | `120000` / `30000` / `900000` | 命令超时 |
133
137
  | `debug` | `false` | supervisor 详细日志 |
134
138
 
135
139
  `roleConcurrency` 只是初始值和兜底;面板写入 `.hive/limits.json` 的每仓库数值优先。也可以在这份配置里用绝对路径 key 写仓库级默认值,例如 `{ "/abs/repo": { "coder": 3 } }`。
136
140
 
137
- `hive-tasks` 必须在 DSH 宿主进程的 `PATH` 里(或配置 `tasksBin`)。DSH 的 shell 服务不可用时插件会直接报错,不会绕过 sandbox。
141
+ `hive-tasks` 和 `hive` 默认从 DSH shell 的 `PATH` 解析。PATH 找不到时,supervisor 会把同一条命令用 `npx -y -p <hive-tasks|hive-consensus>` 重试一次;仍然失败时错误里带安装提示(`npm i -g ...` 和该设置的 `tasksBin`/`hiveBin`)。首次使用需要联网让 npx 填充缓存;离线机器请全局安装或把 `tasksBin`/`hiveBin` 固定成绝对路径。DSH 的 shell 服务不可用时插件会直接报错,不会绕过 sandbox。
138
142
 
139
143
  ## 架构
140
144
 
package/SPEC.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # dsh-hive-runner — protocol specification
2
2
 
3
- Status: 0.6.1, verified against DSH 0.2.2-rc.5.
3
+ Status: 0.6.4, verified against DSH 0.2.2-rc.5.
4
4
 
5
5
  This document is normative for the host contract of the plugin. It is written for
6
6
  maintainers: user documentation is [README.md](README.md) and
@@ -189,8 +189,27 @@ Per card:
189
189
  `resource:` keys, stop and report on exit 2, never edit out of scope or drop lease
190
190
  refs) and the commit rules (plain `git commit` only, never `--no-verify`/history
191
191
  rewrites, resolve hook conflicts in place).
192
- 4. Done verification requires HEAD to have moved and the merge-on-commit hook to still be
192
+ 4. Every Hive/git shell command carries `HIVE_AGENT=<claim identity>` in its environment.
193
+ Worker subagent activations inject that variable into the in-process worker environment
194
+ for their lifetime (DSH's model-facing bash tool inherits ambient env), and the worker
195
+ prompt requires `HIVE_AGENT` on every command, especially `git commit`. A pre-commit
196
+ warning that `HIVE_AGENT is not set` / lease enforcement was skipped is detected in the
197
+ worker output and raised as the deferrable environment error
198
+ `hive/no-hive-agent-env`: the repository backs off and reports `environmentError`; the
199
+ card is neither done nor failed and no auto-pause counts.
200
+ 5. Done verification requires HEAD to have moved and the merge-on-commit hook to still be
193
201
  present; leases for the scope are best-effort released after done or fail.
202
+ 6. Every attempt writes `<repo>/.hive/runs/<cardId>.json`: `running` when the attempt
203
+ starts, then the terminal state for done, failed, guard-denied and exceptional
204
+ endings. The record carries `cardId`, `agent`, `startedAt`, `endedAt`, `status`,
205
+ optional `exitCode`/`commit`, and `output` (the smaller of the worker's last 200
206
+ lines and its last 32 KiB of UTF-8). A started worker activation also adds
207
+ `sessionId` (the child Session id returned by `startActivation`) and `agentName`
208
+ (its model-facing child name); both keys are omitted when no activation was
209
+ accepted, for example after a guard denial, so consumers can distinguish
210
+ "no worker chat" from an empty value. The file is overwritten per attempt, so
211
+ only the most recent run is kept; read failures and write failures are ignored
212
+ by the round and never change the card verdict.
194
213
 
195
214
  The supervisor reads the Hive mode every round: in freeze mode only fix cards are
196
215
  dispatched, other ready cards stay on the board and are reported through `mode`,
package/cordis.patch.yml CHANGED
@@ -72,6 +72,9 @@
72
72
  # Tool default repository when a tool call does not pass `repo`.
73
73
  cwd: null
74
74
  # Binaries (absolute path or PATH name); the HIVE_*_BIN env vars win.
75
+ # Default null means the PATH name (hive-tasks / hive); a missing PATH
76
+ # name is retried once through npx (-y -p hive-tasks / -p hive-consensus).
77
+ # An explicit absolute path is used as-is and never replaced.
75
78
  tasksBin: null
76
79
  hiveBin: null
77
80
  gitBin: git
package/docs/DESIGN.md CHANGED
@@ -155,7 +155,8 @@ consuming the failure budget.
155
155
  | `index.js` | Cordis plugin entry: config, limits store, supervisor service/timer, Fetch route, tools |
156
156
  | `lib/supervisor.js` | Repository registry + state machine + per-repo queue/backlog/roles; exposes `setRoleLimits` |
157
157
  | `lib/queue.js` | Live-only per-role worker pools, immediate slot refill, capacity requeue, per-role state callback |
158
- | `lib/round.js` | One card end to end: claim → subagent activation → commit/acceptance verify → done/fail |
158
+ | `lib/round.js` | One card end to end: claim → subagent activation → commit/acceptance verify → done/fail + last-run record |
159
+ | `lib/runs.js` | `<repo>/.hive/runs/<cardId>.json` last-run records: path validation, 200-line/32-KiB output truncation, optional worker `sessionId`/`agentName`, best-effort write |
159
160
  | `lib/limits.js` | `<repo>/.hive/limits.json` read/write/hot-reload and precedence helpers |
160
161
  | `lib/config.js` | Config defaults/validation, role map parsing, effective-limit helpers |
161
162
  | `lib/commands.js` | Allowlisted `hive-tasks` / `git` / acceptance commands with shell quoting |
package/index.js CHANGED
@@ -114,7 +114,7 @@ export function apply(ctx, config = {}) {
114
114
  ttl: { type: 'string', description: 'Claim TTL, for example 5m.' },
115
115
  agent: { type: 'string', description: 'Identity used for claims. Default: config.agent.' },
116
116
  },
117
- output: { schema: { type: 'string' }, render: (_args, value) => String(value) },
117
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
118
118
  execute: async (args = {}, exec) => {
119
119
  const repo = repoOf(args);
120
120
  const signal = exec?.signal;
@@ -156,7 +156,7 @@ export function apply(ctx, config = {}) {
156
156
  role: { type: 'string', description: 'Filter by Hive role, for example coder or tester.' },
157
157
  limit: { type: 'number', description: 'Maximum number of cards.' },
158
158
  },
159
- output: { schema: { type: 'string' }, render: (_args, value) => String(value) },
159
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
160
160
  execute: async (args = {}, exec) => {
161
161
  const repo = repoOf(args);
162
162
  const cards = await commands.ready(repo, {
@@ -175,7 +175,7 @@ export function apply(ctx, config = {}) {
175
175
  parameters: {
176
176
  repo: { type: 'string', description: 'Repository path. Default: the configured cwd.' },
177
177
  },
178
- output: { schema: { type: 'string' }, render: (_args, value) => String(value) },
178
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
179
179
  execute: async (args = {}, exec) => {
180
180
  const repo = repoOf(args);
181
181
  const board = await commands.board(repo, { signal: exec?.signal, session: exec?.agent?.session });
@@ -189,7 +189,7 @@ export function apply(ctx, config = {}) {
189
189
  'Show the resident Hive supervisor state: per-repository state (idle/running/backoff/paused), '
190
190
  + 'last round time, last error, in-flight flag and pause reason. Same data as GET /api/hive-runner?op=status.',
191
191
  parameters: {},
192
- output: { schema: { type: 'string' }, render: (_args, value) => String(value) },
192
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
193
193
  execute: async () => JSON.stringify(supervisor.status(), null, 2),
194
194
  }));
195
195
  }
package/lib/commands.js CHANGED
@@ -28,6 +28,32 @@ export const AGENT_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
28
28
  export const TTL_RE = /^\d{1,4}[smhd]$/;
29
29
  export const SHA_RE = /^[0-9a-f]{7,64}$/;
30
30
 
31
+ /** npm package(s) behind each Hive bin; used only when the PATH name is missing. */
32
+ export const BIN_PACKAGES = Object.freeze({
33
+ tasks: Object.freeze(['hive-tasks']),
34
+ hive: Object.freeze(['hive-consensus']),
35
+ });
36
+
37
+ /** The executable name inside each published package. */
38
+ const BIN_EXECUTABLES = Object.freeze({ tasks: 'hive-tasks', hive: 'hive' });
39
+
40
+ /** Which Hive bin a verb uses; null verbs (git, the card's own acceptance) cap no fallback. */
41
+ const VERB_BINS = Object.freeze({
42
+ ready: 'tasks',
43
+ claim: 'tasks',
44
+ show: 'tasks',
45
+ done: 'tasks',
46
+ fail: 'tasks',
47
+ board: 'hive',
48
+ guard: 'hive',
49
+ release: 'hive',
50
+ renew: 'hive',
51
+ mode: 'hive',
52
+ recall: 'hive',
53
+ head: null,
54
+ acceptance: null,
55
+ });
56
+
31
57
  /** POSIX single-quote one argv token. */
32
58
  export function quote(value) {
33
59
  return "'" + String(value).replaceAll("'", "'\\''") + "'";
@@ -140,6 +166,51 @@ export function buildCommand(verb, args = {}, bins = {}) {
140
166
  }
141
167
  }
142
168
 
169
+ /**
170
+ * The npx fallback for one allowlisted command: the same argv, prefixed with
171
+ * `npx -y -p <published package> ... <bin>`. Only a bare PATH name gets a
172
+ * fallback; an explicitly configured absolute path is the operator's choice.
173
+ * @param {'ready'|'claim'|'show'|'done'|'fail'|'board'|'head'|'acceptance'|'guard'|'release'|'renew'|'mode'|'recall'} verb
174
+ * @param {Record<string, unknown>} [args]
175
+ * @param {{ tasks?: string, hive?: string, git?: string }} [bins]
176
+ * @returns {string | null} the fallback command string, or null when none applies.
177
+ */
178
+ export function npxFallbackCommand(verb, args = {}, bins = {}) {
179
+ const key = VERB_BINS[verb];
180
+ if (key === undefined || key === null) return null;
181
+ const executable = typeof bins[key] === 'string' && bins[key] !== '' ? bins[key] : BIN_EXECUTABLES[key];
182
+ if (executable.includes('/') || executable.includes('\\')) return null;
183
+ const packages = BIN_PACKAGES[key];
184
+ if (packages === undefined) return null;
185
+ const prefix = ['npx', '-y', ...packages.flatMap((pkg) => ['-p', pkg]), BIN_EXECUTABLES[key]].map(quote).join(' ');
186
+ const command = buildCommand(verb, args, bins);
187
+ return prefix + command.slice(executable.length);
188
+ }
189
+
190
+ /** True when a shell result means the executable itself was missing. */
191
+ export function missingBinary(result) {
192
+ if (result === undefined || result === null) return false;
193
+ if (result.exitCode === 127) return true;
194
+ return /command not found|: not found|No such file or directory/i.test(String(result.stderr ?? ''));
195
+ }
196
+
197
+ /** Actionable install hint for a bin whose PATH name and npx fallback both failed. */
198
+ export function missingBinaryHint(verb, bins = {}) {
199
+ const key = VERB_BINS[verb];
200
+ if (key === undefined || key === null) return null;
201
+ const configured = typeof bins[key] === 'string' && bins[key] !== '' ? bins[key] : BIN_EXECUTABLES[key];
202
+ const packages = BIN_PACKAGES[key];
203
+ const configKey = key === 'tasks' ? 'tasksBin' : 'hiveBin';
204
+ return '[hive-runner] ' + configured + ' was not found on the shell PATH and the npx fallback did not run it; '
205
+ + 'install it with "npm i -g ' + packages.join(' ') + '" or set ' + configKey + '.';
206
+ }
207
+
208
+ /** Append one diagnostic line to a result's stderr without dropping the CLI output. */
209
+ export function appendStderr(result, line) {
210
+ const stderr = String(result.stderr ?? '');
211
+ return { ...result, stderr: stderr === '' ? line : stderr.replace(/\s+$/, '') + '\n' + line };
212
+ }
213
+
143
214
  function parseJson(text, label) {
144
215
  const trimmed = String(text ?? '').trim();
145
216
  if (trimmed === '') return null;
@@ -168,14 +239,28 @@ export function createCommands({ ctx, config }) {
168
239
  const bins = { tasks: config.tasksBin, hive: config.hiveBin, git: config.gitBin };
169
240
 
170
241
  /** Execute one allowlisted verb. @returns {Promise<object>} the raw shell result */
171
- function execute(verb, args, options = {}) {
242
+ async function execute(verb, args, options = {}) {
172
243
  const command = buildCommand(verb, args, bins);
173
- return run(command, {
244
+ const shellOptions = {
174
245
  workdir: options.repo,
175
246
  signal: options.signal,
176
247
  session: options.session,
177
248
  timeoutMs: options.timeoutMs ?? config.cliTimeoutMs,
178
- });
249
+ // Every Hive/git command carries the claim identity explicitly; the
250
+ // pre-commit hook must never fall back to "HIVE_AGENT is not set".
251
+ env: { HIVE_AGENT: options.agent ?? config.agent, ...(options.env ?? {}) },
252
+ };
253
+ let result = await run(command, shellOptions);
254
+ if (!missingBinary(result)) return result;
255
+ const fallback = npxFallbackCommand(verb, args, bins);
256
+ if (fallback === null) {
257
+ const hint = missingBinaryHint(verb, bins);
258
+ return hint === null ? result : appendStderr(result, hint);
259
+ }
260
+ result = await run(fallback, shellOptions);
261
+ if (!missingBinary(result)) return result;
262
+ const hint = missingBinaryHint(verb, bins);
263
+ return hint === null ? result : appendStderr(result, hint);
179
264
  }
180
265
 
181
266
  return {
package/lib/config.js CHANGED
@@ -49,6 +49,7 @@ const DEFAULTS = Object.freeze({
49
49
  provider: 'spawn',
50
50
  parentSession: null,
51
51
  cwd: null,
52
+ // null = the PATH name; commands.js retries a missing PATH name through npx.
52
53
  tasksBin: null,
53
54
  hiveBin: null,
54
55
  gitBin: 'git',
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Scoped `HIVE_AGENT` injection for worker subagents.
3
+ *
4
+ * DSH's subagent seam runs workers in the host process and the model-facing
5
+ * bash tool inherits ambient environment variables (grep/subprocess scrub only
6
+ * credential-shaped and DSH_* names). The plugin therefore injects
7
+ * `HIVE_AGENT` explicitly while a worker is alive, so the worker's
8
+ * `git commit` and `hive` calls pass the merge-on-commit lease check instead of
9
+ * printing "HIVE_AGENT is not set".
10
+ *
11
+ * The value is reference-counted; the previous value is restored when the last
12
+ * worker finishes. All workers of one supervisor drain share the configured
13
+ * claim identity, so overlapping holders agree in normal operation.
14
+ */
15
+
16
+ let depth = 0;
17
+ let saved;
18
+
19
+ /**
20
+ * Set `process.env.HIVE_AGENT` for the duration of one worker.
21
+ * @param {string} agent claim identity
22
+ * @returns {() => void} idempotent release
23
+ */
24
+ export function acquireHiveAgentEnv(agent) {
25
+ if (typeof agent !== 'string' || agent.trim() === '') return () => {};
26
+ if (depth === 0) saved = process.env.HIVE_AGENT;
27
+ depth += 1;
28
+ process.env.HIVE_AGENT = agent;
29
+ let released = false;
30
+ return () => {
31
+ if (released) return;
32
+ released = true;
33
+ depth = Math.max(0, depth - 1);
34
+ if (depth === 0) {
35
+ if (saved === undefined) delete process.env.HIVE_AGENT;
36
+ else process.env.HIVE_AGENT = saved;
37
+ saved = undefined;
38
+ }
39
+ };
40
+ }
41
+
42
+ /** Current number of active worker env holders (diagnostics/tests). */
43
+ export function activeHiveAgentHolders() {
44
+ return depth;
45
+ }
package/lib/round.js CHANGED
@@ -18,7 +18,9 @@
18
18
  import { roleLimitForRepo } from './config.js';
19
19
  import { HiveCommandError, tail } from './commands.js';
20
20
  import { assertMergeOnCommitHook } from './hooks.js';
21
+ import { acquireHiveAgentEnv } from './host-env.js';
21
22
  import { isCapacityError } from './queue.js';
23
+ import { writeRunRecord } from './runs.js';
22
24
 
23
25
  /** A round-level failure. `hive/capacity` is retried from the queue. */
24
26
  export class RoundError extends Error {
@@ -66,6 +68,8 @@ export function renderPrompt(card, lessons = [], claimAgent) {
66
68
  }
67
69
  lines.push('');
68
70
  lines.push('## Commit rules (mandatory)');
71
+ lines.push('0. Every command you run, especially `git commit`, MUST carry `HIVE_AGENT` in its environment: use the claim identity, for example `HIVE_AGENT=' + (claimAgent || '<claim identity>') + ' git commit -m "..."` or export it first. Never rely on the host environment being set.');
72
+ lines.push('0b. If the pre-commit hook prints "HIVE_AGENT is not set" or "lease enforcement skipped", the commit is NOT protected: stop, do not treat the work as done, and report that line as an environment error.');
69
73
  lines.push('1. Commit with a plain `git commit`. The repository pre-commit hook runs merge-on-commit (moc) and performs a three-way merge automatically.');
70
74
  lines.push('2. NEVER bypass the hook: do not use `git commit --no-verify`, do not use `git commit --amend` to skip it, and do not use `git update-ref` or `git reset` to rewrite history that others already committed.');
71
75
  lines.push('3. If the hook reports merge conflicts, resolve them in place using the conflict markers, then commit again. Never discard the other side\'s changes.');
@@ -89,15 +93,46 @@ function messageOf(error) {
89
93
  return error instanceof Error ? error.message : String(error);
90
94
  }
91
95
 
96
+ /** Hook output that means the commit skipped lease enforcement. */
97
+ export function hasHookEnvWarning(text) {
98
+ return /HIVE_AGENT is not set|lease enforcement skipped/i.test(String(text ?? ''));
99
+ }
100
+
101
+ /** Text the worker produced (final assistant output plus provider diagnostic). */
102
+ function workerText(outcome) {
103
+ const blocks = Array.isArray(outcome?.output) ? outcome.output : [];
104
+ const text = blocks
105
+ .filter((block) => block !== null && typeof block === 'object' && typeof block.text === 'string')
106
+ .map((block) => block.text)
107
+ .join('\n');
108
+ return text + '\n' + String(outcome?.diagnostic ?? '');
109
+ }
110
+
111
+ /** Worker output for the last-run record, falling back to the card verdict. */
112
+ export function workerOutput(outcome, fallback = '') {
113
+ const text = workerText(outcome);
114
+ return text.trim() === '' ? String(fallback) : text;
115
+ }
116
+
92
117
  /**
93
118
  * Bind the Hive round helpers to the DSH runtime and the Hive command layer.
94
119
  * @param {{ ctx: object, config: object, commands: object }} options
95
120
  */
96
- export function createRoundRunner({ ctx, config, commands, limitFor, checkHook = assertMergeOnCommitHook }) {
121
+ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook = assertMergeOnCommitHook, writeRun = writeRunRecord }) {
97
122
  if (ctx === null || typeof ctx !== 'object' || typeof ctx.get !== 'function') {
98
123
  throw new TypeError('createRoundRunner: ctx with ctx.get() is required');
99
124
  }
100
125
  if (commands === undefined || commands === null) throw new TypeError('createRoundRunner: commands are required');
126
+ if (typeof writeRun !== 'function') throw new TypeError('createRoundRunner: writeRun must be a function');
127
+
128
+ /** Record one last-run snapshot; observability failures never fail the card. */
129
+ function recordRun(repo, record) {
130
+ try {
131
+ writeRun(repo, record);
132
+ } catch {
133
+ // The record file is a convenience for the panel, not part of the verdict.
134
+ }
135
+ }
101
136
  /** Effective live-worker cap for (repo, role). The plugin passes the persisted-limits store. */
102
137
  const capFor = typeof limitFor === 'function'
103
138
  ? limitFor
@@ -145,14 +180,14 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
145
180
  return service;
146
181
  }
147
182
 
148
- async function verify({ repo, before, card, signal, session }) {
149
- const head = await commands.head(repo, { signal, session });
183
+ async function verify({ repo, before, card, agent, signal, session }) {
184
+ const head = await commands.head(repo, { agent, signal, session });
150
185
  if (head === before) return { ok: false, reason: 'no commit produced' };
151
186
  // The commit must have landed through the merge-on-commit path: if the hook
152
187
  // vanished the commit may have bypassed it, so this is an environment error.
153
188
  checkHook(repo);
154
189
  if (card.acceptance) {
155
- const result = await commands.acceptance(repo, card.acceptance, { signal, session });
190
+ const result = await commands.acceptance(repo, card.acceptance, { agent, signal, session });
156
191
  if (result.exitCode !== 0) {
157
192
  const detail = result.stderr.trim() !== '' ? result.stderr : result.stdout;
158
193
  return { ok: false, reason: 'acceptance failed: ' + tail(detail) };
@@ -172,11 +207,11 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
172
207
  * Recall lessons for the card scope. Best effort: a recall failure never
173
208
  * blocks the card (the runner already has the environment churn signal).
174
209
  */
175
- async function recallLessons(repo, scope, { signal, session }) {
210
+ async function recallLessons(repo, scope, { agent, signal, session }) {
176
211
  const seen = new Map();
177
212
  for (const query of scope.slice(0, 3)) {
178
213
  try {
179
- const items = await commands.recall(repo, query, { signal, session });
214
+ const items = await commands.recall(repo, query, { agent, signal, session });
180
215
  for (const item of items) {
181
216
  if (item === null || typeof item !== 'object' || typeof item.text !== 'string') continue;
182
217
  seen.set(item.id ?? item.text, item);
@@ -221,7 +256,24 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
221
256
  const service = assertProvider(config.provider);
222
257
  const scope = scopeOf(card);
223
258
  const claimAgent = agent ?? config.agent;
259
+ // One last-run record per card: write `running` when the attempt starts and
260
+ // overwrite it with the terminal state before returning/raising.
261
+ const run = {
262
+ cardId: id,
263
+ agent: claimAgent,
264
+ startedAt: new Date().toISOString(),
265
+ endedAt: null,
266
+ status: 'running',
267
+ output: '',
268
+ };
269
+ let runFinished = false;
270
+ recordRun(repo, run);
271
+ const finishRun = (status, patch = {}) => {
272
+ runFinished = true;
273
+ recordRun(repo, { ...run, ...patch, status, endedAt: new Date().toISOString() });
274
+ };
224
275
  let activation;
276
+ let releaseEnv = () => {};
225
277
  try {
226
278
  // hive-consensus: co-sign the card's leases (guard) with the SAME identity
227
279
  // used for the claim. A different identity would collide with the claim's
@@ -243,7 +295,8 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
243
295
  await commands.renew(repo, scope, { agent: claimAgent, ttl: config.ttl, signal, session }).catch(() => {});
244
296
  } else {
245
297
  const reason = 'guard denied: ' + tail(guard.stderr || guard.stdout || 'scope held by another agent');
246
- await commands.fail(repo, id, { reason, signal, session });
298
+ await commands.fail(repo, id, { agent: claimAgent, reason, signal, session });
299
+ finishRun('failed', { exitCode: guard.exitCode, output: guard.stderr || guard.stdout });
247
300
  await releaseScope(repo, scope, { signal, session, agent: claimAgent });
248
301
  return { id, state: 'failed', reason };
249
302
  }
@@ -254,7 +307,11 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
254
307
  );
255
308
  }
256
309
  }
257
- const lessons = scope.length > 0 ? await recallLessons(repo, scope, { signal, session }) : [];
310
+ const lessons = scope.length > 0 ? await recallLessons(repo, scope, { agent: claimAgent, signal, session }) : [];
311
+ // Workers run in-process; DSH's bash tool inherits ambient env. Inject the
312
+ // claim identity while this worker is alive so its git commit passes the
313
+ // hive pre-commit lease check ("HIVE_AGENT is not set" must never happen).
314
+ releaseEnv = acquireHiveAgentEnv(claimAgent);
258
315
  activation = await service.startActivation({
259
316
  provider: config.provider,
260
317
  label: 'hive:' + id,
@@ -264,24 +321,43 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
264
321
  signal,
265
322
  delivery: 'caller',
266
323
  });
324
+ // Keep the worker's Session identity on the run record: the panel opens
325
+ // that conversation exactly like one click in the header's subagent list.
326
+ // A provider without an accepted child (none in practice) leaves it out.
327
+ if (typeof activation.childId === 'string' && activation.childId !== '') run.sessionId = activation.childId;
328
+ if (typeof activation.name === 'string' && activation.name !== '') run.agentName = activation.name;
267
329
  const outcome = await activation.result;
330
+ if (outcome.stopReason === 'completed' && hasHookEnvWarning(workerText(outcome))) {
331
+ // The worker reported that the hook skipped lease enforcement: the
332
+ // commit did not pass the consensus check. Defer, do not mark it done.
333
+ throw new RoundError(
334
+ 'hive/no-hive-agent-env',
335
+ 'pre-commit reported "HIVE_AGENT is not set": lease enforcement skipped; '
336
+ + 'the environment injection did not reach the worker commit',
337
+ { deferrable: true },
338
+ );
339
+ }
268
340
  if (outcome.stopReason !== 'completed') {
269
341
  const detail = outcome.diagnostic ? ': ' + tail(outcome.diagnostic) : '';
270
342
  const reason = 'subagent stopped: ' + outcome.stopReason + detail;
271
- await commands.fail(repo, id, { reason, signal, session });
343
+ await commands.fail(repo, id, { agent: claimAgent, reason, signal, session });
344
+ finishRun('failed', { exitCode: 1, output: workerOutput(outcome, reason) });
272
345
  await releaseScope(repo, scope, { signal, session, agent: claimAgent });
273
346
  return { id, state: 'failed', reason };
274
347
  }
275
- const verdict = await verify({ repo, before, card, signal, session });
348
+ const verdict = await verify({ repo, before, card, agent: claimAgent, signal, session });
276
349
  if (verdict.ok) {
277
- await commands.done(repo, id, { sha: verdict.head, verdict: 'pass', signal, session });
350
+ await commands.done(repo, id, { agent: claimAgent, sha: verdict.head, verdict: 'pass', signal, session });
351
+ finishRun('done', { exitCode: 0, commit: verdict.head, output: workerOutput(outcome) });
278
352
  await releaseScope(repo, scope, { signal, session, agent: claimAgent });
279
353
  return { id, state: 'done', sha: verdict.head };
280
354
  }
281
- await commands.fail(repo, id, { reason: verdict.reason, signal, session });
355
+ await commands.fail(repo, id, { agent: claimAgent, reason: verdict.reason, signal, session });
356
+ finishRun('failed', { exitCode: 1, output: workerOutput(outcome, verdict.reason) });
282
357
  await releaseScope(repo, scope, { signal, session, agent: claimAgent });
283
358
  return { id, state: 'failed', reason: verdict.reason };
284
359
  } catch (error) {
360
+ if (!runFinished) finishRun('failed', { exitCode: 1, output: messageOf(error) });
285
361
  if (isCapacityError(error)) {
286
362
  // Capacity is a scheduling concern, not this card's failure: keep the
287
363
  // claimed item and let the dispatcher retry it.
@@ -302,8 +378,12 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
302
378
  ? error
303
379
  : new RoundError('hive/round-failed', messageOf(error), { cause: error });
304
380
  } finally {
305
- if (activation !== undefined) {
306
- await Promise.resolve(activation.dispose?.()).catch(() => {});
381
+ try {
382
+ if (activation !== undefined) {
383
+ await Promise.resolve(activation.dispose?.()).catch(() => {});
384
+ }
385
+ } finally {
386
+ releaseEnv();
307
387
  }
308
388
  }
309
389
  }
@@ -345,7 +425,7 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
345
425
  const owner = resolveParent(parent);
346
426
  let fresh = card;
347
427
  try {
348
- const shown = await commands.show(repo, id, { signal, session });
428
+ const shown = await commands.show(repo, id, { agent: agent ?? config.agent, signal, session });
349
429
  if (shown !== null && typeof shown === 'object') fresh = shown;
350
430
  } catch {
351
431
  // The ready snapshot is enough to render the prompt.
@@ -363,7 +443,7 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
363
443
  }
364
444
 
365
445
  if (!alreadyClaimed) {
366
- const before = await commands.head(repo, { signal, session });
446
+ const before = await commands.head(repo, { agent: agentId, signal, session });
367
447
  const claim = await commands.claim(repo, id, { signal, session, agent, ttl });
368
448
  if (claim.exitCode !== 0) {
369
449
  return { id, state: 'skipped', reason: tail(claim.stderr || claim.stdout) || 'claim rejected' };
@@ -371,7 +451,7 @@ export function createRoundRunner({ ctx, config, commands, limitFor, checkHook =
371
451
  return await executeCard({ repo, card: fresh, before, owner, agent: agentId, signal, session });
372
452
  }
373
453
 
374
- const before = await commands.head(repo, { signal, session });
454
+ const before = await commands.head(repo, { agent: agentId, signal, session });
375
455
  return await executeCard({ repo, card: fresh, before, owner, agent: agentId, signal, session });
376
456
  },
377
457
  };
package/lib/runs.js ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Last-run records for Hive cards: `<repo>/.hive/runs/<cardId>.json`.
3
+ *
4
+ * One file per card, overwritten by every attempt, so the panel can show what
5
+ * the worker produced the last time the card ran without parsing a log.
6
+ *
7
+ * The record is observability only: a failed write must never fail the card,
8
+ * so `writeRunRecord` swallows every filesystem error and returns a boolean.
9
+ * A record produced by a worker activation also carries the child Session id
10
+ * (`sessionId`) and the model-facing child name (`agentName`), so the panel can
11
+ * open that worker's conversation; both keys are omitted when the attempt never
12
+ * reached an activation (for example a guard denial).
13
+ * The path is derived from the card id after `ID_RE` validation, which rejects
14
+ * path separators, so a card id can never escape `.hive/runs`.
15
+ *
16
+ * `output` keeps the *smaller* of the last 200 lines and the last 32 KiB of
17
+ * UTF-8, which bounds the file on disk no matter how chatty the worker is.
18
+ */
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+
22
+ import { ID_RE } from './commands.js';
23
+
24
+ /** Directory (relative to the repository root) holding one file per card. */
25
+ export const RUNS_DIR = path.join('.hive', 'runs');
26
+ /** Hard cap on the stored `output` bytes. */
27
+ export const RUN_OUTPUT_MAX_BYTES = 32 * 1024;
28
+ /** Hard cap on the stored `output` lines. */
29
+ export const RUN_OUTPUT_MAX_LINES = 200;
30
+
31
+ /** Valid record statuses. */
32
+ export const RUN_STATUSES = Object.freeze(['done', 'failed', 'running']);
33
+
34
+ /** Last `maxBytes` bytes of `text`, advanced to a UTF-8 code point boundary. */
35
+ function tailBytes(text, maxBytes) {
36
+ const buffer = Buffer.from(text, 'utf8');
37
+ if (buffer.length <= maxBytes) return text;
38
+ let start = buffer.length - maxBytes;
39
+ while (start < buffer.length && (buffer[start] & 0xc0) === 0x80) start += 1;
40
+ return buffer.subarray(start).toString('utf8');
41
+ }
42
+
43
+ /**
44
+ * Keep the smaller of the last `maxLines` lines and the last `maxBytes` bytes.
45
+ * @param {string} text - worker output (stdout + stderr tail).
46
+ * @param {{ maxBytes?: number, maxLines?: number }} [limits]
47
+ * @returns {string}
48
+ */
49
+ export function truncateRunOutput(text, { maxBytes = RUN_OUTPUT_MAX_BYTES, maxLines = RUN_OUTPUT_MAX_LINES } = {}) {
50
+ const value = typeof text === 'string' ? text : String(text ?? '');
51
+ const lines = value.split('\n');
52
+ const byLines = lines.length > maxLines ? lines.slice(-maxLines).join('\n') : value;
53
+ const byBytes = tailBytes(value, maxBytes);
54
+ return Buffer.byteLength(byBytes) < Buffer.byteLength(byLines) ? byBytes : byLines;
55
+ }
56
+
57
+ /**
58
+ * Resolve the record file for one card, validating the id and containment.
59
+ * @param {string} repo - repository root.
60
+ * @param {string} cardId - Hive card id (`ID_RE`).
61
+ * @returns {{ dir: string, file: string }}
62
+ */
63
+ export function runRecordPath(repo, cardId) {
64
+ if (typeof repo !== 'string' || repo === '') throw new TypeError('runRecordPath: repo is required');
65
+ if (typeof cardId !== 'string' || !ID_RE.test(cardId)) {
66
+ throw new TypeError('runRecordPath: cardId must match ' + String(ID_RE));
67
+ }
68
+ const dir = path.resolve(repo, RUNS_DIR);
69
+ const file = path.resolve(dir, cardId + '.json');
70
+ if (!file.startsWith(dir + path.sep)) throw new TypeError('runRecordPath: cardId escapes ' + RUNS_DIR);
71
+ return { dir, file };
72
+ }
73
+
74
+ /** Normalize one record to the documented shape. */
75
+ function normalizeRecord(record) {
76
+ const status = RUN_STATUSES.includes(record?.status) ? record.status : 'running';
77
+ const normalized = {
78
+ cardId: record.cardId,
79
+ agent: typeof record.agent === 'string' ? record.agent : '',
80
+ startedAt: typeof record.startedAt === 'string' ? record.startedAt : new Date().toISOString(),
81
+ endedAt: typeof record.endedAt === 'string' ? record.endedAt : null,
82
+ status,
83
+ output: truncateRunOutput(record.output),
84
+ };
85
+ if (Number.isInteger(record.exitCode)) normalized.exitCode = record.exitCode;
86
+ if (typeof record.commit === 'string' && record.commit !== '') normalized.commit = record.commit;
87
+ // Durable child identity: present exactly when a worker activation started.
88
+ if (typeof record.sessionId === 'string' && record.sessionId !== '') normalized.sessionId = record.sessionId;
89
+ if (typeof record.agentName === 'string' && record.agentName !== '') normalized.agentName = record.agentName;
90
+ return normalized;
91
+ }
92
+
93
+ /**
94
+ * Write (overwrite) the last-run record for one card. Best effort.
95
+ * @param {string} repo - repository root.
96
+ * @param {object} record - `{ cardId, agent, startedAt, endedAt, status, exitCode?, commit?, sessionId?, agentName?, output }`.
97
+ * @returns {boolean} true when the file was written.
98
+ */
99
+ export function writeRunRecord(repo, record) {
100
+ try {
101
+ if (record === null || typeof record !== 'object') return false;
102
+ const { dir, file } = runRecordPath(repo, record.cardId);
103
+ const payload = normalizeRecord(record);
104
+ fs.mkdirSync(dir, { recursive: true });
105
+ fs.writeFileSync(file, JSON.stringify(payload, null, 2) + '\n');
106
+ return true;
107
+ } catch {
108
+ // Observability must never break a card run.
109
+ return false;
110
+ }
111
+ }
package/lib/shell.js CHANGED
@@ -37,7 +37,7 @@ export function createShellRunner({ ctx, config = {} }) {
37
37
  /**
38
38
  * Run one already-allowlisted command through the shell seam.
39
39
  * @param {string} command shell command string (the seam executes it with bash -c)
40
- * @param {{ workdir?: string, session?: object, signal?: AbortSignal, timeoutMs?: number, stdoutMaxBytes?: number }} [options]
40
+ * @param {{ workdir?: string, session?: object, signal?: AbortSignal, timeoutMs?: number, stdoutMaxBytes?: number, env?: Record<string, string> }} [options]
41
41
  * @returns {Promise<{ command: string, exitCode: number | null, signal: string | null, timedOut: boolean, aborted: boolean, stdout: string, stderr: string, sandbox?: object }>}
42
42
  */
43
43
  return async function run(command, options = {}) {
@@ -49,6 +49,8 @@ export function createShellRunner({ ctx, config = {} }) {
49
49
  };
50
50
  if (workdir !== undefined) request.workdir = workdir;
51
51
  if (signal !== undefined) request.signal = signal;
52
+ // Ordinary env entries are merged after credential scrubbing by the executor.
53
+ if (options.env !== undefined) request.env = options.env;
52
54
  if (sandboxPolicy !== undefined && sandboxPolicy !== null) {
53
55
  const base = sandboxPolicy.resolve(session === undefined ? {} : { session });
54
56
  request.sandboxPolicy = session === undefined && workdir !== undefined
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-hive-runner",
3
- "version": "0.6.1",
3
+ "version": "0.6.4",
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",
@@ -20,7 +20,7 @@
20
20
  "LICENSE"
21
21
  ],
22
22
  "engines": {
23
- "node": ">=22"
23
+ "node": ">=22.19"
24
24
  },
25
25
  "scripts": {
26
26
  "test": "node --test test/*.test.js",