@dreamtree-org/harness-device 0.3.0 → 0.5.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
@@ -206,9 +206,22 @@ Repositories this device runs, kept in `APPS_DIR` (default `~/apps`). Unlike pro
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
+ | `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
+ | `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 |
209
211
  | `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` |
210
212
  | `job_status` (`job <id>`) | Status, step and the end of the log for clone, setup, pull, deploy and long commands |
211
213
 
214
+ **Recovering a job** (`exec`, clone, setup, deploy):
215
+ - `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.
216
+ - `job_cancel {id}` ends a stuck one, killing its whole process group (TERM, then KILL after 5s).
217
+ - 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.
218
+ - A job whose runner died, for example in a reboot, still shows as running with a dead pid. `job_cancel` clears it.
219
+
220
+ **Recovering a workspace:**
221
+ - `workspace_status` shows what is uncommitted and how far the branch is ahead.
222
+ - A folder removed by hand: run `git worktree prune` in the app, then `workspace_create` again, which reuses the kept branch.
223
+ - A stale `state/locks/git-<app>.lock` from a dead process is cleared automatically.
224
+
212
225
  ### Join a pool (HarnessPro)
213
226
 
214
227
  `harness-device join <hub> --enroll <secret>` adds this device to a HarnessPro pool. You don't type it yourself: the dashboard's **Connect a device** gives a one-time `curl … | bash` command that installs harness-device and runs it.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dreamtree-org/harness-device",
3
- "version": "0.3.0",
3
+ "version": "0.5.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",
@@ -111,7 +111,9 @@ Apps are repositories this device runs, in \`${cfg.APPS_DIR || '~/apps'}\`; unli
111
111
  - \`git_clone\` (job) → \`project_setup\` (detects the stack, installs and builds; job) → \`project_start\` (a long-running process with the app's .env and PORT; restarted on crash and reboot, held to the safe maximums). \`project_stop\` stops it; \`project_deploy\` pulls, rebuilds and restarts in one job; \`git_pull\` only updates.
112
112
  - Jobs run in the background: follow them with \`job_status\`, don't wait in a loop without telling the user.
113
113
  - Files: \`file_read\` / \`file_write\` inside the app folder only; .git and .env are off limits. Environment: \`env_manage\` (names only; \`from_secret\` copies a device secret without you seeing it). Never put secrets in files or commands.
114
- - \`shell_exec\` runs one command in an app folder; through the pool it needs device:admin.
114
+ - One-off programs: \`exec\` with an argv (no shell), e.g. \`{"app":"web","argv":["npm","test"]}\`. The program must be on the allowlist; secrets go in by name with \`env_refs\` and are redacted from output. Long runs come back as a job id: stream with \`job_status\` (offset), stop with \`job_cancel\`. Prefer it to \`proc_add\` for anything that should end, and to \`shell_exec\` whenever shell syntax isn't needed.
115
+ - Per-ticket work: \`workspace_create {"app":"web","ticket":"HARNESS-5"}\` gives a git worktree on branch ticket/HARNESS-5 from a pinned base, with its own port, as the app \`web--harness-5\` (use it with exec, file_*, project_start…). \`workspace_status\` shows uncommitted files and commits ahead; \`workspace_archive\` keeps the branch and refuses to lose uncommitted work unless the user agrees.
116
+ - \`shell_exec\` runs one shell command in an app folder; through the pool it needs device:admin.
115
117
  - Private GitHub repos use the device secret GITHUB_TOKEN; if it is missing, ask the user to set it (on the machine, or as a pool secret), never for the token itself.
116
118
 
117
119
  ## Device, disk and services
package/src/config.js CHANGED
@@ -100,6 +100,12 @@ export function defaults(env = process.env) {
100
100
  POOL_SCOPES: 'device:read,device:operate',
101
101
  // Where git_clone puts managed apps (empty = ~/apps).
102
102
  APPS_DIR: '',
103
+ // Programs the exec tool may run (comma list; empty = the default list in
104
+ // src/exec.js). Shells and wrappers are refused whatever this says.
105
+ EXEC_ALLOW: '',
106
+ // Repositories git_clone and workspaces may use: comma list of owner/repo
107
+ // or owner/* (empty = any).
108
+ REPO_ALLOW: '',
103
109
  };
104
110
  }
105
111
 
@@ -212,6 +218,8 @@ export function validateConfig(cfg, env = process.env) {
212
218
  if (!['on', 'off'].includes(String(cfg.RESOURCE_GUARD))) errs.push('RESOURCE_GUARD must be on or off.');
213
219
  if (!/^\d+$/.test(String(cfg.RES_WAIT_SECONDS)) || Number(cfg.RES_WAIT_SECONDS) > 3600) errs.push('RES_WAIT_SECONDS must be 0-3600.');
214
220
  errs.push(...limitsMod.validate(cfg));
221
+ 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.');
222
+ 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/*.');
215
223
  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.');
216
224
  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.');
217
225
  if (!/^\d+$/.test(String(cfg.SERVE_PORT ?? '7700')) || Number(cfg.SERVE_PORT ?? 7700) < 1 || Number(cfg.SERVE_PORT ?? 7700) > 65535) errs.push('SERVE_PORT must be a port, 1-65535.');
package/src/exec.js ADDED
@@ -0,0 +1,77 @@
1
+ // Controlled one-shot execution (HARNESS-4): structured argv, no shell.
2
+ //
3
+ // - The executable is a bare name resolved on PATH and must be on the
4
+ // allowlist (EXEC_ALLOW). Shells and privilege/indirection wrappers are
5
+ // never allowed here, whatever the allowlist says: shell mode is the
6
+ // separate shell_exec tool (device:admin).
7
+ // - It runs in the app's folder (or a sub-folder, confined like file_read).
8
+ // - env_refs inject named device secrets for this run only; their values are
9
+ // redacted from the output. Nothing else secret is inherited (cleanEnv).
10
+ // - Every run is a durable job (src/jobs.js): own process group, timeout,
11
+ // output cap (head + tail kept), cancel kills the whole tree, exit code and
12
+ // byte counts recorded, never restarted. Linux: a systemd scope holds the
13
+ // per-process memory/CPU caps; macOS: the watchdog covers running jobs.
14
+
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ import { getApp, resolveIn } from './apps.js';
18
+ import { startJob, getJob } from './jobs.js';
19
+ import { readSecrets } from './context.js';
20
+ import { which } from './util.js';
21
+
22
+ export const DEFAULT_ALLOW = ['node', 'npm', 'npx', 'pnpm', 'yarn', 'python3', 'python', 'pip', 'pip3', 'uv', 'poetry', 'go', 'git', 'make', 'docker', 'bundle', 'ruby', 'composer', 'php', 'cargo', 'java', 'mvn', 'gradle', 'pytest', 'jest', 'vitest', 'tsc', 'eslint', 'prettier'];
23
+ /** Never through exec: shells, privilege changes, and wrappers that would run something else unchecked. */
24
+ export const NEVER = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'csh', 'tcsh', 'fish', 'env', 'sudo', 'su', 'doas', 'pkexec', 'xargs', 'nohup', 'setsid', 'nice', 'timeout', 'stdbuf', 'script', 'expect', 'ssh', 'scp', 'eval', 'exec', 'busybox']);
25
+ const BARE = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/;
26
+ const ENV_VAR = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
27
+ const ENV_DENY = /^(PATH|HOME|USER|SHELL|IFS|ENV|BASH_ENV|LD_.*|DYLD_.*|NODE_OPTIONS|NODE_PATH|PYTHONPATH|PYTHONSTARTUP|GIT_.*|SSH_.*|HARNESS_DEVICE_HOME|HD_.*|ANTHROPIC_.*|CLAUDE_.*)$/;
28
+ const SECRET_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
29
+ export const MAX_TIMEOUT = 3600;
30
+ export const MAX_OUTPUT_KB = 4096;
31
+
32
+ export function allowList(cfg) {
33
+ const s = String(cfg.EXEC_ALLOW || '').trim();
34
+ return s ? s.split(',').map((x) => x.trim()).filter(Boolean) : DEFAULT_ALLOW;
35
+ }
36
+
37
+ /** The checked command: { exe (absolute), argv, cwd, envRefs }. Throws with a reason. */
38
+ export function checkExec(ctx, { app: name, argv, cwd = '.', envRefs = {} }) {
39
+ if (!Array.isArray(argv) || !argv.length || argv.some((a) => typeof a !== 'string' || a.includes('\0'))) throw new Error('argv must be a non-empty list of strings');
40
+ if (argv.length > 200 || argv.join('').length > 32 * 1024) throw new Error('argv is too long');
41
+ const exe = argv[0];
42
+ if (!BARE.test(exe)) throw new Error(`"${exe}": give the program's name (e.g. npm), not a path`);
43
+ if (NEVER.has(exe)) throw new Error(`"${exe}" is not allowed in exec (shells and wrappers never are); shell mode is shell_exec, which needs device:admin`);
44
+ if (!allowList(ctx.cfg).includes(exe)) throw new Error(`"${exe}" is not on this device's exec allowlist (EXEC_ALLOW): ${allowList(ctx.cfg).join(', ')}`);
45
+ const resolved = which(exe, ctx.env);
46
+ if (!resolved) throw new Error(`"${exe}" is not installed on this device (not on PATH)`);
47
+ const app = getApp(ctx, name);
48
+ const dir = cwd === '.' || cwd === '' ? fs.realpathSync(app.dir) : resolveIn(app, cwd);
49
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new Error(`cwd ${cwd} is not a folder in ${app.name}`);
50
+ const secrets = readSecrets(ctx.paths.secrets);
51
+ for (const [v, s] of Object.entries(envRefs || {})) {
52
+ if (!ENV_VAR.test(v) || ENV_DENY.test(v)) throw new Error(`env_refs: ${v} can't be set this way`);
53
+ if (!SECRET_NAME.test(String(s)) || secrets[s] === undefined) throw new Error(`env_refs: no device secret ${s}`);
54
+ }
55
+ return { app, exe: resolved, argv: [resolved, ...argv.slice(1)], cwd: dir, envRefs: envRefs || {} };
56
+ }
57
+
58
+ /**
59
+ * Start it as a job; wait up to waitSeconds for it to finish. Returns the job
60
+ * (finished, or still running with its id for job_status / job_cancel).
61
+ */
62
+ export async function exec(ctx, { app, argv, cwd, envRefs, timeoutSeconds = 600, maxOutputKb = 256, waitSeconds = 30 }) {
63
+ const c = checkExec(ctx, { app, argv, cwd, envRefs });
64
+ const t = Math.max(1, Math.min(Number(timeoutSeconds) || 600, MAX_TIMEOUT));
65
+ const kb = Math.max(1, Math.min(Number(maxOutputKb) || 256, MAX_OUTPUT_KB));
66
+ const started = await startJob(ctx, {
67
+ kind: 'exec', app: c.app.name, timeoutSeconds: t, maxOutputBytes: kb * 1024, envRefs: c.envRefs,
68
+ steps: [{ name: path.basename(c.exe), argv: c.argv, cwd: c.cwd }],
69
+ });
70
+ const deadline = Date.now() + Math.max(0, Math.min(Number(waitSeconds) || 0, 120)) * 1000;
71
+ let job = started;
72
+ while (['queued', 'running'].includes(job.status) && Date.now() < deadline) {
73
+ await new Promise((r) => setTimeout(r, 200));
74
+ job = getJob(ctx, started.id);
75
+ }
76
+ return job;
77
+ }
package/src/jobs.js CHANGED
@@ -11,9 +11,10 @@
11
11
  import crypto from 'node:crypto';
12
12
  import fs from 'node:fs';
13
13
  import path from 'node:path';
14
- import { spawn } from 'node:child_process';
14
+ import { spawn, spawnSync } from 'node:child_process';
15
15
  import { readSecrets } from './context.js';
16
- import { PKG_ROOT } from './util.js';
16
+ import { PKG_ROOT, which } from './util.js';
17
+ import { limits as computeLimits } from './limits.js';
17
18
 
18
19
  const KEEP = 50;
19
20
  const dirOf = (ctx) => path.join(ctx.paths.state, 'jobs');
@@ -61,18 +62,40 @@ export function tail(file, lines = 80) {
61
62
  * tokenSecret: the name of a device secret git may use for https://github.com.
62
63
  * Returns the job.
63
64
  */
64
- export function startJob(ctx, { kind, app = null, steps, tokenSecret = null, inline = false }) {
65
+ export function startJob(ctx, { kind, app = null, steps, tokenSecret = null, inline = false, timeoutSeconds = null, maxOutputBytes = null, envRefs = null }) {
65
66
  const id = `${kind}-${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`.toLowerCase();
66
- const job = { id, kind, app, status: 'queued', step: null, steps: steps.map((s) => ({ name: s.name, cmd: s.cmd || null, cwd: s.cwd || null, internal: s.internal || null, args: s.args || null })), tokenSecret, exit: null, error: null, createdAt: new Date().toISOString(), startedAt: null, finishedAt: null };
67
+ const job = {
68
+ id, kind, app, status: 'queued', step: null,
69
+ 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
+ tokenSecret, envRefs, timeoutSeconds, maxOutputBytes, exit: null, error: null, pid: null, timedOut: false, cancelRequested: false, cancelled: false,
71
+ outputBytes: 0, createdAt: new Date().toISOString(), startedAt: null, finishedAt: null,
72
+ };
67
73
  write(ctx, job);
68
74
  prune(ctx);
69
75
  fs.mkdirSync(path.dirname(logOf(ctx, id)), { recursive: true });
70
76
  if (inline || ctx.env.HD_JOBS_INLINE === '1') return runJob(ctx, id).then(() => getJob(ctx, id));
71
77
  const bin = path.join(PKG_ROOT, 'bin', 'harness-device.js');
72
- ctx.platform.spawnDetached(ctx, `job-${id}`, [process.execPath, bin, 'job', 'run', id], logOf(ctx, id));
78
+ const args = [process.execPath, bin, 'job', 'run', id];
79
+ if (ctx.platform.id === 'linux' && !scopesWork(ctx.env)) {
80
+ // No user systemd session (container, CI, `su` shell): a plain detached
81
+ // runner instead of a systemd unit, so the job still runs.
82
+ const fd = fs.openSync(logOf(ctx, id), 'a');
83
+ const child = spawn(args[0], args.slice(1), { env: ctx.env, detached: true, stdio: ['ignore', fd, fd] });
84
+ child.unref();
85
+ fs.closeSync(fd);
86
+ } else {
87
+ ctx.platform.spawnDetached(ctx, `job-${id}`, args, logOf(ctx, id));
88
+ }
73
89
  return Promise.resolve(job);
74
90
  }
75
91
 
92
+ /** The environment a job gets: never Anthropic keys, pool or serve credentials. */
93
+ export function cleanEnv(env) {
94
+ const e = { ...env };
95
+ for (const k of Object.keys(e)) if (/^(ANTHROPIC_|CLAUDE_CODE_USE_|POOL_|SERVE_OWNER_PASSWORD$|RUNLOOM_)/.test(k)) delete e[k];
96
+ return e;
97
+ }
98
+
76
99
  /** Git auth through the environment only (GIT_CONFIG_*), for https://github.com. */
77
100
  export function gitAuthEnv(token) {
78
101
  if (!token) return {};
@@ -80,27 +103,122 @@ export function gitAuthEnv(token) {
80
103
  return { GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'http.https://github.com/.extraheader', GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${basic}`, GIT_TERMINAL_PROMPT: '0' };
81
104
  }
82
105
 
83
- function runStep(cmd, cwd, env, log, redact) {
106
+ /**
107
+ * Output kept for a step: up to max bytes in the log, as the first half and the
108
+ * last half with a marker between (stdout and stderr interleaved as they come).
109
+ */
110
+ function cappedWriter(fd, max, redact) {
111
+ let written = 0;
112
+ let total = 0;
113
+ let tail = '';
114
+ const head = Math.floor(max / 2);
115
+ return {
116
+ write(chunk) {
117
+ const s = redact(String(chunk));
118
+ total += Buffer.byteLength(s);
119
+ if (written < head) {
120
+ const room = head - written;
121
+ const part = Buffer.from(s).subarray(0, room).toString();
122
+ fs.writeSync(fd, part);
123
+ written += Buffer.byteLength(part);
124
+ const rest = s.slice(part.length);
125
+ if (rest) tail = (tail + rest).slice(-(max - head));
126
+ } else {
127
+ tail = (tail + s).slice(-(max - head));
128
+ }
129
+ },
130
+ end() {
131
+ if (total > written + Buffer.byteLength(tail)) fs.writeSync(fd, `\n[… ${total - written - Buffer.byteLength(tail)} bytes of output omitted …]\n`);
132
+ if (tail) fs.writeSync(fd, tail);
133
+ return total;
134
+ },
135
+ };
136
+ }
137
+
138
+ /**
139
+ * Does `systemd-run --user --scope` work here? Not without a user systemd
140
+ * session (containers, CI runners, a plain `su` shell): then the watchdog
141
+ * holds the caps instead. Probed once per process, like hd-proc-loop does.
142
+ */
143
+ const scopeProbe = new Map();
144
+ export function scopesWork(env) {
145
+ const bin = which('systemd-run', env);
146
+ if (!bin) return false;
147
+ if (!scopeProbe.has(bin)) {
148
+ const r = spawnSync(bin, ['--user', '--scope', '--quiet', '-p', 'MemoryMax=64M', 'true'], { env, stdio: 'ignore', timeout: 10000 });
149
+ scopeProbe.set(bin, r.status === 0);
150
+ }
151
+ return scopeProbe.get(bin);
152
+ }
153
+
154
+ /** Linux: run inside a transient systemd scope holding the per-process caps (plain when scopes don't work here). */
155
+ function scoped(ctx, argv, name) {
156
+ if (ctx.platform.id !== 'linux' || ctx.env.HD_JOBS_NO_SCOPE === '1' || !scopesWork(ctx.env)) return argv;
157
+ const l = computeLimits(ctx.cfg);
158
+ return ['systemd-run', '--user', '--scope', '--quiet', '--collect', `--unit=harness-job-${name}-${process.pid}`,
159
+ '-p', `MemoryMax=${Math.round(l.procMem / 1048576)}M`, '-p', `CPUQuota=${l.procCpu}%`, '--', ...argv];
160
+ }
161
+
162
+ /** Kill a process group: TERM, then KILL after `grace` ms if anything is left. */
163
+ export function killGroup(pgid, grace = 5000) {
164
+ if (!pgid) return;
165
+ try { process.kill(-pgid, 'SIGTERM'); } catch { return; }
166
+ const t = setTimeout(() => { try { process.kill(-pgid, 'SIGKILL'); } catch { /* gone */ } }, grace);
167
+ t.unref?.();
168
+ }
169
+
170
+ /** One step: a shell line (cmd) or a structured argv (no shell), in its own process group. */
171
+ function runStep(ctx, job, step, env, log, redact) {
84
172
  return new Promise((resolve) => {
85
173
  const fd = fs.openSync(log, 'a');
86
- const out = [];
87
- const child = spawn('bash', ['-lc', cmd], { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });
88
- const pipe = (b) => { const s = redact(String(b)); out.push(s); fs.writeSync(fd, s); };
89
- child.stdout.on('data', pipe);
90
- child.stderr.on('data', pipe);
91
- child.on('close', (code) => { fs.closeSync(fd); resolve(code ?? 1); });
92
- child.on('error', (e) => { fs.writeSync(fd, `${e.message}\n`); fs.closeSync(fd); resolve(127); });
174
+ const out = cappedWriter(fd, job.maxOutputBytes || 8 * 1024 * 1024, redact);
175
+ const argv = step.argv ? scoped(ctx, step.argv, job.id) : ['bash', '-lc', step.cmd];
176
+ let child;
177
+ try {
178
+ child = spawn(argv[0], argv.slice(1), { cwd: step.cwd || ctx.env.HOME, env, stdio: ['ignore', 'pipe', 'pipe'], detached: true });
179
+ } catch (e) {
180
+ fs.writeSync(fd, `${e.message}\n`); fs.closeSync(fd); resolve({ code: 127 }); return;
181
+ }
182
+ job.pid = child.pid;
183
+ write(ctx, job);
184
+ child.stdout.on('data', (b) => out.write(b));
185
+ child.stderr.on('data', (b) => out.write(b));
186
+ let timer = null;
187
+ if (job.timeoutSeconds) {
188
+ const left = Math.max(1, job.timeoutSeconds * 1000 - (Date.now() - Date.parse(job.startedAt)));
189
+ timer = setTimeout(() => { job.timedOut = true; killGroup(child.pid, 3000); }, left);
190
+ }
191
+ child.on('error', (e) => { out.write(`${e.message}\n`); });
192
+ child.on('close', (code, signal) => {
193
+ if (timer) clearTimeout(timer);
194
+ job.outputBytes += out.end();
195
+ fs.closeSync(fd);
196
+ resolve({ code: code ?? (signal ? 128 + (signal === 'SIGKILL' ? 9 : 15) : 1), signal });
197
+ });
93
198
  });
94
199
  }
95
200
 
201
+ /** Ask a running job to stop: its whole process tree is terminated; the runner records it as cancelled. */
202
+ export function cancelJob(ctx, id) {
203
+ const job = getJob(ctx, id);
204
+ if (!['queued', 'running'].includes(job.status)) return { id, status: job.status, note: 'already finished' };
205
+ job.cancelRequested = true;
206
+ write(ctx, job);
207
+ if (job.pid) killGroup(job.pid);
208
+ return { id, status: 'cancelling' };
209
+ }
210
+
96
211
  /** `harness-device job run <id>`: run the steps, record status. internals: { name: async (ctx, job, args) => void }. */
97
212
  export async function runJob(ctx, id, internals = {}) {
98
213
  const job = getJob(ctx, id);
99
214
  const log = logOf(ctx, id);
100
- const token = job.tokenSecret ? readSecrets(ctx.paths.secrets)[job.tokenSecret] || null : null;
101
- const redact = (s) => (token ? s.split(token).join('***') : s);
102
- const env = { ...ctx.env, ...gitAuthEnv(token), CI: '1' };
103
- for (const k of ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX']) delete env[k];
215
+ const secrets = readSecrets(ctx.paths.secrets);
216
+ const token = job.tokenSecret ? secrets[job.tokenSecret] || null : null;
217
+ // Scoped env references: VAR ← device secret, injected for this job only, redacted from its output.
218
+ const refs = Object.entries(job.envRefs || {}).map(([v, name]) => [v, secrets[name]]).filter(([, val]) => typeof val === 'string' && val);
219
+ const hidden = [token, ...refs.map(([, val]) => val)].filter((x) => x && x.length >= 4);
220
+ const redact = (s) => hidden.reduce((acc, h) => acc.split(h).join('***'), s);
221
+ const env = { ...cleanEnv(ctx.env), ...gitAuthEnv(token), ...Object.fromEntries(refs), CI: '1' };
104
222
  job.status = 'running';
105
223
  job.startedAt = new Date().toISOString();
106
224
  write(ctx, job);
@@ -116,22 +234,32 @@ export async function runJob(ctx, id, internals = {}) {
116
234
  await builtins[s.internal](ctx, job, s.args || {});
117
235
  continue;
118
236
  }
119
- const code = await runStep(s.cmd, s.cwd || ctx.env.HOME, env, log, redact);
120
- if (code !== 0) {
121
- job.exit = code;
122
- throw new Error(`"${s.name}" exited with ${code}`);
123
- }
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}`);
124
244
  }
125
245
  job.status = 'done';
126
246
  job.exit = 0;
127
247
  say('done');
128
248
  } catch (e) {
129
- job.status = 'failed';
249
+ job.cancelled = !!job.cancelRequested;
250
+ job.status = job.cancelled ? 'cancelled' : 'failed';
130
251
  job.error = redact(String(e.message || e));
131
- say(`failed: ${job.error}`);
252
+ say(`${job.status}: ${job.error}`);
132
253
  }
254
+ job.pid = null;
133
255
  job.finishedAt = new Date().toISOString();
134
256
  write(ctx, job);
257
+ if (job.kind === 'exec') {
258
+ const { event } = await import('./state.js');
259
+ const s0 = job.steps[0] || {};
260
+ 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`);
262
+ }
135
263
  return job;
136
264
  }
137
265
 
@@ -139,3 +267,16 @@ export async function runJob(ctx, id, internals = {}) {
139
267
  export function describeJob(ctx, job, lines = 80) {
140
268
  return { ...job, log: tail(logOf(ctx, job.id), lines) };
141
269
  }
270
+
271
+ /** Stream a job's log: the bytes from `offset` on (at most `max`), and where to continue. */
272
+ export function readLog(ctx, id, offset = 0, max = 64 * 1024) {
273
+ const f = logOf(ctx, id);
274
+ if (!fs.existsSync(f)) return { data: '', next: 0, size: 0 };
275
+ const size = fs.statSync(f).size;
276
+ const from = Math.max(0, Math.min(Number(offset) || 0, size));
277
+ const len = Math.min(max, size - from);
278
+ const buf = Buffer.alloc(len);
279
+ const fd = fs.openSync(f, 'r');
280
+ try { fs.readSync(fd, buf, 0, len, from); } finally { fs.closeSync(fd); }
281
+ return { data: buf.toString('utf8'), next: from + len, size };
282
+ }
package/src/limits.js CHANGED
@@ -140,6 +140,15 @@ export function groups(ctx, procs = parsePs(capture('ps', ['-A', '-o', 'pid=,ppi
140
140
  out.push({ name: win, kind: 'session', pids: tree(procs, Number(pid)) });
141
141
  }
142
142
  }
143
+ // Running jobs (exec, setup, deploy…): each process group is held to the per-process caps.
144
+ const jobsDir = path.join(ctx.paths.state, 'jobs');
145
+ if (fs.existsSync(jobsDir)) {
146
+ for (const f of fs.readdirSync(jobsDir).filter((x) => x.endsWith('.json'))) {
147
+ let j;
148
+ try { j = JSON.parse(fs.readFileSync(path.join(jobsDir, f), 'utf8')); } catch { continue; }
149
+ if (j.status === 'running' && j.pid && procs.has(j.pid)) out.push({ name: `job-${j.id}`, kind: 'job', pids: tree(procs, j.pid), jobId: j.id });
150
+ }
151
+ }
143
152
  const port = `--remote-debugging-port=${ctx.cfg.CDP_PORT}`;
144
153
  const roots = [...procs.values()].filter((p) => p.args.includes(port) && !(procs.get(p.ppid)?.args || '').includes(port));
145
154
  if (roots.length) out.push({ name: 'browser', kind: 'browser', pids: roots.flatMap((r) => tree(procs, r.pid)) });
@@ -167,7 +176,7 @@ export function decide(gs, l, prev = {}, now = Date.now()) {
167
176
  if (g.kind === 'session') continue;
168
177
  const memMax = g.kind === 'browser' ? l.browserMem : l.procMem;
169
178
  const memOver = g.rss > memMax;
170
- const cpuOver = g.kind === 'proc' && g.cpuPct !== null && g.cpuPct > l.procCpu;
179
+ const cpuOver = (g.kind === 'proc' || g.kind === 'job') && g.cpuPct !== null && g.cpuPct > l.procCpu;
171
180
  if (over(g.name, memOver || cpuOver)) {
172
181
  actions.push({ name: g.name, kind: g.kind, reason: memOver ? `using ${humanMem(g.rss)}, limit ${humanMem(memMax)}` : `using ${g.cpuPct}% CPU, limit ${l.procCpu}%` });
173
182
  }
@@ -203,7 +212,7 @@ export async function enforce(ctx, { act = true } = {}) {
203
212
  const { event } = await import('./state.js');
204
213
  for (const a of actions) {
205
214
  const g = gs.find((x) => x.name === a.name);
206
- event(ctx, `limits: stopped ${a.name} (${a.reason})${a.kind === 'proc' ? '; it restarts with backoff' : ''}`);
215
+ event(ctx, `limits: stopped ${a.name} (${a.reason})${a.kind === 'proc' ? '; it restarts with backoff' : a.kind === 'job' ? '; the job fails (it is not restarted)' : ''}`);
207
216
  if (a.kind === 'browser') {
208
217
  const { restartService } = await import('./device.js');
209
218
  try { restartService(ctx, 'chromium'); } catch { stopTree(g.pids); }
package/src/mcp/server.js CHANGED
@@ -18,6 +18,8 @@ import * as cleanup from '../cleanup.js';
18
18
  import * as limits from '../limits.js';
19
19
  import * as project from '../project.js';
20
20
  import * as jobs from '../jobs.js';
21
+ import * as execMod from '../exec.js';
22
+ import * as ws from '../workspace.js';
21
23
  import { Cancelled, NeedsUser, interaction } from './interact.js';
22
24
 
23
25
  const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
@@ -172,9 +174,61 @@ export function buildServer(env = process.env, opts = {}) {
172
174
  return text(project.envManage(c, { app: a.app, action: a.action, key: a.key, value: a.value, fromSecret: a.from_secret, file: a.file }));
173
175
  });
174
176
 
175
- tool('job_status', 'A background job (clone, setup, pull, deploy, long shell command): status, current step, exit code and the end of its log. Without id: recent jobs.',
176
- { id: z.string().regex(/^[a-z0-9-]{6,40}$/).optional(), lines: z.number().int().min(1).max(500).optional() },
177
- async (c, a) => text(a.id ? jobs.describeJob(c, jobs.getJob(c, a.id), a.lines || 80) : jobs.listJobs(c).map(({ steps, ...j }) => j)));
177
+ tool('exec', `Run one program in an app folder, without a shell: argv is [program, ...args], the program a bare name on this device's allowlist (${execMod.allowList(base.cfg).join(', ')}). Shells and wrappers (bash, sh, env, sudo, xargs…) are never allowed here; use shell_exec (device:admin) for shell syntax. Optional cwd (a sub-folder of the app), env_refs {VAR: DEVICE_SECRET} (injected for this run, redacted from output), timeout_seconds (default 600, max 3600), max_output_kb (default 256: first and last halves kept). It is a durable job: waits up to wait_seconds (default 30, max 120) and returns the exit code and output, or the job id to follow with job_status (offset streams new output) and stop with job_cancel. Never restarted.`,
178
+ { app: APP, argv: z.array(z.string().max(8000)).min(1).max(200), cwd: z.string().max(500).optional(), env_refs: z.record(z.string(), z.string()).optional(),
179
+ timeout_seconds: z.number().int().min(1).max(3600).optional(), max_output_kb: z.number().int().min(1).max(4096).optional(), wait_seconds: z.number().int().min(0).max(120).optional(), ...FORCE },
180
+ async (c, a) => {
181
+ await guard(c, a, `running ${a.argv[0]}`);
182
+ const job = await execMod.exec(c, { app: a.app, argv: a.argv, cwd: a.cwd, envRefs: a.env_refs, timeoutSeconds: a.timeout_seconds, maxOutputKb: a.max_output_kb, waitSeconds: a.wait_seconds ?? 30 });
183
+ const done = !['queued', 'running'].includes(job.status);
184
+ const log = jobs.readLog(c, job.id, 0, 256 * 1024);
185
+ const body = { job: job.id, status: job.status, exit: job.exit, timed_out: job.timedOut, cancelled: job.cancelled, output_bytes: job.outputBytes,
186
+ output: log.data.replace(/^\n?\[harness-device\] step 1\/1: [^\n]*\n/, '').replace(/\n\[harness-device\] (done|failed|cancelled)[^\n]*\n?$/, ''),
187
+ ...(done ? {} : { next: `still running: job_status {"id":"${job.id}","offset":${log.next}} for new output, job_cancel to stop it` }) };
188
+ return { ...(done && job.status !== 'done' ? { isError: true } : {}), content: [{ type: 'text', text: JSON.stringify(body, null, 2) }] };
189
+ });
190
+
191
+ tool('workspace_create', 'A per-ticket workspace of a cloned app: a git worktree on branch ticket/<TICKET>, from a pinned revision (base, default origin/<branch>), with its own port. It is registered as the app "<app>--<ticket>", so exec, file_*, env_manage, project_setup/start and job_status work on it. Creating it again returns the same one. setup=true (default) installs dependencies as a job. database=true is not available yet (needs the shared development DB provisioner).',
192
+ { app: APP, ticket: z.string().regex(ws.TICKET).describe('ticket key, e.g. HARNESS-5'), base: z.string().regex(/^[A-Za-z0-9._\/^~-]{1,200}$/).optional().describe('branch, tag or commit; default origin/<app branch>'),
193
+ setup: z.boolean().optional(), database: z.boolean().optional(), ...FORCE },
194
+ async (c, a) => {
195
+ await guard(c, a, `creating a workspace for ${a.ticket}`);
196
+ const r = await ws.createWorkspace(c, { app: a.app, ticket: a.ticket, base: a.base, database: !!a.database });
197
+ const w = r.workspace;
198
+ const su = r.created && a.setup !== false ? await project.setup(c, { app: w.name }) : null;
199
+ return text({ workspace: w.name, created: r.created, dir: w.dir, branch: w.workspace.branch, base: w.workspace.baseRef, base_sha: w.workspace.baseSha, port: w.port,
200
+ ...(su?.job ? { setup_job: su.job.id, note: `dependencies install in the background: job_status {"id":"${su.job.id}"}` } : su ? { setup: su.note } : {}) });
201
+ });
202
+
203
+ tool('workspace_list', 'Per-ticket workspaces on this device (all, or of one app): ticket, branch, pinned base, folder, port.',
204
+ { app: APP.optional() },
205
+ async (c, a) => text(ws.listWorkspaces(c, a.app || null)));
206
+
207
+ tool('workspace_status', 'A workspace\'s git state: uncommitted files, commits ahead of / behind its pinned base, HEAD, port and whether its process runs.',
208
+ { workspace: APP },
209
+ async (c, a) => text(ws.workspaceStatus(c, a.workspace)));
210
+
211
+ tool('workspace_archive', 'Archive a workspace (asks the user first): stops its process, removes the worktree folder and frees its port. The branch and its commits are kept. Uncommitted changes make it refuse, unless discard_changes=true (they are lost).',
212
+ { workspace: APP, discard_changes: z.boolean().optional(), ...CONFIRM },
213
+ async (c, a, u) => {
214
+ const st = ws.workspaceStatus(c, a.workspace);
215
+ if (st.dirty.length && !a.discard_changes) return { isError: true, content: [{ type: 'text', text: `${a.workspace} has ${st.dirty.length} uncommitted change(s): ${st.dirty.slice(0, 10).join(', ')}. Commit them (exec git …) or archive with discard_changes=true after the user agrees to lose them.` }] };
216
+ await u.confirm(`Archive ${a.workspace}? Its folder is removed and its branch ${st.branch} kept at ${st.head.slice(0, 12)}.${st.dirty.length ? ` ${st.dirty.length} uncommitted change(s) will be LOST.` : ''}`);
217
+ return text(await ws.archiveWorkspace(c, { name: a.workspace, force: !!a.discard_changes }));
218
+ });
219
+
220
+ 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.',
221
+ { id: z.string().regex(/^[a-z0-9-]{6,40}$/) },
222
+ async (c, a) => text(jobs.cancelJob(c, a.id)));
223
+
224
+ tool('job_status', 'A background job (exec, clone, setup, pull, deploy, long shell command): status, current step, exit code and the end of its log. With offset: the log bytes from there on and the next offset (stream the output). Without id: recent jobs.',
225
+ { id: z.string().regex(/^[a-z0-9-]{6,40}$/).optional(), lines: z.number().int().min(1).max(500).optional(), offset: z.number().int().min(0).optional() },
226
+ async (c, a) => {
227
+ if (!a.id) return text(jobs.listJobs(c).map(({ steps, ...j }) => j));
228
+ const job = jobs.getJob(c, a.id);
229
+ if (a.offset !== undefined) { const { steps, ...j } = job; return text({ ...j, ...jobs.readLog(c, a.id, a.offset) }); }
230
+ return text(jobs.describeJob(c, job, a.lines || 80));
231
+ });
178
232
 
179
233
  tool('viewers', 'URLs where the user watches live progress (noVNC display, read-only tmux, Playwright UI) and the SSH tunnel command to reach them.', {},
180
234
  async (c) => text({ ...device.viewers(c.cfg, c.platform), sshTunnel: device.tunnelCommand(c.cfg, c.platform), ngrok: await device.ngrokStatus() }));
package/src/project.js CHANGED
@@ -5,6 +5,7 @@
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import { spawn } from 'node:child_process';
8
+ import { repoAllowed, repoSlug } from './workspace.js';
8
9
  import { appsDir, getApp, saveApp, listApps, nameFromUrl, checkRepoUrl, resolveIn, procName, APP_NAME } from './apps.js';
9
10
  import { detect } from './stack.js';
10
11
  import { startJob } from './jobs.js';
@@ -41,6 +42,7 @@ const CLEAN_CHECK = 'test -z "$(git status --porcelain --untracked-files=no)" ||
41
42
 
42
43
  export async function clone(ctx, { url, name, branch, tokenSecret, session = false }) {
43
44
  checkRepoUrl(url);
45
+ if (!repoAllowed(ctx.cfg, url)) throw new Error(`${repoSlug(url) || url} is not on this device's REPO_ALLOW list (${ctx.cfg.REPO_ALLOW})`);
44
46
  const n = name || nameFromUrl(url);
45
47
  if (!APP_NAME.test(n)) throw new Error(`App name "${n}" must be lowercase letters, digits, _ or - (max 40)`);
46
48
  if (branch && !BRANCH.test(branch)) throw new Error(`Not a branch name: ${branch}`);
@@ -12,9 +12,10 @@ const ORDER = ['device:read', 'device:operate', 'device:admin'];
12
12
 
13
13
  const TOOLS = {
14
14
  'device:read': ['device_status', 'sessions', 'proc_list', 'viewers', 'disk_usage', 'logs', 'resources', 'screenshot', 'docker_summary', 'ngrok_status', 'config_get',
15
- 'app_list', 'file_read', 'job_status'],
15
+ 'app_list', 'file_read', 'job_status', 'workspace_list', 'workspace_status'],
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
- 'git_clone', 'git_pull', 'project_setup', 'project_start', 'project_stop', 'project_deploy', 'file_write', 'env_manage'],
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'],
18
19
  // shell_exec is not listed: it needs device:admin (unknown tools do).
19
20
  };
20
21
 
@@ -0,0 +1,183 @@
1
+ // Per-ticket workspaces (HARNESS-5): a git worktree of a managed app on its own
2
+ // branch, at a pinned revision, with its own port. A workspace is registered
3
+ // as an app named "<app>--<ticket>", so every app tool (exec, file_*,
4
+ // env_manage, project_setup/start, job_status) works on it unchanged.
5
+ //
6
+ // - Two tickets never share a path or a branch; git operations on one repo
7
+ // are serialized by a lock file, so concurrent creates can't collide.
8
+ // - Creating again is idempotent: the same record (and port) comes back.
9
+ // - Archiving refuses a dirty tree unless forced with the user's OK; it keeps
10
+ // the branch (the work is never deleted, only the checkout).
11
+ // - Per-workspace databases need the trusted provisioner (DEV_PROVISIONER_DB_URL),
12
+ // which does not exist yet: asking for one fails with an explicit BLOCKED
13
+ // status, never a local Docker fallback.
14
+
15
+ import fs from 'node:fs';
16
+ import net from 'node:net';
17
+ import path from 'node:path';
18
+ import { spawnSync } from 'node:child_process';
19
+ import { appsDir, getApp, saveApp, listApps, procName } from './apps.js';
20
+ import { readSecrets } from './context.js';
21
+ import { gitAuthEnv, cleanEnv } from './jobs.js';
22
+ import * as state from './state.js';
23
+
24
+ export const TICKET = /^[A-Z][A-Z0-9]{0,15}-\d{1,7}$/;
25
+ const PORT_MIN = 4100;
26
+ const PORT_MAX = 4999;
27
+
28
+ export function wsName(app, ticket) {
29
+ const n = `${app}--${ticket.toLowerCase()}`;
30
+ if (n.length > 40) throw new Error(`workspace name ${n} is over 40 characters; use a shorter app name`);
31
+ return n;
32
+ }
33
+ const lockFile = (ctx, app) => path.join(ctx.paths.state, 'locks', `git-${app}.lock`);
34
+ const portsFile = (ctx) => path.join(ctx.paths.state, 'ports.json');
35
+
36
+ /** `owner/repo` of a repo URL (https, git@ or file://), for the allowlist. */
37
+ export function repoSlug(url) {
38
+ const m = String(url || '').replace(/\.git$/, '').match(/[/:]([^/:]+)\/([^/]+)$/);
39
+ return m ? `${m[1]}/${m[2]}`.toLowerCase() : '';
40
+ }
41
+
42
+ /** REPO_ALLOW: comma-separated owner/repo globs (owner/*); empty allows any repository. */
43
+ export function repoAllowed(cfg, url) {
44
+ const list = String(cfg.REPO_ALLOW || '').split(',').map((s) => s.trim().toLowerCase()).filter(Boolean);
45
+ if (!list.length) return true;
46
+ const slug = repoSlug(url);
47
+ return list.some((g) => (g.endsWith('/*') ? slug.startsWith(g.slice(0, -1)) : slug === g));
48
+ }
49
+
50
+ /** Run git in a folder; returns stdout or throws with git's own message (token never in args). */
51
+ function git(ctx, cwd, args, { token = null, timeout = 120000 } = {}) {
52
+ const r = spawnSync('git', args, { cwd, env: { ...cleanEnv(ctx.env), ...gitAuthEnv(token) }, encoding: 'utf8', timeout });
53
+ if (r.status !== 0) {
54
+ const msg = `${r.stderr || r.stdout || r.error?.message || ''}`.trim().split('\n').slice(-3).join(' ');
55
+ throw new Error(`git ${args[0]} failed: ${token ? msg.split(token).join('***') : msg}`);
56
+ }
57
+ return (r.stdout || '').trim();
58
+ }
59
+
60
+ /** Serialize git operations on one repository (worktree add/remove take .git locks). */
61
+ async function withLock(ctx, app, fn, waitMs = 60000) {
62
+ const f = lockFile(ctx, app);
63
+ fs.mkdirSync(path.dirname(f), { recursive: true });
64
+ const start = Date.now();
65
+ for (;;) {
66
+ try { fs.writeFileSync(f, String(process.pid), { flag: 'wx' }); break; } catch (e) {
67
+ if (e.code !== 'EEXIST') throw e;
68
+ // A lock left by a dead process is stale.
69
+ const pid = Number(fs.readFileSync(f, 'utf8')) || 0;
70
+ try { if (pid) process.kill(pid, 0); else throw new Error(); } catch { fs.rmSync(f, { force: true }); continue; }
71
+ if (Date.now() - start > waitMs) throw new Error(`another git operation on ${app} is still running`);
72
+ await new Promise((r) => setTimeout(r, 100));
73
+ }
74
+ }
75
+ try { return await fn(); } finally { fs.rmSync(f, { force: true }); }
76
+ }
77
+
78
+ const portFree = (port) => new Promise((resolve) => {
79
+ const s = net.createServer().once('error', () => resolve(false)).once('listening', () => s.close(() => resolve(true)));
80
+ s.listen(port, '127.0.0.1');
81
+ });
82
+
83
+ /** A port for this owner: the one it had, else the lowest free one in the range. */
84
+ export async function allocatePort(ctx, owner) {
85
+ let map = {};
86
+ try { map = JSON.parse(fs.readFileSync(portsFile(ctx), 'utf8')); } catch { /* none yet */ }
87
+ const mine = Object.entries(map).find(([, o]) => o === owner);
88
+ if (mine) return Number(mine[0]);
89
+ for (let p = PORT_MIN; p <= PORT_MAX; p++) {
90
+ if (map[p]) continue;
91
+ if (await portFree(p)) {
92
+ map[p] = owner;
93
+ fs.mkdirSync(path.dirname(portsFile(ctx)), { recursive: true });
94
+ fs.writeFileSync(portsFile(ctx), JSON.stringify(map, null, 1));
95
+ return p;
96
+ }
97
+ }
98
+ throw new Error(`no free port in ${PORT_MIN}-${PORT_MAX}`);
99
+ }
100
+
101
+ export function releasePort(ctx, owner) {
102
+ let map = {};
103
+ try { map = JSON.parse(fs.readFileSync(portsFile(ctx), 'utf8')); } catch { return; }
104
+ for (const [p, o] of Object.entries(map)) if (o === owner) delete map[p];
105
+ fs.writeFileSync(portsFile(ctx), JSON.stringify(map, null, 1));
106
+ }
107
+
108
+ /** Workspaces of one app (or all), newest first. */
109
+ export function listWorkspaces(ctx, app = null) {
110
+ return listApps(ctx).filter((a) => a.workspace && (!app || a.workspace.parent === app)).map((a) => ({ name: a.name, ...a.workspace, dir: a.dir, port: a.port }));
111
+ }
112
+
113
+ export async function createWorkspace(ctx, { app: parentName, ticket, base, database = false }) {
114
+ if (!TICKET.test(String(ticket || ''))) throw new Error(`ticket must be a key like HARNESS-5 (got ${ticket})`);
115
+ if (database) {
116
+ const err = new Error('BLOCKED: a per-workspace database needs the trusted provisioner (DEV_PROVISIONER_DB_URL), which is not available yet. Nothing was started; no local database container is used instead. Track it on HARNESS-5 (ACs for the shared development database).');
117
+ err.code = 'BLOCKED';
118
+ throw err;
119
+ }
120
+ const parent = getApp(ctx, parentName);
121
+ if (parent.workspace) throw new Error(`${parentName} is itself a workspace; give the app it came from`);
122
+ if (parent.project || !fs.existsSync(path.join(parent.dir, '.git'))) throw new Error(`${parentName} is not a cloned git app (git_clone it first)`);
123
+ if (parent.repo && !repoAllowed(ctx.cfg, parent.repo)) throw new Error(`${repoSlug(parent.repo)} is not on this device's REPO_ALLOW list`);
124
+ const name = wsName(parent.name, ticket);
125
+ const branch = `ticket/${ticket}`;
126
+ const dir = path.join(appsDir(ctx), '.worktrees', parent.name, ticket.toLowerCase());
127
+ const token = parent.tokenSecret ? readSecrets(ctx.paths.secrets)[parent.tokenSecret] || null : null;
128
+
129
+ return withLock(ctx, parent.name, async () => {
130
+ const existing = listApps(ctx).find((a) => a.name === name);
131
+ if (existing && fs.existsSync(existing.dir)) return { workspace: existing, created: false };
132
+
133
+ git(ctx, parent.dir, ['fetch', '--prune', 'origin'], { token });
134
+ const ref = base || `origin/${parent.branch || git(ctx, parent.dir, ['rev-parse', '--abbrev-ref', 'origin/HEAD']).replace(/^origin\//, '')}`;
135
+ let sha;
136
+ try { sha = git(ctx, parent.dir, ['rev-parse', '--verify', `${ref}^{commit}`]); } catch { throw new Error(`base revision "${ref}" not found in ${parent.name}`); }
137
+ const branchExists = spawnSync('git', ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`], { cwd: parent.dir }).status === 0;
138
+ fs.mkdirSync(path.dirname(dir), { recursive: true });
139
+ if (branchExists) git(ctx, parent.dir, ['worktree', 'add', dir, branch]);
140
+ else git(ctx, parent.dir, ['worktree', 'add', '-b', branch, dir, sha]);
141
+
142
+ const port = await allocatePort(ctx, name);
143
+ const ws = saveApp(ctx, {
144
+ name, dir, repo: parent.repo, branch, tokenSecret: parent.tokenSecret || null,
145
+ stack: parent.stack, start: parent.startOverride || parent.start, port,
146
+ workspace: { parent: parent.name, ticket, branch, baseRef: ref, baseSha: sha, createdAt: new Date().toISOString() },
147
+ createdAt: new Date().toISOString(),
148
+ });
149
+ state.event(ctx, `workspace ${name}: ${branch} at ${sha.slice(0, 12)} (${ref}), port ${port}`);
150
+ return { workspace: ws, created: true };
151
+ });
152
+ }
153
+
154
+ export function workspaceStatus(ctx, name) {
155
+ const ws = getApp(ctx, name);
156
+ if (!ws.workspace) throw new Error(`${name} is not a workspace`);
157
+ const porcelain = git(ctx, ws.dir, ['status', '--porcelain']);
158
+ const dirty = porcelain ? porcelain.split('\n').map((l) => l.slice(3)) : [];
159
+ const head = git(ctx, ws.dir, ['rev-parse', 'HEAD']);
160
+ const [behind, ahead] = git(ctx, ws.dir, ['rev-list', '--left-right', '--count', `${ws.workspace.baseSha}...HEAD`]).split(/\s+/).map(Number);
161
+ const running = state.listProcs(ctx).some((p) => p.name === procName(ws));
162
+ return { name, ticket: ws.workspace.ticket, branch: ws.workspace.branch, base: ws.workspace.baseRef, baseSha: ws.workspace.baseSha, head, ahead, behind, dirty, port: ws.port, running, dir: ws.dir };
163
+ }
164
+
165
+ /** Remove the checkout (the branch and its commits stay). Dirty trees need force (with the user's OK). */
166
+ export async function archiveWorkspace(ctx, { name, force = false }) {
167
+ const ws = getApp(ctx, name);
168
+ if (!ws.workspace) throw new Error(`${name} is not a workspace`);
169
+ const st = workspaceStatus(ctx, name);
170
+ if (st.dirty.length && !force) {
171
+ throw new Error(`${name} has uncommitted changes (${st.dirty.slice(0, 10).join(', ')}${st.dirty.length > 10 ? ', …' : ''}); commit or stash them, or archive with force (the changes are lost)`);
172
+ }
173
+ if (st.running) state.removeProc(ctx, procName(ws));
174
+ const parent = getApp(ctx, ws.workspace.parent);
175
+ await withLock(ctx, parent.name, async () => {
176
+ git(ctx, parent.dir, ['worktree', 'remove', ...(force ? ['--force'] : []), ws.dir]);
177
+ git(ctx, parent.dir, ['worktree', 'prune']);
178
+ });
179
+ releasePort(ctx, name);
180
+ fs.rmSync(path.join(ctx.paths.state, 'apps', `${name}.json`), { force: true });
181
+ state.event(ctx, `workspace ${name} archived${force && st.dirty.length ? ` (forced; ${st.dirty.length} uncommitted change(s) discarded)` : ''}; branch ${st.branch} kept at ${st.head.slice(0, 12)}`);
182
+ return { archived: name, branch: st.branch, head: st.head, discarded: force ? st.dirty : [] };
183
+ }