@dreamtree-org/harness-device 0.4.0 → 0.6.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
@@ -207,6 +207,8 @@ Repositories this device runs, kept in `APPS_DIR` (default `~/apps`). Unlike pro
207
207
  | `file_read` / `file_write` | Inside the app folder only; `.git` and `.env` are off limits |
208
208
  | `env_manage` | The app's `.env`. `list` shows names only. `set` takes a value or `from_secret` (copies a device secret without exposing it), and asks first |
209
209
  | `exec` | One program with an argv and no shell. The program must be on `EXEC_ALLOW` (a default list of dev tools); shells and wrappers such as `bash`, `env`, `sudo` or `xargs` are always refused. Runs in the app folder or a confined sub-folder. `env_refs` injects device secrets by name and redacts them from output. Timeout and output cap (head and tail kept). A durable job: `job_status` with `offset` streams new output, `job_cancel` kills the whole process tree. Never restarted. Linux holds the per-process caps in a systemd scope; on macOS the watchdog covers running jobs. Each run is recorded in `events` (program, folder, outcome, exit code, duration; never env or output) |
210
+ | `workspace_create` / `workspace_list` / `workspace_status` / `workspace_archive` | Per-ticket workspaces of a cloned app. Each is a git worktree under `APPS_DIR/.worktrees/<app>/<ticket>` on branch `ticket/<TICKET>`, created from a pinned revision (`base`, default `origin/<branch>`; the SHA is recorded). It gets its own port (4100–4999, kept across retries) and is registered as the app `<app>--<ticket>`, so every app tool works on it. Creating it again returns the same workspace. Git operations on one repository are serialized by a lock. Archiving stops its process, removes the folder, frees the port and keeps the branch; uncommitted changes make it refuse unless the user agrees to discard them. `REPO_ALLOW` (owner/repo, owner/*) limits which repositories `git_clone` and workspaces accept. Per-workspace databases (`database: true`) answer BLOCKED until the shared development DB provisioner exists; no local database container is started instead |
211
+ | `preview_start` / `preview_list` / `preview_stop` / `preview_screenshot` | Protected previews of an app or workspace. Starts its dev server on its own port if nothing answers there and health-checks it; on failure it returns the app's last output and stops it. A per-preview proxy listens on 127.0.0.1 only and forwards to that one app port. Every request needs a token bound to the preview and its expiry, signed with a device key (`state/preview.key`). The link sets an HttpOnly cookie. The record is checked on each request, so a stopped preview is refused at once, and WebSocket upgrades are checked too. Reach it with the SSH tunnel command it returns. A public ngrok URL is opt-in (`public: true`, user-approved) and still needs the token. `preview_stop` revokes the link, stops the proxy, closes the tunnel and stops the app if the preview started it. Expired previews, and previews whose app or proxy is gone, are ended by `preview_list` and by every watchdog pass (`limits --enforce`). `preview_screenshot` (browser capability) loads it in the device browser and returns a PNG |
210
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` |
211
213
  | `job_status` (`job <id>`) | Status, step and the end of the log for clone, setup, pull, deploy and long commands |
212
214
 
@@ -216,6 +218,16 @@ Repositories this device runs, kept in `APPS_DIR` (default `~/apps`). Unlike pro
216
218
  - 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.
217
219
  - A job whose runner died, for example in a reboot, still shows as running with a dead pid. `job_cancel` clears it.
218
220
 
221
+ **Recovering a workspace:**
222
+ - `workspace_status` shows what is uncommitted and how far the branch is ahead.
223
+ - A folder removed by hand: run `git worktree prune` in the app, then `workspace_create` again, which reuses the kept branch.
224
+ - A stale `state/locks/git-<app>.lock` from a dead process is cleared automatically.
225
+
226
+ **Recovering a preview:**
227
+ - `harness-device preview` lists previews after reconciling them; `harness-device preview stop <id>` ends one.
228
+ - Records are in `state/previews/`, and the proxy logs are under the target `proc-preview-<id>`.
229
+ - Rotating `state/preview.key` (delete it) invalidates every outstanding link.
230
+
219
231
  ### Join a pool (HarnessPro)
220
232
 
221
233
  `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.4.0",
3
+ "version": "0.6.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",
@@ -112,6 +112,8 @@ Apps are repositories this device runs, in \`${cfg.APPS_DIR || '~/apps'}\`; unli
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
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
+ - Previews: \`preview_start {"app":"web--harness-5"}\` starts the dev server if needed, health-checks it and returns an expiring link through an authenticating proxy (127.0.0.1; give the user the url and the ssh_tunnel command). Only with \`public: true\` (asks the user) does it get a public ngrok URL. \`preview_screenshot\` is evidence; \`preview_stop\` revokes the link.
115
117
  - \`shell_exec\` runs one shell command in an app folder; through the pool it needs device:admin.
116
118
  - 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.
117
119
 
package/src/cli.js CHANGED
@@ -276,6 +276,7 @@ export async function main(argv) {
276
276
  const ctx = loadContext(env);
277
277
  if (f.enforce) {
278
278
  const r = await limits.enforce(ctx);
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}`); }
279
280
  if (f.json) return console.log(JSON.stringify(r, null, 2));
280
281
  for (const a of r.actions) log.warn(`stopped ${a.name}: ${a.reason}`);
281
282
  if (!f.quiet && !r.actions.length) log.ok('all within limits');
@@ -337,6 +338,19 @@ export async function main(argv) {
337
338
  throw new Error('usage: harness-device app list|clone|pull|setup|start|stop|deploy|exec');
338
339
  }
339
340
 
341
+ case 'preview': {
342
+ const ctx = loadContext(env);
343
+ const preview = await import('./preview.js');
344
+ if (sub === 'proxy') {
345
+ await preview.serveProxy(ctx, rest[0]);
346
+ log.ok(`preview proxy ${rest[0]} listening`);
347
+ return new Promise(() => {}); // runs until its process is stopped
348
+ }
349
+ if (sub === 'stop') return console.log(JSON.stringify(await preview.stopPreview(ctx, { id: rest[0] }), null, 2));
350
+ await preview.reconcile(ctx);
351
+ return console.log(JSON.stringify(preview.listPreviews(ctx), null, 2));
352
+ }
353
+
340
354
  case 'job':
341
355
  case 'jobs': {
342
356
  const ctx = loadContext(env);
package/src/config.js CHANGED
@@ -103,6 +103,9 @@ export function defaults(env = process.env) {
103
103
  // Programs the exec tool may run (comma list; empty = the default list in
104
104
  // src/exec.js). Shells and wrappers are refused whatever this says.
105
105
  EXEC_ALLOW: '',
106
+ // Repositories git_clone and workspaces may use: comma list of owner/repo
107
+ // or owner/* (empty = any).
108
+ REPO_ALLOW: '',
106
109
  };
107
110
  }
108
111
 
@@ -216,6 +219,7 @@ export function validateConfig(cfg, env = process.env) {
216
219
  if (!/^\d+$/.test(String(cfg.RES_WAIT_SECONDS)) || Number(cfg.RES_WAIT_SECONDS) > 3600) errs.push('RES_WAIT_SECONDS must be 0-3600.');
217
220
  errs.push(...limitsMod.validate(cfg));
218
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/*.');
219
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.');
220
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.');
221
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/mcp/server.js CHANGED
@@ -19,6 +19,8 @@ import * as limits from '../limits.js';
19
19
  import * as project from '../project.js';
20
20
  import * as jobs from '../jobs.js';
21
21
  import * as execMod from '../exec.js';
22
+ import * as ws from '../workspace.js';
23
+ import * as preview from '../preview.js';
22
24
  import { Cancelled, NeedsUser, interaction } from './interact.js';
23
25
 
24
26
  const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
@@ -187,6 +189,68 @@ export function buildServer(env = process.env, opts = {}) {
187
189
  return { ...(done && job.status !== 'done' ? { isError: true } : {}), content: [{ type: 'text', text: JSON.stringify(body, null, 2) }] };
188
190
  });
189
191
 
192
+ 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).',
193
+ { 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>'),
194
+ setup: z.boolean().optional(), database: z.boolean().optional(), ...FORCE },
195
+ async (c, a) => {
196
+ await guard(c, a, `creating a workspace for ${a.ticket}`);
197
+ const r = await ws.createWorkspace(c, { app: a.app, ticket: a.ticket, base: a.base, database: !!a.database });
198
+ const w = r.workspace;
199
+ const su = r.created && a.setup !== false ? await project.setup(c, { app: w.name }) : null;
200
+ 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,
201
+ ...(su?.job ? { setup_job: su.job.id, note: `dependencies install in the background: job_status {"id":"${su.job.id}"}` } : su ? { setup: su.note } : {}) });
202
+ });
203
+
204
+ tool('workspace_list', 'Per-ticket workspaces on this device (all, or of one app): ticket, branch, pinned base, folder, port.',
205
+ { app: APP.optional() },
206
+ async (c, a) => text(ws.listWorkspaces(c, a.app || null)));
207
+
208
+ tool('workspace_status', 'A workspace\'s git state: uncommitted files, commits ahead of / behind its pinned base, HEAD, port and whether its process runs.',
209
+ { workspace: APP },
210
+ async (c, a) => text(ws.workspaceStatus(c, a.workspace)));
211
+
212
+ 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).',
213
+ { workspace: APP, discard_changes: z.boolean().optional(), ...CONFIRM },
214
+ async (c, a, u) => {
215
+ const st = ws.workspaceStatus(c, a.workspace);
216
+ 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.` }] };
217
+ 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.` : ''}`);
218
+ return text(await ws.archiveWorkspace(c, { name: a.workspace, force: !!a.discard_changes }));
219
+ });
220
+
221
+ tool('preview_start', 'Preview an app or workspace (e.g. web--harness-5): starts its dev server on its own port if nothing answers there (command, else its start command), health-checks it (failures return the app\'s last output), and returns an expiring link through an authenticating proxy on this device (127.0.0.1 only: reach it with the ssh_tunnel command). public=true also opens a public ngrok URL, still behind the link\'s token; it asks the user first. Stop with preview_stop.',
222
+ { app: APP, command: z.string().max(500).optional(), ttl_minutes: z.number().int().min(1).max(10080).optional(), health_seconds: z.number().int().min(1).max(300).optional(),
223
+ health_path: z.string().regex(/^\/[^\s]{0,200}$/).optional(), public: z.boolean().optional(), ...CONFIRM, ...FORCE },
224
+ async (c, a, u) => {
225
+ await guard(c, a, `previewing ${a.app}`);
226
+ if (a.public) await u.confirm(`Open a public internet URL (ngrok) for the preview of ${a.app}? Anyone with the link can open it until it expires or is stopped.`);
227
+ await preview.reconcile(c);
228
+ try {
229
+ return text(await preview.startPreview(c, { app: a.app, command: a.command, ttlMinutes: a.ttl_minutes, healthSeconds: a.health_seconds, healthPath: a.health_path, public: !!a.public }));
230
+ } catch (e) {
231
+ if (e.logs !== undefined) return { isError: true, content: [{ type: 'text', text: e.message }] };
232
+ throw e;
233
+ }
234
+ });
235
+
236
+ tool('preview_list', 'Previews on this device: app, ports, expiry, public or not, status (stopped ones show why). Ends previews that expired or whose app went away. With id: a fresh link for an active preview.',
237
+ { id: z.string().regex(/^pv-[0-9a-f]{8}$/).optional() },
238
+ async (c, a) => {
239
+ await preview.reconcile(c);
240
+ if (a.id) { const p = preview.getPreview(c, a.id); if (!p) throw new Error(`No preview ${a.id}`); return text(p.status === 'active' ? preview.link(c, p) : p); }
241
+ return text(preview.listPreviews(c).slice(0, 30));
242
+ });
243
+
244
+ tool('preview_stop', 'Stop a preview: its link stops working at once, its proxy and public URL (if any) close, and the app stops too if the preview started it (keep_app=true leaves it running).',
245
+ { id: z.string().regex(/^pv-[0-9a-f]{8}$/), keep_app: z.boolean().optional() },
246
+ async (c, a) => text(await preview.stopPreview(c, { id: a.id, stopApp: !a.keep_app })));
247
+
248
+ if (has(base, 'browser')) {
249
+ tool('preview_screenshot', 'Evidence: open an active preview in the device browser and return a PNG of the page.',
250
+ { id: z.string().regex(/^pv-[0-9a-f]{8}$/), width: z.number().int().min(320).max(2560).optional(), height: z.number().int().min(240).max(2560).optional() },
251
+ async (c, a) => ({ content: [{ type: 'image', data: await preview.screenshot(c, a.id, { width: a.width, height: a.height }), mimeType: 'image/png' }] }));
252
+ }
253
+
190
254
  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.',
191
255
  { id: z.string().regex(/^[a-z0-9-]{6,40}$/) },
192
256
  async (c, a) => text(jobs.cancelJob(c, a.id)));
package/src/preview.js ADDED
@@ -0,0 +1,351 @@
1
+ // Protected application previews (HARNESS-9).
2
+ //
3
+ // preview_start runs an app (or workspace) on its own port, health-checks it,
4
+ // and puts a small authenticating proxy in front of it on another port:
5
+ //
6
+ // - The proxy only listens on 127.0.0.1 and only forwards to that one app
7
+ // port on 127.0.0.1. Reaching it from elsewhere means the SSH tunnel, or a
8
+ // public ngrok URL, which is opt-in (the user approves it).
9
+ // - Every request needs a token bound to this preview and an expiry, signed
10
+ // with a device key (state/preview.key). The link carries it once
11
+ // (?hd_preview=…); the proxy then sets an HttpOnly cookie and redirects to
12
+ // the clean URL. The preview record is re-read on each request, so a
13
+ // stopped preview is refused at once, even with an unexpired token.
14
+ // - preview_stop revokes it, stops the proxy, closes its tunnel and, if the
15
+ // preview started the app, the app. reconcile() (each watchdog pass and
16
+ // every preview_list) ends previews that expired or whose app went away.
17
+ // - preview_screenshot loads the preview in the device browser (CDP) and
18
+ // returns a PNG, as evidence.
19
+
20
+ import crypto from 'node:crypto';
21
+ import fs from 'node:fs';
22
+ import http from 'node:http';
23
+ import net from 'node:net';
24
+ import path from 'node:path';
25
+ import { spawn } from 'node:child_process';
26
+ import { getApp, saveApp, procName } from './apps.js';
27
+ import { allocatePort, releasePort } from './workspace.js';
28
+ import * as project from './project.js';
29
+ import * as state from './state.js';
30
+ import { PKG_ROOT } from './util.js';
31
+
32
+ const ID = /^pv-[0-9a-f]{8}$/;
33
+ const COOKIE = (id) => `hd_preview_${id.slice(3)}`;
34
+ const PARAM = 'hd_preview';
35
+ const dir = (ctx) => path.join(ctx.paths.state, 'previews');
36
+ const recFile = (ctx, id) => path.join(dir(ctx), `${id}.json`);
37
+ const q = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
38
+ const inline = (ctx) => ctx.env.HD_PREVIEW_INLINE === '1';
39
+ const servers = new Map(); // inline mode: id -> proxy server
40
+
41
+ function deviceKey(ctx) {
42
+ const f = path.join(ctx.paths.state, 'preview.key');
43
+ if (!fs.existsSync(f)) {
44
+ fs.mkdirSync(path.dirname(f), { recursive: true });
45
+ try { fs.writeFileSync(f, crypto.randomBytes(32).toString('hex'), { mode: 0o600, flag: 'wx' }); } catch (e) { if (e.code !== 'EEXIST') throw e; }
46
+ }
47
+ return Buffer.from(fs.readFileSync(f, 'utf8').trim(), 'hex');
48
+ }
49
+
50
+ const sign = (ctx, body) => crypto.createHmac('sha256', deviceKey(ctx)).update(body).digest('base64url');
51
+ export const makeToken = (ctx, id, exp) => `${id}.${exp}.${sign(ctx, `${id}.${exp}`)}`;
52
+
53
+ /** { ok, reason } for a token presented to preview `id`. */
54
+ export function checkToken(ctx, id, token, now = Date.now()) {
55
+ const [tid, exp, sig] = String(token || '').split('.');
56
+ if (!tid || !exp || !sig) return { ok: false, reason: 'no preview token' };
57
+ const want = Buffer.from(sign(ctx, `${tid}.${exp}`));
58
+ const got = Buffer.from(sig);
59
+ if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return { ok: false, reason: 'invalid preview token' };
60
+ if (tid !== id) return { ok: false, reason: 'this token is for another preview' };
61
+ if (Number(exp) <= now) return { ok: false, reason: 'preview link expired' };
62
+ const rec = getPreview(ctx, id);
63
+ if (!rec || rec.status !== 'active') return { ok: false, reason: 'preview stopped' };
64
+ if (Date.parse(rec.expiresAt) <= now) return { ok: false, reason: 'preview link expired' };
65
+ return { ok: true, rec };
66
+ }
67
+
68
+ export function getPreview(ctx, id) {
69
+ if (!ID.test(String(id || ''))) return null;
70
+ try { return JSON.parse(fs.readFileSync(recFile(ctx, id), 'utf8')); } catch { return null; }
71
+ }
72
+ function savePreview(ctx, rec) {
73
+ fs.mkdirSync(dir(ctx), { recursive: true });
74
+ const tmp = `${recFile(ctx, rec.id)}.${process.pid}.tmp`;
75
+ fs.writeFileSync(tmp, JSON.stringify(rec, null, 2), { mode: 0o600 });
76
+ fs.renameSync(tmp, recFile(ctx, rec.id));
77
+ return rec;
78
+ }
79
+ export function listPreviews(ctx) {
80
+ if (!fs.existsSync(dir(ctx))) return [];
81
+ return fs.readdirSync(dir(ctx)).filter((f) => f.endsWith('.json')).map((f) => getPreview(ctx, f.slice(0, -5))).filter(Boolean)
82
+ .sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));
83
+ }
84
+
85
+ /** Any HTTP answer below 500 on 127.0.0.1:port within `seconds`. */
86
+ export async function waitHealthy(port, seconds = 60, pathName = '/') {
87
+ const deadline = Date.now() + seconds * 1000;
88
+ for (;;) {
89
+ const code = await new Promise((resolve) => {
90
+ const r = http.get({ host: '127.0.0.1', port, path: pathName, timeout: 2000 }, (res) => { res.resume(); resolve(res.statusCode); });
91
+ r.on('error', () => resolve(0)); r.on('timeout', () => { r.destroy(); resolve(0); });
92
+ });
93
+ if (code && code < 500) return code;
94
+ if (Date.now() >= deadline) return 0;
95
+ await new Promise((r) => setTimeout(r, 500));
96
+ }
97
+ }
98
+
99
+ const procLog = (ctx, name) => path.join(ctx.paths.logs, `proc-${name}.log`);
100
+ function tailOf(file, lines = 40) {
101
+ if (!fs.existsSync(file)) return '(no output yet)';
102
+ return fs.readFileSync(file, 'utf8').split('\n').slice(-lines).join('\n').trim() || '(no output)';
103
+ }
104
+
105
+ /** Register a process; inline (tests) it is spawned here with the same log file the tmux window would use. */
106
+ function runProc(ctx, name, cwd, command) {
107
+ if (!inline(ctx)) return state.addProc(ctx, name, cwd, command);
108
+ fs.mkdirSync(ctx.paths.logs, { recursive: true });
109
+ const fd = fs.openSync(procLog(ctx, name), 'a');
110
+ const child = spawn('sh', ['-c', command], { cwd, env: ctx.env, detached: true, stdio: ['ignore', fd, fd] });
111
+ child.unref();
112
+ fs.closeSync(fd);
113
+ fs.mkdirSync(path.join(ctx.paths.state, 'inline-procs'), { recursive: true });
114
+ fs.writeFileSync(path.join(ctx.paths.state, 'inline-procs', name), String(child.pid));
115
+ }
116
+ function stopProc(ctx, name) {
117
+ if (!inline(ctx)) { try { state.removeProc(ctx, name); } catch { /* already gone */ } return; }
118
+ const f = path.join(ctx.paths.state, 'inline-procs', name);
119
+ if (!fs.existsSync(f)) return;
120
+ try { process.kill(-Number(fs.readFileSync(f, 'utf8')), 'SIGTERM'); } catch { /* gone */ }
121
+ fs.rmSync(f, { force: true });
122
+ }
123
+ const procKnown = (ctx, name) => (inline(ctx) ? fs.existsSync(path.join(ctx.paths.state, 'inline-procs', name)) : state.listProcs(ctx).some((p) => p.name === name));
124
+
125
+ export async function startPreview(ctx, { app: name, ttlMinutes = 60, healthSeconds = 60, command, healthPath = '/', public: pub = false, publish = null }) {
126
+ let app = getApp(ctx, name);
127
+ const ttl = Math.max(1, Math.min(Number(ttlMinutes) || 60, 7 * 24 * 60));
128
+ const port = app.port || await allocatePort(ctx, app.name);
129
+ if (!app.project && app.port !== port) app = saveApp(ctx, { ...app, port });
130
+
131
+ // Start the app unless something already answers on its port.
132
+ let startedApp = false;
133
+ if (!(await waitHealthy(port, 0, healthPath))) {
134
+ const cmd = command || app.startOverride || app.start;
135
+ if (!cmd) throw new Error(`No start command known for ${app.name}: give command (e.g. "npm run dev")`);
136
+ if (inline(ctx)) runProc(ctx, procName(app), app.dir, project.startLine(cmd, port));
137
+ else project.start(ctx, { app: app.name, command, port });
138
+ startedApp = true;
139
+ if (!(await waitHealthy(port, healthSeconds, healthPath))) {
140
+ const logs = tailOf(procLog(ctx, procName(app)));
141
+ stopProc(ctx, procName(app));
142
+ state.event(ctx, `preview of ${app.name}: health check failed on port ${port}; app stopped`);
143
+ const err = new Error(`${app.name} did not answer on http://127.0.0.1:${port}${healthPath} within ${healthSeconds}s, so it was stopped. Last output:\n${logs}`);
144
+ err.logs = logs;
145
+ throw err;
146
+ }
147
+ }
148
+
149
+ const id = `pv-${crypto.randomBytes(4).toString('hex')}`;
150
+ const proxyPort = await allocatePort(ctx, `preview-${id}`);
151
+ const expiresAt = new Date(Date.now() + ttl * 60000).toISOString();
152
+ const rec = savePreview(ctx, {
153
+ id, app: app.name, ticket: app.workspace?.ticket || null, appPort: port, proxyPort, startedApp,
154
+ status: 'active', public: false, publicUrl: null, createdAt: new Date().toISOString(), expiresAt,
155
+ });
156
+ if (inline(ctx)) servers.set(id, await serveProxy(ctx, id));
157
+ else {
158
+ state.addProc(ctx, `preview-${id}`, app.dir, `HARNESS_DEVICE_HOME=${q(ctx.paths.home)} exec ${q(process.execPath)} ${q(path.join(PKG_ROOT, 'bin', 'harness-device.js'))} preview proxy ${id}`);
159
+ if (!(await waitPort(proxyPort, 15))) { await stopPreview(ctx, { id, reason: 'proxy did not start', stopApp: startedApp }); throw new Error(`The preview proxy did not start (logs: proc-preview-${id})`); }
160
+ }
161
+ if (pub) {
162
+ const r = await (publish || defaultPublish)(ctx, proxyPort);
163
+ savePreview(ctx, { ...getPreview(ctx, id), public: true, publicUrl: r.url || null });
164
+ }
165
+ state.event(ctx, `preview ${id} of ${app.name}: app port ${port}, proxy ${proxyPort}, expires ${expiresAt}${pub ? ', public URL opened' : ''}`);
166
+ return link(ctx, getPreview(ctx, id));
167
+ }
168
+
169
+ /** The links for a preview (a fresh token valid until the preview expires). */
170
+ export function link(ctx, rec) {
171
+ const token = makeToken(ctx, rec.id, Date.parse(rec.expiresAt));
172
+ return {
173
+ id: rec.id, app: rec.app, ticket: rec.ticket, app_port: rec.appPort, proxy_port: rec.proxyPort, expires_at: rec.expiresAt,
174
+ url: `http://127.0.0.1:${rec.proxyPort}/?${PARAM}=${token}`,
175
+ ssh_tunnel: `ssh -N -L ${rec.proxyPort}:127.0.0.1:${rec.proxyPort} <user>@<this-machine> (then open the url on your computer)`,
176
+ ...(rec.publicUrl ? { public_url: `${rec.publicUrl}/?${PARAM}=${token}` } : {}),
177
+ };
178
+ }
179
+
180
+ async function defaultPublish(ctx, port) {
181
+ const device = await import('./device.js');
182
+ const r = await device.ngrokUp(ctx, { ports: [port] });
183
+ const t = r.tunnels.find((x) => String(x.addr || '').endsWith(`:${port}`) || x.name === `app${port}`);
184
+ return { url: t ? t.url : null };
185
+ }
186
+
187
+ async function defaultUnpublish(ctx, stillPublic) {
188
+ const device = await import('./device.js');
189
+ if (stillPublic.length) await device.ngrokUp(ctx, { tunnels: stillPublic.map((p) => `app${p.proxyPort}`) });
190
+ else ctx.platform.ngrokDown(ctx);
191
+ }
192
+
193
+ export async function stopPreview(ctx, { id, reason = 'stopped', stopApp = true, unpublish = null }) {
194
+ const rec = getPreview(ctx, id);
195
+ if (!rec) throw new Error(`No preview ${id}`);
196
+ const closeInline = async () => {
197
+ const srv = servers.get(id);
198
+ if (!srv) return;
199
+ servers.delete(id);
200
+ await new Promise((r) => { srv.close(r); srv.closeAllConnections(); });
201
+ };
202
+ if (rec.status !== 'active') { await closeInline(); return { id, status: rec.status, note: 'already stopped' }; }
203
+ savePreview(ctx, { ...rec, status: 'stopped', stoppedAt: new Date().toISOString(), stopReason: reason });
204
+ await closeInline();
205
+ stopProc(ctx, `preview-${id}`);
206
+ releasePort(ctx, `preview-${id}`);
207
+ let tunnel = 'none';
208
+ if (rec.public) {
209
+ const still = listPreviews(ctx).filter((p) => p.status === 'active' && p.public);
210
+ await (unpublish || defaultUnpublish)(ctx, still);
211
+ tunnel = still.length ? 'closed (other public previews kept)' : 'closed';
212
+ }
213
+ let app = 'left running';
214
+ const others = listPreviews(ctx).some((p) => p.status === 'active' && p.app === rec.app);
215
+ if (stopApp && rec.startedApp && !others) {
216
+ try { const a = getApp(ctx, rec.app); stopProc(ctx, procName(a)); app = 'stopped'; } catch { app = 'gone'; }
217
+ }
218
+ state.event(ctx, `preview ${id} of ${rec.app} ${reason}: link revoked, tunnel ${tunnel}, app ${app}`);
219
+ return { id, status: 'stopped', reason, tunnel, app };
220
+ }
221
+
222
+ /** End previews that expired or whose app or proxy went away. */
223
+ export async function reconcile(ctx, opts = {}) {
224
+ const changed = [];
225
+ for (const p of listPreviews(ctx).filter((x) => x.status === 'active')) {
226
+ let reason = null;
227
+ if (Date.parse(p.expiresAt) <= Date.now()) reason = 'expired';
228
+ else if (!procKnown(ctx, `preview-${p.id}`) && !servers.has(p.id)) reason = 'proxy gone';
229
+ else {
230
+ let appProc = false;
231
+ try { appProc = procKnown(ctx, procName(getApp(ctx, p.app))); } catch { /* app removed */ }
232
+ if (!appProc && !(await waitHealthy(p.appPort, 0))) reason = 'app gone';
233
+ }
234
+ if (reason) changed.push(await stopPreview(ctx, { id: p.id, reason, ...opts }));
235
+ }
236
+ return changed;
237
+ }
238
+
239
+ async function waitPort(port, seconds) {
240
+ const deadline = Date.now() + seconds * 1000;
241
+ while (Date.now() < deadline) {
242
+ const up = await new Promise((r) => { const s = net.connect(port, '127.0.0.1', () => { s.end(); r(true); }); s.on('error', () => r(false)); });
243
+ if (up) return true;
244
+ await new Promise((r) => setTimeout(r, 250));
245
+ }
246
+ return false;
247
+ }
248
+
249
+ function cookieOf(req, name) {
250
+ for (const part of String(req.headers.cookie || '').split(';')) {
251
+ const [k, ...v] = part.trim().split('=');
252
+ if (k === name) return v.join('=');
253
+ }
254
+ return '';
255
+ }
256
+ function stripCookie(header, name) {
257
+ const kept = String(header || '').split(';').map((s) => s.trim()).filter((s) => s && !s.startsWith(`${name}=`));
258
+ return kept.length ? kept.join('; ') : undefined;
259
+ }
260
+
261
+ /** The proxy for one preview: 127.0.0.1:proxyPort → 127.0.0.1:appPort, token required. */
262
+ export function serveProxy(ctx, id) {
263
+ const rec = getPreview(ctx, id);
264
+ if (!rec) throw new Error(`No preview ${id}`);
265
+ const name = COOKIE(id);
266
+ const auth = (req) => {
267
+ const u = new URL(req.url, 'http://x');
268
+ const fromQuery = u.searchParams.get(PARAM);
269
+ const c = checkToken(ctx, id, fromQuery || cookieOf(req, name));
270
+ return { ...c, fromQuery, u };
271
+ };
272
+ const server = http.createServer((req, res) => {
273
+ const a = auth(req);
274
+ if (!a.ok) { res.writeHead(401, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' }); return res.end(`Preview access denied: ${a.reason}.\n`); }
275
+ if (a.fromQuery) {
276
+ a.u.searchParams.delete(PARAM);
277
+ const maxAge = Math.max(1, Math.floor((Date.parse(a.rec.expiresAt) - Date.now()) / 1000));
278
+ res.writeHead(302, { location: `${a.u.pathname}${a.u.search}`, 'set-cookie': `${name}=${a.fromQuery}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${maxAge}`, 'cache-control': 'no-store' });
279
+ return res.end();
280
+ }
281
+ const headers = { ...req.headers, host: `127.0.0.1:${a.rec.appPort}` };
282
+ const ck = stripCookie(req.headers.cookie, name);
283
+ if (ck) headers.cookie = ck; else delete headers.cookie;
284
+ const up = http.request({ host: '127.0.0.1', port: a.rec.appPort, method: req.method, path: req.url, headers }, (r) => {
285
+ res.writeHead(r.statusCode, r.headers);
286
+ r.pipe(res);
287
+ });
288
+ up.on('error', (e) => { if (!res.headersSent) res.writeHead(502, { 'content-type': 'text/plain' }); res.end(`The app is not answering: ${e.code || e.message}\n`); });
289
+ req.pipe(up);
290
+ });
291
+ // WebSockets (dev-server reload): same check, then a raw pipe to the app.
292
+ server.on('upgrade', (req, socket, head) => {
293
+ const a = auth(req);
294
+ if (!a.ok || a.fromQuery) { socket.end('HTTP/1.1 401 Unauthorized\r\n\r\n'); return; }
295
+ const upstream = net.connect(a.rec.appPort, '127.0.0.1', () => {
296
+ const ck = stripCookie(req.headers.cookie, name);
297
+ const lines = [`${req.method} ${req.url} HTTP/1.1`];
298
+ for (const [k, v] of Object.entries({ ...req.headers, host: `127.0.0.1:${a.rec.appPort}` })) {
299
+ if (k === 'cookie') { if (ck) lines.push(`cookie: ${ck}`); continue; }
300
+ for (const one of [].concat(v)) lines.push(`${k}: ${one}`);
301
+ }
302
+ upstream.write(`${lines.join('\r\n')}\r\n\r\n`);
303
+ if (head && head.length) upstream.write(head);
304
+ upstream.pipe(socket); socket.pipe(upstream);
305
+ });
306
+ upstream.on('error', () => socket.destroy());
307
+ socket.on('error', () => upstream.destroy());
308
+ });
309
+ return new Promise((resolve, reject) => {
310
+ server.once('error', reject);
311
+ server.listen(rec.proxyPort, '127.0.0.1', () => resolve(server));
312
+ });
313
+ }
314
+
315
+ /** Load the preview in the device browser over CDP and return a PNG (base64). */
316
+ export async function screenshot(ctx, id, { width = 1280, height = 800, waitMs = 1500 } = {}) {
317
+ const rec = getPreview(ctx, id);
318
+ if (!rec || rec.status !== 'active') throw new Error(`No active preview ${id}`);
319
+ const { default: WebSocket } = await import('ws');
320
+ const base = `http://127.0.0.1:${ctx.cfg.CDP_PORT}`;
321
+ const target = await fetch(`${base}/json/new?about:blank`, { method: 'PUT' }).then((r) => r.json()).catch(() => null);
322
+ if (!target?.webSocketDebuggerUrl) throw new Error(`The device browser is not reachable on ${base} (browser capability off, or browser_restart it)`);
323
+ const ws = new WebSocket(target.webSocketDebuggerUrl);
324
+ let n = 0;
325
+ const pending = new Map();
326
+ const events = [];
327
+ ws.on('message', (m) => {
328
+ const msg = JSON.parse(m);
329
+ if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); } else if (msg.method) events.push(msg.method);
330
+ });
331
+ const send = (method, params = {}) => new Promise((resolve, reject) => {
332
+ const i = ++n;
333
+ pending.set(i, (msg) => (msg.error ? reject(new Error(`${method}: ${msg.error.message}`)) : resolve(msg.result)));
334
+ ws.send(JSON.stringify({ id: i, method, params }));
335
+ });
336
+ try {
337
+ await new Promise((r, j) => { ws.once('open', r); ws.once('error', j); });
338
+ await send('Page.enable');
339
+ await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });
340
+ await send('Page.navigate', { url: link(ctx, rec).url });
341
+ const until = Date.now() + 15000;
342
+ while (!events.includes('Page.loadEventFired') && Date.now() < until) await new Promise((r) => setTimeout(r, 100));
343
+ await new Promise((r) => setTimeout(r, waitMs));
344
+ const shot = await send('Page.captureScreenshot', { format: 'png' });
345
+ state.event(ctx, `preview ${id}: screenshot taken`);
346
+ return shot.data;
347
+ } finally {
348
+ ws.close();
349
+ await fetch(`${base}/json/close/${target.id}`).catch(() => {});
350
+ }
351
+ }
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,10 +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', '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'],
18
+ 'exec', '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
 
@@ -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
+ }