arco-workbench 0.2.5 → 0.2.7

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.
Files changed (33) hide show
  1. package/client/dist/assets/{PhosphorBackdrop-CLILIwOQ.js → PhosphorBackdrop-Df7xl7fv.js} +1 -1
  2. package/client/dist/assets/{ThemedBackgroundShaderImpl-B87chcb5.js → ThemedBackgroundShaderImpl-HQHu9fmC.js} +1 -1
  3. package/client/dist/assets/{XtermView-BP_j7WSN.js → XtermView-BlQ7QADf.js} +1 -1
  4. package/client/dist/assets/{galleryEditor-B90phoBI.js → galleryEditor-Db_t1HrV.js} +1 -1
  5. package/client/dist/assets/{index-BfPp1Oup.js → index-BPeBsjq5.js} +99 -99
  6. package/client/dist/index.html +1 -1
  7. package/client/src/components/UpdateAction.tsx +43 -16
  8. package/client/src/help/content/cluster.tsx +1 -1
  9. package/client/src/help/content/header.tsx +7 -3
  10. package/client/src/help/content/settings.tsx +2 -2
  11. package/client/src/help/manualSections/clusters.tsx +2 -1
  12. package/client/src/help/manualSections/maintenance.tsx +10 -7
  13. package/docs/DOCKER.md +4 -3
  14. package/docs/GLOSSARY.md +1 -1
  15. package/docs/OPERATIONS.md +32 -16
  16. package/docs/PROTOCOL_CLUSTER.md +1 -1
  17. package/docs/SETTINGS.md +8 -7
  18. package/node_modules/@arco/shared/dist/clusterCoordination.js +1 -1
  19. package/node_modules/@arco/shared/package.json +1 -1
  20. package/package.json +3 -2
  21. package/scripts/packaging/arco.mjs +17 -3
  22. package/scripts/packaging/update-process.mjs +160 -0
  23. package/scripts/packaging/update.mjs +50 -11
  24. package/server/dist/clusterDirector.js +1 -2
  25. package/server/dist/providers/claude-native/worker.js +6 -5
  26. package/server/dist/updateManager.d.ts +6 -1
  27. package/server/dist/updateManager.js +87 -20
  28. package/server/package.json +1 -1
  29. package/server/src/clusterDirector.ts +1 -2
  30. package/server/src/providers/claude-native/worker.ts +6 -5
  31. package/server/src/updateManager.ts +62 -18
  32. package/shared/dist/clusterCoordination.js +1 -1
  33. package/shared/src/clusterCoordination.ts +1 -1
@@ -0,0 +1,160 @@
1
+ import { spawn, spawnSync } from 'node:child_process';
2
+ import { join } from 'node:path';
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+ import { browserHost, homeFingerprint } from './ports.mjs';
5
+ import { updatePackage, verifiedPackagePrefix, waitForRecordedPid } from './update.mjs';
6
+ import { readWindowsServicePid, servicePaths } from './services.mjs';
7
+
8
+ const timeout = 45_000;
9
+
10
+ // A supervisor may acknowledge stop before the process releases package files.
11
+ // Zero means the supervisor reports no running process. An unknown owner or a
12
+ // different process leaves the snapshot in place for recovery.
13
+ export async function stopManagedReplacement(originalPid, observedPid, { servicePid, stop, waitForPid }) {
14
+ const currentPid = servicePid();
15
+ if (!Number.isSafeInteger(currentPid) || currentPid < 0 || currentPid === originalPid
16
+ || (observedPid && currentPid > 0 && currentPid !== observedPid)) return false;
17
+ if (currentPid > 0) await stop();
18
+ const stoppingPid = currentPid || observedPid;
19
+ if (stoppingPid && await waitForPid(stoppingPid)) return false;
20
+ return servicePid() === 0;
21
+ }
22
+
23
+ export async function updateRunningPackage({ root, manifest, expected, pid, runningVersion, managed, checkNative, service }) {
24
+ const home = process.env.ARCO_HOME;
25
+ const port = Number(process.env.ARCO_PORT);
26
+ if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(port) || port < 1 || port > 65535) {
27
+ throw new Error('Could not identify the running Arco installation.');
28
+ }
29
+ const prefix = verifiedPackagePrefix(root);
30
+ const base = `http://${browserHost(process.env.ARCO_HOST || '127.0.0.1')}:${port}`;
31
+ const env = { ...process.env };
32
+ const fingerprint = homeFingerprint(home);
33
+ const rootFingerprint = homeFingerprint(root);
34
+ const cli = join(root, 'scripts', 'packaging', 'arco.mjs');
35
+ if (!managed && !process.connected) throw new Error('The updater is not connected to the running Arco process.');
36
+
37
+ function servicePid() {
38
+ if (process.platform === 'win32') {
39
+ const recorded = readWindowsServicePid(home);
40
+ if (recorded) {
41
+ try { process.kill(recorded, 0); return recorded; }
42
+ catch (error) { if (error.code !== 'ESRCH') return null; }
43
+ }
44
+ const result = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
45
+ "$ErrorActionPreference='Stop'; (Get-ScheduledTask -TaskName 'arco-workbench').State.ToString()"],
46
+ { encoding: 'utf8', env, timeout: 5000, windowsHide: true });
47
+ return result.status === 0 && /^(Ready|Disabled)$/i.test((result.stdout || '').trim()) ? 0 : null;
48
+ }
49
+ if (process.platform === 'linux') {
50
+ const { unit } = servicePaths('linux', env);
51
+ const result = spawnSync('systemctl', ['--user', 'show', '-p', 'MainPID', '-p', 'FragmentPath', '-p', 'ActiveState', 'arco.service'], { encoding: 'utf8', env, timeout: 5000 });
52
+ const fields = (result.stdout || '').split('\n');
53
+ if (result.status !== 0 || !fields.includes(`FragmentPath=${unit}`)) return null;
54
+ const mainPid = Number(fields.find((field) => field.startsWith('MainPID='))?.slice('MainPID='.length));
55
+ if (mainPid > 0) return mainPid;
56
+ return mainPid === 0 && (fields.includes('ActiveState=inactive') || fields.includes('ActiveState=failed')) ? 0 : null;
57
+ }
58
+ const result = spawnSync('launchctl', ['print', `gui/${process.getuid()}/arco-workbench`], { encoding: 'utf8', env, timeout: 5000 });
59
+ const path = /^\s*path = (.+)$/m.exec(result.stdout || '')?.[1];
60
+ if (result.status !== 0 || path !== servicePaths('darwin', env).unit) return null;
61
+ const { unit } = servicePaths('darwin', env);
62
+ if (/^\s*path = (.+)$/m.exec(result.stdout)?.[1] !== unit) return null;
63
+ const serviceProcess = /^\s*pid = (\d+)\s*$/m.exec(result.stdout)?.[1];
64
+ if (serviceProcess) return Number(serviceProcess);
65
+ return /^\s*state = not running\s*$/m.test(result.stdout) ? 0 : null;
66
+ }
67
+
68
+ async function request(path) {
69
+ try {
70
+ return await fetch(base + path, { signal: AbortSignal.timeout(1000), redirect: 'error' });
71
+ } catch { return null; }
72
+ }
73
+ async function live() {
74
+ try {
75
+ const response = await request('/healthz');
76
+ const status = response?.ok ? await response.json() : null;
77
+ return status?.homeFingerprint === fingerprint && status.checkoutFingerprint === rootFingerprint ? status : null;
78
+ } catch { return null; }
79
+ }
80
+ async function waitFor(version, readPid, exited = () => false) {
81
+ const deadline = Date.now() + timeout;
82
+ while (!exited() && Date.now() < deadline) {
83
+ const status = await live();
84
+ const ownerPid = readPid();
85
+ if (status && status.pid !== pid && status.version === version && status.pid === ownerPid) {
86
+ if ((await request('/readyz'))?.ok) return;
87
+ }
88
+ await delay(250);
89
+ }
90
+ throw new Error('Arco did not become ready on the original address with the expected version.');
91
+ }
92
+ let replacementStillRunning = false;
93
+ const lifecycle = {
94
+ ownsProcess: true,
95
+ canRestore: () => !replacementStillRunning,
96
+ async stop() {
97
+ const status = await live();
98
+ if (status?.pid !== pid || status.version !== runningVersion) throw new Error('The running Arco installation changed.');
99
+ if (managed) {
100
+ if (servicePid() !== pid) throw new Error('The service manager does not own the running Arco process.');
101
+ await service('stop');
102
+ } else {
103
+ await new Promise((resolve, reject) => process.send('stop-for-update', (error) => error ? reject(error) : resolve()));
104
+ }
105
+ if (await waitForRecordedPid(pid)) throw new Error('The old Arco process is still running.');
106
+ },
107
+ async start(version) {
108
+ if (managed) {
109
+ let observedPid = null;
110
+ try {
111
+ await service('start');
112
+ await waitFor(version, () => {
113
+ const ownerPid = servicePid();
114
+ if (ownerPid > 0 && ownerPid !== pid) observedPid = ownerPid;
115
+ return ownerPid;
116
+ });
117
+ } catch (error) {
118
+ try {
119
+ replacementStillRunning = !await stopManagedReplacement(pid, observedPid, {
120
+ servicePid, stop: () => service('stop'), waitForPid: waitForRecordedPid,
121
+ });
122
+ } catch { replacementStillRunning = true; }
123
+ throw error;
124
+ }
125
+ return;
126
+ }
127
+ const child = spawn(process.execPath, [cli, 'start'], { env, cwd: home, detached: true, stdio: 'ignore', windowsHide: true });
128
+ let exited = false;
129
+ child.once('error', () => { exited = true; });
130
+ child.once('exit', () => { exited = true; });
131
+ child.unref();
132
+ try {
133
+ if (!child.pid) throw new Error('Could not start Arco on the installed release.');
134
+ await waitFor(version, () => child.pid, () => exited);
135
+ } catch (error) {
136
+ if (!exited) {
137
+ child.kill();
138
+ if (await waitForRecordedPid(child.pid)) replacementStillRunning = true;
139
+ }
140
+ throw error;
141
+ }
142
+ },
143
+ };
144
+ const status = await live();
145
+ if (status?.pid !== pid || status.version !== runningVersion) throw new Error('Could not identify the running Arco installation.');
146
+ if (expected === `v${manifest.version}` && manifest.version !== runningVersion) {
147
+ await checkNative(cli);
148
+ await lifecycle.stop();
149
+ await lifecycle.start(manifest.version);
150
+ return { outcome: 'updated', message: `Arco restarted on the installed release ${expected}.` };
151
+ }
152
+ if (manifest.version !== runningVersion) throw new Error('The package on disk has changed since Arco started.');
153
+ const prepare = async (archive, scratch, npm) => {
154
+ const stagingPrefix = join(scratch, 'staging-prefix');
155
+ npm('Could not stage the new release', ['install', '--global', '--ignore-scripts', '--no-audit', '--no-fund', '--prefix', stagingPrefix, archive], { timeout: 120_000 });
156
+ const entry = process.platform === 'win32' ? join(stagingPrefix, 'node_modules') : join(stagingPrefix, 'lib', 'node_modules');
157
+ await checkNative(join(entry, 'arco-workbench', 'scripts', 'packaging', 'arco.mjs'));
158
+ };
159
+ return updatePackage(manifest, root, { expected, home, prefix, env, managed, lifecycle, prepare });
160
+ }
@@ -1,6 +1,6 @@
1
1
  // Package updates snapshot the installed tree before replacing files.
2
2
  import { spawnSync } from 'node:child_process';
3
- import { closeSync, cpSync, existsSync, lstatSync, mkdtempSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { closeSync, cpSync, existsSync, lstatSync, mkdtempSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
4
4
  import { basename, dirname, join, resolve } from 'node:path';
5
5
  import { npmCliPath } from './native-repair.mjs';
6
6
  import { linuxServiceState, readWindowsServicePid, runWindowsProbe, serviceAction, servicePaths } from './services.mjs';
@@ -29,8 +29,27 @@ export function globalPrefix(root, platform = process.platform) {
29
29
  ? dirname(parent)
30
30
  : null;
31
31
  if (!modules) throw new Error('This is not a global npm installation.');
32
+ if (platform !== 'win32' && basename(dirname(modules)) !== 'lib') throw new Error('This is not a global npm installation.');
32
33
  return platform === 'win32' ? dirname(modules) : dirname(dirname(modules));
33
34
  }
35
+
36
+ // A global-looking folder alone also matches linked checkouts and some
37
+ // project-owned npm layouts. Resolve the launcher belonging to this prefix.
38
+ export function verifiedPackagePrefix(root, platform = process.platform) {
39
+ const prefix = globalPrefix(root, platform);
40
+ const path = realpathSync.native(root);
41
+ const norm = (value) => platform === 'win32' ? value.toLowerCase() : value;
42
+ const modules = platform === 'win32' ? join(prefix, 'node_modules') : join(prefix, 'lib', 'node_modules');
43
+ const expected = join(realpathSync.native(modules), 'arco-workbench');
44
+ if (norm(path) !== norm(expected) || lstatSync(root).isSymbolicLink()) throw new Error('The running package is not an owned global npm installation.');
45
+ const entry = join(path, 'scripts', 'packaging', 'arco.mjs');
46
+ const launcher = platform === 'win32' ? join(prefix, 'arco.cmd') : join(prefix, 'bin', 'arco');
47
+ const valid = platform === 'win32'
48
+ ? lstatSync(launcher).isFile() && readFileSync(launcher, 'utf8').includes('%dp0%\\node_modules\\arco-workbench\\scripts\\packaging\\arco.mjs')
49
+ : realpathSync.native(launcher) === entry;
50
+ if (!valid) throw new Error('The global launcher does not match the running package.');
51
+ return prefix;
52
+ }
34
53
  export function writeUpdateResult(resultFile, attemptId, result, now = Date.now) {
35
54
  const attempt = JSON.parse(readFileSync(resultFile, 'utf8'));
36
55
  if (attempt.attemptId !== attemptId || attempt.outcome !== 'running') return false;
@@ -125,6 +144,7 @@ export async function updatePackage(manifest, packageRoot, deps = {}) {
125
144
  if (order === 0) return { outcome: 'unchanged', message: 'Already on the newest release.' };
126
145
  }
127
146
  const archive = deps.target ?? stagePackage(call, manifest.name, version, scratch);
147
+ if (deps.prepare) await deps.prepare(archive, scratch, call, version);
128
148
  // Dependencies are not all bundled in the tarball. A full local snapshot
129
149
  // permits rollback even when the registry or the network is unavailable.
130
150
  cpSync(root, backup, { recursive: true, dereference: false, verbatimSymlinks: true, errorOnExist: true, force: false });
@@ -136,32 +156,46 @@ export async function updatePackage(manifest, packageRoot, deps = {}) {
136
156
  // canceled by another start or restart of the service while it waits.
137
157
  const linuxState = platform === 'linux' && managed ? deps.serviceState ?? (deps.service ? null : () => linuxServiceState()) : null;
138
158
  const before = linuxState ? await linuxState() : null;
139
- if (managed) {
159
+ if (deps.lifecycle) {
160
+ await deps.lifecycle.stop();
161
+ stopped = true;
162
+ } else if (managed) {
140
163
  try { await service('stop'); }
141
164
  catch (error) { if (linuxState) throw await afterFailedStop(error, before, linuxState, service, deps); throw error; }
142
165
  stopped = true;
143
166
  }
144
- if (platform === 'win32') {
167
+ if (platform === 'win32' && !deps.lifecycle?.ownsProcess) {
145
168
  const running = servicePid ? await waitForRecordedPid(servicePid, deps) : await windowsRunning();
146
169
  if (running) throw new Error(servicePid ? `The Arco service process ${servicePid} is still running. Stop it before updating on Windows.` : 'Stop all Arco processes before updating on Windows.');
147
170
  }
148
171
  installAttempted = true;
149
- call('Package installation failed', ['install', '--global', '--ignore-scripts', '--no-audit', '--no-fund', '--prefix', prefix, archive]);
172
+ call('Package installation failed', ['install', '--global', '--ignore-scripts', '--no-audit', '--no-fund', '--prefix', prefix, archive],
173
+ deps.lifecycle ? { timeout: 120_000 } : {});
150
174
  // The new package may define the service differently. A fresh process loads
151
175
  // the new code to
152
176
  // rewrite an unmodified Arco-owned definition; a failure keeps the old one.
153
177
  let refreshNote = '';
154
178
  if (managed && (platform === 'win32' || platform === 'linux')) {
155
179
  const refresh = deps.refresh ?? (() => run(process.execPath, [join(root, 'scripts/packaging/arco.mjs'), 'service', 'refresh'], { windowsHide: true }));
156
- try { const r = await refresh(); if (r?.error || (r?.status ?? 0) !== 0) refreshNote = ' The service definition was not refreshed; run arco service refresh.'; }
157
- catch { refreshNote = ' The service definition was not refreshed; run arco service refresh.'; }
180
+ const refreshFailure = deps.lifecycle ? ' The service definition could not be refreshed.' : ' The service definition was not refreshed; run arco service refresh.';
181
+ try { const r = await refresh(); if (r?.error || (r?.status ?? 0) !== 0) refreshNote = refreshFailure; }
182
+ catch { refreshNote = refreshFailure; }
183
+ }
184
+ if (stopped) {
185
+ if (deps.lifecycle) await deps.lifecycle.start(version);
186
+ else await service('start');
187
+ stopped = false;
158
188
  }
159
- if (stopped) { await service('start'); stopped = false; }
160
- return { outcome: 'updated', message: `Updated${version ? ` to v${version}` : ` ${manifest.name}`}; ${managed ? 'service restarted' : 'restart Arco to use the update'}.${refreshNote}` };
189
+ const restartNote = deps.lifecycle ? 'Arco restarted' : managed ? 'service restarted' : 'restart Arco to use the update';
190
+ return { outcome: 'updated', message: `Updated${version ? ` to v${version}` : ` ${manifest.name}`}; ${restartNote}.${refreshNote}` };
161
191
  } catch (error) {
162
192
  const detail = String(error.message).replace(/[.\s]+$/, '');
163
193
  let damaged;
164
194
  if (installAttempted) {
195
+ if (deps.lifecycle?.canRestore?.() === false) {
196
+ preserve = true;
197
+ throw new Error(`Update failed: ${detail}. Arco could not confirm that the replacement stopped. Previous package snapshot: ${backup}`);
198
+ }
165
199
  // Keep both copies until a complete restoration is available. If the
166
200
  // copy fails, retain the snapshot and report its location for recovery.
167
201
  damaged = `${root}.arco-update-failed-${process.pid}`;
@@ -177,16 +211,21 @@ export async function updatePackage(manifest, packageRoot, deps = {}) {
177
211
  }
178
212
  }
179
213
  if (stopped) {
180
- try { await service('start'); }
214
+ try {
215
+ if (deps.lifecycle) await deps.lifecycle.start(manifest.version);
216
+ else await service('start');
217
+ }
181
218
  catch {
182
219
  preserve = true;
183
220
  const recovery = installAttempted
184
221
  ? `The previous package was restored. Previous package snapshot: ${backup}`
185
222
  : 'The installed package was left unchanged.';
186
- throw new Error(`Update failed: ${detail}. The service could not restart. Check the service and run arco service start after resolving the error. ${recovery}`);
223
+ throw new Error(deps.lifecycle
224
+ ? `Update failed: ${detail}. Arco could not restart even on the previous release. ${recovery}`
225
+ : `Update failed: ${detail}. The service could not restart. Check the service and run arco service start after resolving the error. ${recovery}`);
187
226
  }
188
227
  }
189
- const recovery = installAttempted ? ' The previous package was restored.' + (stopped ? ' The service was restarted.' : '') : '';
228
+ const recovery = installAttempted ? ' The previous package was restored.' + (stopped ? (deps.lifecycle ? ' Arco restarted on the previous release.' : ' The service was restarted.') : '') : '';
190
229
  let cleanupNote = '';
191
230
  if (damaged) {
192
231
  try { rmSync(damaged, { recursive: true, force: true }); }
@@ -18,14 +18,13 @@ export function buildClusterDirectorDoctrine(role) {
18
18
  'Delegate implementation, builds, and test runs only through peer_send and track them on the board. Do not write or edit product code or tests yourself.',
19
19
  'An assignment never asks for something the project\'s own rules forbid (how commits land, changelog, documentation, testing); state the delivery those rules require. When the work truly needs an exception, ask the operator first.',
20
20
  'When you assign work, ask for one report at the end, or one at an agreed milestone, plus blockers, and ask for step notes as comments on the board task. Never ask members to coordinate with each other by message for routine things, such as taking turns on a shared resource, status or acknowledgements, when a lock, a file or the board can do it.',
21
- 'Stay available to the operator. Hand long-running work to peers: the project\'s checks to the tester (or a builder when there is no tester), CI watching to the change\'s author. Use their reports of what was done, run and not covered; do not run builds, test suites or CI waits yourself.',
21
+ 'For long checks, stay responsive and follow operator and project instructions. Wait for the result, hand off the check, or continue other approved work as the workflow requires. Follow the same instructions on when to end the turn.',
22
22
  'Landing is yours: read the complete accepted diff, check that what the project requires was run, then commit and push per project rules. Ask the peer for missing or stale results rather than regenerating them yourself. Do not invent a gate where the project has none. Do not turn a one-off incident into a standing rule or permanent test without the operator.',
23
23
  'When a task is met, sign it off with a plain operator-facing summary without commit hashes. If the whole linked plan item is also complete, pass completePlan with the attached plan ID, reviewed revision and unique numbered item ID; otherwise leave the plan unchanged. If the tool reports a pending plan completion, read the original plan ID, item ID and reviewed revision with cluster_task_show, then retry; if the plan changed, resolve the pending sign-off and review again. A met sign-off closes it unless Board auto-done is off in Settings. Tell the operator in chat what to try.',
24
24
  'Before a failure holds work up, say what a user would lose if it were real; note cosmetic or momentary faults and carry on.',
25
25
  'A red check must mean something. Sort each failure first: a fault in the product, or a fault in a test, a housekeeping rule or the CI service. Fix product faults. When the test or rule is at fault, fix it, skip it on that system with a stated reason, or delete it, so the check goes green and can be trusted; do not release over a red check and do not leave one red. Rerun alone a job the CI service dropped. Keep CI to checks whose failure tells the operator something about the product, and small enough to pass in one run; housekeeping findings warn, they do not fail a run.',
26
26
  'When reading a diff, also check its shape: a second implementation of existing logic, a wrapper that only passes calls through, tests that miss the module\'s interface, or one change spread over many places. These findings are advisory unless they meet the blocking rules; record them as tasks.',
27
27
  'The plan holds standing rules and tasks only. You may add, split, reword, or restructure tasks and tick them with cluster_plan_tick; change standing rules only when the operator asks. Put progress, evidence, commit hashes, CI ids, test counts, and dates on board tasks, never in the plan body.',
28
- 'When runnable work remains, delegate it via peer_send and end your turn; do not do a peer\'s work to keep the turn going.',
29
28
  'If two instructions conflict or required authority is genuinely missing, identify the exact conflict immediately and ask the operator; do not silently stall.',
30
29
  ].join('\n');
31
30
  }
@@ -1,7 +1,7 @@
1
1
  import { setMaxListeners } from 'node:events';
2
2
  import { assertNativeTaskAllowed, nativeTaskBatchApprovalReasons } from './taskAdmission.js';
3
3
  import { readSettings } from '../../settings.js';
4
- import { buildTurnWaitInstructions, resolveNativeSubagents, CLAUDE_MODELS, isIsolatedAccessMode } from '@arco/shared';
4
+ import { buildTurnWaitInstructions, isClusterDirector, resolveNativeSubagents, CLAUDE_MODELS, isIsolatedAccessMode } from '@arco/shared';
5
5
  import { RESEARCHER_DOCTRINE, researchDirectorDoctrine } from '../../research/researchDoctrine.js';
6
6
  import { availableHandoffSources, executeHandoffHistory, HANDOFF_HISTORY_TOOL, HANDOFF_HISTORY_CONTEXT } from '../../handoffHistoryTool.js';
7
7
  import { mediaRetirementNotice } from './mediaRetirementNotice.js';
@@ -1910,10 +1910,11 @@ export class ClaudeNativeWorker extends EventEmitter {
1910
1910
  // retain precedence if there is a conflict.
1911
1911
  blocks.push({
1912
1912
  type: 'text',
1913
- text: 'Turn discipline: the operator is not watching in real time and cannot answer mid-turn. ' +
1914
- 'Continue working until the request is complete or you are genuinely blocked on operator input. ' +
1915
- "Never end your turn with a status update, a plan, or a promise of future work ('Continuing now', 'I'll do X next') — " +
1916
- 'if your final paragraph describes work you have not done, do that work now instead of ending the turn. ' +
1913
+ text: (isClusterDirector(this.config.clusterRole) ? '' :
1914
+ 'Turn discipline: the operator is not watching in real time and cannot answer mid-turn. ' +
1915
+ 'Continue working until the request is complete or you are genuinely blocked on operator input. ' +
1916
+ "Never end your turn with a status update, a plan, or a promise of future work ('Continuing now', 'I'll do X next') — " +
1917
+ 'if your final paragraph describes work you have not done, do that work now instead of ending the turn. ') +
1917
1918
  buildTurnWaitInstructions(this.config.clusterRole) + ' ' +
1918
1919
  'If a delegated Task child fails or returns an error or nonsense (e.g. a login error), say so explicitly in your reply and adapt openly — never silently work around a failed delegation. ' +
1919
1920
  // Fable 5.1 / 5.2 can rewrite whole files where a targeted edit would do
@@ -1,6 +1,6 @@
1
1
  import type { UpdateCheckStatus } from '@arco/shared';
2
2
  export type UpdateMode = 'service' | 'foreground' | 'docker';
3
- export declare function updateMode(platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv): UpdateMode;
3
+ export declare function updateMode(platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv, launcher?: 'start' | 'service-run'): UpdateMode;
4
4
  type Status = {
5
5
  outcome: string;
6
6
  message?: string;
@@ -23,10 +23,14 @@ export declare function createUpdateManager(deps?: {
23
23
  error?: Error;
24
24
  stderr?: string | null;
25
25
  };
26
+ launchForeground?: (args: string[]) => Promise<void>;
27
+ packageInstallation?: () => boolean;
28
+ argv?: string[];
26
29
  now?: () => number;
27
30
  version?: string;
28
31
  }): {
29
32
  status: () => {
33
+ canUpdate: boolean;
30
34
  mode: UpdateMode;
31
35
  platform: NodeJS.Platform;
32
36
  packaged: boolean;
@@ -57,6 +61,7 @@ export declare function createUpdateManager(deps?: {
57
61
  };
58
62
  export declare const updateManager: {
59
63
  status: () => {
64
+ canUpdate: boolean;
60
65
  mode: UpdateMode;
61
66
  platform: NodeJS.Platform;
62
67
  packaged: boolean;
@@ -1,21 +1,27 @@
1
- import { spawnSync } from 'node:child_process';
2
- import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
1
+ import { spawn, spawnSync } from 'node:child_process';
2
+ import { once } from 'node:events';
3
+ import { mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
3
4
  import { dirname, join, resolve } from 'node:path';
4
5
  import { fileURLToPath } from 'node:url';
5
6
  import { randomUUID } from 'node:crypto';
7
+ import { createRequire } from 'node:module';
6
8
  import { arcoHome } from './arcoHome.js';
7
9
  import { updateChecker } from './server/updateCheck.js';
8
10
  import { APP_VERSION } from './appVersion.js';
9
- export function updateMode(platform = process.platform, env = process.env) {
11
+ export function updateMode(platform = process.platform, env = process.env, launcher) {
10
12
  if (env.ARCO_DEPLOYMENT === 'docker')
11
13
  return 'docker';
12
- if (env.ARCO_PACKAGED === '1' && env.ARCO_PACKAGE_SERVICE === '1')
13
- return 'service';
14
+ if (env.ARCO_PACKAGED === '1') {
15
+ // A foreground launcher can inherit systemd markers from its parent.
16
+ if (launcher === 'start')
17
+ return 'foreground';
18
+ if (launcher === 'service-run' || env.ARCO_PACKAGE_SERVICE === '1')
19
+ return 'service';
20
+ }
14
21
  return platform === 'linux' && !!(env.INVOCATION_ID || env.SYSTEMD_EXEC_PID) ? 'service' : 'foreground';
15
22
  }
16
23
  const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
17
24
  export function createUpdateManager(deps = {}) {
18
- const mode = deps.mode ?? (() => updateMode());
19
25
  const home = deps.home ?? arcoHome;
20
26
  const env = deps.env ?? process.env;
21
27
  const platform = deps.platform ?? process.platform;
@@ -24,6 +30,57 @@ export function createUpdateManager(deps = {}) {
24
30
  const launch = deps.launch ?? ((command, args) => spawnSync(command, args, { encoding: 'utf8', timeout: 15_000 }));
25
31
  const now = deps.now ?? Date.now;
26
32
  const version = deps.version ?? APP_VERSION;
33
+ const repo = deps.root ?? repoRoot;
34
+ const cli = join(repo, 'scripts', 'packaging', 'arco.mjs');
35
+ const argv = deps.argv ?? process.argv;
36
+ const launcher = (() => {
37
+ const command = argv[2];
38
+ if (!packaged || (command !== 'start' && command !== 'service-run') || !argv[1])
39
+ return undefined;
40
+ try {
41
+ return realpathSync.native(argv[1]) === realpathSync.native(cli) ? command : undefined;
42
+ }
43
+ catch {
44
+ return undefined;
45
+ }
46
+ })();
47
+ const mode = deps.mode ?? (() => updateMode(platform, env, launcher));
48
+ const packageInstallation = deps.packageInstallation ?? (() => {
49
+ try {
50
+ const { verifiedPackagePrefix } = createRequire(import.meta.url)(join(repo, 'scripts', 'packaging', 'update.mjs'));
51
+ verifiedPackagePrefix(repo);
52
+ return true;
53
+ }
54
+ catch {
55
+ return false;
56
+ }
57
+ });
58
+ const canUpdate = () => {
59
+ const current = mode();
60
+ if (!packaged)
61
+ return current === 'service' && platform === 'linux';
62
+ if (!['linux', 'darwin', 'win32'].includes(platform))
63
+ return false;
64
+ if (current === 'foreground')
65
+ return launcher === 'start' && packageInstallation();
66
+ return current === 'service' && launcher === 'service-run' && packageInstallation();
67
+ };
68
+ const launchForeground = deps.launchForeground ?? (async (args) => {
69
+ const child = spawn(process.execPath, args, {
70
+ detached: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'], cwd: home(), env, windowsHide: true,
71
+ });
72
+ child.once('message', (message) => {
73
+ if (message === 'stop-for-update')
74
+ process.emit('SIGTERM', 'SIGTERM');
75
+ });
76
+ try {
77
+ await once(child, 'spawn');
78
+ }
79
+ finally {
80
+ child.unref();
81
+ child.channel?.unref();
82
+ }
83
+ });
27
84
  const resultPath = () => join(home(), 'update-result.json');
28
85
  function read() { try {
29
86
  const x = JSON.parse(readFileSync(resultPath(), 'utf8'));
@@ -33,6 +90,9 @@ export function createUpdateManager(deps = {}) {
33
90
  return null;
34
91
  } }
35
92
  function status() {
93
+ return { ...readStatus(), canUpdate: canUpdate() };
94
+ }
95
+ function readStatus() {
36
96
  const result = read();
37
97
  if (!result?.attemptId || !Number.isFinite(result.startedAt) || !result.fromVersion || !/^v\d+\.\d+\.\d+$/.test(result.target ?? ''))
38
98
  return { mode: mode(), platform, packaged, result: null };
@@ -60,8 +120,8 @@ export function createUpdateManager(deps = {}) {
60
120
  }
61
121
  let starting = false;
62
122
  async function start(body) {
63
- if (mode() !== 'service')
64
- return { ok: false, status: 409, error: 'Use the update command for this run mode.' };
123
+ if (!canUpdate())
124
+ return { ok: false, status: 409, error: 'Arco cannot update this launch from the browser.' };
65
125
  if (!body || typeof body !== 'object' || Array.isArray(body) || Object.keys(body).some((key) => key !== 'expectedLatest') || typeof body.expectedLatest !== 'string')
66
126
  return { ok: false, status: 400, error: 'Confirm the displayed release; update accepts no target.' };
67
127
  if (starting)
@@ -90,18 +150,26 @@ export function createUpdateManager(deps = {}) {
90
150
  const resultFile = resultPath();
91
151
  mkdirSync(home(), { recursive: true, mode: 0o700 });
92
152
  writeFileSync(resultFile, JSON.stringify({ ...attempt, outcome: 'running' }), { mode: 0o600 });
93
- const repo = deps.root ?? repoRoot;
94
- const task = `arco-updater-${randomUUID()}`;
95
- const cli = join(repo, 'scripts', 'packaging', 'arco.mjs');
96
- const updateArgs = [cli, 'package-update', latest.latest, resultFile, task, attempt.attemptId];
153
+ const task = mode() === 'service' ? `arco-updater-${randomUUID()}` : '';
154
+ const updateArgs = [cli, 'package-update', latest.latest, resultFile, task, attempt.attemptId,
155
+ String(process.pid), version, env.ARCO_PORT || '3001', env.ARCO_HOST || '127.0.0.1'];
97
156
  let result;
98
- if (platform === 'linux') {
157
+ if (!task) {
158
+ try {
159
+ await launchForeground(updateArgs);
160
+ result = { status: 0 };
161
+ }
162
+ catch {
163
+ result = { status: 1 };
164
+ }
165
+ }
166
+ else if (platform === 'linux') {
99
167
  if ([repo, resultFile, home(), process.execPath].some((value) => value.includes('$'))) {
100
- const message = 'Run arco update from a terminal.';
168
+ const message = 'The installation path cannot be passed safely to the service updater.';
101
169
  writeFileSync(resultFile, JSON.stringify({ ...attempt, outcome: 'failed', message, finishedAt: now() }), { mode: 0o600 });
102
170
  return { ok: false, status: 503, error: message };
103
171
  }
104
- result = launch('systemd-run', ['--user', '--collect', '--no-ask-password', '--service-type=exec', '--quiet', `--unit=${task}`, `--working-directory=${home()}`, `--setenv=ARCO_HOME=${home()}`, ...(env.PATH ? [`--setenv=PATH=${env.PATH}`] : []), process.execPath, ...updateArgs]);
172
+ result = launch('systemd-run', ['--user', '--collect', '--no-ask-password', '--service-type=exec', '--quiet', `--unit=${task}`, `--working-directory=${home()}`, `--setenv=ARCO_HOME=${home()}`, ...(env.PATH ? [`--setenv=PATH=${env.PATH}`] : []), ...(env.XDG_CONFIG_HOME ? [`--setenv=XDG_CONFIG_HOME=${env.XDG_CONFIG_HOME}`] : []), process.execPath, ...updateArgs]);
105
173
  }
106
174
  else if (platform === 'darwin') {
107
175
  result = launch('launchctl', ['submit', '-l', task, '--', process.execPath, ...updateArgs]);
@@ -109,7 +177,7 @@ export function createUpdateManager(deps = {}) {
109
177
  else if (platform === 'win32') {
110
178
  const user = env.USERDOMAIN && env.USERNAME ? `${env.USERDOMAIN}\\${env.USERNAME}` : env.USERNAME;
111
179
  if (!user || [user, repo, resultFile, process.execPath].some((value) => /[\r\n\0]/.test(value))) {
112
- const message = 'Run arco update from a terminal.';
180
+ const message = 'The updater could not identify the Windows account or installation.';
113
181
  writeFileSync(resultFile, JSON.stringify({ ...attempt, outcome: 'failed', message, finishedAt: now() }), { mode: 0o600 });
114
182
  return { ok: false, status: 503, error: message };
115
183
  }
@@ -132,7 +200,7 @@ export function createUpdateManager(deps = {}) {
132
200
  else
133
201
  result = { status: 1 };
134
202
  if (result.error || result.status !== 0) {
135
- const message = 'Could not start a separate updater. Run arco update from a terminal.';
203
+ const message = 'Could not start a separate updater. Try again.';
136
204
  writeFileSync(resultFile, JSON.stringify({ ...attempt, outcome: 'failed', message, finishedAt: now() }), { mode: 0o600 });
137
205
  return { ok: false, status: 503, error: message };
138
206
  }
@@ -144,9 +212,8 @@ export function createUpdateManager(deps = {}) {
144
212
  const resultFile = resultPath();
145
213
  mkdirSync(home(), { recursive: true, mode: 0o700 });
146
214
  writeFileSync(resultFile, JSON.stringify({ ...attempt, outcome: 'running' }), { mode: 0o600 });
147
- const repo = deps.root ?? repoRoot;
148
215
  if ([repo, resultFile, home(), process.execPath].some((value) => value.includes('$'))) {
149
- const message = 'The checkout or home path cannot be passed safely to the service. Run npm run arco:update from a terminal.';
216
+ const message = 'The checkout or home path cannot be passed safely to the service updater.';
150
217
  writeFileSync(resultFile, JSON.stringify({ ...attempt, outcome: 'failed', message, finishedAt: now() }), { mode: 0o600 });
151
218
  return { ok: false, status: 503, error: message };
152
219
  }
@@ -155,7 +222,7 @@ export function createUpdateManager(deps = {}) {
155
222
  process.execPath, join(repo, 'scripts', 'arco-update.mjs'), '--yes', '--require-service', '--expected-release', latest.latest, '--result-file', resultFile, '--attempt-id', attempt.attemptId];
156
223
  const result = launch('systemd-run', args);
157
224
  if (result.error || result.status !== 0) {
158
- const message = 'Could not start a separate updater. Run npm run arco:update from a terminal.';
225
+ const message = 'Could not start a separate updater. Try again.';
159
226
  writeFileSync(resultFile, JSON.stringify({ ...attempt, outcome: 'failed', message, finishedAt: now() }), { mode: 0o600 });
160
227
  return { ok: false, status: 503, error: message };
161
228
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arco/server",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
4
4
  "private": true,
5
5
  "type": "module"
6
6
  }
@@ -20,14 +20,13 @@ export function buildClusterDirectorDoctrine(role: string | undefined): string |
20
20
  'Delegate implementation, builds, and test runs only through peer_send and track them on the board. Do not write or edit product code or tests yourself.',
21
21
  'An assignment never asks for something the project\'s own rules forbid (how commits land, changelog, documentation, testing); state the delivery those rules require. When the work truly needs an exception, ask the operator first.',
22
22
  'When you assign work, ask for one report at the end, or one at an agreed milestone, plus blockers, and ask for step notes as comments on the board task. Never ask members to coordinate with each other by message for routine things, such as taking turns on a shared resource, status or acknowledgements, when a lock, a file or the board can do it.',
23
- 'Stay available to the operator. Hand long-running work to peers: the project\'s checks to the tester (or a builder when there is no tester), CI watching to the change\'s author. Use their reports of what was done, run and not covered; do not run builds, test suites or CI waits yourself.',
23
+ 'For long checks, stay responsive and follow operator and project instructions. Wait for the result, hand off the check, or continue other approved work as the workflow requires. Follow the same instructions on when to end the turn.',
24
24
  'Landing is yours: read the complete accepted diff, check that what the project requires was run, then commit and push per project rules. Ask the peer for missing or stale results rather than regenerating them yourself. Do not invent a gate where the project has none. Do not turn a one-off incident into a standing rule or permanent test without the operator.',
25
25
  'When a task is met, sign it off with a plain operator-facing summary without commit hashes. If the whole linked plan item is also complete, pass completePlan with the attached plan ID, reviewed revision and unique numbered item ID; otherwise leave the plan unchanged. If the tool reports a pending plan completion, read the original plan ID, item ID and reviewed revision with cluster_task_show, then retry; if the plan changed, resolve the pending sign-off and review again. A met sign-off closes it unless Board auto-done is off in Settings. Tell the operator in chat what to try.',
26
26
  'Before a failure holds work up, say what a user would lose if it were real; note cosmetic or momentary faults and carry on.',
27
27
  'A red check must mean something. Sort each failure first: a fault in the product, or a fault in a test, a housekeeping rule or the CI service. Fix product faults. When the test or rule is at fault, fix it, skip it on that system with a stated reason, or delete it, so the check goes green and can be trusted; do not release over a red check and do not leave one red. Rerun alone a job the CI service dropped. Keep CI to checks whose failure tells the operator something about the product, and small enough to pass in one run; housekeeping findings warn, they do not fail a run.',
28
28
  'When reading a diff, also check its shape: a second implementation of existing logic, a wrapper that only passes calls through, tests that miss the module\'s interface, or one change spread over many places. These findings are advisory unless they meet the blocking rules; record them as tasks.',
29
29
  'The plan holds standing rules and tasks only. You may add, split, reword, or restructure tasks and tick them with cluster_plan_tick; change standing rules only when the operator asks. Put progress, evidence, commit hashes, CI ids, test counts, and dates on board tasks, never in the plan body.',
30
- 'When runnable work remains, delegate it via peer_send and end your turn; do not do a peer\'s work to keep the turn going.',
31
30
  'If two instructions conflict or required authority is genuinely missing, identify the exact conflict immediately and ask the operator; do not silently stall.',
32
31
  ].join('\n');
33
32
  }
@@ -1,7 +1,7 @@
1
1
  import { setMaxListeners } from 'node:events';
2
2
  import { assertNativeTaskAllowed, nativeTaskBatchApprovalReasons } from './taskAdmission.js';
3
3
  import { readSettings } from '../../settings.js';
4
- import { buildTurnWaitInstructions, resolveNativeSubagents, CLAUDE_MODELS, isIsolatedAccessMode, type NativeSubagentPolicy } from '@arco/shared';
4
+ import { buildTurnWaitInstructions, isClusterDirector, resolveNativeSubagents, CLAUDE_MODELS, isIsolatedAccessMode, type NativeSubagentPolicy } from '@arco/shared';
5
5
  import { RESEARCHER_DOCTRINE, researchDirectorDoctrine } from '../../research/researchDoctrine.js';
6
6
  import { availableHandoffSources, executeHandoffHistory, HANDOFF_HISTORY_TOOL, HANDOFF_HISTORY_CONTEXT } from '../../handoffHistoryTool.js';
7
7
  import { mediaRetirementNotice } from './mediaRetirementNotice.js';
@@ -2121,10 +2121,11 @@ export class ClaudeNativeWorker extends EventEmitter {
2121
2121
  blocks.push({
2122
2122
  type: 'text',
2123
2123
  text:
2124
- 'Turn discipline: the operator is not watching in real time and cannot answer mid-turn. ' +
2125
- 'Continue working until the request is complete or you are genuinely blocked on operator input. ' +
2126
- "Never end your turn with a status update, a plan, or a promise of future work ('Continuing now', 'I'll do X next') — " +
2127
- 'if your final paragraph describes work you have not done, do that work now instead of ending the turn. ' +
2124
+ (isClusterDirector(this.config.clusterRole) ? '' :
2125
+ 'Turn discipline: the operator is not watching in real time and cannot answer mid-turn. ' +
2126
+ 'Continue working until the request is complete or you are genuinely blocked on operator input. ' +
2127
+ "Never end your turn with a status update, a plan, or a promise of future work ('Continuing now', 'I'll do X next') — " +
2128
+ 'if your final paragraph describes work you have not done, do that work now instead of ending the turn. ') +
2128
2129
  buildTurnWaitInstructions(this.config.clusterRole) + ' ' +
2129
2130
  'If a delegated Task child fails or returns an error or nonsense (e.g. a login error), say so explicitly in your reply and adapt openly — never silently work around a failed delegation. ' +
2130
2131
  // Fable 5.1 / 5.2 can rewrite whole files where a targeted edit would do