@dreamtree-org/harness-device 0.9.0 → 0.9.1

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
@@ -211,6 +211,10 @@ Repositories this device runs, kept in `APPS_DIR` (default `~/apps`). Unlike pro
211
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; `save: true` also keeps it in the app's `.dreamtree/evidence/captures/` for ai-builder's `evidence add screenshot` |
212
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` |
213
213
  | `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 |
214
+ | `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` |
215
+ | `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 |
216
+ | `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 |
217
+ | `graph_summary` | Graphify's architecture report (`GRAPH_REPORT.md`) with the revision it describes |
214
218
  | `job_status` (`job <id>`) | Status, step and the end of the log for clone, setup, pull, deploy and long commands |
215
219
 
216
220
  **Recovering a job** (`exec`, clone, setup, deploy):
@@ -230,6 +234,12 @@ Repositories this device runs, kept in `APPS_DIR` (default `~/apps`). Unlike pro
230
234
  - **Failures** are reported as not retryable: retries happen on the device, within the job's budget.
231
235
  - **Routing:** the claim API has no per-device queue yet, so give each device its own worker pool.
232
236
 
237
+ **Recovering a code graph:**
238
+ - The index is in `state/graphs/<app>/`: `index.json` (revision, file hashes, last error) and `tree/` (the mirrored files and `graphify-out/`).
239
+ - A failed `graph_index` keeps the previous index, so queries still answer, marked stale. The error and its fix show in `graph_status`.
240
+ - `graph_index {full: true}` rebuilds from scratch. Deleting `state/graphs/<app>` is always safe.
241
+ - Archiving a workspace removes its graph.
242
+
233
243
  **Recovering a workspace:**
234
244
  - `workspace_status` shows what is uncommitted and how far the branch is ahead.
235
245
  - 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.1",
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/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,7 @@ 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';
24
25
  import { Cancelled, NeedsUser, interaction } from './interact.js';
25
26
 
26
27
  const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
@@ -275,6 +276,35 @@ export function buildServer(env = process.env, opts = {}) {
275
276
  ...(done ? {} : { next: `still running: job_status {"id":"${job.id}"}; job_cancel to stop it` }) }, null, 2) }] };
276
277
  });
277
278
 
279
+ 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.',
280
+ { app: APP, full: z.boolean().optional(), wait_seconds: z.number().int().min(0).max(120).optional(), ...FORCE },
281
+ async (c, a) => {
282
+ await guard(c, a, `indexing ${a.app}`);
283
+ getApp(c, a.app);
284
+ 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 } }] });
285
+ const deadline = Date.now() + Math.min(a.wait_seconds ?? 60, 120) * 1000;
286
+ let j = job;
287
+ while (['queued', 'running'].includes(j.status) && Date.now() < deadline) { await new Promise((res) => setTimeout(res, 200)); j = jobs.getJob(c, job.id); }
288
+ const graph = await import('../graph.js');
289
+ if (j.status === 'done') return text({ job: j.id, ...graph.status(c, a.app) });
290
+ if (j.status === 'failed') return { isError: true, content: [{ type: 'text', text: `${j.error}\n${graph.readIndex(c, a.app)?.lastError?.fix || ''}`.trim() }] };
291
+ return text({ job: j.id, status: j.status, next: `indexing: job_status {"id":"${j.id}"}, then graph_status` });
292
+ });
293
+
294
+ 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.',
295
+ { app: APP },
296
+ async (c, a) => text((await import('../graph.js')).status(c, a.app)));
297
+
298
+ 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).',
299
+ { app: APP, question: z.string().min(1).max(2000), mode: z.enum(['context', 'query']).optional(), budget: z.number().int().min(200).max(20000).optional() },
300
+ async (c, a) => {
301
+ 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; }
302
+ });
303
+
304
+ 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.',
305
+ { app: APP },
306
+ 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; } });
307
+
278
308
  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
309
  { id: z.string().regex(/^[a-z0-9-]{6,40}$/) },
280
310
  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() });
@@ -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
18
  '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'],
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
  }