@dreamtree-org/harness-device 0.9.0 → 0.9.2

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,10 +207,15 @@ 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
+ | `app_remove` | Removes a managed app (asks first; CLI `harness-device app rm <app> [--force]`): stops its process and previews, archives its workspaces, deletes its folder and forgets its record, port and code graph. It refuses while the app holds work found nowhere else (uncommitted or untracked files, commits on no remote, workspaces) unless `discard_changes` is set after the user agrees. Session projects and folders outside `APPS_DIR` are never deleted |
210
211
  | `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
212
  | `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; `save: true` also keeps it in the app's `.dreamtree/evidence/captures/` for ai-builder's `evidence add screenshot` |
212
213
  | `shell_exec` (`app exec <app> -- <cmd>`) | One command in the app folder: up to 120s inline, otherwise as a job. Through the pool it needs `device:admin` |
213
214
  | `job_submit` | A durable job under an `effect_key`: steps, each an argv as in `exec` (same allowlist). The same key always returns the same job and never runs it twice; the same key with another payload is refused (`EFFECT_KEY_CONFLICT`). Finished steps are checkpointed. `retries` (up to 5, exponential backoff from `retry_backoff_seconds`) resume at the failed step. `artifacts` are recorded with size and sha256 |
215
+ | `graph_index` | Builds or updates the app's Graphify code graph (needs the `graphify` capability), as a job. It indexes the git view only: tracked files plus untracked files that aren't ignored. Secrets and key material (`.env*`, `*.pem`, `*.key`, `id_*`, credentials, files named secret), ignored paths and anything outside the repository are never indexed. Pinned to the HEAD it saw; later runs copy only the changed files and use `graphify --update` |
216
+ | `graph_status` | The indexed revision against HEAD, and the files changed, added or removed since (stale when there are any). Also the last indexing error, with what to do about it |
217
+ | `graph_query` | Asks the graph. `mode: context` returns a token-budgeted pack of the relevant code; `mode: query` returns matching symbols and their links. Each answer has its source references (repository file and line) and says when the index is stale |
218
+ | `graph_summary` | Graphify's architecture report (`GRAPH_REPORT.md`) with the revision it describes |
214
219
  | `job_status` (`job <id>`) | Status, step and the end of the log for clone, setup, pull, deploy and long commands |
215
220
 
216
221
  **Recovering a job** (`exec`, clone, setup, deploy):
@@ -230,6 +235,12 @@ Repositories this device runs, kept in `APPS_DIR` (default `~/apps`). Unlike pro
230
235
  - **Failures** are reported as not retryable: retries happen on the device, within the job's budget.
231
236
  - **Routing:** the claim API has no per-device queue yet, so give each device its own worker pool.
232
237
 
238
+ **Recovering a code graph:**
239
+ - The index is in `state/graphs/<app>/`: `index.json` (revision, file hashes, last error) and `tree/` (the mirrored files and `graphify-out/`).
240
+ - A failed `graph_index` keeps the previous index, so queries still answer, marked stale. The error and its fix show in `graph_status`.
241
+ - `graph_index {full: true}` rebuilds from scratch. Deleting `state/graphs/<app>` is always safe.
242
+ - Archiving a workspace removes its graph.
243
+
233
244
  **Recovering a workspace:**
234
245
  - `workspace_status` shows what is uncommitted and how far the branch is ahead.
235
246
  - A folder removed by hand: run `git worktree prune` in the app, then `workspace_create` again, which reuses the kept branch.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dreamtree-org/harness-device",
3
- "version": "0.9.0",
3
+ "version": "0.9.2",
4
4
  "description": "Turn a Linux server into a reboot-proof Claude Code harness: Remote Control per project in tmux, a persistent Chromium + Playwright MCP on a virtual display, live viewers (noVNC, ttyd, Playwright UI), self-healing systemd services, plus Docker, Dokploy, ngrok and AI-provider tooling.",
5
5
  "author": {
6
6
  "name": "Partha Preetham Krishna",
package/src/cli.js CHANGED
@@ -57,7 +57,7 @@ ${color.bold('Device')}
57
57
  join <hub-url> --enroll <secret> join a HarnessPro pool (the dashboard's install command runs this)
58
58
  leave leave the pool and forget its credential
59
59
  pool [status] pool hub, link state, POOL_SCOPES; \`pool link\` is the service
60
- app list | clone <url> [--name N] [--branch B] | pull|setup|start|stop|deploy <app> | exec <app> -- <cmd>
60
+ app list | clone <url> [--name N] [--branch B] | pull|setup|start|stop|deploy <app> | exec <app> -- <cmd> | rm <app> [--force]
61
61
  managed apps in APPS_DIR (~/apps): clone, install, run, update (jobs run in the background)
62
62
  job list | job <id> | job run <id> background jobs (clone, setup, deploy) and their logs
63
63
  limits [--enforce] [--json] safe maximums (RAM reserve, per process, browser, sessions) and current use; --enforce runs one watchdog pass
@@ -335,8 +335,9 @@ export async function main(argv) {
335
335
  if (['pull', 'setup', 'deploy'].includes(sub)) return out(await pr[sub](ctx, { app: rest[0] }));
336
336
  if (sub === 'start') return out(pr.start(ctx, { app: rest[0], command: f.command, port: f.port, restart: !!f.restart }));
337
337
  if (sub === 'stop') return out(pr.stop(ctx, { app: rest[0] }));
338
+ if (sub === 'rm' || sub === 'remove') return out(await (await import('./remove.js')).removeApp(ctx, { name: rest[0], force: !!f.force }));
338
339
  if (sub === 'exec') return out(await pr.shellExec(ctx, { app: rest[0], command: rest.slice(1).join(' '), timeoutSeconds: f.timeout }));
339
- throw new Error('usage: harness-device app list|clone|pull|setup|start|stop|deploy|exec');
340
+ throw new Error('usage: harness-device app list|clone|pull|setup|start|stop|deploy|exec|rm <app> [--force]');
340
341
  }
341
342
 
342
343
  case 'preview': {
package/src/graph.js ADDED
@@ -0,0 +1,226 @@
1
+ // Graphify project intelligence (HARNESS-8): a code graph per app or
2
+ // workspace, built by Graphify (@dreamtree-org/graphify, the "graphify"
3
+ // capability), not by a second engine here.
4
+ //
5
+ // What gets indexed: the app's git view of itself, never the folder as it
6
+ // lies. The files are `git ls-files -co --exclude-standard` (tracked, plus
7
+ // untracked files that are not ignored), minus secrets and key material
8
+ // (DENY below; Graphify skips these too) and files over 1 MB. They are mirrored
9
+ // into state/graphs/<app>/tree, and Graphify runs there, so:
10
+ // - ignored files, other projects and the harness home are never read;
11
+ // - every source reference in a result is a path inside the app's repository;
12
+ // - the next index copies only what changed and runs `graphify --update`,
13
+ // which reuses its cache for unchanged files (incremental).
14
+ //
15
+ // state/graphs/<app>/index.json records the revision (HEAD), whether the tree
16
+ // was dirty, a sha1 per file, when and how long. Status compares that with the
17
+ // app's files now: changed / added / removed files make the index stale, and
18
+ // every query result says so. A failed index keeps the previous one (still
19
+ // usable, marked stale) and records an actionable error; no other tool
20
+ // depends on the graph.
21
+
22
+ import crypto from 'node:crypto';
23
+ import fs from 'node:fs';
24
+ import path from 'node:path';
25
+ import { spawn, spawnSync } from 'node:child_process';
26
+ import { getApp } from './apps.js';
27
+ import { cleanEnv } from './jobs.js';
28
+
29
+ const MAX_FILE = 1024 * 1024;
30
+ const DENY = [
31
+ /(^|\/)\.env(\.[^/]*)?$/i, /(^|\/)\.npmrc$/i, /(^|\/)\.pypirc$/i, /(^|\/)\.netrc$/i, /credentials/i, /secret/i,
32
+ /(^|\/)id_(rsa|dsa|ecdsa|ed25519)(\.pub)?$/i, /\.(pem|key|pfx|p12|jks|keystore|kdbx)$/i, /(^|\/)\.aws\//i, /(^|\/)\.ssh\//i,
33
+ /service[-_]?account.*\.json$/i, /(^|\/)\.harness-device\//, /(^|\/)graphify-out\//, /(^|\/)node_modules\//, /(^|\/)\.git\//,
34
+ ];
35
+ export const denied = (rel) => DENY.some((re) => re.test(rel));
36
+
37
+ const dirOf = (ctx, app) => path.join(ctx.paths.state, 'graphs', app);
38
+ const metaOf = (ctx, app) => path.join(dirOf(ctx, app), 'index.json');
39
+ const treeOf = (ctx, app) => path.join(dirOf(ctx, app), 'tree');
40
+
41
+ export function readIndex(ctx, app) {
42
+ try { return JSON.parse(fs.readFileSync(metaOf(ctx, app), 'utf8')); } catch { return null; }
43
+ }
44
+ function writeIndex(ctx, app, meta) {
45
+ fs.mkdirSync(dirOf(ctx, app), { recursive: true });
46
+ const tmp = `${metaOf(ctx, app)}.${process.pid}.tmp`;
47
+ fs.writeFileSync(tmp, JSON.stringify(meta, null, 2));
48
+ fs.renameSync(tmp, metaOf(ctx, app));
49
+ }
50
+
51
+ /** The graphify binary: GRAPHIFY_BIN (tests), the capability's link, or PATH. */
52
+ export function graphifyBin(ctx) {
53
+ if (ctx.env.GRAPHIFY_BIN) return fs.existsSync(ctx.env.GRAPHIFY_BIN) ? ctx.env.GRAPHIFY_BIN : null;
54
+ const linked = path.join(ctx.paths.bin, 'graphify');
55
+ if (fs.existsSync(linked)) return linked;
56
+ const r = spawnSync('which', ['graphify'], { encoding: 'utf8' });
57
+ return r.status === 0 ? r.stdout.trim() : null;
58
+ }
59
+
60
+ function git(dir, args) {
61
+ const r = spawnSync('git', args, { cwd: dir, encoding: 'buffer', maxBuffer: 64 * 1024 * 1024 });
62
+ if (r.status !== 0) throw new Error(`git ${args[0]}: ${String(r.stderr || '').trim() || `exit ${r.status}`}`);
63
+ return r.stdout;
64
+ }
65
+
66
+ /** What the app looks like now: { revision, dirty, files: { rel: sha1 }, excluded }. */
67
+ export function snapshot(ctx, name) {
68
+ const app = getApp(ctx, name);
69
+ const root = fs.realpathSync(app.dir);
70
+ if (!fs.existsSync(path.join(root, '.git'))) {
71
+ throw Object.assign(new Error(`${name} is not a git repository, so there is no revision to index; clone it with git_clone (or git init it)`), { code: 'NOT_GIT' });
72
+ }
73
+ let revision = null;
74
+ try { revision = String(git(root, ['rev-parse', 'HEAD'])).trim(); } catch { /* no commit yet */ }
75
+ const list = String(git(root, ['ls-files', '-z', '-co', '--exclude-standard'])).split('\0').filter(Boolean);
76
+ const files = {};
77
+ let excluded = 0;
78
+ for (const rel of list) {
79
+ if (denied(rel)) { excluded++; continue; }
80
+ const abs = path.join(root, rel);
81
+ let st;
82
+ try { st = fs.lstatSync(abs); } catch { continue; } // deleted, not yet staged
83
+ if (!st.isFile() || st.size > MAX_FILE) { excluded++; continue; } // symlinks, too big
84
+ files[rel] = crypto.createHash('sha1').update(fs.readFileSync(abs)).digest('hex');
85
+ }
86
+ const dirty = String(git(root, ['status', '--porcelain'])).trim().length > 0;
87
+ return { app: name, root, revision, dirty, files, excluded };
88
+ }
89
+
90
+ function diff(before = {}, now = {}) {
91
+ const changed = []; const added = []; const removed = [];
92
+ for (const [f, h] of Object.entries(now)) if (!(f in before)) added.push(f); else if (before[f] !== h) changed.push(f);
93
+ for (const f of Object.keys(before)) if (!(f in now)) removed.push(f);
94
+ return { changed: changed.sort(), added: added.sort(), removed: removed.sort() };
95
+ }
96
+
97
+ /** Freshness of the index against the app now. */
98
+ export function status(ctx, name) {
99
+ const meta = readIndex(ctx, name);
100
+ const snap = snapshot(ctx, name);
101
+ if (!meta?.files) {
102
+ return { app: name, indexed: false, fresh: false, head_revision: snap.revision, last_error: meta?.lastError || null,
103
+ next: meta?.lastError ? meta.lastError.fix : `no index yet: graph_index {"app":"${name}"}` };
104
+ }
105
+ const d = diff(meta.files, snap.files);
106
+ const stale = [...d.changed, ...d.added, ...d.removed];
107
+ return {
108
+ app: name, indexed: true, fresh: stale.length === 0,
109
+ indexed_revision: meta.revision, indexed_dirty: meta.dirty, head_revision: snap.revision, revision_moved: meta.revision !== snap.revision,
110
+ indexed_at: meta.indexedAt, files: Object.keys(meta.files).length, excluded: meta.excluded, duration_ms: meta.durationMs, mode: meta.mode,
111
+ stale_files: { changed: d.changed.slice(0, 50), added: d.added.slice(0, 50), removed: d.removed.slice(0, 50), total: stale.length },
112
+ last_error: meta.lastError || null,
113
+ ...(stale.length ? { next: `stale: ${stale.length} file(s) changed since the index; graph_index {"app":"${name}"} updates it incrementally` } : {}),
114
+ };
115
+ }
116
+
117
+ function run(bin, args, cwd, env, timeoutMs) {
118
+ return new Promise((resolve) => {
119
+ let out = '';
120
+ const child = spawn(bin, args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'], detached: true });
121
+ const add = (b) => { out = (out + b).slice(-64 * 1024); };
122
+ child.stdout.on('data', add);
123
+ child.stderr.on('data', add);
124
+ const t = setTimeout(() => { try { process.kill(-child.pid, 'SIGKILL'); } catch { /* gone */ } out += `\n(timed out after ${Math.round(timeoutMs / 1000)}s)`; }, timeoutMs);
125
+ child.on('error', (e) => { out += e.message; });
126
+ child.on('close', (code) => { clearTimeout(t); resolve({ code: code ?? 1, out }); });
127
+ });
128
+ }
129
+
130
+ const locks = new Set();
131
+
132
+ /**
133
+ * Build or update the index. Returns the new status; on failure records an
134
+ * actionable error (the previous index stays, marked stale) and throws it.
135
+ */
136
+ export async function index(ctx, name, { full = false, timeoutSeconds = 900, log = () => {} } = {}) {
137
+ if (locks.has(name)) throw Object.assign(new Error(`${name} is being indexed already`), { code: 'BUSY' });
138
+ locks.add(name);
139
+ const started = Date.now();
140
+ const prev = readIndex(ctx, name);
141
+ const { event } = await import('./state.js');
142
+ const fail = (msg, fix, code = 'INDEX_FAILED') => {
143
+ const lastError = { at: new Date().toISOString(), message: msg.slice(-4000), fix };
144
+ writeIndex(ctx, name, { ...(prev || {}), lastError });
145
+ event(ctx, `graph ${name}: index failed: ${msg.split('\n').filter(Boolean).pop()?.slice(0, 160) || 'error'}`);
146
+ return Object.assign(new Error(`${msg.split('\n').filter(Boolean).slice(-6).join('\n')}\n${fix}`), { code });
147
+ };
148
+ try {
149
+ const bin = graphifyBin(ctx);
150
+ if (!bin) throw fail('graphify is not installed on this device', 'Turn on the "graphify" capability (harness-device capabilities add graphify, then harness-device install). Other tools work without it.', 'NO_GRAPHIFY');
151
+ let snap;
152
+ try { snap = snapshot(ctx, name); } catch (e) {
153
+ throw fail(e.message, e.code === 'NOT_GIT' ? 'Only git repositories are indexed (their revision is what the index is pinned to).' : 'Check the repository (workspace_status, git status in the app).', e.code || 'INDEX_FAILED');
154
+ }
155
+ const tree = treeOf(ctx, name);
156
+ const incremental = !full && prev?.files && fs.existsSync(path.join(tree, 'graphify-out', 'graph.json'));
157
+ if (!incremental) fs.rmSync(tree, { recursive: true, force: true });
158
+ fs.mkdirSync(tree, { recursive: true });
159
+ const d = diff(incremental ? prev.files : {}, snap.files);
160
+ for (const rel of [...d.added, ...d.changed]) {
161
+ const to = path.join(tree, rel);
162
+ fs.mkdirSync(path.dirname(to), { recursive: true });
163
+ fs.copyFileSync(path.join(snap.root, rel), to);
164
+ }
165
+ for (const rel of d.removed) fs.rmSync(path.join(tree, rel), { force: true });
166
+ log(`${incremental ? 'incremental' : 'full'} index of ${name}: ${d.added.length} added, ${d.changed.length} changed, ${d.removed.length} removed`);
167
+ const args = ['.', '--no-viz', '--no-install', ...(incremental ? ['--update'] : [])];
168
+ const r = await run(bin, args, tree, { ...cleanEnv(ctx.env), CI: '1' }, timeoutSeconds * 1000);
169
+ if (r.code !== 0 || !fs.existsSync(path.join(tree, 'graphify-out', 'graph.json'))) {
170
+ throw fail(`graphify ${args.join(' ')} failed (exit ${r.code}):\n${r.out.trim()}`,
171
+ 'The previous index (if any) is kept and marked stale. Fix what the output says (a file graphify cannot parse can be excluded in .gitignore), or retry with full=true for a clean rebuild.');
172
+ }
173
+ const meta = { app: name, revision: snap.revision, dirty: snap.dirty, files: snap.files, excluded: snap.excluded, indexedAt: new Date().toISOString(),
174
+ durationMs: Date.now() - started, mode: incremental ? 'incremental' : 'full', delta: { added: d.added.length, changed: d.changed.length, removed: d.removed.length } };
175
+ writeIndex(ctx, name, meta);
176
+ event(ctx, `graph ${name}: ${meta.mode} index of ${snap.revision ? snap.revision.slice(0, 12) : 'no commit'}${snap.dirty ? ' (dirty)' : ''}, ${Object.keys(snap.files).length} files (+${d.added.length} ~${d.changed.length} -${d.removed.length}), ${meta.durationMs}ms`);
177
+ return { ...status(ctx, name), delta: meta.delta };
178
+ } finally { locks.delete(name); }
179
+ }
180
+
181
+ /** Repo-relative file references (path:Lline) in Graphify output, only for files in the index. */
182
+ export function sourcesIn(text, files) {
183
+ const out = new Map();
184
+ for (const m of text.matchAll(/`?([\w@.+/-]+\.[\w]+):L(\d+)(?:-L(\d+))?`?/g)) {
185
+ const [, file, from, to] = m;
186
+ if (!(file in files)) continue;
187
+ const key = `${file}:${from}`;
188
+ if (!out.has(key)) out.set(key, { file, line: Number(from), ...(to ? { end: Number(to) } : {}) });
189
+ }
190
+ return [...out.values()].slice(0, 100);
191
+ }
192
+
193
+ /**
194
+ * Ask the graph: mode "context" (a token-budgeted pack of the relevant code)
195
+ * or "query" (a traversal from the matching symbols). The answer carries its
196
+ * source references and whether the index is stale.
197
+ */
198
+ export async function ask(ctx, name, { question, mode = 'context', budget = 2000 }) {
199
+ const meta = readIndex(ctx, name);
200
+ if (!meta?.files) throw Object.assign(new Error(`${name} has no graph index yet: graph_index {"app":"${name}"} (it does not block anything else)`), { code: 'NO_INDEX' });
201
+ const bin = graphifyBin(ctx);
202
+ if (!bin) throw Object.assign(new Error('graphify is not installed on this device: turn on the "graphify" capability'), { code: 'NO_GRAPHIFY' });
203
+ if (!['context', 'query'].includes(mode)) throw new Error('mode is context or query');
204
+ const r = await run(bin, [mode, String(question).slice(0, 2000), '--budget', String(Math.max(200, Math.min(Number(budget) || 2000, 20000)))], treeOf(ctx, name), cleanEnv(ctx.env), 120_000);
205
+ if (r.code !== 0) throw Object.assign(new Error(`graphify ${mode} failed (exit ${r.code}): ${r.out.trim().slice(-2000)}`), { code: 'QUERY_FAILED' });
206
+ const st = status(ctx, name);
207
+ return {
208
+ app: name, mode, revision: meta.revision, indexed_at: meta.indexedAt, fresh: st.fresh,
209
+ ...(st.fresh ? {} : { stale: `results reflect revision ${String(meta.revision).slice(0, 12)} at ${meta.indexedAt}; ${st.stale_files.total} file(s) changed since (${[...st.stale_files.changed, ...st.stale_files.added, ...st.stale_files.removed].slice(0, 8).join(', ')}): graph_index updates it` }),
210
+ sources: sourcesIn(r.out, meta.files), answer: r.out.trim(),
211
+ };
212
+ }
213
+
214
+ /** The architecture report Graphify writes (GRAPH_REPORT.md), with the index status. */
215
+ export function summary(ctx, name, { maxChars = 20000 } = {}) {
216
+ const meta = readIndex(ctx, name);
217
+ if (!meta?.files) throw Object.assign(new Error(`${name} has no graph index yet: graph_index {"app":"${name}"}`), { code: 'NO_INDEX' });
218
+ let report = '';
219
+ try { report = fs.readFileSync(path.join(treeOf(ctx, name), 'graphify-out', 'GRAPH_REPORT.md'), 'utf8'); } catch { /* none */ }
220
+ return { status: status(ctx, name), report: report.slice(0, maxChars), truncated: report.length > maxChars };
221
+ }
222
+
223
+ /** Drop an app's index (the app or workspace went away). */
224
+ export function drop(ctx, name) {
225
+ fs.rmSync(dirOf(ctx, name), { recursive: true, force: true });
226
+ }
package/src/mcp/server.js CHANGED
@@ -21,6 +21,8 @@ import * as jobs from '../jobs.js';
21
21
  import * as execMod from '../exec.js';
22
22
  import * as ws from '../workspace.js';
23
23
  import * as preview from '../preview.js';
24
+ import { getApp } from '../apps.js';
25
+ import * as removal from '../remove.js';
24
26
  import { Cancelled, NeedsUser, interaction } from './interact.js';
25
27
 
26
28
  const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
@@ -119,6 +121,15 @@ export function buildServer(env = process.env, opts = {}) {
119
121
  tool('app_list', 'Managed apps on this device (cloned with git_clone): folder, repo and branch, detected stack, start command and port, and whether its process runs.', {},
120
122
  async (c) => text(project.list(c)));
121
123
 
124
+ tool('app_remove', 'Remove a managed app (asks the user first): stops its process and previews, archives its workspaces, deletes its folder in the apps folder and forgets its record, port and code graph. Refuses while it holds work found nowhere else (uncommitted or untracked files, commits on no remote, workspaces) unless discard_changes=true after the user agrees to lose it. Session projects and folders outside the apps folder are never deleted.',
125
+ { app: APP, discard_changes: z.boolean().optional(), ...CONFIRM },
126
+ async (c, a, u) => {
127
+ const p = removal.removalPlan(c, a.app);
128
+ if (!p.safe && !a.discard_changes) return { isError: true, content: [{ type: 'text', text: `${removal.describePlan(p).replace(/^Remove app \S+\? /, `${a.app} was not removed. `)} Push or archive that work first, or call again with discard_changes=true after the user agrees to lose it.` }] };
129
+ await u.confirm(removal.describePlan(p));
130
+ return text(await removal.removeApp(c, { name: a.app, force: !!a.discard_changes }));
131
+ });
132
+
122
133
  tool('git_clone', 'Clone a repository into the apps folder as a managed app, then detect its stack (job). Private GitHub repos use the device secret GITHUB_TOKEN (or token_secret), passed to git through the environment only. No agent session unless session=true. Next: project_setup, then project_start.',
123
134
  { url: z.string().max(300).describe('https://host/owner/repo(.git), git@host:owner/repo, or file:///path'), name: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/).optional(), branch: z.string().max(100).optional(),
124
135
  token_secret: z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional().describe('device secret holding a git token (default GITHUB_TOKEN for github.com)'), session: z.boolean().optional().describe('also give it a persistent agent session'), ...FORCE },
@@ -275,6 +286,35 @@ export function buildServer(env = process.env, opts = {}) {
275
286
  ...(done ? {} : { next: `still running: job_status {"id":"${job.id}"}; job_cancel to stop it` }) }, null, 2) }] };
276
287
  });
277
288
 
289
+ tool('graph_index', 'Build or update the Graphify code graph of an app or workspace (needs the graphify capability). Indexes the git view only: tracked and untracked-but-not-ignored files, never secrets (.env, keys, credentials), ignored paths or anything outside the repository. Pinned to the revision (HEAD) it saw; the next run is incremental (only changed files). Runs as a job: waits up to wait_seconds (default 60), then follow it with job_status. A failure is recorded with what to do and keeps the previous index (marked stale); nothing else depends on it. full=true rebuilds from scratch.',
290
+ { app: APP, full: z.boolean().optional(), wait_seconds: z.number().int().min(0).max(120).optional(), ...FORCE },
291
+ async (c, a) => {
292
+ await guard(c, a, `indexing ${a.app}`);
293
+ getApp(c, a.app);
294
+ const job = await jobs.startJob(c, { kind: 'graph', app: a.app, steps: [{ name: 'graph-index', internal: 'graph-index', args: { name: a.app, full: !!a.full } }] });
295
+ const deadline = Date.now() + Math.min(a.wait_seconds ?? 60, 120) * 1000;
296
+ let j = job;
297
+ while (['queued', 'running'].includes(j.status) && Date.now() < deadline) { await new Promise((res) => setTimeout(res, 200)); j = jobs.getJob(c, job.id); }
298
+ const graph = await import('../graph.js');
299
+ if (j.status === 'done') return text({ job: j.id, ...graph.status(c, a.app) });
300
+ if (j.status === 'failed') return { isError: true, content: [{ type: 'text', text: `${j.error}\n${graph.readIndex(c, a.app)?.lastError?.fix || ''}`.trim() }] };
301
+ return text({ job: j.id, status: j.status, next: `indexing: job_status {"id":"${j.id}"}, then graph_status` });
302
+ });
303
+
304
+ tool('graph_status', 'Freshness of an app\'s code graph: the revision it was indexed at, the current HEAD, and the files changed, added or removed since (stale when any); the last indexing error and what to do about it.',
305
+ { app: APP },
306
+ async (c, a) => text((await import('../graph.js')).status(c, a.app)));
307
+
308
+ tool('graph_query', 'Ask an app\'s code graph (Graphify). mode "context" (default): a token-budgeted pack of the code relevant to a task, real snippets at real line ranges. mode "query": the symbols matching a question and what they connect to. Returns the answer, its source references (repository file and line) and whether the index is stale (then results reflect the indexed revision; graph_index updates it).',
309
+ { app: APP, question: z.string().min(1).max(2000), mode: z.enum(['context', 'query']).optional(), budget: z.number().int().min(200).max(20000).optional() },
310
+ async (c, a) => {
311
+ try { return text(await (await import('../graph.js')).ask(c, a.app, { question: a.question, mode: a.mode, budget: a.budget })); } catch (e) { if (e.code) return { isError: true, content: [{ type: 'text', text: `${e.code}: ${e.message}` }] }; throw e; }
312
+ });
313
+
314
+ tool('graph_summary', 'The architecture summary Graphify writes for an app (communities, central modules, surprising links, open questions) with the index status and revision it describes.',
315
+ { app: APP },
316
+ async (c, a) => { try { return text((await import('../graph.js')).summary(c, a.app)); } catch (e) { if (e.code) return { isError: true, content: [{ type: 'text', text: `${e.code}: ${e.message}` }] }; throw e; } });
317
+
278
318
  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.',
279
319
  { id: z.string().regex(/^[a-z0-9-]{6,40}$/) },
280
320
  async (c, a) => text(jobs.cancelJob(c, a.id)));
package/src/project.js CHANGED
@@ -230,6 +230,11 @@ export function envManage(ctx, { app: name, action, key, value, fromSecret, file
230
230
 
231
231
  // ---- Steps the job runner performs in-process ----------------------------------------
232
232
  export const INTERNALS = {
233
+ async 'graph-index'(ctx, job, { name, full }) {
234
+ const graph = await import('./graph.js');
235
+ const r = await graph.index(ctx, name, { full, log: (m) => fs.appendFileSync(path.join(ctx.paths.logs, 'jobs', `${job.id}.log`), `${m}\n`) });
236
+ fs.appendFileSync(path.join(ctx.paths.logs, 'jobs', `${job.id}.log`), `indexed ${name} at ${r.indexed_revision || 'no commit'}: ${r.files} files (+${r.delta.added} ~${r.delta.changed} -${r.delta.removed})\n`);
237
+ },
233
238
  async register(ctx, job, { name, dir, url, branch, session }) {
234
239
  const plan = detect(dir);
235
240
  saveApp(ctx, { name, dir, repo: url, branch, tokenSecret: job.tokenSecret || null, stack: plan.stack, start: plan.start, port: plan.port, createdAt: new Date().toISOString() });
package/src/remove.js ADDED
@@ -0,0 +1,72 @@
1
+ // Removing a managed app (app_remove / `harness-device app rm`).
2
+ //
3
+ // The reverse of git_clone: stops what runs for the app (its process and its
4
+ // previews), archives its workspaces, deletes its folder and forgets its
5
+ // record, port and code graph. Only apps cloned into the apps folder can be
6
+ // removed: session projects and folders elsewhere are never deleted.
7
+ //
8
+ // Work that exists nowhere else blocks it unless `force`: uncommitted or
9
+ // untracked files, commits not on any remote, and workspaces (their ticket
10
+ // branches live in the app's repository and go with it).
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { spawnSync } from 'node:child_process';
15
+ import { appsDir, getApp, procName } from './apps.js';
16
+ import { listWorkspaces, archiveWorkspace, releasePort } from './workspace.js';
17
+ import { listPreviews, stopPreview } from './preview.js';
18
+ import * as state from './state.js';
19
+
20
+ const git = (dir, args) => {
21
+ const r = spawnSync('git', args, { cwd: dir, encoding: 'utf8' });
22
+ return r.status === 0 ? r.stdout.trim() : null;
23
+ };
24
+ const lines = (s) => (s ? s.split('\n').filter(Boolean) : []);
25
+
26
+ /** What removing `name` would lose, and whether it may be removed at all. */
27
+ export function removalPlan(ctx, name) {
28
+ const app = getApp(ctx, name);
29
+ if (app.project) throw new Error(`${name} is a session project, not a managed app: it is never removed by app_remove (harness-device project rm unregisters it, keeping its folder)`);
30
+ if (app.workspace) throw new Error(`${name} is a workspace: use workspace_archive`);
31
+ const root = fs.realpathSync(appsDir(ctx));
32
+ let dir = null;
33
+ if (fs.existsSync(app.dir)) {
34
+ dir = fs.realpathSync(app.dir);
35
+ if (!dir.startsWith(root + path.sep)) throw new Error(`${name}'s folder ${app.dir} is outside the apps folder (${root}); it is not deleted by app_remove`);
36
+ }
37
+ const isGit = dir && git(dir, ['rev-parse', '--is-inside-work-tree']) === 'true';
38
+ const dirty = isGit ? lines(git(dir, ['status', '--porcelain'])).map((l) => l.slice(3)) : [];
39
+ const unpushed = isGit ? lines(git(dir, ['log', '--branches', '--not', '--remotes', '--format=%h %s'])) : [];
40
+ const workspaces = listWorkspaces(ctx, name).map((w) => w.name);
41
+ const previews = listPreviews(ctx).filter((p) => p.status === 'active' && p.app === name).map((p) => p.id);
42
+ const running = state.listProcs(ctx).some((p) => p.name === procName(app));
43
+ return { name, dir: app.dir, exists: !!dir, git: !!isGit, dirty, unpushed, workspaces, previews, running, safe: !dirty.length && !unpushed.length && !workspaces.length };
44
+ }
45
+
46
+ /** One line for the confirmation question. */
47
+ export function describePlan(p) {
48
+ const lost = [
49
+ p.dirty.length && `${p.dirty.length} uncommitted/untracked file(s) (${p.dirty.slice(0, 5).join(', ')}${p.dirty.length > 5 ? ', …' : ''})`,
50
+ p.unpushed.length && `${p.unpushed.length} commit(s) on no remote (${p.unpushed.slice(0, 3).join('; ')}${p.unpushed.length > 3 ? '; …' : ''})`,
51
+ p.workspaces.length && `workspace(s) ${p.workspaces.join(', ')} and their ticket branches`,
52
+ ].filter(Boolean);
53
+ return `Remove app ${p.name}? Its folder ${p.dir} is deleted${p.running ? ', its process stopped' : ''}${p.previews.length ? `, ${p.previews.length} preview(s) stopped` : ''}, and its record, port and code graph forgotten.${lost.length ? ` LOST for good: ${lost.join('; ')}.` : ' Everything in it is on its remote.'}`;
54
+ }
55
+
56
+ export async function removeApp(ctx, { name, force = false }) {
57
+ const p = removalPlan(ctx, name);
58
+ if (!p.safe && !force) {
59
+ throw Object.assign(new Error(`${describePlan(p).replace(/^Remove app \S+\? /, `${name} was not removed. `)} Push or archive that work first, or remove with force once the user agrees to lose it.`), { code: 'NOT_SAFE', plan: p });
60
+ }
61
+ const app = getApp(ctx, name);
62
+ for (const id of p.previews) await stopPreview(ctx, { id, reason: 'app removed' }).catch(() => {});
63
+ for (const w of p.workspaces) await archiveWorkspace(ctx, { name: w, force: true });
64
+ if (p.running) state.removeProc(ctx, procName(app));
65
+ if (p.exists) fs.rmSync(app.dir, { recursive: true, force: true });
66
+ releasePort(ctx, name);
67
+ fs.rmSync(path.join(ctx.paths.state, 'graphs', name), { recursive: true, force: true });
68
+ fs.rmSync(path.join(ctx.paths.state, 'apps', `${name}.json`), { force: true });
69
+ const lost = force && !p.safe ? ` (forced: ${p.dirty.length} uncommitted file(s), ${p.unpushed.length} unpushed commit(s), ${p.workspaces.length} workspace(s) discarded)` : '';
70
+ state.event(ctx, `app ${name} removed: folder ${p.dir} deleted${lost}`);
71
+ return { removed: name, dir: p.dir, stopped: { process: p.running, previews: p.previews }, archived_workspaces: p.workspaces, discarded: force ? { dirty: p.dirty, unpushed: p.unpushed } : { dirty: [], unpushed: [] } };
72
+ }
@@ -12,10 +12,11 @@ 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', 'workspace_list', 'workspace_status', 'preview_list', 'preview_screenshot'],
15
+ 'app_list', 'file_read', 'job_status', 'workspace_list', 'workspace_status', 'preview_list', 'preview_screenshot',
16
+ 'graph_status', 'graph_query', 'graph_summary'],
16
17
  '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',
18
- 'exec', 'job_submit', 'job_cancel', 'workspace_create', 'workspace_archive', 'preview_start', 'preview_stop'],
18
+ 'git_clone', 'app_remove', 'git_pull', 'project_setup', 'project_start', 'project_stop', 'project_deploy', 'file_write', 'env_manage',
19
+ 'exec', 'job_submit', 'job_cancel', 'graph_index', 'workspace_create', 'workspace_archive', 'preview_start', 'preview_stop'],
19
20
  // shell_exec is not listed: it needs device:admin (unknown tools do).
20
21
  };
21
22
 
package/src/workspace.js CHANGED
@@ -178,6 +178,7 @@ export async function archiveWorkspace(ctx, { name, force = false }) {
178
178
  });
179
179
  releasePort(ctx, name);
180
180
  fs.rmSync(path.join(ctx.paths.state, 'apps', `${name}.json`), { force: true });
181
+ fs.rmSync(path.join(ctx.paths.state, 'graphs', name), { recursive: true, force: true }); // its code graph (HARNESS-8)
181
182
  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
183
  return { archived: name, branch: st.branch, head: st.head, discarded: force ? st.dirty : [] };
183
184
  }