@dreamtree-org/harness-device 0.4.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
@@ -207,6 +207,7 @@ 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 |
210
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` |
211
212
  | `job_status` (`job <id>`) | Status, step and the end of the log for clone, setup, pull, deploy and long commands |
212
213
 
@@ -216,6 +217,11 @@ Repositories this device runs, kept in `APPS_DIR` (default `~/apps`). Unlike pro
216
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.
217
218
  - A job whose runner died, for example in a reboot, still shows as running with a dead pid. `job_cancel` clears it.
218
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
+
219
225
  ### Join a pool (HarnessPro)
220
226
 
221
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.4.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",
@@ -112,6 +112,7 @@ 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.
115
116
  - \`shell_exec\` runs one shell command in an app folder; through the pool it needs device:admin.
116
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.
117
118
 
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,7 @@ 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';
22
23
  import { Cancelled, NeedsUser, interaction } from './interact.js';
23
24
 
24
25
  const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
@@ -187,6 +188,35 @@ export function buildServer(env = process.env, opts = {}) {
187
188
  return { ...(done && job.status !== 'done' ? { isError: true } : {}), content: [{ type: 'text', text: JSON.stringify(body, null, 2) }] };
188
189
  });
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
+
190
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.',
191
221
  { id: z.string().regex(/^[a-z0-9-]{6,40}$/) },
192
222
  async (c, a) => text(jobs.cancelJob(c, a.id)));
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'],
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'],
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
+ }