@online-tools/work-agent-runner 0.0.5-alpha-1 → 0.1.0-alpha-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/lib/log.mjs CHANGED
@@ -1,18 +1,106 @@
1
1
  // Timestamped Chinese log lines on stdout / stderr (systemd puts them in the
2
- // journal, launchd in ~/Library/Logs). Never log a token, an API key,
3
- // GITCODE_CRED or a proxy password: use redactUrl() for anything URL-like.
2
+ // journal, launchd in ~/Library/Logs) and, for the running instance, in
3
+ // <program home>/logs/runner.log (10 MiB × 5, rotated), which `work-agent-runner
4
+ // logs` reads. Never log a token, an API key, GITCODE_CRED or a proxy password:
5
+ // every line goes through redact(), which masks the known shapes and the
6
+ // secrets of the jobs that are running (addSecret / removeSecret).
7
+
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+
11
+ export const LOG_MAX_BYTES = 10 * 1024 * 1024;
12
+ export const LOG_KEEP = 5; // runner.log and runner.log.1 … .4
4
13
 
5
14
  function stamp(date = new Date()) {
6
15
  const pad = (value) => String(value).padStart(2, '0');
7
16
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
8
17
  }
9
18
 
10
- export function createLogger({ out = process.stdout, err = process.stderr } = {}) {
11
- const write = (stream, prefix, message) => stream.write(`${stamp()} ${prefix}${message}\n`);
19
+ const SECRET_SHAPES = [
20
+ [/gcm_[A-Za-z0-9_-]{43}/g, 'gcm_***'],
21
+ [/(\/\/)[^/@\s]*@/g, '$1***@'],
22
+ [/(access_token=)[^&\s"']+/gi, '$1***'],
23
+ [/(authorization:\s*bearer\s+)\S+/gi, '$1***'],
24
+ [/\bsk-[A-Za-z0-9_-]{16,}/g, 'sk-***'],
25
+ ];
26
+ const secrets = new Set();
27
+
28
+ /** A value (a job's API key, its GITCODE_CRED) that must never appear in a log line. */
29
+ export function addSecret(value) {
30
+ if (typeof value === 'string' && value.length >= 8) secrets.add(value);
31
+ }
32
+
33
+ export function removeSecret(value) {
34
+ secrets.delete(value);
35
+ }
36
+
37
+ /** The text with tokens, keys and credentials masked. */
38
+ export function redact(text) {
39
+ let out = String(text ?? '');
40
+ for (const secret of secrets) out = out.split(secret).join('***');
41
+ for (const [pattern, replacement] of SECRET_SHAPES) out = out.replace(pattern, replacement);
42
+ return out;
43
+ }
44
+
45
+ /** runner.log → runner.log.1 → … → runner.log.<keep-1>; the oldest goes. */
46
+ function rotate(file, keep) {
47
+ for (let index = keep - 1; index >= 1; index -= 1) {
48
+ const from = index === 1 ? file : `${file}.${index - 1}`;
49
+ try {
50
+ fs.renameSync(from, `${file}.${index}`);
51
+ } catch {
52
+ // Not there yet.
53
+ }
54
+ }
55
+ }
56
+
57
+ function sizeOf(file) {
58
+ try {
59
+ return fs.statSync(file).size;
60
+ } catch {
61
+ return 0;
62
+ }
63
+ }
64
+
65
+ export function createLogger({ out = process.stdout, err = process.stderr, file = '', maxBytes = LOG_MAX_BYTES, keep = LOG_KEEP } = {}) {
66
+ let target = file;
67
+ let size = target ? sizeOf(target) : 0;
68
+ const listeners = new Set();
69
+ const toFile = (line) => {
70
+ if (!target) return;
71
+ try {
72
+ if (size + Buffer.byteLength(line) > maxBytes) {
73
+ rotate(target, keep);
74
+ size = 0;
75
+ }
76
+ fs.appendFileSync(target, line, { mode: 0o600 });
77
+ size += Buffer.byteLength(line);
78
+ } catch {
79
+ // The log file must never stop the program.
80
+ }
81
+ };
82
+ const write = (stream, level, prefix, message) => {
83
+ const text = redact(message);
84
+ const time = stamp();
85
+ stream.write(`${time} ${prefix}${text}\n`);
86
+ toFile(`${time} ${level.padEnd(5)} ${text}\n`);
87
+ for (const listener of listeners) listener({ time, level, text });
88
+ };
12
89
  return {
13
- info: (message) => write(out, '', message),
14
- warn: (message) => write(err, '警告:', message),
15
- error: (message) => write(err, '错误:', message),
90
+ info: (message) => write(out, 'INFO', '', message),
91
+ warn: (message) => write(err, 'WARN', '警告:', message),
92
+ error: (message) => write(err, 'ERROR', '错误:', message),
93
+ /** From now on also into `next` (0600, its directory 0700); '' stops it. */
94
+ setFile(next) {
95
+ target = next || '';
96
+ if (target) fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
97
+ size = target ? sizeOf(target) : 0;
98
+ },
99
+ /** Every line as it is written: { time, level, text }. Returns the function that stops it. */
100
+ subscribe(listener) {
101
+ listeners.add(listener);
102
+ return () => listeners.delete(listener);
103
+ },
16
104
  };
17
105
  }
18
106
 
@@ -0,0 +1,394 @@
1
+ // When the running instance maintains things (docs/design.md 2.3, 7.1):
2
+ //
3
+ // work-agent clone every day at maintenance.repoRefreshAt (08:00) plus up to
4
+ // 10 minutes; a missing or broken clone again after 1, 2,
5
+ // 4 … 30 minutes
6
+ // knowledge pool every day at maintenance.poolUpdateAt (03:00, or 'hourly')
7
+ // plus up to 10 minutes, only while no job runs (then every
8
+ // 15 minutes until it can); a terminal's `update` asks for
9
+ // one (control interface, or state/requests/pool-update)
10
+ // checks every hour: dependencies and the sandbox (recheck())
11
+ // housekeeping every hour: trash/, archive/, what has gone wrong for long
12
+ //
13
+ // One maintenance step at a time (a download of the pool is the exception: it
14
+ // only adds repositories, so it runs beside the rest). Timers are re-armed with
15
+ // setTimeout each time, so a schedule stays on its clock across a change of
16
+ // day length or a sleep. The random offset keeps machines in one time zone
17
+ // from all reaching gitcode.com at the same minute.
18
+ //
19
+ // Only node: built-ins and files in this directory.
20
+
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+
24
+ import { retryTrash, removeTree } from './fs-safe.mjs';
25
+ import { clearPoolUpdateRequest, poolBusyInfo, poolUpdateRequested } from './work-agent.mjs';
26
+
27
+ export const CLONE_RETRY_START_MS = 60_000;
28
+ export const CLONE_RETRY_MAX_MS = 30 * 60_000;
29
+ export const POOL_RETRY_MS = 15 * 60_000;
30
+ export const POOL_STALE_DAYS = 3;
31
+ const HOUR_MS = 60 * 60_000;
32
+ const REQUEST_POLL_MS = 30_000;
33
+ const JITTER_MS = 10 * 60_000;
34
+ // archive/ as a whole (docs/design.md 3.16): the oldest go first beyond this.
35
+ export const ARCHIVE_MAX_BYTES = 2 * 1024 ** 3;
36
+ // workAgent.state() runs git; the status is published at every heartbeat and job phase.
37
+ const STATE_CACHE_MS = 60_000;
38
+
39
+ /** The first time after `now` that the clock shows `clock` ('HH:MM', local), plus `jitterMs`. */
40
+ export function nextDailyRun(clock, now = new Date(), jitterMs = 0) {
41
+ const [hours, minutes] = String(clock).split(':').map(Number);
42
+ const next = new Date(now.getTime());
43
+ next.setHours(hours, minutes, 0, 0);
44
+ if (next.getTime() <= now.getTime()) next.setDate(next.getDate() + 1);
45
+ return new Date(next.getTime() + jitterMs);
46
+ }
47
+
48
+ const iso = (ms) => (ms ? new Date(ms).toISOString() : '');
49
+
50
+ /** Bytes of the regular files under `dir` (symlinks not followed). */
51
+ function treeBytes(dir) {
52
+ let total = 0;
53
+ let entries = [];
54
+ try {
55
+ entries = fs.readdirSync(dir, { withFileTypes: true });
56
+ } catch {
57
+ return 0;
58
+ }
59
+ for (const entry of entries) {
60
+ const full = path.join(dir, entry.name);
61
+ if (entry.isDirectory()) total += treeBytes(full);
62
+ else if (entry.isFile()) {
63
+ try {
64
+ total += fs.statSync(full).size;
65
+ } catch {
66
+ // Gone meanwhile.
67
+ }
68
+ }
69
+ }
70
+ return total;
71
+ }
72
+
73
+ export class Maintenance {
74
+ /**
75
+ * `recheck()`: the dependency / sandbox check (updates capabilities);
76
+ * `settings()`: { maintenance: { repoRefreshAt, poolUpdateAt }, limits: { archiveDays } };
77
+ * `onChange()`: the status changed.
78
+ */
79
+ constructor({
80
+ workAgent,
81
+ jobs,
82
+ log,
83
+ paths,
84
+ workRoot,
85
+ settings,
86
+ recheck,
87
+ onChange = () => {},
88
+ random = Math.random,
89
+ now = () => Date.now(),
90
+ }) {
91
+ this.workAgent = workAgent;
92
+ this.jobs = jobs;
93
+ this.log = log;
94
+ this.paths = paths;
95
+ this.trashDir = path.join(workRoot, 'trash');
96
+ this.archiveDir = path.join(workRoot, 'archive');
97
+ this.settings = settings;
98
+ this.recheck = recheck;
99
+ this.onChange = onChange;
100
+ this.random = random;
101
+ this.now = now;
102
+ this.queue = Promise.resolve();
103
+ this.timers = {};
104
+ this.cloneDelay = CLONE_RETRY_START_MS;
105
+ this.poolRequested = false;
106
+ this.stopped = false;
107
+ this.repo = { result: '', error: '', lastRunAt: '', nextAt: '' };
108
+ this.pool = { result: '', error: '', lastRunAt: '', lastOkAt: 0, nextAt: '', running: false };
109
+ this.checks = { lastRunAt: '' };
110
+ this.trashLeft = 0;
111
+ this.stateCache = null;
112
+ }
113
+
114
+ start() {
115
+ this.scheduleRepo();
116
+ this.schedulePool();
117
+ this.scheduleCloneRetry();
118
+ this.timers.hourly = setInterval(() => this.hourly(), HOUR_MS);
119
+ this.timers.hourly.unref?.();
120
+ this.timers.requests = setInterval(() => this.takeRequest(), REQUEST_POLL_MS);
121
+ this.timers.requests.unref?.();
122
+ }
123
+
124
+ stop() {
125
+ this.stopped = true;
126
+ clearInterval(this.timers.hourly);
127
+ clearInterval(this.timers.requests);
128
+ for (const name of ['repo', 'pool', 'clone', 'poolRetry']) clearTimeout(this.timers[name]);
129
+ }
130
+
131
+ changed() {
132
+ try {
133
+ this.onChange();
134
+ } catch {
135
+ // Display only.
136
+ }
137
+ }
138
+
139
+ /** One maintenance step at a time; failures are reported, never thrown at timers. */
140
+ exclusive(work) {
141
+ const next = this.queue.then(work);
142
+ this.queue = next.then(
143
+ () => {},
144
+ () => {},
145
+ );
146
+ return next;
147
+ }
148
+
149
+ jitter() {
150
+ return Math.floor(this.random() * JITTER_MS);
151
+ }
152
+
153
+ /** The clone and the pool (workAgent.state()), read at most once a minute unless something changed them. */
154
+ repoState() {
155
+ if (!this.stateCache || this.now() - this.stateCache.at >= STATE_CACHE_MS) {
156
+ this.stateCache = { at: this.now(), value: this.workAgent.state() };
157
+ }
158
+ return this.stateCache.value;
159
+ }
160
+
161
+ // ---- work-agent clone -----------------------------------------------------------
162
+
163
+ scheduleRepo() {
164
+ clearTimeout(this.timers.repo);
165
+ if (this.stopped) return;
166
+ const at = nextDailyRun(this.settings().maintenance.repoRefreshAt, new Date(this.now()), this.jitter());
167
+ this.repo.nextAt = at.toISOString();
168
+ this.timers.repo = setTimeout(() => {
169
+ this.refreshClone({ say: (line) => this.log.info(line) })
170
+ .catch(() => {})
171
+ .finally(() => this.scheduleRepo());
172
+ }, Math.max(0, at.getTime() - this.now()));
173
+ this.timers.repo.unref?.();
174
+ }
175
+
176
+ /** Brings the clone up to date now; a clone that stays unusable is tried again soon. */
177
+ refreshClone({ say = () => {} } = {}) {
178
+ return this.exclusive(async () => {
179
+ const state = await this.workAgent.refresh().catch((error) => ({ ...this.workAgent.state(), ok: false, reason: error.message }));
180
+ this.stateCache = null;
181
+ this.repo.lastRunAt = iso(this.now());
182
+ this.repo.result = state.ok ? 'ok' : 'failed';
183
+ this.repo.error = state.ok ? state.fetchReason || '' : state.reason;
184
+ if (state.ok) say(`✓ work-agent ${state.commit.slice(0, 7)}`);
185
+ else say(`work-agent 仓库不可用:${state.reason}`);
186
+ this.changed();
187
+ this.scheduleCloneRetry(state);
188
+ return state;
189
+ });
190
+ }
191
+
192
+ scheduleCloneRetry(state = this.workAgent.state()) {
193
+ clearTimeout(this.timers.clone);
194
+ if (this.stopped || state.ok || state.foreign) {
195
+ this.cloneDelay = CLONE_RETRY_START_MS;
196
+ return;
197
+ }
198
+ const delay = this.cloneDelay;
199
+ this.cloneDelay = Math.min(CLONE_RETRY_MAX_MS, this.cloneDelay * 2);
200
+ this.timers.clone = setTimeout(async () => {
201
+ const fresh = await this.refreshClone({ say: (line) => this.log.info(line) }).catch(() => null);
202
+ if (fresh?.ok) await this.runChecks().catch(() => {});
203
+ else this.log.warn(`work-agent 仓库仍不可用,${Math.round(this.cloneDelay / 60_000)} 分钟后再试`);
204
+ }, delay);
205
+ this.timers.clone.unref?.();
206
+ }
207
+
208
+ // ---- knowledge pool -------------------------------------------------------------
209
+
210
+ schedulePool() {
211
+ clearTimeout(this.timers.pool);
212
+ if (this.stopped) return;
213
+ const clock = this.settings().maintenance.poolUpdateAt;
214
+ if (clock === 'hourly') {
215
+ this.pool.nextAt = '';
216
+ return; // the hourly tick does it
217
+ }
218
+ const at = nextDailyRun(clock, new Date(this.now()), this.jitter());
219
+ this.pool.nextAt = at.toISOString();
220
+ this.timers.pool = setTimeout(() => {
221
+ this.tryPoolUpdate(at.getTime() + 24 * HOUR_MS);
222
+ this.schedulePool();
223
+ }, Math.max(0, at.getTime() - this.now()));
224
+ this.timers.pool.unref?.();
225
+ }
226
+
227
+ /** Updates the pool now if nothing runs; else again every 15 minutes until `until`. */
228
+ tryPoolUpdate(until) {
229
+ clearTimeout(this.timers.poolRetry);
230
+ if (this.stopped || !this.workAgent.mountablePool()) return;
231
+ if (this.busyReason()) {
232
+ if (this.now() + POOL_RETRY_MS < until) {
233
+ this.timers.poolRetry = setTimeout(() => this.tryPoolUpdate(until), POOL_RETRY_MS);
234
+ this.timers.poolRetry.unref?.();
235
+ }
236
+ return;
237
+ }
238
+ this.updatePool({ say: (line) => this.log.info(line) }).catch(() => {});
239
+ }
240
+
241
+ /** Why a pull cannot start now ('' = it can): jobs running, or another process at the pool. */
242
+ busyReason() {
243
+ const running = this.jobs.runningIds().length;
244
+ if (running) return `${running} 个任务正在运行`;
245
+ const other = poolBusyInfo(this.paths);
246
+ if (other) return `进程 ${other.pid} 正在${other.kind === 'init' ? '下载' : '更新'}知识仓`;
247
+ return '';
248
+ }
249
+
250
+ /** A terminal asked: as soon as nothing runs. */
251
+ requestPoolUpdate() {
252
+ this.poolRequested = true;
253
+ }
254
+
255
+ takeRequest() {
256
+ if (!this.poolRequested && !poolUpdateRequested(this.paths)) return;
257
+ if (this.busyReason()) return;
258
+ this.poolRequested = false;
259
+ clearPoolUpdateRequest(this.paths);
260
+ this.log.info('按终端里 work-agent-runner update 的请求更新知识仓');
261
+ this.updatePool({ say: (line) => this.log.info(line) }).catch(() => {});
262
+ }
263
+
264
+ /**
265
+ * `git pull` in every repository of the pool, if no job runs (checked here,
266
+ * in the same tick as workAgent.updatePool() makes new jobs wait); else it is
267
+ * queued for when nothing runs: { queued: true, reason }.
268
+ */
269
+ updatePool({ say = () => {} } = {}) {
270
+ return this.exclusive(async () => {
271
+ if (!this.workAgent.mountablePool()) return { skipped: '没有知识仓' };
272
+ const busy = this.busyReason();
273
+ if (busy) {
274
+ this.poolRequested = true;
275
+ this.changed();
276
+ return { queued: true, reason: busy };
277
+ }
278
+ this.pool.running = true;
279
+ this.changed();
280
+ try {
281
+ await this.workAgent.updatePool({ say });
282
+ this.pool.result = 'ok';
283
+ this.pool.error = '';
284
+ this.pool.lastOkAt = this.now();
285
+ } catch (error) {
286
+ this.pool.result = 'failed';
287
+ this.pool.error = error.message;
288
+ this.log.warn(`知识仓更新失败:${error.message}`);
289
+ } finally {
290
+ this.stateCache = null;
291
+ this.pool.running = false;
292
+ this.pool.lastRunAt = iso(this.now());
293
+ this.changed();
294
+ }
295
+ await this.recheck().catch(() => {});
296
+ return { result: this.pool.result, error: this.pool.error };
297
+ });
298
+ }
299
+
300
+ // ---- checks and housekeeping -----------------------------------------------------
301
+
302
+ /** The dependency and sandbox check (recheck()); resolves what it returned. */
303
+ runChecks() {
304
+ return this.exclusive(async () => {
305
+ this.stateCache = null;
306
+ const result = await this.recheck();
307
+ this.checks.lastRunAt = iso(this.now());
308
+ this.changed();
309
+ return result;
310
+ });
311
+ }
312
+
313
+ async hourly() {
314
+ if (this.stopped) return;
315
+ await this.runChecks().catch((error) => this.log.warn(`定期检查失败:${error.message}`));
316
+ if (this.settings().maintenance.poolUpdateAt === 'hourly') this.tryPoolUpdate(this.now() + HOUR_MS);
317
+ this.housekeeping();
318
+ }
319
+
320
+ housekeeping() {
321
+ this.trashLeft = retryTrash(this.trashDir).length;
322
+ this.pruneArchive();
323
+ this.changed();
324
+ }
325
+
326
+ /**
327
+ * archive/<runId>/ older than limits.archiveDays (all of it when archiving
328
+ * is off); then the oldest until the rest fits ARCHIVE_MAX_BYTES.
329
+ */
330
+ pruneArchive({ maxBytes = ARCHIVE_MAX_BYTES } = {}) {
331
+ const days = this.settings().limits.archiveDays;
332
+ let names = [];
333
+ try {
334
+ names = fs.readdirSync(this.archiveDir);
335
+ } catch {
336
+ return;
337
+ }
338
+ const cutoff = this.now() - days * 86_400_000;
339
+ const kept = [];
340
+ for (const name of names) {
341
+ const dir = path.join(this.archiveDir, name);
342
+ let finished = 0;
343
+ try {
344
+ finished = Date.parse(JSON.parse(fs.readFileSync(path.join(dir, 'meta.json'), 'utf8')).finishedAt) || fs.statSync(dir).mtimeMs;
345
+ } catch {
346
+ try {
347
+ finished = fs.statSync(dir).mtimeMs;
348
+ } catch {
349
+ continue;
350
+ }
351
+ }
352
+ if (!days || finished < cutoff) removeTree(dir);
353
+ else kept.push({ dir, finished, bytes: treeBytes(dir) });
354
+ }
355
+ let total = kept.reduce((sum, item) => sum + item.bytes, 0);
356
+ for (const item of kept.sort((a, b) => a.finished - b.finished)) {
357
+ if (total <= maxBytes) break;
358
+ removeTree(item.dir);
359
+ total -= item.bytes;
360
+ }
361
+ }
362
+
363
+ /** What has gone wrong and is still wrong: [{ code, message }]. */
364
+ degraded() {
365
+ const problems = [];
366
+ const repo = this.repoState();
367
+ if (!repo.ok) problems.push({ code: 'E5101', message: `work-agent 仓库不可用:${repo.reason}` });
368
+ if (repo.repos > 0) {
369
+ const last = Math.max(this.pool.lastOkAt || 0, repo.poolFetchedAt || 0);
370
+ if (last && this.now() - last > POOL_STALE_DAYS * 86_400_000) {
371
+ problems.push({ code: 'E5202', message: `知识仓已 ${Math.floor((this.now() - last) / 86_400_000)} 天没有更新${this.pool.error ? `(${this.pool.error})` : ''}` });
372
+ } else if (this.pool.result === 'failed') {
373
+ problems.push({ code: 'E5201', message: `知识仓上次更新失败:${this.pool.error}` });
374
+ }
375
+ }
376
+ if (this.trashLeft) problems.push({ code: 'E5301', message: `${this.trashDir} 里有 ${this.trashLeft} 个目录删不掉` });
377
+ return problems;
378
+ }
379
+
380
+ snapshot() {
381
+ const repo = this.repoState();
382
+ return {
383
+ repo: { commit: repo.commit || '', committedAt: repo.committedAt || '', ...this.repo },
384
+ pool: {
385
+ repos: repo.repos || 0,
386
+ updatedAt: iso(repo.poolFetchedAt),
387
+ requested: this.poolRequested || Boolean(poolUpdateRequested(this.paths)),
388
+ ...this.pool,
389
+ lastOkAt: iso(this.pool.lastOkAt),
390
+ },
391
+ checks: { ...this.checks },
392
+ };
393
+ }
394
+ }
package/lib/sandbox.mjs CHANGED
@@ -125,10 +125,21 @@ export function sandboxSettings({ workDir, realHome, readAllow = [], writeAllow
125
125
  * $WORK_AGENT_HOME and the pool. Not claude-home:
126
126
  * claude's own state is none of the model's business.
127
127
  * deny the program's own files and pool writes.
128
+ * A per-run layout (docs/design.md 2.6) has its own WORK_AGENT_HOME (wah/):
129
+ * its logs/tmp/docs are the writable ones, and the shared home stays
130
+ * readable for what wah/ links to (essential-repos.txt…). `denySharedWork`
131
+ * (server execution machines, where other users' jobs ran before) closes the
132
+ * shared logs/tmp/docs to both kinds of tool. `controlDirs`: the local control
133
+ * interface (lib/control.mjs); `privateDirs`: the program's own records
134
+ * (archive/, trash/, state/, logs/) — never a job's business (design 3.15).
128
135
  */
129
- export function runAllowances(layout, { realHome, pathEnv = '', caPaths = [], pool = '', paths = null }) {
136
+ export function runAllowances(
137
+ layout,
138
+ { realHome, pathEnv = '', caPaths = [], pool = '', paths = null, denySharedWork = false, controlDirs = [], privateDirs = [] },
139
+ ) {
130
140
  const runDirs = [layout.workDir, layout.homeDir, layout.tmpDir, layout.configDir].map((dir) => realpathOr(dir));
131
141
  const workAgentHome = layout.workAgentHome ? realpathOr(layout.workAgentHome) : '';
142
+ const sharedHome = layout.sharedWorkAgentHome && layout.sharedWorkAgentHome !== layout.workAgentHome ? realpathOr(layout.sharedWorkAgentHome) : '';
132
143
  // Writable: this run, and the three directories the Skills write into. Not
133
144
  // the work-agent home itself and not the pool — a job must not be able to
134
145
  // delete the repositories it shares with the user's own work-agent.
@@ -139,6 +150,7 @@ export function runAllowances(layout, { realHome, pathEnv = '', caPaths = [], po
139
150
  const readAllow = [
140
151
  ...writeAllow,
141
152
  ...(workAgentHome ? [workAgentHome] : []),
153
+ ...(sharedHome ? [sharedHome] : []),
142
154
  ...(pool ? [realpathOr(pool)] : []),
143
155
  ...homeReadAllow({ realHome, pathEnv, caPaths }),
144
156
  ];
@@ -149,9 +161,18 @@ export function runAllowances(layout, { realHome, pathEnv = '', caPaths = [], po
149
161
  const toolRead = [
150
162
  ...toolWrite,
151
163
  ...(workAgentHome ? [workAgentHome] : []),
164
+ ...(sharedHome ? [sharedHome] : []),
152
165
  ...(pool ? [realpathOr(pool)] : []),
153
166
  ];
154
167
  const deny = [];
168
+ const denyBoth = (dir) => {
169
+ for (const at of new Set([path.resolve(dir), realpathOr(dir)])) {
170
+ deny.push(`Read(//${fromRoot(at)}/**)`, `Read(//${fromRoot(at)})`, `Edit(//${fromRoot(at)}/**)`, `Edit(//${fromRoot(at)})`);
171
+ }
172
+ };
173
+ // Other users' Skill logs, scratch and deliverables (server execution machines).
174
+ if (denySharedWork && sharedHome) for (const name of ['logs', 'tmp', 'docs']) denyBoth(path.join(sharedHome, name));
175
+ for (const dir of [...controlDirs, ...privateDirs]) if (dir) denyBoth(dir);
155
176
  if (paths) {
156
177
  // The access token, and the clone every job copies from: by the path the
157
178
  // program uses and by the real one, so a home behind a symlink (/home ->
@@ -236,11 +257,19 @@ export function newRunDir(runsDir, prefix) {
236
257
 
237
258
  /**
238
259
  * Creates the run directory tree (0700) and returns its paths. `workAgentHome`
239
- * is the program's persistent WORK_AGENT_HOME; the job's HOME gets a
240
- * `.work-agent` symlink to it, so a Skill's `~/.work-agent/...` and
241
- * `$WORK_AGENT_HOME` are one directory.
260
+ * is the program's persistent WORK_AGENT_HOME (shared with the user's own
261
+ * work-agent). `isolation`:
262
+ * 'shared' the job's HOME gets a `.work-agent` symlink to it, so a Skill's
263
+ * `~/.work-agent/...` and `$WORK_AGENT_HOME` are one directory
264
+ * 'per-run' the job gets a WORK_AGENT_HOME of its own, <run>/wah/ (docs/design.md
265
+ * 2.6): logs/ tmp/ docs/ are its own; everything else of the shared
266
+ * home (essential-repos.txt…) is linked read-only, ascend-repos to
267
+ * `pool`, work-agent.py to the run's copy of the script; HOME's
268
+ * `.work-agent` points at wah/. What it leaves is merged or archived
269
+ * by the job manager when it ends.
270
+ * `layout.workAgentHome` is what the job gets; `layout.sharedWorkAgentHome` the shared one.
242
271
  */
243
- export function createRunLayout(runDir, { workAgentHome = '' } = {}) {
272
+ export function createRunLayout(runDir, { workAgentHome = '', isolation = 'shared', pool = '' } = {}) {
244
273
  fs.mkdirSync(runDir, { recursive: true, mode: 0o700 });
245
274
  const layout = {
246
275
  runDir,
@@ -251,6 +280,8 @@ export function createRunLayout(runDir, { workAgentHome = '' } = {}) {
251
280
  homeDir: path.join(runDir, '.home'),
252
281
  tmpDir: path.join(runDir, '.tmp'),
253
282
  workAgentHome,
283
+ sharedWorkAgentHome: workAgentHome,
284
+ isolation: workAgentHome && isolation === 'per-run' ? 'per-run' : 'shared',
254
285
  };
255
286
  layout.skillsDir = path.join(layout.workDir, '.claude', 'skills');
256
287
  // The Skills' `/tmp/work-agent` (clones, intermediate files): deleted with the run.
@@ -258,7 +289,25 @@ export function createRunLayout(runDir, { workAgentHome = '' } = {}) {
258
289
  for (const dir of [layout.configDir, layout.workDir, layout.homeDir, layout.tmpDir, layout.scratchDir]) {
259
290
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
260
291
  }
261
- if (workAgentHome) {
292
+ if (layout.isolation === 'per-run') {
293
+ const wah = path.join(runDir, 'wah');
294
+ for (const name of ['logs', 'tmp', 'docs']) fs.mkdirSync(path.join(wah, name), { recursive: true, mode: 0o700 });
295
+ let shared = [];
296
+ try {
297
+ shared = fs.readdirSync(workAgentHome);
298
+ } catch {
299
+ // No shared home yet: nothing to link.
300
+ }
301
+ for (const name of shared) {
302
+ if (['logs', 'tmp', 'docs', 'ascend-repos', 'work-agent.py'].includes(name)) continue;
303
+ fs.symlinkSync(path.join(path.resolve(workAgentHome), name), path.join(wah, name));
304
+ }
305
+ if (pool) fs.symlinkSync(realpathOr(pool), path.join(wah, 'ascend-repos'));
306
+ // The run's own copy of the script (inside the run, readable by the job).
307
+ fs.symlinkSync(path.join('..', 'work-agent', 'scripts', 'work-agent.py'), path.join(wah, 'work-agent.py'));
308
+ fs.symlinkSync(path.join('..', 'wah'), path.join(layout.homeDir, '.work-agent'));
309
+ layout.workAgentHome = wah;
310
+ } else if (workAgentHome) {
262
311
  fs.symlinkSync(path.resolve(workAgentHome), path.join(layout.homeDir, '.work-agent'));
263
312
  }
264
313
  return layout;