@dreamtree-org/harness-device 0.6.0 → 0.7.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
@@ -379,3 +379,17 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
379
379
  ---
380
380
 
381
381
  **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)
382
+
383
+ **Link health, readiness and leases:**
384
+ - **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.
385
+ - 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.
386
+ - Each beat also reports the running jobs and processes, and the boot time; a reboot shows in the hub's audit.
387
+ - A device silent for 45s is offline, and no work goes to it.
388
+ - **Reconnects:** 1s, doubling to 60s while it fails, with jitter.
389
+ - **Leases:** every pool call with side effects carries a lease (id, a fence that only grows, expiry), and runs at most once:
390
+ - The device journals each lease in `state/leases/`. A lease delivered again is answered from the journal.
391
+ - An expired lease, or one older than the last finished, is refused.
392
+ - 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.
393
+ - A call cut off by a restart or reboot is reported as uncertain and never re-run, so check the state before retrying.
394
+ - The hub refuses results for expired leases or with the wrong fence, and records them in the device's audit.
395
+
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.7.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",
@@ -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();