@dreamtree-org/harness-device 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.0
4
+
5
+ Ties the device into the Dreamtree agent standard 3, as described in ai-builder's `standard sdlc/environment` and `sdlc/evidence`.
6
+
7
+ - **`project_start` never starts a second copy.** If the process already runs, it is left alone and the reply says `alreadyRunning`. Pass `restart: true` to replace it. Previews and workspaces get this through `project_start`.
8
+ - **`preview_screenshot {save: true, label}`** also writes the PNG into the app's or workspace's `.dreamtree/evidence/captures/` and returns the path. Register it with `ai-builder evidence add screenshot <path> --ac <id>`.
9
+ - **`device_status.devDbProvisioner`** reports `absent` or `configured`. It checks only the name `DEV_PROVISIONER_DB_URL`, never its value. Per-workspace provisioning is still not built, so database-backed work stays BLOCKED, as before.
10
+ - **`proc list --json`** lists name, folder and running state, without the command. ai-builder's `session reconcile` reads it.
11
+
3
12
  ## 0.1.7
4
13
 
5
14
  - **Linux: upgrades and uninstall no longer fail on systemd's `harness.target.wants/` folder.** The installer took the folder for an old unit file and tried to delete it (EISDIR), so from 0.1.4 to 0.1.6 every upgrade after the first install was rolled back. An upgrade runs the new version's installer, so upgrading to 0.1.7 fixes an affected device with no manual steps.
package/README.md CHANGED
@@ -201,14 +201,14 @@ Repositories this device runs, kept in `APPS_DIR` (default `~/apps`). Unlike pro
201
201
  | --- | --- |
202
202
  | `git_clone` (`app clone <url>`) | Clones the repo and detects its stack, as a job. Private GitHub repos use the device secret `GITHUB_TOKEN`, passed to git through the environment only |
203
203
  | `project_setup` (`app setup`) | Detects node (npm, pnpm or yarn by lockfile), python (uv, poetry or pip), go, ruby, php or docker compose, then installs and builds, as a job |
204
- | `project_start` / `project_stop` | Runs the app as a long-running process with its `.env` and `PORT`. It's restarted on crash and reboot and held to the safe maximums |
204
+ | `project_start` / `project_stop` | Runs the app as a long-running process with its `.env` and `PORT`. It's restarted on crash and reboot and held to the safe maximums. Idempotent: a process that already runs is left alone (`restart: true` replaces it) |
205
205
  | `project_deploy` (`app deploy`) | Pull (fast-forward only), install, build, then restart if running, as one job. GitHub push webhooks run it |
206
206
  | `git_pull` | Updates only. It refuses when there are uncommitted changes |
207
207
  | `file_read` / `file_write` | Inside the app folder only; `.git` and `.env` are off limits |
208
208
  | `env_manage` | The app's `.env`. `list` shows names only. `set` takes a value or `from_secret` (copies a device secret without exposing it), and asks first |
209
209
  | `exec` | One program with an argv and no shell. The program must be on `EXEC_ALLOW` (a default list of dev tools); shells and wrappers such as `bash`, `env`, `sudo` or `xargs` are always refused. Runs in the app folder or a confined sub-folder. `env_refs` injects device secrets by name and redacts them from output. Timeout and output cap (head and tail kept). A durable job: `job_status` with `offset` streams new output, `job_cancel` kills the whole process tree. Never restarted. Linux holds the per-process caps in a systemd scope; on macOS the watchdog covers running jobs. Each run is recorded in `events` (program, folder, outcome, exit code, duration; never env or output) |
210
210
  | `workspace_create` / `workspace_list` / `workspace_status` / `workspace_archive` | Per-ticket workspaces of a cloned app. Each is a git worktree under `APPS_DIR/.worktrees/<app>/<ticket>` on branch `ticket/<TICKET>`, created from a pinned revision (`base`, default `origin/<branch>`; the SHA is recorded). It gets its own port (4100–4999, kept across retries) and is registered as the app `<app>--<ticket>`, so every app tool works on it. Creating it again returns the same workspace. Git operations on one repository are serialized by a lock. Archiving stops its process, removes the folder, frees the port and keeps the branch; uncommitted changes make it refuse unless the user agrees to discard them. `REPO_ALLOW` (owner/repo, owner/*) limits which repositories `git_clone` and workspaces accept. Per-workspace databases (`database: true`) answer BLOCKED until the shared development DB provisioner exists; no local database container is started instead |
211
- | `preview_start` / `preview_list` / `preview_stop` / `preview_screenshot` | Protected previews of an app or workspace. Starts its dev server on its own port if nothing answers there and health-checks it; on failure it returns the app's last output and stops it. A per-preview proxy listens on 127.0.0.1 only and forwards to that one app port. Every request needs a token bound to the preview and its expiry, signed with a device key (`state/preview.key`). The link sets an HttpOnly cookie. The record is checked on each request, so a stopped preview is refused at once, and WebSocket upgrades are checked too. Reach it with the SSH tunnel command it returns. A public ngrok URL is opt-in (`public: true`, user-approved) and still needs the token. `preview_stop` revokes the link, stops the proxy, closes the tunnel and stops the app if the preview started it. Expired previews, and previews whose app or proxy is gone, are ended by `preview_list` and by every watchdog pass (`limits --enforce`). `preview_screenshot` (browser capability) loads it in the device browser and returns a PNG |
211
+ | `preview_start` / `preview_list` / `preview_stop` / `preview_screenshot` | Protected previews of an app or workspace. Starts its dev server on its own port if nothing answers there and health-checks it; on failure it returns the app's last output and stops it. A per-preview proxy listens on 127.0.0.1 only and forwards to that one app port. Every request needs a token bound to the preview and its expiry, signed with a device key (`state/preview.key`). The link sets an HttpOnly cookie. The record is checked on each request, so a stopped preview is refused at once, and WebSocket upgrades are checked too. Reach it with the SSH tunnel command it returns. A public ngrok URL is opt-in (`public: true`, user-approved) and still needs the token. `preview_stop` revokes the link, stops the proxy, closes the tunnel and stops the app if the preview started it. Expired previews, and previews whose app or proxy is gone, are ended by `preview_list` and by every watchdog pass (`limits --enforce`). `preview_screenshot` (browser capability) loads it in the device browser and returns a PNG; `save: true` also keeps it in the app's `.dreamtree/evidence/captures/` for ai-builder's `evidence add screenshot` |
212
212
  | `shell_exec` (`app exec <app> -- <cmd>`) | One command in the app folder: up to 120s inline, otherwise as a job. Through the pool it needs `device:admin` |
213
213
  | `job_submit` | A durable job under an `effect_key`: steps, each an argv as in `exec` (same allowlist). The same key always returns the same job and never runs it twice; the same key with another payload is refused (`EFFECT_KEY_CONFLICT`). Finished steps are checkpointed. `retries` (up to 5, exponential backoff from `retry_backoff_seconds`) resume at the failed step. `artifacts` are recorded with size and sha256 |
214
214
  | `job_status` (`job <id>`) | Status, step and the end of the log for clone, setup, pull, deploy and long commands |
@@ -264,7 +264,7 @@ Repositories this device runs, kept in `APPS_DIR` (default `~/apps`). Unlike pro
264
264
  | `session list`, `session new <project>` | Add another persistent conversation for a project |
265
265
  | `session reset <project> [slot]` | Start a fresh conversation in a slot (the old ID is kept in history) |
266
266
  | `session adopt <project> <slot> <id>` | Pin a slot to an existing conversation ID |
267
- | `proc add <name> <dir> '<cmd>'`, `proc rm`, `proc list` | Keep a process running across crashes and reboots |
267
+ | `proc add <name> <dir> '<cmd>'`, `proc rm`, `proc list [--json]` | Keep a process running across crashes and reboots |
268
268
  | `attach [project]`, `logs <target> [-n] [-f]`, `events` | Look inside; `events` shows restores, resets and failures |
269
269
  | `restart <service>` | Restart one harness service |
270
270
  | `tunnel` | The SSH command for the viewers |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dreamtree-org/harness-device",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Turn a Linux server into a reboot-proof Claude Code harness: Remote Control per project in tmux, a persistent Chromium + Playwright MCP on a virtual display, live viewers (noVNC, ttyd, Playwright UI), self-healing systemd services, plus Docker, Dokploy, ngrok and AI-provider tooling.",
5
5
  "author": {
6
6
  "name": "Partha Preetham Krishna",
package/src/cli.js CHANGED
@@ -37,7 +37,7 @@ ${color.bold('Projects and sessions')} (survive reboots: each slot resumes its o
37
37
  session adopt <project> <slot> <id> pin a slot to an existing conversation id
38
38
  session rm <project> <slot>
39
39
  proc add <name> <dir> '<command>' keep a process running across crashes and reboots
40
- proc rm <name> | list
40
+ proc rm <name> | list [--json]
41
41
  attach [project|window] open the tmux session (Ctrl-b d to detach)
42
42
  logs <project|rc-…|proc-…|tests|service> [-n 100] [-f]
43
43
  events restores, resets and failures, newest last
@@ -333,7 +333,7 @@ export async function main(argv) {
333
333
  if (!sub || sub === 'list') return out(pr.list(ctx));
334
334
  if (sub === 'clone') return out(await pr.clone(ctx, { url: rest[0], name: f.name, branch: f.branch, tokenSecret: f.tokenSecret, session: !!f.session }));
335
335
  if (['pull', 'setup', 'deploy'].includes(sub)) return out(await pr[sub](ctx, { app: rest[0] }));
336
- if (sub === 'start') return out(pr.start(ctx, { app: rest[0], command: f.command, port: f.port }));
336
+ if (sub === 'start') return out(pr.start(ctx, { app: rest[0], command: f.command, port: f.port, restart: !!f.restart }));
337
337
  if (sub === 'stop') return out(pr.stop(ctx, { app: rest[0] }));
338
338
  if (sub === 'exec') return out(await pr.shellExec(ctx, { app: rest[0], command: rest.slice(1).join(' '), timeoutSeconds: f.timeout }));
339
339
  throw new Error('usage: harness-device app list|clone|pull|setup|start|stop|deploy|exec');
@@ -478,6 +478,7 @@ export async function main(argv) {
478
478
  return log.ok(`proc ${name} registered; running in tmux window proc-${name}`);
479
479
  }
480
480
  if (sub === 'rm') { guardOwn(ctx, `proc-${rest[0]}`, f); state.removeProc(ctx, rest[0]); return log.ok(`proc ${rest[0]} removed`); }
481
+ if (f.json) return console.log(JSON.stringify(state.listProcs(ctx).map(({ name, dir, running }) => ({ name, dir, running })), null, 2));
481
482
  for (const p of state.listProcs(ctx)) console.log(`${p.running ? '●' : '○'} ${p.name}\t${p.dir}\t${p.command}`);
482
483
  return;
483
484
  }
package/src/device.js CHANGED
@@ -10,6 +10,7 @@ import { loadConfig, saveConfig, mergePorts } from './config.js';
10
10
  import * as ngrok from './ngrok.js';
11
11
  import { isStopped } from './lifecycle.js';
12
12
  import * as resources from './resources.js';
13
+ import { readSecrets } from './context.js';
13
14
 
14
15
  const short = (u) => u.replace(/^harness-/, '');
15
16
  const logical = (name) => (name.startsWith('harness-') ? name : `harness-${name}`).replace(/\.(service|timer)$/, '');
@@ -77,6 +78,7 @@ export async function status(ctx) {
77
78
  browser: cdp ? cdp.Browser : null,
78
79
  viewers: viewers(ctx.cfg, ctx.platform),
79
80
  resources: await resources.sample(ctx, { quick: true }),
81
+ devDbProvisioner: devDbProvisioner(ctx),
80
82
  };
81
83
  }
82
84
 
@@ -189,3 +191,14 @@ export async function ngrokUp(ctx, { tunnels = [], ports = [] } = {}) {
189
191
  login: guarded.length ? { user: cfg.NGROK_VIEWER_USER, password: cfg.NGROK_VIEWER_PASS, for: guarded } : null,
190
192
  };
191
193
  }
194
+
195
+ /**
196
+ * Whether the shared dev-database provisioner is configured here: the secret's
197
+ * name only, never its value. Provisioning itself is not built (Dreamtree
198
+ * standard sdlc/dev-database), so database-backed work reports BLOCKED.
199
+ */
200
+ export function devDbProvisioner(ctx) {
201
+ const present = Object.prototype.hasOwnProperty.call(readSecrets(ctx.paths.secrets), 'DEV_PROVISIONER_DB_URL');
202
+ return { status: present ? 'configured' : 'absent', provisioning: 'not implemented (contract only)',
203
+ note: present ? 'configured, but per-workspace provisioning does not exist yet: report the database step as BLOCKED' : 'no DEV_PROVISIONER_DB_URL on this device: database-backed work is BLOCKED' };
204
+ }
package/src/mcp/server.js CHANGED
@@ -139,9 +139,9 @@ export function buildServer(env = process.env, opts = {}) {
139
139
  return text({ plan: r.plan, ...(r.job ? { job: r.job.id, status: r.job.status, note: `follow it with job_status {"id":"${r.job.id}"}` } : { note: r.note }) });
140
140
  });
141
141
 
142
- tool('project_start', 'Run an app as a long-running process (restarted on crash and reboot, held to the safe maximums), with its .env loaded and PORT set when known. Uses the detected start command unless command is given.',
143
- { app: APP, command: z.string().max(500).optional().describe('one shell line, e.g. "npm run dev -- --port 4000"'), port: z.number().int().min(1).max(65535).optional(), ...FORCE },
144
- async (c, a) => { await guard(c, a, `starting ${a.app}`); return text(project.start(c, { app: a.app, command: a.command, port: a.port })); });
142
+ tool('project_start', 'Run an app as a long-running process (restarted on crash and reboot, held to the safe maximums), with its .env loaded and PORT set when known. Uses the detected start command unless command is given. Idempotent: a process that already runs is left alone (restart=true replaces it), so it never starts a second copy.',
143
+ { app: APP, command: z.string().max(500).optional().describe('one shell line, e.g. "npm run dev -- --port 4000"'), port: z.number().int().min(1).max(65535).optional(), restart: z.boolean().optional(), ...FORCE },
144
+ async (c, a) => { await guard(c, a, `starting ${a.app}`); return text(project.start(c, { app: a.app, command: a.command, port: a.port, restart: a.restart })); });
145
145
 
146
146
  tool('project_stop', 'Stop an app\'s process (asks the user first). The app and its files stay; project_start runs it again.',
147
147
  { app: APP, ...CONFIRM },
@@ -246,9 +246,14 @@ export function buildServer(env = process.env, opts = {}) {
246
246
  async (c, a) => text(await preview.stopPreview(c, { id: a.id, stopApp: !a.keep_app })));
247
247
 
248
248
  if (has(base, 'browser')) {
249
- tool('preview_screenshot', 'Evidence: open an active preview in the device browser and return a PNG of the page.',
250
- { id: z.string().regex(/^pv-[0-9a-f]{8}$/), width: z.number().int().min(320).max(2560).optional(), height: z.number().int().min(240).max(2560).optional() },
251
- async (c, a) => ({ content: [{ type: 'image', data: await preview.screenshot(c, a.id, { width: a.width, height: a.height }), mimeType: 'image/png' }] }));
249
+ tool('preview_screenshot', 'Evidence: open an active preview in the device browser and return a PNG of the page. save=true also writes it into the app\'s .dreamtree/evidence/captures/ (Dreamtree standard sdlc/evidence) and returns the path, to register with `ai-builder evidence add screenshot <path> --ac <id>`.',
250
+ { id: z.string().regex(/^pv-[0-9a-f]{8}$/), width: z.number().int().min(320).max(2560).optional(), height: z.number().int().min(240).max(2560).optional(),
251
+ save: z.boolean().optional(), label: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/).optional() },
252
+ async (c, a) => {
253
+ const data = await preview.screenshot(c, a.id, { width: a.width, height: a.height });
254
+ const saved = a.save ? preview.saveEvidence(c, a.id, data, a.label) : null;
255
+ return { content: [...(saved ? [{ type: 'text', text: JSON.stringify(saved, null, 2) }] : []), { type: 'image', data, mimeType: 'image/png' }] };
256
+ });
252
257
  }
253
258
 
254
259
  tool('job_submit', 'Submit a durable job under an effect key: steps run in order without a shell (each argv as in exec, same allowlist), in an app folder. The same effect_key always returns the same job (never run twice); the same key with a different payload is refused (EFFECT_KEY_CONFLICT). Finished steps are checkpointed: retries (0-5, exponential backoff from retry_backoff_seconds) resume at the failed step. If the device restarts mid-job, the job fails as uncertain (not re-run) unless retry_interrupted=true says its steps are safe to resume. artifacts: files (relative to the app) recorded with size and sha256. Waits up to wait_seconds (default 30), then follow it with job_status; stop it with job_cancel.',
package/src/preview.js CHANGED
@@ -134,7 +134,8 @@ export async function startPreview(ctx, { app: name, ttlMinutes = 60, healthSeco
134
134
  const cmd = command || app.startOverride || app.start;
135
135
  if (!cmd) throw new Error(`No start command known for ${app.name}: give command (e.g. "npm run dev")`);
136
136
  if (inline(ctx)) runProc(ctx, procName(app), app.dir, project.startLine(cmd, port));
137
- else project.start(ctx, { app: app.name, command, port });
137
+ // Nothing answers on the port: a registered process there is stuck, so replace it (restart) rather than leave it.
138
+ else project.start(ctx, { app: app.name, command, port, restart: true });
138
139
  startedApp = true;
139
140
  if (!(await waitHealthy(port, healthSeconds, healthPath))) {
140
141
  const logs = tailOf(procLog(ctx, procName(app)));
@@ -312,6 +313,24 @@ export function serveProxy(ctx, id) {
312
313
  });
313
314
  }
314
315
 
316
+ /**
317
+ * Keep a screenshot as evidence in the previewed app's (or workspace's) folder:
318
+ * .dreamtree/evidence/captures/<label>-<time>.png. ai-builder binds it to the
319
+ * source revision when it is registered (`evidence add screenshot`).
320
+ */
321
+ export function saveEvidence(ctx, id, base64, label = 'screen') {
322
+ if (!/^[a-z0-9][a-z0-9_-]{0,39}$/.test(label)) throw new Error(`label must be lowercase letters, digits, _ or - (got "${label}")`);
323
+ const rec = getPreview(ctx, id);
324
+ if (!rec) throw new Error(`No preview ${id}`);
325
+ const appDir = getApp(ctx, rec.app).dir;
326
+ const out = path.join(appDir, '.dreamtree', 'evidence', 'captures');
327
+ fs.mkdirSync(out, { recursive: true });
328
+ const file = path.join(out, `${label}-${new Date().toISOString().replace(/[:.]/g, '-')}.png`);
329
+ fs.writeFileSync(file, Buffer.from(base64, 'base64'));
330
+ const rel = path.relative(appDir, file);
331
+ return { file, relative: rel, bytes: fs.statSync(file).size, next: `npx @dreamtree-org/ai-builder evidence add screenshot ${rel} --ac <AC id>` };
332
+ }
333
+
315
334
  /** Load the preview in the device browser over CDP and return a PNG (base64). */
316
335
  export async function screenshot(ctx, id, { width = 1280, height = 800, waitMs = 1500 } = {}) {
317
336
  const rec = getPreview(ctx, id);
package/src/project.js CHANGED
@@ -90,7 +90,8 @@ export function startLine(command, port) {
90
90
  return `set -a; [ -f .env ] && . ./.env; set +a; ${port ? `export PORT=\${PORT:-${Number(port)}}; ` : ''}exec ${command}`;
91
91
  }
92
92
 
93
- export function start(ctx, { app: name, command, port }) {
93
+ /** Run an app as a managed process. Idempotent: a running process is left alone (restart:true replaces it). */
94
+ export function start(ctx, { app: name, command, port, restart = false }) {
94
95
  const app = getApp(ctx, name);
95
96
  const plan = command ? null : detect(app.dir);
96
97
  const cmd = command || app.startOverride || app.start || plan?.start;
@@ -98,6 +99,9 @@ export function start(ctx, { app: name, command, port }) {
98
99
  if (/\n/.test(cmd)) throw new Error('One line, please');
99
100
  const p = port ? Number(port) : app.port || plan?.port || null;
100
101
  if (port && !(p >= 1 && p <= 65535)) throw new Error('port must be 1-65535');
102
+ if (running(ctx, app) && !restart) {
103
+ return { app: app.name, process: procName(app), alreadyRunning: true, port: app.port || p, note: 'already running: left alone (restart:true replaces it)' };
104
+ }
101
105
  if (!app.project) saveApp(ctx, { ...app, ...(command ? { startOverride: command } : {}), ...(p ? { port: p } : {}) });
102
106
  state.addProc(ctx, procName(app), app.dir, startLine(cmd, p));
103
107
  return { app: app.name, process: procName(app), command: cmd, port: p, logs: `logs tool, target "proc-${procName(app)}"` };