@online-tools/work-agent-runner 0.0.3-alpha-1 → 0.0.5-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.
@@ -1,8 +1,10 @@
1
1
  // The work-agent repository on this machine: the Skill source for every job,
2
2
  // and the optional AscendC knowledge pool (lib/config.mjs owns the paths):
3
3
  //
4
- // ~/.work-agent-runner/work-agent/ the clone, tracking origin/main
5
- // ~/.work-agent-runner/work-agent.lock lock: a terminal `update` vs the service
4
+ // ~/.work-agent-runner/work-agent/ the clone, tracking origin/main;
5
+ // .git/work-agent-runner.json marks it
6
+ // as this program's
7
+ // ~/.work-agent-runner/work-agent.lock the clone's lock (a terminal `update` vs the service)
6
8
  // ~/.work-agent/ work-agent's own home = the
7
9
  // WORK_AGENT_HOME of every job
8
10
  // ├ ascend-repos/ the repository pool, built by
@@ -20,16 +22,28 @@
20
22
  // development and tests) may point it at a mirror, and clone() logs the URL it
21
23
  // used.
22
24
  //
23
- // Jobs read the clone (a copy per run) while the hourly refresh may rewrite it,
24
- // and `update` in a terminal is a second process, so every operation runs
25
- // inside both the in-process queue and the file lock.
25
+ // Ownership (docs/design.md 3.8): only a clone this program made (marked, or
26
+ // found at its default place in the program's home) is ever replaced or
27
+ // deleted. A workAgentRepoDir pointed at anything else — a project of the
28
+ // user's, another repository, their own work-agent with local commits — is
29
+ // reported and left exactly as it is.
30
+ //
31
+ // Concurrency: clone operations (refresh, a job's copy) run one at a time in
32
+ // this process and under work-agent.lock across processes; a job waits for
33
+ // the lock instead of failing. Knowledge-pool operations run one at a time on
34
+ // their own queue and never hold the clone's lock (a download can take hours);
35
+ // work-agent.py's own lock covers other processes. While the pool is being
36
+ // updated (git pull) — here or by a terminal `update` (state/pool-busy) —
37
+ // jobs wait before they start (waitForPoolIdle).
26
38
 
27
39
  import { spawn, spawnSync } from 'node:child_process';
40
+ import crypto from 'node:crypto';
28
41
  import fs from 'node:fs';
29
42
  import os from 'node:os';
30
43
  import path from 'node:path';
31
44
 
32
- import { LockedError, acquireLock } from './lock.mjs';
45
+ import { readJsonFile, removeTree, writeJsonAtomic } from './fs-safe.mjs';
46
+ import { LockedError, acquireLockWaiting, isRunnerAlive } from './lock.mjs';
33
47
  import { CA_VARIABLES, PROXY_VARIABLES, prepareWorkAgentHome } from './sandbox.mjs';
34
48
  import { copyTreeDetached, rewriteSkillPaths } from './skill-tree.mjs';
35
49
 
@@ -51,7 +65,11 @@ const ASCEND_ENTRY = {
51
65
  // directory with something in it — not a particular Skill, which work-agent is
52
66
  // free to rename.
53
67
  const SKILLS_SUBDIR = path.join('.claude', 'skills');
54
- const GIT_TIMEOUT_MS = 10 * 60_000;
68
+ // The repository is a few MB: these are generous, and run without blocking
69
+ // the program (heartbeats and job output keep flowing).
70
+ const FETCH_TIMEOUT_MS = 2 * 60_000;
71
+ const CLONE_TIMEOUT_MS = 5 * 60_000;
72
+ const LOCAL_GIT_TIMEOUT_MS = 30_000;
55
73
  // The essential list is large and grows with upstream, cloned 8 at a time;
56
74
  // work-agent.py gives each git operation 1800 s, so never be the one that kills
57
75
  // it first. The free-space figure is a floor, not a claim about the list's size.
@@ -61,14 +79,10 @@ const ESSENTIAL_FILE = 'essential-repos.txt';
61
79
  const KILL_GRACE_MS = 5000;
62
80
  // work-agent.py cleanup: tmp/ is emptied and logs older than this are dropped.
63
81
  const LOG_DAYS = 30;
64
-
65
- function realpathOr(value) {
66
- try {
67
- return fs.realpathSync(value);
68
- } catch {
69
- return path.resolve(value);
70
- }
71
- }
82
+ /** How long a job waits for another process to be done with the clone. */
83
+ export const CLONE_LOCK_WAIT_MS = 10 * 60_000;
84
+ /** The ownership marker, inside .git: git ignores it and a job's copy skips .git. */
85
+ export const CLONE_MARKER = 'work-agent-runner.json';
72
86
 
73
87
  function exists(file) {
74
88
  try {
@@ -79,6 +93,8 @@ function exists(file) {
79
93
  }
80
94
  }
81
95
 
96
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
97
+
82
98
  /**
83
99
  * git's environment: PATH and HOME (for ~/.gitconfig), the proxy and CA
84
100
  * variables this machine passes through (corporate machines need them, and the
@@ -100,7 +116,12 @@ function gitEnv(env) {
100
116
  // repos into the Skill tree (work-agent has submodules inside .claude/skills).
101
117
  const GIT_CONFIG = ['-c', 'credential.helper=', '-c', 'submodule.recurse=false'];
102
118
 
103
- function git(args, { cwd, env = process.env, timeout = GIT_TIMEOUT_MS } = {}) {
119
+ function lastLine(text) {
120
+ return String(text || '').trim().split('\n').filter(Boolean).pop() || '';
121
+ }
122
+
123
+ /** Quick local queries (rev-parse, log, status): synchronous. */
124
+ function git(args, { cwd, env = process.env, timeout = LOCAL_GIT_TIMEOUT_MS } = {}) {
104
125
  const result = spawnSync('git', [...GIT_CONFIG, ...args], {
105
126
  cwd,
106
127
  env: gitEnv(env),
@@ -108,15 +129,48 @@ function git(args, { cwd, env = process.env, timeout = GIT_TIMEOUT_MS } = {}) {
108
129
  timeout,
109
130
  stdio: ['ignore', 'pipe', 'pipe'],
110
131
  });
111
- const stderr = String(result.stderr || '').trim();
112
132
  return {
113
133
  ok: !result.error && result.status === 0,
114
134
  stdout: String(result.stdout || '').trim(),
115
- stderr,
116
- reason: result.error ? result.error.message : stderr.split('\n').filter(Boolean).pop() || `git ${args[0]} 退出码 ${result.status}`,
135
+ reason: result.error ? result.error.message : lastLine(result.stderr) || `git ${args[0]} 退出码 ${result.status}`,
117
136
  };
118
137
  }
119
138
 
139
+ /** Anything that may wait on the network (clone, fetch, merge): asynchronous. */
140
+ function gitAsync(args, { cwd, env = process.env, timeout }) {
141
+ return new Promise((resolve) => {
142
+ let child;
143
+ try {
144
+ child = spawn('git', [...GIT_CONFIG, ...args], { cwd, env: gitEnv(env), stdio: ['ignore', 'pipe', 'pipe'] });
145
+ } catch (error) {
146
+ resolve({ ok: false, stdout: '', reason: error.message });
147
+ return;
148
+ }
149
+ let stdout = '';
150
+ let stderr = '';
151
+ let timedOut = false;
152
+ const timer = setTimeout(() => {
153
+ timedOut = true;
154
+ child.kill('SIGKILL');
155
+ }, timeout);
156
+ child.stdout.on('data', (chunk) => {
157
+ stdout += chunk;
158
+ });
159
+ child.stderr.on('data', (chunk) => {
160
+ stderr += chunk;
161
+ });
162
+ child.once('error', (error) => {
163
+ clearTimeout(timer);
164
+ resolve({ ok: false, stdout: '', reason: error.message });
165
+ });
166
+ child.once('close', (code) => {
167
+ clearTimeout(timer);
168
+ const reason = timedOut ? `git ${args[0]} 超过 ${Math.round(timeout / 1000)} 秒,已停止` : lastLine(stderr) || `git ${args[0]} 退出码 ${code}`;
169
+ resolve({ ok: code === 0 && !timedOut, stdout: stdout.trim(), reason });
170
+ });
171
+ });
172
+ }
173
+
120
174
  /** Bytes free on the filesystem holding `dir` (its nearest existing parent); 0 when unknown. */
121
175
  export function freeBytes(dir) {
122
176
  let target = path.resolve(dir);
@@ -142,14 +196,73 @@ function killGroup(child, signal) {
142
196
  }
143
197
  }
144
198
 
199
+ function hasSkillTree(dir) {
200
+ try {
201
+ return fs.readdirSync(path.join(dir, SKILLS_SUBDIR)).some((name) => !name.startsWith('.'));
202
+ } catch {
203
+ return false;
204
+ }
205
+ }
206
+
207
+ // ---- The knowledge pool between processes ----------------------------------------
208
+ // A terminal's `update` / `setup` marks the pool busy (state/pool-busy) so the
209
+ // service holds new jobs while a `git pull` runs and postpones its own update;
210
+ // with the service running, a terminal `update` leaves the pull to it
211
+ // (state/requests/pool-update).
212
+
213
+ /** The knowledge-pool operation another process is running: { pid, kind: 'update' | 'init', startedAt }, or null. */
214
+ export function poolBusyInfo(paths) {
215
+ if (!paths?.poolBusyFile) return null;
216
+ const info = readJsonFile(paths.poolBusyFile);
217
+ const pid = Number(info?.pid);
218
+ if (!info || pid === process.pid || !isRunnerAlive(pid)) return null;
219
+ return { pid, kind: info.kind === 'init' ? 'init' : 'update', startedAt: String(info.startedAt || '') };
220
+ }
221
+
222
+ /** Marks this process's knowledge-pool operation; returns the function that clears the mark. */
223
+ export function markPoolBusy(paths, kind) {
224
+ fs.mkdirSync(path.dirname(paths.poolBusyFile), { recursive: true, mode: 0o700 });
225
+ writeJsonAtomic(paths.poolBusyFile, { pid: process.pid, kind, startedAt: new Date().toISOString() });
226
+ return () => {
227
+ if (Number(readJsonFile(paths.poolBusyFile)?.pid) === process.pid) fs.rmSync(paths.poolBusyFile, { force: true });
228
+ };
229
+ }
230
+
231
+ function requestFile(paths) {
232
+ return path.join(paths.requestsDir, 'pool-update');
233
+ }
234
+
235
+ /** Asks the running service to update the knowledge pool as soon as no job runs. */
236
+ export function requestPoolUpdate(paths) {
237
+ fs.mkdirSync(paths.requestsDir, { recursive: true, mode: 0o700 });
238
+ writeJsonAtomic(requestFile(paths), { requestedAt: new Date().toISOString(), pid: process.pid });
239
+ }
240
+
241
+ /** When a pool update was requested (ISO time), or ''. */
242
+ export function poolUpdateRequested(paths) {
243
+ const request = readJsonFile(requestFile(paths));
244
+ return request ? String(request.requestedAt || 'unknown') : '';
245
+ }
246
+
247
+ export function clearPoolUpdateRequest(paths) {
248
+ fs.rmSync(requestFile(paths), { force: true });
249
+ }
250
+
145
251
  export class WorkAgent {
146
- /** `paths` from configPaths(); `repoUrl` only from the machine's own config. */
147
- constructor({ paths, env = process.env, log = null, repoUrl = REPO_URL } = {}) {
252
+ /**
253
+ * `paths` from configPaths() / withRepoPaths(); `repoUrl` only from the
254
+ * machine's own config; `lockWaitMs`: how long clone operations wait for
255
+ * another process (jobs: 10 minutes; a terminal command: less).
256
+ */
257
+ constructor({ paths, env = process.env, log = null, repoUrl = REPO_URL, lockWaitMs = CLONE_LOCK_WAIT_MS } = {}) {
148
258
  this.paths = paths;
149
259
  this.env = env;
150
260
  this.log = log;
151
261
  this.repoUrl = repoUrl || REPO_URL;
152
- this.queue = Promise.resolve();
262
+ this.lockWaitMs = lockWaitMs;
263
+ this.cloneQueue = Promise.resolve();
264
+ this.poolQueue = Promise.resolve();
265
+ this.poolUpdates = 0;
153
266
  this.child = null;
154
267
  this.stopped = false;
155
268
  }
@@ -166,14 +279,24 @@ export class WorkAgent {
166
279
  return path.join(this.paths.repoDir, SKILLS_SUBDIR);
167
280
  }
168
281
 
169
- /** Runs `fn` alone: after anything queued here, and not while another process holds the lock. */
170
- run(fn) {
171
- const next = this.queue.then(async () => {
282
+ /** A `git pull` in the pool is running or about to (updatePool). */
283
+ get poolUpdating() {
284
+ return this.poolUpdates > 0;
285
+ }
286
+
287
+ /**
288
+ * Runs `fn` alone among clone operations: after anything queued here, and
289
+ * holding work-agent.lock, for which it waits up to `waitMs`.
290
+ */
291
+ withClone(fn, { waitMs = this.lockWaitMs } = {}) {
292
+ const next = this.cloneQueue.then(async () => {
293
+ fs.mkdirSync(path.dirname(this.paths.repoLockFile), { recursive: true, mode: 0o700 });
172
294
  let lock;
173
295
  try {
174
- // First run: the data directory does not exist yet.
175
- fs.mkdirSync(path.dirname(this.paths.repoLockFile), { recursive: true, mode: 0o700 });
176
- lock = acquireLock(this.paths.repoLockFile);
296
+ lock = await acquireLockWaiting(this.paths.repoLockFile, {
297
+ timeoutMs: waitMs,
298
+ onWait: (pid) => this.note('info', `work-agent 仓库正被另一个进程使用(pid ${pid}),等待它结束……`),
299
+ });
177
300
  } catch (error) {
178
301
  if (error instanceof LockedError) {
179
302
  throw new Error(`work-agent 仓库正被另一个进程使用(pid ${error.pid}),请稍后再试`);
@@ -187,41 +310,119 @@ export class WorkAgent {
187
310
  }
188
311
  });
189
312
  // Keep the chain alive whatever this call does.
190
- this.queue = next.then(
313
+ this.cloneQueue = next.then(
191
314
  () => {},
192
315
  () => {},
193
316
  );
194
317
  return next;
195
318
  }
196
319
 
320
+ /** The former name of withClone(), for callers that still use it. */
321
+ run(fn) {
322
+ return this.withClone(fn);
323
+ }
324
+
325
+ /** Runs `fn` alone among knowledge-pool operations in this process. */
326
+ withPool(fn) {
327
+ const next = this.poolQueue.then(fn);
328
+ this.poolQueue = next.then(
329
+ () => {},
330
+ () => {},
331
+ );
332
+ return next;
333
+ }
334
+
335
+ isDefaultLocation() {
336
+ return Boolean(this.paths.defaultRepoDir) && path.resolve(this.paths.repoDir) === path.resolve(this.paths.defaultRepoDir);
337
+ }
338
+
339
+ /** A clean clone of work-agent's main from this URL, with nothing local to lose. */
340
+ isCleanClone() {
341
+ const { repoDir } = this.paths;
342
+ if (!exists(path.join(repoDir, '.git'))) return false;
343
+ const query = (args) => git(args, { cwd: repoDir, env: this.env });
344
+ const origin = query(['remote', 'get-url', 'origin']);
345
+ if (!origin.ok || origin.stdout !== this.repoUrl) return false;
346
+ const branch = query(['rev-parse', '--abbrev-ref', 'HEAD']);
347
+ if (!branch.ok || branch.stdout !== REPO_BRANCH) return false;
348
+ const status = query(['status', '--porcelain']);
349
+ if (!status.ok || status.stdout !== '') return false;
350
+ const ahead = query(['rev-list', '--count', `origin/${REPO_BRANCH}..HEAD`]);
351
+ return ahead.ok && ahead.stdout === '0';
352
+ }
353
+
354
+ /**
355
+ * Whose the clone directory is: { kind: 'absent' } (missing or empty: clone
356
+ * there), { kind: 'owned', adopt? } (marked; or a clone at the default place,
357
+ * or a clean work-agent clone, made by an earlier version: mark it), or
358
+ * { kind: 'foreign', reason } — never changed, never deleted.
359
+ */
360
+ ownership() {
361
+ const { repoDir } = this.paths;
362
+ let stat;
363
+ try {
364
+ stat = fs.lstatSync(repoDir);
365
+ } catch {
366
+ return { kind: 'absent' };
367
+ }
368
+ const foreign = (what) => ({
369
+ kind: 'foreign',
370
+ reason:
371
+ `${repoDir} ${what},不是本程序创建的 work-agent 仓库,程序不会改动或删除它;` +
372
+ '请在 config.json 里把 workAgentRepoDir 改成一个不存在的或空的目录(或删掉这一项,使用默认位置)',
373
+ });
374
+ if (stat.isSymbolicLink()) return foreign('是符号链接');
375
+ if (!stat.isDirectory()) return foreign('不是目录');
376
+ if (exists(path.join(repoDir, '.git', CLONE_MARKER))) return { kind: 'owned' };
377
+ let names = [];
378
+ try {
379
+ names = fs.readdirSync(repoDir);
380
+ } catch {
381
+ return foreign('无法读取');
382
+ }
383
+ if (!names.length) return { kind: 'absent' };
384
+ if (this.isDefaultLocation() || this.isCleanClone()) return { kind: 'owned', adopt: true };
385
+ return foreign('已有内容');
386
+ }
387
+
388
+ markOwned(dir = this.paths.repoDir) {
389
+ writeJsonAtomic(path.join(dir, '.git', CLONE_MARKER), {
390
+ kind: 'work-agent-clone',
391
+ repoUrl: this.repoUrl,
392
+ programHome: this.paths.baseDir || '',
393
+ markedAt: new Date().toISOString(),
394
+ });
395
+ }
396
+
197
397
  /**
198
398
  * What this machine has, read without the lock (callers display it):
199
- * { ok, reason, commit, committedAt, repos, ascend, incomplete, poolFetchedAt }.
399
+ * { ok, reason, commit, committedAt, repos, ascend, incomplete, poolFetchedAt }
400
+ * (and foreign: true when the configured directory is not this program's).
200
401
  */
201
402
  state() {
202
403
  const { repoDir } = this.paths;
203
404
  const pool = { ...this.poolState(), poolFetchedAt: this.poolFetchedAt() };
405
+ const own = this.ownership();
406
+ if (own.kind === 'foreign') {
407
+ return { ok: false, reason: own.reason, commit: '', committedAt: '', foreign: true, ...pool };
408
+ }
204
409
  if (!exists(path.join(repoDir, '.git'))) {
205
410
  return { ok: false, reason: '未下载 work-agent 仓库', commit: '', committedAt: '', ...pool };
206
411
  }
207
412
  if (!this.hasSkills()) {
208
413
  return { ok: false, reason: 'work-agent 仓库不完整(没有 .claude/skills)', commit: '', committedAt: '', ...pool };
209
414
  }
210
- const head = git(['rev-parse', 'HEAD'], { cwd: repoDir, env: this.env, timeout: 30_000 });
415
+ const head = git(['rev-parse', 'HEAD'], { cwd: repoDir, env: this.env });
211
416
  if (!head.ok || !/^[0-9a-f]{40}$/.test(head.stdout)) {
212
417
  return { ok: false, reason: 'work-agent 仓库损坏', commit: '', committedAt: '', ...pool };
213
418
  }
214
- const when = git(['log', '-1', '--format=%cI'], { cwd: repoDir, env: this.env, timeout: 30_000 });
419
+ const when = git(['log', '-1', '--format=%cI'], { cwd: repoDir, env: this.env });
215
420
  return { ok: true, reason: '', commit: head.stdout, committedAt: when.ok ? when.stdout : '', ...pool };
216
421
  }
217
422
 
218
423
  /** Whether the clone holds a Skill tree to copy. */
219
424
  hasSkills() {
220
- try {
221
- return fs.readdirSync(this.skillsDir).some((name) => !name.startsWith('.'));
222
- } catch {
223
- return false;
224
- }
425
+ return hasSkillTree(this.paths.repoDir);
225
426
  }
226
427
 
227
428
  /** The repositories the pool holds, by name. */
@@ -300,31 +501,47 @@ export class WorkAgent {
300
501
  * Makes the clone current: clone when missing or broken, otherwise fetch and
301
502
  * fast-forward. A fetch that fails keeps the commit the machine already has.
302
503
  * A fast-forward that fails (dirty tree, rewritten upstream) re-clones rather
303
- * than `reset --hard`, which would silently adopt a force-push. Never throws
304
- * — returns state() with a reason. Only through run(), so a job's copy never
305
- * sees a tree being rewritten.
504
+ * than `reset --hard`, which would silently adopt a force-push. A new clone
505
+ * replaces the old one only once it is complete, so a failed one leaves the
506
+ * machine with what it had. A directory that is not this program's is never
507
+ * touched. Never throws — returns state() with a reason.
306
508
  */
307
- refresh() {
308
- return this.run(() => this.refreshNow());
509
+ refresh({ waitMs } = {}) {
510
+ return this.withClone(() => this.refreshNow(), { waitMs });
309
511
  }
310
512
 
311
- refreshNow() {
513
+ async refreshNow() {
312
514
  const { repoDir } = this.paths;
515
+ this.removeLeftovers();
516
+ const own = this.ownership();
517
+ if (own.kind === 'foreign') {
518
+ this.note('warn', own.reason);
519
+ return this.state();
520
+ }
313
521
  const before = this.state();
314
522
  if (!before.ok) {
315
- return this.clone(before.reason === '未下载 work-agent 仓库' ? '' : before.reason);
523
+ return this.reclone(before.reason === '未下载 work-agent 仓库' ? '' : before.reason);
316
524
  }
317
- const fetched = git(['fetch', '--no-recurse-submodules', '--prune', 'origin', REPO_BRANCH], { cwd: repoDir, env: this.env });
525
+ if (own.adopt) this.markOwned();
526
+ const fetched = await gitAsync(['fetch', '--no-recurse-submodules', '--prune', 'origin', REPO_BRANCH], {
527
+ cwd: repoDir,
528
+ env: this.env,
529
+ timeout: FETCH_TIMEOUT_MS,
530
+ });
318
531
  if (!fetched.ok) {
319
- this.note('warn', `无法从 ${REPO_URL} 拉取更新(${fetched.reason}),继续使用本地的 ${before.commit.slice(0, 7)}`);
532
+ this.note('warn', `无法从 ${this.repoUrl} 拉取更新(${fetched.reason}),继续使用本地的 ${before.commit.slice(0, 7)}`);
320
533
  return { ...before, fetchReason: fetched.reason };
321
534
  }
322
- const merged = git(['merge', '--ff-only', '--no-recurse-submodules', 'FETCH_HEAD'], { cwd: repoDir, env: this.env });
535
+ const merged = await gitAsync(['merge', '--ff-only', '--no-recurse-submodules', 'FETCH_HEAD'], {
536
+ cwd: repoDir,
537
+ env: this.env,
538
+ timeout: LOCAL_GIT_TIMEOUT_MS,
539
+ });
323
540
  if (!merged.ok) {
324
541
  // Dirty tree or rewritten history: re-clone rather than reset --hard, which
325
542
  // would silently accept a force-push.
326
543
  this.note('warn', `work-agent 仓库无法快进(${merged.reason}),重新克隆`);
327
- return this.clone(merged.reason);
544
+ return this.reclone(merged.reason);
328
545
  }
329
546
  const after = this.state();
330
547
  if (after.commit && after.commit !== before.commit) {
@@ -333,51 +550,115 @@ export class WorkAgent {
333
550
  return after;
334
551
  }
335
552
 
336
- /** Replaces the clone. `why` only appears in the log. */
337
- clone(why = '') {
553
+ /** Earlier versions of this method's work in progress, next to the clone: .<name>.new-* / .old-*. */
554
+ removeLeftovers() {
555
+ const parent = path.dirname(this.paths.repoDir);
556
+ const name = path.basename(this.paths.repoDir);
557
+ let entries = [];
558
+ try {
559
+ entries = fs.readdirSync(parent);
560
+ } catch {
561
+ return;
562
+ }
563
+ const pattern = new RegExp(`^\\.${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\.(new|old)-[A-Za-z0-9]{6}$`);
564
+ for (const entry of entries) if (pattern.test(entry)) removeTree(path.join(parent, entry));
565
+ }
566
+
567
+ /** The clone that is there stays: its state, with why the new one could not be made. */
568
+ failed(reason) {
569
+ const current = this.state();
570
+ if (current.ok) {
571
+ this.note('warn', `${reason};继续使用本地的 ${current.commit.slice(0, 7)}`);
572
+ return { ...current, fetchReason: reason };
573
+ }
574
+ return { ...current, ok: false, reason };
575
+ }
576
+
577
+ /**
578
+ * A fresh clone next to the current one (.<name>.new-*), checked, marked,
579
+ * then swapped in with two renames; the old one is deleted afterwards. `why`
580
+ * only appears in the log.
581
+ */
582
+ async reclone(why = '') {
338
583
  const { repoDir } = this.paths;
339
- fs.mkdirSync(path.dirname(repoDir), { recursive: true, mode: 0o700 });
340
- fs.rmSync(repoDir, { recursive: true, force: true });
584
+ const parent = path.dirname(repoDir);
585
+ const name = path.basename(repoDir);
586
+ let temp;
587
+ try {
588
+ fs.mkdirSync(parent, { recursive: true, mode: 0o700 });
589
+ temp = fs.mkdtempSync(path.join(parent, `.${name}.new-`));
590
+ } catch (error) {
591
+ return this.failed(`无法在 ${parent} 下准备 work-agent 仓库:${error.message}`);
592
+ }
341
593
  this.note('info', `正在下载 work-agent 仓库(${this.repoUrl})${why ? `:${why}` : ''}`);
342
- const cloned = git(
343
- ['clone', '--quiet', '--single-branch', '--branch', REPO_BRANCH, '--no-recurse-submodules', this.repoUrl, repoDir],
344
- { env: this.env },
594
+ const cloned = await gitAsync(
595
+ ['clone', '--quiet', '--single-branch', '--branch', REPO_BRANCH, '--no-recurse-submodules', this.repoUrl, temp],
596
+ { env: this.env, timeout: CLONE_TIMEOUT_MS },
345
597
  );
346
598
  if (!cloned.ok) {
347
- fs.rmSync(repoDir, { recursive: true, force: true });
348
- return { ok: false, reason: `下载 work-agent 仓库失败:${cloned.reason}`, commit: '', committedAt: '', ...this.poolState() };
599
+ removeTree(temp);
600
+ return this.failed(`下载 work-agent 仓库失败:${cloned.reason}`);
349
601
  }
350
602
  // A rewritten URL (url.<x>.insteadOf) means the code came from somewhere else.
351
- const origin = git(['remote', 'get-url', 'origin'], { cwd: repoDir, env: this.env, timeout: 30_000 });
603
+ const origin = git(['remote', 'get-url', 'origin'], { cwd: temp, env: this.env });
352
604
  if (origin.ok && origin.stdout !== this.repoUrl) {
353
- fs.rmSync(repoDir, { recursive: true, force: true });
354
- return {
355
- ok: false,
356
- reason: `git 把仓库地址改写成了 ${origin.stdout}(检查 ~/.gitconfig 的 url.*.insteadOf),已删除`,
357
- commit: '',
358
- committedAt: '',
359
- ...this.poolState(),
360
- };
605
+ removeTree(temp);
606
+ return this.failed(`git 把仓库地址改写成了 ${origin.stdout}(检查 ~/.gitconfig 的 url.*.insteadOf),已删除`);
607
+ }
608
+ if (!hasSkillTree(temp)) {
609
+ removeTree(temp);
610
+ return this.failed('下载的 work-agent 仓库不完整(没有 .claude/skills)');
361
611
  }
612
+ this.markOwned(temp);
613
+ let old = '';
614
+ try {
615
+ let present = true;
616
+ try {
617
+ fs.lstatSync(repoDir);
618
+ } catch {
619
+ present = false;
620
+ }
621
+ if (present) {
622
+ old = path.join(parent, `.${name}.old-${crypto.randomBytes(3).toString('hex')}`);
623
+ fs.renameSync(repoDir, old);
624
+ }
625
+ fs.renameSync(temp, repoDir);
626
+ } catch (error) {
627
+ if (old && !exists(repoDir)) {
628
+ try {
629
+ fs.renameSync(old, repoDir);
630
+ old = '';
631
+ } catch {
632
+ // Left for removeLeftovers(); the state below says what is there.
633
+ }
634
+ }
635
+ removeTree(temp);
636
+ return this.failed(`无法替换 work-agent 仓库:${error.message}`);
637
+ }
638
+ if (old) removeTree(old);
362
639
  const state = this.state();
363
640
  if (state.ok) this.note('info', `work-agent 仓库就绪:${state.commit.slice(0, 7)}`);
364
- else fs.rmSync(repoDir, { recursive: true, force: true });
365
641
  return state;
366
642
  }
367
643
 
368
644
  /**
369
645
  * Copies the whole repository into `targetDir` — the job's working directory,
370
646
  * so it runs inside a work-agent repository of its own — and points the
371
- * Skills' `/tmp/work-agent` at `scratchDir` (the persistent WORK_AGENT_HOME).
372
- * `.git` is left out: the copy is for reading and running, not for pushing.
373
- * Returns the commit that was copied.
647
+ * Skills' `/tmp/work-agent` at `targets`: { logs } (the persistent
648
+ * $WORK_AGENT_HOME/logs) and { scratch } (the job's own scratch directory)
649
+ * — lib/skill-text.mjs rewriteWorkAgentPath. `.git` is left out: the copy is
650
+ * for reading and running, not for pushing; so is any symlink that leads out
651
+ * of the repository. Returns the commit that was copied.
374
652
  */
375
- copyRepoInto(targetDir, scratchDir) {
376
- return this.run(() => {
653
+ copyRepoInto(targetDir, targets) {
654
+ return this.withClone(() => {
377
655
  const state = this.state();
378
656
  if (!state.ok) throw new Error(state.reason);
379
- copyTreeDetached(this.paths.repoDir, targetDir);
380
- rewriteSkillPaths(path.join(targetDir, SKILLS_SUBDIR), scratchDir);
657
+ copyTreeDetached(this.paths.repoDir, targetDir, {
658
+ boundary: fs.realpathSync(this.paths.repoDir),
659
+ onSkip: (rel, target) => this.note('warn', `work-agent 仓库里的 ${rel} 指向仓库之外(${target}),没有复制给任务`),
660
+ });
661
+ rewriteSkillPaths(path.join(targetDir, SKILLS_SUBDIR), targets);
381
662
  return { commit: state.commit };
382
663
  });
383
664
  }
@@ -448,10 +729,11 @@ export class WorkAgent {
448
729
  * ($WORK_AGENT_HOME/essential-repos.txt, which init creates and the user may
449
730
  * edit) into the pool, or the ones `repos` names. Only ever from a terminal:
450
731
  * the list is large. `work-agent.py` skips repos that are already there, so
451
- * this is safe to re-run.
732
+ * this is safe to re-run — and it only adds repositories, so jobs keep
733
+ * running meanwhile.
452
734
  */
453
735
  initPool({ repos = null, say = () => {}, requireFreeBytes = POOL_FREE_BYTES } = {}) {
454
- return this.run(async () => {
736
+ return this.withPool(async () => {
455
737
  const state = this.state();
456
738
  if (!state.ok) throw new Error(state.reason);
457
739
  const free = freeBytes(this.paths.poolDir);
@@ -482,11 +764,12 @@ export class WorkAgent {
482
764
  * Updates every repository the pool holds — whatever they are, no names
483
765
  * involved (`work-agent.py update` pulls each local repo's master and skips
484
766
  * anything dirty or not from the CANN organisation). Never clones a new one.
485
- * Callers run it only when no job is running: `git pull` must not replace
486
- * files while a review reads them.
767
+ * Callers start it only when no job is running: from the call on, new jobs
768
+ * wait (waitForPoolIdle) until the pull is over.
487
769
  */
488
770
  updatePool({ say = () => {} } = {}) {
489
- return this.run(async () => {
771
+ this.poolUpdates += 1;
772
+ return this.withPool(async () => {
490
773
  if (!this.poolState().repos) {
491
774
  say('没有知识仓可更新(运行 work-agent-runner setup 可以下载)');
492
775
  return this.poolState();
@@ -494,16 +777,38 @@ export class WorkAgent {
494
777
  say(`正在更新知识仓:${this.paths.poolDir}`);
495
778
  await this.python(['update'], { say });
496
779
  return this.poolState();
780
+ }).finally(() => {
781
+ this.poolUpdates -= 1;
497
782
  });
498
783
  }
499
784
 
785
+ /**
786
+ * Resolves true once no `git pull` runs in the pool — this process's
787
+ * updatePool() or another process's (state/pool-busy) — so a job never reads
788
+ * files being replaced; false after `timeoutMs` or once `isCancelled()`.
789
+ */
790
+ async waitForPoolIdle({ timeoutMs = 15 * 60_000, isCancelled = () => false, onWait = () => {}, pollMs = 1000 } = {}) {
791
+ const deadline = Date.now() + timeoutMs;
792
+ let told = false;
793
+ for (;;) {
794
+ if (isCancelled()) return false;
795
+ if (!this.poolUpdating && poolBusyInfo(this.paths)?.kind !== 'update') return true;
796
+ if (Date.now() >= deadline) return false;
797
+ if (!told) {
798
+ told = true;
799
+ onWait();
800
+ }
801
+ await sleep(Math.max(1, Math.min(pollMs, deadline - Date.now())));
802
+ }
803
+ }
804
+
500
805
  /**
501
806
  * work-agent's own housekeeping: empties `$WORK_AGENT_HOME/tmp` and drops logs
502
807
  * older than 30 days. Only safe when no job is running (it deletes all of
503
808
  * tmp/), so `start` calls it before it connects.
504
809
  */
505
810
  cleanup({ say = () => {} } = {}) {
506
- return this.run(async () => {
811
+ return this.withPool(async () => {
507
812
  if (!this.state().ok) return false;
508
813
  await this.python(['cleanup', '--log-days', String(LOG_DAYS)], { say, timeoutMs: 10 * 60_000 });
509
814
  return true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@online-tools/work-agent-runner",
3
- "version": "0.0.3-alpha-1",
3
+ "version": "0.0.5-alpha-1",
4
4
  "description": "GitCode 在线工具的 Agent 执行机器:在自己的机器上运行 work-agent 的 Skill(PR 描述、代码检视)",
5
5
  "license": "MIT",
6
6
  "type": "module",