@dreamtree-org/harness-device 0.6.0 → 0.8.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/README.md CHANGED
@@ -210,13 +210,25 @@ Repositories this device runs, kept in `APPS_DIR` (default `~/apps`). Unlike pro
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
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 |
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
+ | `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 |
213
214
  | `job_status` (`job <id>`) | Status, step and the end of the log for clone, setup, pull, deploy and long commands |
214
215
 
215
216
  **Recovering a job** (`exec`, clone, setup, deploy):
216
217
  - `job_status {id}` shows its status, step, pid and the end of its log; `job_status {id, offset}` continues the log from a byte offset.
217
218
  - `job_cancel {id}` ends a stuck one, killing its whole process group (TERM, then KILL after 5s).
218
219
  - Records and logs are in `~/.harness-device/state/jobs/` and `logs/jobs/`, and the last 50 are kept. A job the watchdog stops for going over its caps ends as failed, with an event.
219
- - A job whose runner died, for example in a reboot, still shows as running with a dead pid. `job_cancel` clears it.
220
+ - A job whose runner died (a crash or a reboot) is settled by the watchdog (`limits --enforce`), or at once by `harness-device job reconcile`:
221
+ - Whatever is left of its process tree is stopped.
222
+ - A `job_submit` job with `retry_interrupted: true` and retry budget left resumes from its last checkpoint.
223
+ - Any other job fails as **uncertain** (a step may have half-run) and is never run again. Check the state before submitting it under a new key.
224
+
225
+ **RunLoom worker** (`harness-device runloom`): this device claims leased tasks from RunLoom; RunLoom stays the scheduler.
226
+ - **Setup:** set `RUNLOOM_URL`, store the worker-pool credential as the device secret `RUNLOOM_CREDENTIAL`, and run it as a registered process (`proc_add`).
227
+ - **Tasks:** a task is an action with `{connector: "harness-device", operation: "job", input: <job_submit payload>}`. It runs as a durable job keyed by the task's `effect_key`, so a re-leased task finds the same job instead of running it again.
228
+ - **Heartbeats** carry `job:<id>:checkpoint:<n>`. A cancel request stops the job's process tree.
229
+ - **Stale leases:** a lost lease (409) stops the reporting, never the job; the next lease reports its result.
230
+ - **Failures** are reported as not retryable: retries happen on the device, within the job's budget.
231
+ - **Routing:** the claim API has no per-device queue yet, so give each device its own worker pool.
220
232
 
221
233
  **Recovering a workspace:**
222
234
  - `workspace_status` shows what is uncommitted and how far the branch is ahead.
@@ -379,3 +391,17 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
379
391
  ---
380
392
 
381
393
  **Made with ❤️ by [Partha Preetham Krishna](https://www.linkedin.com/in/partha-preetham-krishna-68ba00197/)** under [Dreamtree-Org](https://www.dreamtreeglobal.com) · [www.dreamtreeglobal.com](https://www.dreamtreeglobal.com)
394
+
395
+ **Link health, readiness and leases:**
396
+ - **Heartbeats:** each link to the hub is a session, and every heartbeat carries a sequence number, so the hub drops beats that are replayed or out of order.
397
+ - Each beat also reports readiness separately from being connected: not stopped or restarting on purpose, not critical, and `POOL_SCOPES` allowing work. Placement uses only devices that are both online and ready.
398
+ - Each beat also reports the running jobs and processes, and the boot time; a reboot shows in the hub's audit.
399
+ - A device silent for 45s is offline, and no work goes to it.
400
+ - **Reconnects:** 1s, doubling to 60s while it fails, with jitter.
401
+ - **Leases:** every pool call with side effects carries a lease (id, a fence that only grows, expiry), and runs at most once:
402
+ - The device journals each lease in `state/leases/`. A lease delivered again is answered from the journal.
403
+ - An expired lease, or one older than the last finished, is refused.
404
+ - A dropped link does not stop a running call. After reconnecting, the hub asks for the leases it still waits on and the device answers from the journal.
405
+ - A call cut off by a restart or reboot is reported as uncertain and never re-run, so check the state before retrying.
406
+ - The hub refuses results for expired leases or with the wrong fence, and records them in the device's audit.
407
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dreamtree-org/harness-device",
3
- "version": "0.6.0",
3
+ "version": "0.8.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
@@ -277,6 +277,7 @@ export async function main(argv) {
277
277
  if (f.enforce) {
278
278
  const r = await limits.enforce(ctx);
279
279
  try { for (const p of await (await import('./preview.js')).reconcile(ctx)) log.info(`preview ${p.id} ended: ${p.reason}`); } catch (e) { log.warn(`previews: ${e.message}`); }
280
+ try { for (const j of (await import('./jobs.js')).reconcileJobs(ctx)) log.warn(`job ${j.id} interrupted: ${j.action}${j.uncertain ? ' (effect uncertain, not re-run)' : ''}`); } catch (e) { log.warn(`jobs: ${e.message}`); }
280
281
  if (f.json) return console.log(JSON.stringify(r, null, 2));
281
282
  for (const a of r.actions) log.warn(`stopped ${a.name}: ${a.reason}`);
282
283
  if (!f.quiet && !r.actions.length) log.ok('all within limits');
@@ -351,11 +352,19 @@ export async function main(argv) {
351
352
  return console.log(JSON.stringify(preview.listPreviews(ctx), null, 2));
352
353
  }
353
354
 
355
+ case 'runloom': {
356
+ const ctx = loadContext(env);
357
+ const ac = new AbortController();
358
+ for (const sig of ['SIGTERM', 'SIGINT']) process.once(sig, () => { log.info('stopping: in-flight tasks finish first'); ac.abort(); });
359
+ return (await import('./runloom.js')).run(ctx, { signal: ac.signal, log: (m) => log.info(m) });
360
+ }
361
+
354
362
  case 'job':
355
363
  case 'jobs': {
356
364
  const ctx = loadContext(env);
357
365
  const jobs = await import('./jobs.js');
358
366
  if (sub === 'run') { const j = await jobs.runJob(ctx, rest[0]); process.exitCode = j.status === 'done' ? 0 : 1; return; }
367
+ if (sub === 'reconcile') return console.log(JSON.stringify(jobs.reconcileJobs(ctx), null, 2));
359
368
  if (!sub || sub === 'list') return console.log(JSON.stringify(jobs.listJobs(ctx), null, 2));
360
369
  return console.log(JSON.stringify(jobs.describeJob(ctx, jobs.getJob(ctx, sub)), null, 2));
361
370
  }
package/src/config.js CHANGED
@@ -106,6 +106,11 @@ export function defaults(env = process.env) {
106
106
  // Repositories git_clone and workspaces may use: comma list of owner/repo
107
107
  // or owner/* (empty = any).
108
108
  REPO_ALLOW: '',
109
+ // RunLoom worker (harness-device runloom): the RunLoom API this device
110
+ // claims leased tasks from, with the worker-pool credential stored as the
111
+ // device secret RUNLOOM_CREDENTIAL. Empty = not a RunLoom worker.
112
+ RUNLOOM_URL: '',
113
+ RUNLOOM_CONCURRENCY: '2',
109
114
  };
110
115
  }
111
116
 
@@ -219,6 +224,8 @@ export function validateConfig(cfg, env = process.env) {
219
224
  if (!/^\d+$/.test(String(cfg.RES_WAIT_SECONDS)) || Number(cfg.RES_WAIT_SECONDS) > 3600) errs.push('RES_WAIT_SECONDS must be 0-3600.');
220
225
  errs.push(...limitsMod.validate(cfg));
221
226
  if (cfg.EXEC_ALLOW && !/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}(,[A-Za-z0-9][A-Za-z0-9._+-]{0,63})*$/.test(String(cfg.EXEC_ALLOW).replace(/\s/g, ''))) errs.push('EXEC_ALLOW must be a comma-separated list of program names.');
227
+ if (cfg.RUNLOOM_URL) { let u = null; try { u = new URL(cfg.RUNLOOM_URL); } catch { /* invalid */ } if (!u || !(u.protocol === 'https:' || ['localhost', '127.0.0.1'].includes(u.hostname)) || u.search || u.hash) errs.push('RUNLOOM_URL must be an https URL (no query), e.g. https://runloom.example.com.'); }
228
+ if (cfg.RUNLOOM_CONCURRENCY && !/^([1-9]|1[0-6])$/.test(String(cfg.RUNLOOM_CONCURRENCY))) errs.push('RUNLOOM_CONCURRENCY must be a number from 1 to 16.');
222
229
  if (cfg.REPO_ALLOW && !String(cfg.REPO_ALLOW).split(',').map((x) => x.trim()).filter(Boolean).every((x) => /^[A-Za-z0-9_.-]+\/([A-Za-z0-9_.-]+|\*)$/.test(x))) errs.push('REPO_ALLOW must be a comma-separated list of owner/repo or owner/*.');
223
230
  if (cfg.APPS_DIR && (!path.isAbsolute(String(cfg.APPS_DIR)) || /['"\t\n\\$`]/.test(String(cfg.APPS_DIR)))) errs.push('APPS_DIR must be an absolute path without quotes or special characters.');
224
231
  if (cfg.POOL_SCOPES !== undefined && !/^device:(read|operate|admin)(,device:(read|operate|admin))*$/.test(String(cfg.POOL_SCOPES).replace(/\s/g, ''))) errs.push('POOL_SCOPES must be a comma-separated list of device:read, device:operate, device:admin.');
package/src/durable.js ADDED
@@ -0,0 +1,103 @@
1
+ // Durable job submission (HARNESS-3): submit a job under an effect key, once.
2
+ //
3
+ // The effect key names the effect, not the attempt: the same key always maps
4
+ // to the same job (its id is derived from the key), so a caller that retries
5
+ // after a timeout, a dropped link or a lost RunLoom lease gets the job that is
6
+ // already running or finished instead of a second run. Submitting the same key
7
+ // with a different payload is refused (EFFECT_KEY_CONFLICT): it would be a
8
+ // different effect under a name already used.
9
+ //
10
+ // The index (state/effects/<sha256(key)>.json) is created with O_EXCL, so two
11
+ // submitters racing on one key cannot both start a job.
12
+ //
13
+ // Payload: { app, steps: [{ argv, cwd? }], env_refs?, timeout_seconds?,
14
+ // max_output_kb?, retries?, retry_backoff_seconds?, retry_interrupted?,
15
+ // artifacts? }. Every step goes through the exec allowlist and confinement
16
+ // (src/exec.js), like the exec tool.
17
+
18
+ import crypto from 'node:crypto';
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+ import { checkExec } from './exec.js';
22
+ import { startJob, getJob } from './jobs.js';
23
+
24
+ export const EFFECT_KEY = /^[\w.:@/-]{8,191}$/;
25
+ const LIMITS = { retries: 5, backoff: 300, timeout: 3600, outputKb: 4096, steps: 20, artifacts: 50 };
26
+
27
+ const sha = (s) => crypto.createHash('sha256').update(s).digest('hex');
28
+ /** JSON with sorted keys: the same payload always hashes the same. */
29
+ export function canonical(v) {
30
+ if (Array.isArray(v)) return `[${v.map(canonical).join(',')}]`;
31
+ if (v && typeof v === 'object') return `{${Object.keys(v).filter((k) => v[k] !== undefined).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(',')}}`;
32
+ return JSON.stringify(v ?? null);
33
+ }
34
+ const indexOf = (ctx, key) => path.join(ctx.paths.state, 'effects', `${sha(key)}.json`);
35
+ export const jobIdFor = (key) => `task-${sha(key).slice(0, 24)}`;
36
+
37
+ const fail = (code, message) => Object.assign(new Error(message), { code });
38
+
39
+ /** Check the payload and turn it into startJob options. Throws with a reason. */
40
+ export function plan(ctx, payload) {
41
+ const p = payload || {};
42
+ if (!Array.isArray(p.steps) || !p.steps.length) throw fail('VALIDATION', 'steps: give at least one step, { argv: [program, ...args], cwd? }');
43
+ if (p.steps.length > LIMITS.steps) throw fail('VALIDATION', `steps: at most ${LIMITS.steps}`);
44
+ const int = (v, name, max, dflt) => {
45
+ if (v === undefined || v === null) return dflt;
46
+ if (!Number.isInteger(v) || v < 0 || v > max) throw fail('VALIDATION', `${name} must be a whole number from 0 to ${max}`);
47
+ return v;
48
+ };
49
+ const checked = p.steps.map((s, i) => {
50
+ try { return checkExec(ctx, { app: p.app, argv: s?.argv, cwd: s?.cwd ?? '.', envRefs: p.env_refs || {} }); } catch (e) { throw fail('VALIDATION', `step ${i + 1}: ${e.message}`); }
51
+ });
52
+ const artifacts = p.artifacts === undefined ? null : p.artifacts;
53
+ if (artifacts && (!Array.isArray(artifacts) || artifacts.length > LIMITS.artifacts || artifacts.some((a) => typeof a !== 'string' || !a || path.isAbsolute(a) || a.split(/[\\/]/).includes('..')))) {
54
+ throw fail('VALIDATION', `artifacts: up to ${LIMITS.artifacts} paths relative to the app folder, without ..`);
55
+ }
56
+ return {
57
+ kind: 'task', app: checked[0].app.name, appDir: checked[0].app.dir, envRefs: checked[0].envRefs,
58
+ steps: checked.map((c) => ({ name: path.basename(c.exe), argv: c.argv, cwd: c.cwd })),
59
+ timeoutSeconds: int(p.timeout_seconds, 'timeout_seconds', LIMITS.timeout, 600) || 600,
60
+ maxOutputBytes: (int(p.max_output_kb, 'max_output_kb', LIMITS.outputKb, 256) || 256) * 1024,
61
+ retries: int(p.retries, 'retries', LIMITS.retries, 0),
62
+ backoffSeconds: int(p.retry_backoff_seconds, 'retry_backoff_seconds', LIMITS.backoff, 5),
63
+ retryInterrupted: p.retry_interrupted === true,
64
+ artifacts,
65
+ };
66
+ }
67
+
68
+ /**
69
+ * Submit `payload` under `effectKey`. Returns { job, existing }: existing=true
70
+ * when the key was already submitted (same payload); the job is not started
71
+ * again. Throws EFFECT_KEY_CONFLICT for the same key with another payload.
72
+ */
73
+ export async function submit(ctx, { effectKey, payload }) {
74
+ if (!EFFECT_KEY.test(String(effectKey || ''))) throw fail('VALIDATION', 'effect_key: 8-191 characters of letters, digits and . : @ / _ -');
75
+ const hash = sha(canonical(payload || {}));
76
+ const idx = indexOf(ctx, effectKey);
77
+ fs.mkdirSync(path.dirname(idx), { recursive: true });
78
+ const id = jobIdFor(effectKey);
79
+ try {
80
+ fs.writeFileSync(idx, JSON.stringify({ key: effectKey, hash, job: id, at: new Date().toISOString() }), { flag: 'wx', mode: 0o600 });
81
+ } catch (e) {
82
+ if (e.code !== 'EEXIST') throw e;
83
+ const prev = JSON.parse(fs.readFileSync(idx, 'utf8'));
84
+ if (prev.hash !== hash) throw fail('EFFECT_KEY_CONFLICT', `effect_key ${effectKey} was already used for a different payload (job ${prev.job}); use a new key for a different effect`);
85
+ let job;
86
+ try { job = getJob(ctx, prev.job); } catch { throw fail('EFFECT_KEY_EXPIRED', `effect_key ${effectKey} ran as job ${prev.job}, whose record has since been pruned; it is not run again`); }
87
+ return { job, existing: true };
88
+ }
89
+ let opts;
90
+ try { opts = plan(ctx, payload); } catch (e) { fs.rmSync(idx, { force: true }); throw e; }
91
+ // Inline (tests): startJob runs the job and resolves at the end; the record exists at once.
92
+ startJob(ctx, { ...opts, id, effectKey }).catch(() => {});
93
+ return { job: getJob(ctx, id), existing: false };
94
+ }
95
+
96
+ /** The result a caller (or RunLoom) gets for a finished job. */
97
+ export function result(ctx, job, tail) {
98
+ return {
99
+ job_id: job.id, effect_key: job.effectKey, status: job.status, exit: job.exit, uncertain: !!job.uncertain,
100
+ timed_out: !!job.timedOut, cancelled: !!job.cancelled, attempts: (job.attempts || []).length, checkpoint: job.checkpoint,
101
+ steps: job.steps.length, artifacts: job.artifactInfo || [], error: job.error || null, output_tail: tail,
102
+ };
103
+ }
package/src/jobs.js CHANGED
@@ -7,9 +7,22 @@
7
7
  // that this module runs in-process (saving the app after a clone, restarting
8
8
  // its process). Secrets reach git only through the environment, never the
9
9
  // command line, the job file or the log.
10
+ //
11
+ // Durable jobs (HARNESS-3) add, per job:
12
+ // - checkpoint: the number of steps finished; a retry or a resume after a
13
+ // crash starts from there, never re-running finished steps;
14
+ // - retries / backoffSeconds: a bounded retry budget for a failed step
15
+ // (exponential backoff, cancellable); every attempt is kept in `attempts`;
16
+ // - runnerPid / runnerBoot: who runs it, so reconcileJobs() can tell a job
17
+ // whose runner died (crash, reboot) and settle it: the orphaned process
18
+ // tree is killed, and the job is resumed from its checkpoint only when it
19
+ // was declared safe to (retryInterrupted) with budget left; otherwise it
20
+ // fails as "uncertain" (a step may have half-run) and is never re-run;
21
+ // - artifacts: files (relative to the app) recorded with size and sha256.
10
22
 
11
23
  import crypto from 'node:crypto';
12
24
  import fs from 'node:fs';
25
+ import os from 'node:os';
13
26
  import path from 'node:path';
14
27
  import { spawn, spawnSync } from 'node:child_process';
15
28
  import { readSecrets } from './context.js';
@@ -62,9 +75,11 @@ export function tail(file, lines = 80) {
62
75
  * tokenSecret: the name of a device secret git may use for https://github.com.
63
76
  * Returns the job.
64
77
  */
65
- export function startJob(ctx, { kind, app = null, steps, tokenSecret = null, inline = false, timeoutSeconds = null, maxOutputBytes = null, envRefs = null }) {
66
- const id = `${kind}-${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`.toLowerCase();
78
+ export function startJob(ctx, { kind, app = null, steps, tokenSecret = null, inline = false, timeoutSeconds = null, maxOutputBytes = null, envRefs = null,
79
+ id: givenId = null, effectKey = null, retries = 0, backoffSeconds = 5, retryInterrupted = false, artifacts = null, appDir = null }) {
80
+ const id = givenId || `${kind}-${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`.toLowerCase();
67
81
  const job = {
82
+ effectKey, retries, backoffSeconds, retryInterrupted, artifacts, appDir, checkpoint: 0, attempts: [], runnerPid: null, runnerBoot: null, uncertain: false,
68
83
  id, kind, app, status: 'queued', step: null,
69
84
  steps: steps.map((s) => ({ name: s.name, cmd: s.cmd || null, argv: s.argv || null, cwd: s.cwd || null, internal: s.internal || null, args: s.args || null })),
70
85
  tokenSecret, envRefs, timeoutSeconds, maxOutputBytes, exit: null, error: null, pid: null, timedOut: false, cancelRequested: false, cancelled: false,
@@ -74,6 +89,12 @@ export function startJob(ctx, { kind, app = null, steps, tokenSecret = null, inl
74
89
  prune(ctx);
75
90
  fs.mkdirSync(path.dirname(logOf(ctx, id)), { recursive: true });
76
91
  if (inline || ctx.env.HD_JOBS_INLINE === '1') return runJob(ctx, id).then(() => getJob(ctx, id));
92
+ launch(ctx, id);
93
+ return Promise.resolve(job);
94
+ }
95
+
96
+ /** Start the detached runner of a job (`harness-device job run <id>`). */
97
+ function launch(ctx, id) {
77
98
  const bin = path.join(PKG_ROOT, 'bin', 'harness-device.js');
78
99
  const args = [process.execPath, bin, 'job', 'run', id];
79
100
  if (ctx.platform.id === 'linux' && !scopesWork(ctx.env)) {
@@ -86,9 +107,13 @@ export function startJob(ctx, { kind, app = null, steps, tokenSecret = null, inl
86
107
  } else {
87
108
  ctx.platform.spawnDetached(ctx, `job-${id}`, args, logOf(ctx, id));
88
109
  }
89
- return Promise.resolve(job);
90
110
  }
91
111
 
112
+ /** When this machine booted (seconds, rounded: stable across calls). */
113
+ export const bootTime = () => Math.round((Date.now() / 1000 - os.uptime()) / 30) * 30;
114
+ const alive = (pid) => { if (!pid) return false; try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
115
+ const groupAlive = (pgid) => { if (!pgid) return false; try { process.kill(-pgid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
116
+
92
117
  /** The environment a job gets: never Anthropic keys, pool or serve credentials. */
93
118
  export function cleanEnv(env) {
94
119
  const e = { ...env };
@@ -185,7 +210,7 @@ function runStep(ctx, job, step, env, log, redact) {
185
210
  child.stderr.on('data', (b) => out.write(b));
186
211
  let timer = null;
187
212
  if (job.timeoutSeconds) {
188
- const left = Math.max(1, job.timeoutSeconds * 1000 - (Date.now() - Date.parse(job.startedAt)));
213
+ const left = Math.max(1, job.timeoutSeconds * 1000 - (Date.now() - Date.parse(job.attemptStartedAt || job.startedAt)));
189
214
  timer = setTimeout(() => { job.timedOut = true; killGroup(child.pid, 3000); }, left);
190
215
  }
191
216
  child.on('error', (e) => { out.write(`${e.message}\n`); });
@@ -220,49 +245,137 @@ export async function runJob(ctx, id, internals = {}) {
220
245
  const redact = (s) => hidden.reduce((acc, h) => acc.split(h).join('***'), s);
221
246
  const env = { ...cleanEnv(ctx.env), ...gitAuthEnv(token), ...Object.fromEntries(refs), CI: '1' };
222
247
  job.status = 'running';
223
- job.startedAt = new Date().toISOString();
248
+ job.startedAt ||= new Date().toISOString();
249
+ job.runnerPid = process.pid;
250
+ job.runnerBoot = bootTime();
251
+ job.checkpoint ||= 0;
252
+ job.attempts ||= [];
224
253
  write(ctx, job);
225
254
  const say = (m) => fs.appendFileSync(log, `\n[harness-device] ${m}\n`);
226
255
  const builtins = { ...(await import('./project.js')).INTERNALS, ...internals };
227
- try {
228
- for (const [i, s] of job.steps.entries()) {
229
- job.step = i;
230
- write(ctx, job);
231
- say(`step ${i + 1}/${job.steps.length}: ${s.name}${s.cmd ? `: ${redact(s.cmd)}` : ''}`);
232
- if (s.internal) {
233
- if (!builtins[s.internal]) throw new Error(`unknown internal step ${s.internal}`);
234
- await builtins[s.internal](ctx, job, s.args || {});
235
- continue;
256
+ const cancelled = () => { job.cancelRequested = job.cancelRequested || getJob(ctx, id).cancelRequested; return job.cancelRequested; };
257
+ for (;;) {
258
+ const attempt = { n: job.attempts.length + 1, from: job.checkpoint, startedAt: new Date().toISOString() };
259
+ job.attemptStartedAt = attempt.startedAt;
260
+ job.timedOut = false;
261
+ if (attempt.n > 1) say(`attempt ${attempt.n} of ${(job.retries || 0) + 1}, from step ${job.checkpoint + 1}`);
262
+ try {
263
+ for (let i = job.checkpoint; i < job.steps.length; i++) {
264
+ const s = job.steps[i];
265
+ job.step = i;
266
+ write(ctx, job);
267
+ say(`step ${i + 1}/${job.steps.length}: ${s.name}${s.cmd ? `: ${redact(s.cmd)}` : ''}`);
268
+ if (s.internal) {
269
+ if (!builtins[s.internal]) throw new Error(`unknown internal step ${s.internal}`);
270
+ await builtins[s.internal](ctx, job, s.args || {});
271
+ } else {
272
+ if (cancelled()) throw new Error('cancelled');
273
+ const { code } = await runStep(ctx, job, s, env, log, redact);
274
+ job.pid = null;
275
+ job.exit = code;
276
+ if (cancelled()) throw new Error('cancelled');
277
+ if (job.timedOut) throw new Error(`timed out after ${job.timeoutSeconds}s`);
278
+ if (code !== 0) throw new Error(`"${s.name}" exited with ${code}`);
279
+ }
280
+ job.checkpoint = i + 1; // durable: a retry or a resume starts after this step
281
+ write(ctx, job);
282
+ }
283
+ job.status = 'done';
284
+ job.exit = 0;
285
+ job.attempts.push({ ...attempt, finishedAt: new Date().toISOString(), status: 'done' });
286
+ say('done');
287
+ break;
288
+ } catch (e) {
289
+ job.pid = null;
290
+ job.error = redact(String(e.message || e));
291
+ job.attempts.push({ ...attempt, finishedAt: new Date().toISOString(), status: job.cancelRequested ? 'cancelled' : job.timedOut ? 'timed out' : 'failed', step: job.step, exit: job.exit, error: job.error });
292
+ const left = (job.retries || 0) + 1 - job.attempts.length;
293
+ if (!job.cancelRequested && left > 0) {
294
+ const wait = Math.min(300, (job.backoffSeconds ?? 5) * 2 ** (job.attempts.length - 1));
295
+ say(`${job.error}: retrying in ${wait}s (${left} attempt${left === 1 ? '' : 's'} left)`);
296
+ write(ctx, job);
297
+ const until = Date.now() + wait * 1000;
298
+ while (Date.now() < until && !cancelled()) await new Promise((r) => setTimeout(r, Math.min(250, until - Date.now())));
299
+ if (!job.cancelRequested) continue;
236
300
  }
237
- if (getJob(ctx, id).cancelRequested) { job.cancelRequested = true; throw new Error('cancelled'); }
238
- const { code } = await runStep(ctx, job, s, env, log, redact);
239
- job.cancelRequested = getJob(ctx, id).cancelRequested;
240
- job.exit = code;
241
- if (job.cancelRequested) throw new Error('cancelled');
242
- if (job.timedOut) throw new Error(`timed out after ${job.timeoutSeconds}s`);
243
- if (code !== 0) throw new Error(`"${s.name}" exited with ${code}`);
301
+ job.cancelled = !!job.cancelRequested;
302
+ job.status = job.cancelled ? 'cancelled' : 'failed';
303
+ if (job.cancelled) job.error = 'cancelled';
304
+ say(`${job.status}: ${job.error}${job.retries ? ` (after ${job.attempts.length} attempt${job.attempts.length === 1 ? '' : 's'})` : ''}`);
305
+ break;
244
306
  }
245
- job.status = 'done';
246
- job.exit = 0;
247
- say('done');
248
- } catch (e) {
249
- job.cancelled = !!job.cancelRequested;
250
- job.status = job.cancelled ? 'cancelled' : 'failed';
251
- job.error = redact(String(e.message || e));
252
- say(`${job.status}: ${job.error}`);
253
307
  }
308
+ if (job.artifacts?.length) job.artifactInfo = recordArtifacts(ctx, job);
254
309
  job.pid = null;
255
310
  job.finishedAt = new Date().toISOString();
256
311
  write(ctx, job);
257
- if (job.kind === 'exec') {
312
+ if (job.kind === 'exec' || job.kind === 'task') {
258
313
  const { event } = await import('./state.js');
259
314
  const s0 = job.steps[0] || {};
260
315
  const secs = Math.round((Date.parse(job.finishedAt) - Date.parse(job.startedAt)) / 1000);
261
- event(ctx, `exec ${job.id}: ${s0.argv ? path.basename(s0.argv[0]) : 'shell'} in ${job.app || '?'} → ${job.status}${job.exit !== null ? ` (exit ${job.exit})` : ''}, ${secs}s, ${job.outputBytes} bytes out`);
316
+ event(ctx, `${job.kind} ${job.id}: ${s0.argv ? path.basename(s0.argv[0]) : 'shell'}${job.steps.length > 1 ? ` (+${job.steps.length - 1} steps)` : ''} in ${job.app || '?'} → ${job.status}${job.exit !== null ? ` (exit ${job.exit})` : ''}, ${secs}s, ${job.attempts.length} attempt(s), ${job.outputBytes} bytes out`);
262
317
  }
263
318
  return job;
264
319
  }
265
320
 
321
+ /** Size and sha256 of each declared artifact (paths inside the app folder only). */
322
+ function recordArtifacts(ctx, job) {
323
+ let root;
324
+ try { root = fs.realpathSync(job.steps.find((s) => s.cwd)?.cwd || ''); } catch { return []; }
325
+ const appRoot = job.appDir ? fs.realpathSync(job.appDir) : root;
326
+ return job.artifacts.slice(0, 50).map((rel) => {
327
+ const abs = path.resolve(appRoot, rel);
328
+ let real;
329
+ try { real = fs.realpathSync(abs); } catch { return { path: rel, missing: true }; }
330
+ if (real !== appRoot && !real.startsWith(appRoot + path.sep)) return { path: rel, refused: 'outside the app folder' };
331
+ const st = fs.statSync(real);
332
+ if (!st.isFile()) return { path: rel, refused: 'not a file' };
333
+ const sha256 = st.size <= 512 * 1024 * 1024 ? crypto.createHash('sha256').update(fs.readFileSync(real)).digest('hex') : null;
334
+ return { path: rel, bytes: st.size, sha256 };
335
+ });
336
+ }
337
+
338
+ /**
339
+ * Settle jobs whose runner is gone (the runner crashed, or the machine
340
+ * rebooted): kill what is left of the step's process tree, then resume from
341
+ * the checkpoint (retryInterrupted, with budget left) or fail as uncertain.
342
+ * Returns what was done.
343
+ */
344
+ export function reconcileJobs(ctx) {
345
+ const out = [];
346
+ for (const job of listJobs(ctx, 10000)) {
347
+ if (!['queued', 'running'].includes(job.status) || !job.runnerPid) continue;
348
+ const rebooted = job.runnerBoot && Math.abs(job.runnerBoot - bootTime()) > 60;
349
+ if (!rebooted && alive(job.runnerPid)) continue;
350
+ const orphan = !rebooted && groupAlive(job.pid);
351
+ if (orphan) killGroup(job.pid, 2000);
352
+ const midStep = job.step !== null && job.step >= (job.checkpoint || 0);
353
+ const why = rebooted ? 'the device rebooted' : 'its runner stopped';
354
+ job.attempts = [...(job.attempts || []), { n: (job.attempts || []).length + 1, from: job.checkpoint || 0, status: 'interrupted', step: job.step, error: why, finishedAt: new Date().toISOString() }];
355
+ job.pid = null;
356
+ const left = (job.retries || 0) + 1 - job.attempts.length;
357
+ if (job.retryInterrupted && left > 0 && !job.cancelRequested) {
358
+ job.status = 'queued';
359
+ write(ctx, job);
360
+ fs.appendFileSync(logOf(ctx, job.id), `\n[harness-device] interrupted (${why}${orphan ? '; its leftover processes were stopped' : ''}): resuming from step ${(job.checkpoint || 0) + 1}\n`);
361
+ if (ctx.env.HD_JOBS_INLINE === '1') runJob(ctx, job.id).catch(() => {}); else launch(ctx, job.id);
362
+ out.push({ id: job.id, action: 'resumed', from: job.checkpoint || 0, orphanKilled: orphan });
363
+ } else {
364
+ job.status = job.cancelRequested ? 'cancelled' : 'failed';
365
+ job.cancelled = !!job.cancelRequested;
366
+ job.uncertain = midStep && !job.cancelRequested;
367
+ job.error = job.uncertain
368
+ ? `interrupted mid-step ${job.step + 1} (${why}): its effect is uncertain, so it was not run again; check the state before retrying`
369
+ : `interrupted (${why})`;
370
+ job.finishedAt = new Date().toISOString();
371
+ write(ctx, job);
372
+ fs.appendFileSync(logOf(ctx, job.id), `\n[harness-device] ${job.status}: ${job.error}\n`);
373
+ out.push({ id: job.id, action: job.status, uncertain: job.uncertain, orphanKilled: orphan });
374
+ }
375
+ }
376
+ return out;
377
+ }
378
+
266
379
  /** Status plus the end of the log, for job_status. */
267
380
  export function describeJob(ctx, job, lines = 80) {
268
381
  return { ...job, log: tail(logOf(ctx, job.id), lines) };
package/src/mcp/server.js CHANGED
@@ -251,6 +251,25 @@ export function buildServer(env = process.env, opts = {}) {
251
251
  async (c, a) => ({ content: [{ type: 'image', data: await preview.screenshot(c, a.id, { width: a.width, height: a.height }), mimeType: 'image/png' }] }));
252
252
  }
253
253
 
254
+ 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.',
255
+ { effect_key: z.string().regex(/^[\w.:@/-]{8,191}$/), app: APP, steps: z.array(z.object({ argv: z.array(z.string().max(8000)).min(1).max(200), cwd: z.string().max(500).optional() })).min(1).max(20),
256
+ env_refs: z.record(z.string(), z.string()).optional(), timeout_seconds: z.number().int().min(1).max(3600).optional(), max_output_kb: z.number().int().min(1).max(4096).optional(),
257
+ retries: z.number().int().min(0).max(5).optional(), retry_backoff_seconds: z.number().int().min(0).max(300).optional(), retry_interrupted: z.boolean().optional(),
258
+ artifacts: z.array(z.string().max(500)).max(50).optional(), wait_seconds: z.number().int().min(0).max(120).optional(), ...FORCE },
259
+ async (c, a) => {
260
+ await guard(c, a, `submitting a job in ${a.app}`);
261
+ const { effect_key: effectKey, wait_seconds: wait, confirm: _c, force: _f, ...payload } = a;
262
+ const durable = await import('../durable.js');
263
+ let r;
264
+ try { r = await durable.submit(c, { effectKey, payload }); } catch (e) { if (e.code) return { isError: true, content: [{ type: 'text', text: `${e.code}: ${e.message}` }] }; throw e; }
265
+ const deadline = Date.now() + Math.min(wait ?? 30, 120) * 1000;
266
+ let job = r.job;
267
+ while (['queued', 'running'].includes(job.status) && Date.now() < deadline) { await new Promise((res) => setTimeout(res, 200)); job = jobs.getJob(c, job.id); }
268
+ const done = !['queued', 'running'].includes(job.status);
269
+ return { ...(done && job.status !== 'done' ? { isError: true } : {}), content: [{ type: 'text', text: JSON.stringify({ ...durable.result(c, job, jobs.tail(jobs.logOf(c, job.id), 40)), existing: r.existing,
270
+ ...(done ? {} : { next: `still running: job_status {"id":"${job.id}"}; job_cancel to stop it` }) }, null, 2) }] };
271
+ });
272
+
254
273
  tool('job_cancel', 'Stop a running job (exec, clone, setup, deploy…): its whole process tree is terminated (TERM, then KILL after 5s); the job ends as cancelled.',
255
274
  { id: z.string().regex(/^[a-z0-9-]{6,40}$/) },
256
275
  async (c, a) => text(jobs.cancelJob(c, a.id)));
@@ -0,0 +1,126 @@
1
+ // Fenced execution leases (HARNESS-1), device side.
2
+ //
3
+ // The hub attaches a lease to every pool call with side effects:
4
+ // { id, fence, exp } id = the call id, fence = a number the hub only ever
5
+ // increases per device, exp = when the hub stops waiting.
6
+ //
7
+ // The device keeps a durable journal of leases (state/leases/<id>.json):
8
+ // started → done with the result. So:
9
+ // - A lease seen again (the hub re-sent it after a reconnect) is never run
10
+ // twice: a finished one is answered from the journal, one still running is
11
+ // answered when it finishes, and one that was interrupted (the device
12
+ // restarted mid-call) is reported as uncertain, not re-run.
13
+ // - An expired lease (delivered late, after the hub gave up) is refused, and
14
+ // so is a fence lower than the highest this device has finished (a delayed
15
+ // message from before a newer lease on the same work).
16
+ // - Results are sent on whatever link is current when the call ends; a result
17
+ // that finds no link waits in the journal for the hub's `reconcile`.
18
+
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+
22
+ const ID = /^[\w-]{6,64}$/;
23
+ const KEEP = 500;
24
+ const SKEW_MS = 30_000; // clock tolerance between hub and device
25
+ const inflight = new Map(); // lease id -> Promise<result> (this process only)
26
+
27
+ const dir = (ctx) => path.join(ctx.paths.state, 'leases');
28
+ const file = (ctx, id) => path.join(dir(ctx), `${id}.json`);
29
+
30
+ export function readLease(ctx, id) {
31
+ if (!ID.test(String(id || ''))) return null;
32
+ try { return JSON.parse(fs.readFileSync(file(ctx, id), 'utf8')); } catch { return null; }
33
+ }
34
+ function writeLease(ctx, rec) {
35
+ fs.mkdirSync(dir(ctx), { recursive: true });
36
+ const tmp = `${file(ctx, rec.id)}.${process.pid}.tmp`;
37
+ fs.writeFileSync(tmp, JSON.stringify(rec), { mode: 0o600 });
38
+ fs.renameSync(tmp, file(ctx, rec.id)); // atomic: a crash leaves the old or the new record
39
+ }
40
+
41
+ /** The highest fence of a finished lease (the device's high-water mark). */
42
+ export function highFence(ctx) {
43
+ try { return Number(fs.readFileSync(path.join(dir(ctx), 'HIGH'), 'utf8')) || 0; } catch { return 0; }
44
+ }
45
+ function raiseFence(ctx, fence) {
46
+ if (fence > highFence(ctx)) fs.writeFileSync(path.join(dir(ctx), 'HIGH'), String(fence));
47
+ }
48
+
49
+ function prune(ctx) {
50
+ const all = fs.readdirSync(dir(ctx)).filter((f) => f.endsWith('.json'));
51
+ if (all.length <= KEEP) return;
52
+ all.map((f) => ({ f, t: fs.statSync(path.join(dir(ctx), f)).mtimeMs })).sort((a, b) => a.t - b.t)
53
+ .slice(0, all.length - KEEP).forEach(({ f }) => fs.rmSync(path.join(dir(ctx), f), { force: true }));
54
+ }
55
+
56
+ const refused = (text, extra = {}) => ({ isError: true, content: [{ type: 'text', text }], ...extra });
57
+ export const UNCERTAIN = 'This call was interrupted before it finished (the device restarted or the call was cut off). It was not run again, so its effect is uncertain: check the state (job_status, app_list, logs) before retrying.';
58
+
59
+ /**
60
+ * Run `exec()` under a lease, at most once. Returns the result to send, or
61
+ * null when nothing should be sent now (a duplicate of a call still running:
62
+ * its result is sent when it ends).
63
+ */
64
+ export async function runLeased(ctx, lease, { tool, now = Date.now() }, exec) {
65
+ const id = String(lease.id || '');
66
+ const fence = Number(lease.fence);
67
+ if (!ID.test(id) || !Number.isSafeInteger(fence) || fence < 1) return refused('Malformed lease; not run.');
68
+ const prev = readLease(ctx, id);
69
+ if (prev) {
70
+ if (prev.status === 'done') return { ...prev.result, replayed: true };
71
+ if (inflight.has(id)) return null;
72
+ return refused(UNCERTAIN, { uncertain: true });
73
+ }
74
+ if (lease.exp && Number(lease.exp) + SKEW_MS < now) return refused(`Stale lease ${id}: it expired before it reached this device, so it was not run.`, { stale: true });
75
+ if (fence <= highFence(ctx)) return refused(`Stale lease ${id}: fence ${fence} is not newer than this device's last finished lease (${highFence(ctx)}); not run.`, { stale: true });
76
+
77
+ writeLease(ctx, { id, fence, tool, status: 'started', startedAt: new Date(now).toISOString(), pid: process.pid });
78
+ const p = (async () => {
79
+ let result;
80
+ try { result = await exec(); } catch (e) { result = refused(String(e?.message || e)); }
81
+ writeLease(ctx, { ...readLease(ctx, id), status: 'done', result, finishedAt: new Date().toISOString() });
82
+ raiseFence(ctx, fence);
83
+ try { prune(ctx); } catch { /* best effort */ }
84
+ return result;
85
+ })();
86
+ inflight.set(id, p);
87
+ try { return await p; } finally { inflight.delete(id); }
88
+ }
89
+
90
+ /** Is this lease still running in this process? (Its result will be sent when it ends.) */
91
+ export const running = (id) => inflight.has(String(id));
92
+ export const whenDone = (id) => inflight.get(String(id));
93
+
94
+ /**
95
+ * The hub's view after a reconnect: for each lease it still waits on, what to
96
+ * send back. done → the stored result; running here → nothing yet; unknown or
97
+ * interrupted → uncertain (never re-run).
98
+ */
99
+ export function reconcile(ctx, leases = []) {
100
+ const out = [];
101
+ for (const l of leases.slice(0, 200)) {
102
+ const id = String(l?.id || '');
103
+ if (!ID.test(id)) continue;
104
+ const rec = readLease(ctx, id);
105
+ if (rec?.status === 'done') out.push({ id, state: 'done', result: { ...rec.result, replayed: true } });
106
+ else if (inflight.has(id)) out.push({ id, state: 'running' });
107
+ else if (rec) out.push({ id, state: 'interrupted', result: refused(UNCERTAIN, { uncertain: true }) });
108
+ else out.push({ id, state: 'unknown', result: refused(`This device has no record of lease ${id}: it never arrived, so it was not run.`, { notRun: true }) });
109
+ }
110
+ return out;
111
+ }
112
+
113
+ /** Leases interrupted by a restart (started, not done, not running here): marked so on startup. */
114
+ export function markInterrupted(ctx) {
115
+ if (!fs.existsSync(dir(ctx))) return [];
116
+ const hit = [];
117
+ for (const f of fs.readdirSync(dir(ctx)).filter((x) => x.endsWith('.json'))) {
118
+ const rec = readLease(ctx, f.slice(0, -5));
119
+ if (rec?.status === 'started' && !inflight.has(rec.id)) {
120
+ writeLease(ctx, { ...rec, status: 'done', interrupted: true, result: refused(UNCERTAIN, { uncertain: true }), finishedAt: new Date().toISOString() });
121
+ raiseFence(ctx, rec.fence);
122
+ hit.push(rec.id);
123
+ }
124
+ }
125
+ return hit;
126
+ }
package/src/pool/link.js CHANGED
@@ -1,13 +1,19 @@
1
1
  // The `harness-pool` service: one outbound WebSocket to the pool hub.
2
2
  //
3
- // device → hub hello { version, device, caps, tools: [{name, description, inputSchema}] }
4
- // beat { resources, limits, max, counts, secretsVer, configVer } every 15s
5
- // result { id, result } per call
3
+ // device → hub hello { version, device, caps, tools, session, boot, highFence }
4
+ // beat { session, seq, boot, ready, resources, limits, max, counts, running, secretsVer, configVer } every 15s
5
+ // result { id, result, fence? } per call
6
6
  // synced { kind, report } after secrets/config
7
- // hub → device call { id, tool, args }
7
+ // hub → device call { id, tool, args, lease?: { id, fence, exp } }
8
+ // reconcile { leases: [{ id, fence }] } after a reconnect: what the hub still waits on
8
9
  // secrets { ver, values } config { ver, values }
9
10
  // disconnect
10
11
  //
12
+ // HARNESS-1: `seq` grows with every beat of a link `session`, so the hub can
13
+ // drop replayed or out-of-order beats; `ready` says whether this device can
14
+ // take work now (connected is not the same as ready). Calls with side effects
15
+ // carry a lease and run at most once (./leases.js).
16
+ //
11
17
  // Calls run through this device's own MCP server (buildServer) over an
12
18
  // in-memory transport, so every local rule applies unchanged: POOL_SCOPES
13
19
  // (set on the machine, never by the hub), confirmations, the resource gate,
@@ -23,7 +29,12 @@ import * as resources from '../resources.js';
23
29
  import * as limits from '../limits.js';
24
30
  import * as state from '../state.js';
25
31
  import path from 'node:path';
32
+ import os from 'node:os';
33
+ import crypto from 'node:crypto';
34
+ import fs from 'node:fs';
26
35
  import { PKG } from '../util.js';
36
+ import { isStopped } from '../lifecycle.js';
37
+ import * as leases from './leases.js';
27
38
  import { readPool, writePool } from './join.js';
28
39
  import { applySecrets, applyConfig, versions } from './sync.js';
29
40
 
@@ -40,17 +51,45 @@ export async function localTools(env) {
40
51
  await server.connect(a);
41
52
  const client = new Client({ name: 'harness-pool', version: PKG.version });
42
53
  await client.connect(b);
43
- return { client, close: () => client.close() };
54
+ // A dropped link must not cut off calls still running: close once the last one ends.
55
+ const t = { client, busy: 0, closing: false };
56
+ t.close = async () => { t.closing = true; if (t.busy === 0) await client.close(); };
57
+ t.done = () => { t.busy--; if (t.closing && t.busy === 0) client.close().catch(() => {}); };
58
+ return t;
44
59
  }
45
60
 
46
- async function beat(env) {
61
+ /** When this machine booted (ms, rounded): changes after a reboot. */
62
+ export const bootTime = () => Math.round((Date.now() - os.uptime() * 1000) / 10000) * 10000;
63
+
64
+ /**
65
+ * Can this device take new work now? Connected is not enough: it must not be
66
+ * stopped or restarting on purpose, critical on CPU/RAM/disk, or without the
67
+ * scope to run anything.
68
+ */
69
+ export function readiness(ctx, sample, { tools = 1 } = {}) {
70
+ const reasons = [];
71
+ const stopped = isStopped(ctx);
72
+ if (stopped) reasons.push(`stopped on purpose (${stopped.why || 'stop'})`);
73
+ if (fs.existsSync(path.join(ctx.paths.state, 'restarting'))) reasons.push('restarting');
74
+ if (sample?.level === 'critical') reasons.push(`critical: ${(sample.reasons || []).join('; ') || 'CPU, RAM or disk'}`);
75
+ if (!poolScopes(ctx.cfg).some((s) => s === 'device:operate' || s === 'device:admin')) reasons.push('POOL_SCOPES is read-only: it can be watched, not given work');
76
+ if (!tools) reasons.push('its tools did not start');
77
+ return { ok: reasons.length === 0, reasons };
78
+ }
79
+
80
+ async function beat(env, link = {}) {
47
81
  const ctx = loadContext(env);
48
82
  const s = await resources.sample(ctx, { quick: true });
49
83
  let gs = [];
50
84
  try { gs = limits.groups(ctx); } catch { /* no tmux yet */ }
51
85
  const l = limits.limits(ctx.cfg);
86
+ let runningJobs = [];
87
+ try { runningJobs = (await import('../jobs.js')).listJobs(ctx).filter((j) => j.status === 'running').map((j) => j.id).slice(0, 50); } catch { /* none */ }
52
88
  return {
53
89
  t: 'beat',
90
+ session: link.session, seq: link.seq ? ++link.seq.n : undefined, boot: bootTime(),
91
+ ready: readiness(ctx, s, { tools: link.tools ?? 1 }),
92
+ running: { jobs: runningJobs, procs: state.listProcs(ctx).filter((p) => p.running).map((p) => p.name).slice(0, 50) },
54
93
  resources: { level: s.level, reasons: s.reasons, cpu: s.cpu, memory: s.memory, disk: s.disk },
55
94
  limits: limits.report(ctx, gs),
56
95
  max: { reserveMem: l.reserveMem, harnessMem: l.harnessMem, procMem: l.procMem, procCpu: l.procCpu, maxSessions: l.maxSessions, maxProcs: l.maxProcs, cores: l.cores, totalMem: l.totalMem },
@@ -68,13 +107,28 @@ export async function handle(env, tools, msg, send) {
68
107
  const ctx = loadContext(env);
69
108
  switch (msg.t) {
70
109
  case 'call': {
71
- let result;
72
- try {
73
- result = await tools.client.callTool({ name: String(msg.tool), arguments: msg.args || {} }, undefined, { timeout: Math.min(Number(msg.timeoutMs) || 120000, 2 * 3600 * 1000) });
74
- } catch (e) {
75
- result = { isError: true, content: [{ type: 'text', text: String(e && e.message ? e.message : e) }] };
110
+ const run = async () => {
111
+ tools.busy = (tools.busy || 0) + 1;
112
+ try {
113
+ return await tools.client.callTool({ name: String(msg.tool), arguments: msg.args || {} }, undefined, { timeout: Math.min(Number(msg.timeoutMs) || 120000, 2 * 3600 * 1000) });
114
+ } catch (e) {
115
+ return { isError: true, content: [{ type: 'text', text: String(e && e.message ? e.message : e) }] };
116
+ } finally { if (tools.done) tools.done(); else tools.busy--; }
117
+ };
118
+ if (!msg.lease) { send({ t: 'result', id: msg.id, result: await run() }); return; }
119
+ const result = await leases.runLeased(ctx, msg.lease, { tool: String(msg.tool) }, run);
120
+ if (result?.stale) state.event(ctx, `pool: refused stale lease ${msg.lease.id} for ${msg.tool}`);
121
+ if (result) send({ t: 'result', id: msg.id, result, fence: Number(msg.lease.fence) });
122
+ return;
123
+ }
124
+ case 'reconcile': {
125
+ const out = leases.reconcile(ctx, Array.isArray(msg.leases) ? msg.leases : []);
126
+ const fenceOf = Object.fromEntries((msg.leases || []).map((l) => [String(l?.id), Number(l?.fence)]));
127
+ for (const r of out) {
128
+ if (r.state === 'running') leases.whenDone(r.id).then((res) => send({ t: 'result', id: r.id, result: res, fence: fenceOf[r.id] })).catch(() => {});
129
+ else send({ t: 'result', id: r.id, result: r.result, fence: fenceOf[r.id] });
76
130
  }
77
- send({ t: 'result', id: msg.id, result });
131
+ if (out.length) state.event(ctx, `pool: reconnect reconciled ${out.length} lease(s): ${out.map((r) => `${r.id} ${r.state}`).join(', ')}`);
78
132
  return;
79
133
  }
80
134
  case 'secrets': {
@@ -109,6 +163,12 @@ export async function handle(env, tools, msg, send) {
109
163
 
110
164
  /** Run the link until stopped: reconnects with backoff, stops for good when revoked or disconnected. */
111
165
  export async function runLink(env = process.env, { log = (m) => console.error(`[pool] ${m}`) } = {}) {
166
+ // Leased calls run inside this process: any left "started" were cut off by a restart or reboot.
167
+ try {
168
+ const ctx = loadContext(env);
169
+ const hit = leases.markInterrupted(ctx);
170
+ if (hit.length) { state.event(ctx, `pool: ${hit.length} lease(s) interrupted by a restart, marked uncertain (not re-run): ${hit.join(', ')}`); log(`${hit.length} interrupted lease(s) marked uncertain`); }
171
+ } catch (e) { log(`lease journal: ${e.message}`); }
112
172
  let delay = 1000;
113
173
  for (;;) {
114
174
  const p = readPool(loadContext(env).paths.pool);
@@ -120,14 +180,19 @@ export async function runLink(env = process.env, { log = (m) => console.error(`[
120
180
  const outcome = await connectOnce(env, p, log);
121
181
  if (outcome === 'stop') { log('disconnected by the hub; waiting to be joined again'); delay = 1000; continue; }
122
182
  if (outcome === 'revoked') { log('the hub revoked this device; join again to reconnect'); await new Promise((r) => setTimeout(r, 600000)); continue; }
123
- if (outcome === 'ok') delay = 1000;
124
- const wait = Math.round(delay * (0.5 + Math.random()));
125
- log(`reconnecting in ${Math.round(wait / 1000)}s`);
126
- await new Promise((r) => setTimeout(r, wait));
127
- delay = Math.min(delay * 2, 60000);
183
+ const b = backoff(delay, outcome);
184
+ log(`reconnecting in ${Math.round(b.wait / 1000)}s`);
185
+ await new Promise((r) => setTimeout(r, b.wait));
186
+ delay = b.next;
128
187
  }
129
188
  }
130
189
 
190
+ /** Reconnect backoff: 1s after a link that worked, doubling to 60s while it fails; ±50% jitter so a fleet doesn't reconnect at once. */
191
+ export function backoff(delay, outcome, rand = Math.random) {
192
+ const base = outcome === 'ok' ? 1000 : delay;
193
+ return { wait: Math.round(base * (0.5 + rand())), next: Math.min(base * 2, 60000) };
194
+ }
195
+
131
196
  /** One connection. Resolves 'ok' (was connected, then dropped), 'failed', 'revoked' or 'stop'. */
132
197
  export function connectOnce(env, p, log = () => {}) {
133
198
  return new Promise((resolve) => {
@@ -136,6 +201,7 @@ export function connectOnce(env, p, log = () => {}) {
136
201
  let tools;
137
202
  let timer;
138
203
  let connected = false;
204
+ const link = { session: crypto.randomBytes(8).toString('hex'), seq: { n: 0 }, tools: 0 };
139
205
  let stopped = false;
140
206
  const send = (m) => { if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(m)); };
141
207
  const finish = (how) => { clearInterval(timer); if (tools) tools.close().catch(() => {}); resolve(how); };
@@ -148,9 +214,10 @@ export function connectOnce(env, p, log = () => {}) {
148
214
  tools = await localTools(env);
149
215
  const list = (await tools.client.listTools()).tools.map((x) => ({ name: x.name, description: x.description, inputSchema: x.inputSchema }));
150
216
  const ctx = loadContext(env);
151
- send({ t: 'hello', version: PKG.version, device: ctx.cfg.DEVICE, caps: ctx.caps.map((c) => c.id), scopes: poolScopes(ctx.cfg), tools: list });
152
- send(await beat(env));
153
- timer = setInterval(() => { beat(env).then(send).catch((e) => log(`heartbeat failed: ${e.message}`)); }, BEAT_MS);
217
+ link.tools = list.length;
218
+ send({ t: 'hello', version: PKG.version, device: ctx.cfg.DEVICE, caps: ctx.caps.map((c) => c.id), scopes: poolScopes(ctx.cfg), tools: list, session: link.session, boot: bootTime(), highFence: leases.highFence(ctx) });
219
+ send(await beat(env, link));
220
+ timer = setInterval(() => { beat(env, link).then(send).catch((e) => log(`heartbeat failed: ${e.message}`)); }, Number(env.HD_POOL_BEAT_MS) || BEAT_MS);
154
221
  } catch (e) {
155
222
  log(`could not start the device tools: ${e.message}`);
156
223
  ws.close();
package/src/runloom.js ADDED
@@ -0,0 +1,141 @@
1
+ // RunLoom lease adapter (HARNESS-3): this device as a RunLoom worker.
2
+ //
3
+ // RunLoom stays the scheduler (no second one here). The device claims leased
4
+ // `action` tasks from RunLoom's internal worker API with a worker-pool
5
+ // credential, the same contract as RunLoom's own Node worker
6
+ // (apps/workers-node/src/engine/worker.ts):
7
+ // POST /internal/v1/tasks/claim { max, wait_ms, worker_id, worker_version }
8
+ // POST /internal/v1/tasks/:id/heartbeat { lease_token, checkpoint_ref? } → { cancel_requested } | 409 STALE_LEASE
9
+ // POST /internal/v1/tasks/:id/complete { lease_token, output } → 200 | 409
10
+ // POST /internal/v1/tasks/:id/fail { lease_token, error_class, message, retryable } → 200 | 409
11
+ //
12
+ // A task for this device is an action with payload
13
+ // { connector: 'harness-device', operation: 'job', input: <durable job payload> }
14
+ // and is run as a durable job keyed by the task's effect_key (src/durable.js).
15
+ // So:
16
+ // - a retried task (new lease, same effect key) finds the same job: it is
17
+ // never run twice; its result is reported when it ends;
18
+ // - a lost lease (heartbeat or report answers 409) stops reporting, never the
19
+ // job: the next lease on the effect key picks up the same job;
20
+ // - cancel_requested cancels the job's process tree;
21
+ // - retries happen on the device (the job's budget); RunLoom gets one result,
22
+ // and failures are reported non-retryable so the engine does not run the
23
+ // effect again on top of the device's own retries.
24
+ //
25
+ // Routing: the claim API has no per-device task kind or queue yet, so a device
26
+ // gets RunLoom work by holding its own worker-pool credential (a pool per
27
+ // device); a shared pool would let any of its workers claim the task.
28
+
29
+ import os from 'node:os';
30
+ import { readSecrets } from './context.js';
31
+ import { PKG } from './util.js';
32
+ import * as durable from './durable.js';
33
+ import { getJob, cancelJob, tail, logOf, reconcileJobs } from './jobs.js';
34
+
35
+ export const CONNECTOR = 'harness-device';
36
+ const VERSION = PKG.version;
37
+
38
+ /** The worker API over HTTP, authenticated as this device's pool. */
39
+ export function httpClient({ url, credential, workerId, waitMs = 10_000, fetch: f = fetch }) {
40
+ const call = async (p, body) => {
41
+ const res = await f(`${url.replace(/\/$/, '')}/internal/v1/tasks${p}`, {
42
+ method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${credential}` }, body: JSON.stringify(body),
43
+ });
44
+ const json = await res.json().catch(() => ({}));
45
+ if (res.status >= 500 || res.status === 401 || res.status === 400) throw new Error(`RunLoom ${p} answered ${res.status} ${json.error?.code ?? ''}`.trim());
46
+ return { status: res.status, json };
47
+ };
48
+ return {
49
+ async claim(max) { return (await call('/claim', { max, wait_ms: waitMs, worker_id: workerId, worker_version: VERSION })).json.data ?? []; },
50
+ async heartbeat(task, checkpointRef) {
51
+ const r = await call(`/${task.id}/heartbeat`, { lease_token: task.lease_token, ...(checkpointRef ? { checkpoint_ref: checkpointRef } : {}) });
52
+ return r.status === 409 ? null : (r.json.data ?? { cancel_requested: false });
53
+ },
54
+ async complete(task, output) { return (await call(`/${task.id}/complete`, { lease_token: task.lease_token, output })).status === 200; },
55
+ async fail(task, failure) { return (await call(`/${task.id}/fail`, { lease_token: task.lease_token, ...failure })).status === 200; },
56
+ };
57
+ }
58
+
59
+ const FAILURE = {
60
+ VALIDATION: 'ValidationError', EFFECT_KEY_CONFLICT: 'EffectKeyConflict', EFFECT_KEY_EXPIRED: 'EffectKeyExpired',
61
+ };
62
+
63
+ /** Run one claimed task to its report. Returns what happened (for logs and tests). */
64
+ export async function handleTask(ctx, task, client, { log = () => {}, pollMs = 250 } = {}) {
65
+ const p = task.payload || {};
66
+ if (p.connector !== CONNECTOR || p.operation !== 'job') {
67
+ await client.fail(task, { error_class: 'UnknownConnector', message: `${p.connector}.${p.operation} is not run by harness-device (it runs ${CONNECTOR}.job)`, retryable: false });
68
+ return { outcome: 'refused' };
69
+ }
70
+ let job;
71
+ let existing;
72
+ try {
73
+ ({ job, existing } = await durable.submit(ctx, { effectKey: task.effect_key, payload: p.input }));
74
+ } catch (e) {
75
+ const ok = await client.fail(task, { error_class: FAILURE[e.code] || 'Error', message: String(e.message).slice(0, 2000), retryable: false });
76
+ return { outcome: ok ? 'failed' : 'stale', error: e.code };
77
+ }
78
+ log(`task ${task.id} (${task.mission_id}/${task.step_id} attempt ${task.attempt}) → job ${job.id}${existing ? ' (already submitted: not run again)' : ''}`);
79
+
80
+ let leaseLost = false;
81
+ let cancelAsked = false;
82
+ const beatEvery = Math.max(250, Math.floor((task.heartbeat_ms || 30_000) / 3));
83
+ let nextBeat = 0;
84
+ for (;;) {
85
+ job = getJob(ctx, job.id);
86
+ if (!['queued', 'running'].includes(job.status)) break;
87
+ if (Date.now() >= nextBeat) {
88
+ nextBeat = Date.now() + beatEvery;
89
+ try {
90
+ const r = await client.heartbeat(task, `job:${job.id}:checkpoint:${job.checkpoint || 0}`);
91
+ if (r === null) { leaseLost = true; break; }
92
+ if (r.cancel_requested && !cancelAsked) { cancelAsked = true; cancelJob(ctx, job.id); log(`task ${task.id}: cancel requested → job ${job.id} cancelled`); }
93
+ } catch (e) { log(`task ${task.id}: heartbeat failed: ${e.message}`); }
94
+ }
95
+ await new Promise((r) => setTimeout(r, pollMs));
96
+ }
97
+ if (leaseLost) {
98
+ log(`task ${task.id}: lease lost (stale); job ${job.id} keeps running and is reported on the next lease of ${task.effect_key}`);
99
+ return { outcome: 'stale', job: job.id };
100
+ }
101
+ const out = durable.result(ctx, job, tail(logOf(ctx, job.id), 40).slice(-4000));
102
+ const ok = job.status === 'done'
103
+ ? await client.complete(task, out)
104
+ : await client.fail(task, {
105
+ error_class: job.cancelled ? 'Cancelled' : job.uncertain ? 'EffectUncertain' : job.timedOut ? 'Timeout' : 'JobFailed',
106
+ message: `job ${job.id} ${job.status}${job.exit !== null ? ` (exit ${job.exit})` : ''} after ${out.attempts} attempt(s): ${job.error || ''}`.slice(0, 2000),
107
+ retryable: false,
108
+ });
109
+ if (!ok) log(`task ${task.id}: the lease went stale before the report; job ${job.id} is ${job.status} and is reported on the next lease`);
110
+ return { outcome: ok ? job.status : 'stale', job: job.id };
111
+ }
112
+
113
+ /** Claim and run tasks until `signal` aborts; in-flight tasks finish (their jobs keep running anyway). */
114
+ export async function workerLoop(ctx, { client, concurrency = 2, signal, log = () => {}, idleMs = 250, errorMs = 2000 }) {
115
+ for (const r of reconcileJobs(ctx)) log(`job ${r.id}: ${r.action}${r.uncertain ? ' (uncertain effect)' : ''}`);
116
+ const inFlight = new Set();
117
+ const pause = (ms) => new Promise((res) => { const t = setTimeout(res, ms); signal?.addEventListener('abort', () => { clearTimeout(t); res(); }, { once: true }); });
118
+ while (!signal?.aborted) {
119
+ if (inFlight.size >= concurrency) { await Promise.race(inFlight); continue; }
120
+ let tasks = [];
121
+ try { tasks = await client.claim(concurrency - inFlight.size); } catch (e) { log(`claim failed: ${e.message}`); await pause(errorMs); continue; }
122
+ if (!tasks.length) { await pause(idleMs); continue; }
123
+ for (const t of tasks) {
124
+ const p = handleTask(ctx, t, client, { log }).catch((e) => log(`task ${t.id} crashed: ${e.message}`));
125
+ const tracked = p.finally(() => inFlight.delete(tracked));
126
+ inFlight.add(tracked);
127
+ }
128
+ }
129
+ await Promise.all(inFlight);
130
+ }
131
+
132
+ /** `harness-device runloom`: RUNLOOM_URL from config, the pool credential from the device secret RUNLOOM_CREDENTIAL. */
133
+ export async function run(ctx, { signal, log = console.log } = {}) {
134
+ const url = ctx.cfg.RUNLOOM_URL;
135
+ const credential = readSecrets(ctx.paths.secrets).RUNLOOM_CREDENTIAL;
136
+ if (!url) throw new Error('Set RUNLOOM_URL (harness-device config set RUNLOOM_URL=https://…) to the RunLoom API.');
137
+ if (!credential) throw new Error('Store the RunLoom worker-pool credential as the device secret RUNLOOM_CREDENTIAL (harness-device secrets set RUNLOOM_CREDENTIAL).');
138
+ const workerId = `harness-device:${ctx.cfg.DEVICE || os.hostname()}`;
139
+ log(`RunLoom worker ${workerId} → ${url}`);
140
+ await workerLoop(ctx, { client: httpClient({ url, credential, workerId }), concurrency: Number(ctx.cfg.RUNLOOM_CONCURRENCY) || 2, signal, log });
141
+ }
@@ -15,7 +15,7 @@ const TOOLS = {
15
15
  'app_list', 'file_read', 'job_status', 'workspace_list', 'workspace_status', 'preview_list', 'preview_screenshot'],
16
16
  'device:operate': ['proc_add', 'proc_remove', 'session_new', 'restart_service', 'browser_restart', 'run_tests_live', 'playwright_ui', 'ngrok_up', 'ngrok_down', 'disk_cleanup', 'docker_limit',
17
17
  'git_clone', 'git_pull', 'project_setup', 'project_start', 'project_stop', 'project_deploy', 'file_write', 'env_manage',
18
- 'exec', 'job_cancel', 'workspace_create', 'workspace_archive', 'preview_start', 'preview_stop'],
18
+ 'exec', 'job_submit', 'job_cancel', 'workspace_create', 'workspace_archive', 'preview_start', 'preview_stop'],
19
19
  // shell_exec is not listed: it needs device:admin (unknown tools do).
20
20
  };
21
21