@tnunamak/dalan 0.7.0 → 0.8.0

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 (46) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/CONTRIBUTING.md +4 -0
  3. package/PROTOCOL.md +2 -0
  4. package/README.md +68 -28
  5. package/bin/dalan.mjs +1 -1
  6. package/bin/dot-worker.mjs +13 -2
  7. package/contracts/adapter-qualification.schema.json +170 -0
  8. package/docs/chatgpt-worker-onboarding.md +1 -1
  9. package/docs/local-agent-requester.md +46 -0
  10. package/docs/manual-setup.md +1 -1
  11. package/docs/operations.md +2 -2
  12. package/docs/service-setup.md +40 -17
  13. package/docs/setup-reference.md +1 -1
  14. package/docs/t3-question-relationship.md +43 -0
  15. package/docs/t3-reverse-control.md +12 -8
  16. package/docs/t3-wake-fence-r4.md +42 -0
  17. package/docs/test-suite-isolation.md +204 -0
  18. package/docs/worker-clients.md +3 -1
  19. package/package.json +5 -2
  20. package/qualification/README.md +13 -0
  21. package/qualification/mcp.json +121 -0
  22. package/qualification/protocol-v0.json +127 -0
  23. package/src/admin-socket.mjs +2 -1
  24. package/src/answer-journal.mjs +200 -0
  25. package/src/auth-check.mjs +8 -2
  26. package/src/cli-help.mjs +4 -3
  27. package/src/destinations/index.mjs +6 -0
  28. package/src/destinations/none.mjs +3 -0
  29. package/src/destinations/t3.mjs +63 -6
  30. package/src/execution.mjs +20 -2
  31. package/src/follow-current.mjs +4 -2
  32. package/src/gozar-routes.mjs +4 -3
  33. package/src/host-budget.mjs +17 -11
  34. package/src/host-execution-policy.mjs +2 -2
  35. package/src/host-stop-reverify.mjs +6 -4
  36. package/src/integrator.mjs +3 -1
  37. package/src/server.mjs +62 -12
  38. package/src/service-launchd.mjs +28 -8
  39. package/src/service-migrate-workers.mjs +12 -2
  40. package/src/service.mjs +52 -16
  41. package/src/store.mjs +77 -14
  42. package/src/submission-policy.mjs +8 -4
  43. package/src/t3.mjs +21 -2
  44. package/src/tool-registry.mjs +54 -8
  45. package/src/workers.mjs +4 -3
  46. package/src/workspace.mjs +94 -15
package/src/execution.mjs CHANGED
@@ -22,10 +22,13 @@ export const CAPABILITY_NAMES = Object.freeze([
22
22
  'offline_transition_revokes_connections', 'artifact_export_no_follow', 'runner_observed_evidence', 'native_darwin_execution', 'immutable_input_snapshot']);
23
23
  export const CAPABILITY_STATES = Object.freeze(['verified', 'unsupported', 'unknown']);
24
24
 
25
+ export const ADAPTER_CAPABILITY_NAMES = Object.freeze(['identified_questions']);
26
+ const REQUIRED_CAPABILITY_NAMES = Object.freeze([...CAPABILITY_NAMES, ...ADAPTER_CAPABILITY_NAMES]);
27
+
25
28
  export function parseRequiredCapabilities(value) {
26
29
  if (value === undefined || value === null) return null;
27
- if (!Array.isArray(value) || value.length > CAPABILITY_NAMES.length || value.some(c => !CAPABILITY_NAMES.includes(c))) {
28
- throw new Error(`invalid required_capabilities: expected a list of ${CAPABILITY_NAMES.join(', ')}`);
30
+ if (!Array.isArray(value) || value.length > REQUIRED_CAPABILITY_NAMES.length || value.some(c => !REQUIRED_CAPABILITY_NAMES.includes(c))) {
31
+ throw new Error(`invalid required_capabilities: expected a list of ${REQUIRED_CAPABILITY_NAMES.join(', ')}`);
29
32
  }
30
33
  return value.length ? [...new Set(value)].sort() : null;
31
34
  }
@@ -110,3 +113,18 @@ export function withEvidence(row) {
110
113
  const evidence = row.evidence ? JSON.parse(row.evidence) : null;
111
114
  return withCheckCoverage({ ...row, evidence, trust: evidence?.trust ?? null });
112
115
  }
116
+
117
+ // Committed adapter qualification is independent of per-worker authority grants.
118
+ export const ADAPTER_QUALIFICATIONS = Object.freeze({
119
+ mcp: Object.freeze({capabilities: Object.freeze({})}),
120
+ 'protocol-v0': Object.freeze({capabilities: Object.freeze({identified_questions: 'verified'})}),
121
+ });
122
+
123
+ export function admitAdapterCapabilities(adapter, required, catalogProfile) {
124
+ const qualification = Object.hasOwn(ADAPTER_QUALIFICATIONS, adapter) ? ADAPTER_QUALIFICATIONS[adapter] : null;
125
+ for (const name of required ?? []) {
126
+ const state = adapter === 'protocol-v0' && catalogProfile !== 'protocol-v0' ? 'unknown' : qualification?.capabilities[name] ?? 'unknown';
127
+ if (state !== 'verified') throw new Error(
128
+ 'capability_not_available: ' + name + ' (adapter ' + (adapter ?? 'undeclared') + ' declares ' + state + ')');
129
+ }
130
+ }
@@ -7,9 +7,11 @@ import { readDefaultHome } from './default-home.mjs';
7
7
 
8
8
  const real = file => { try { return fs.realpathSync(file); } catch { return null; } };
9
9
 
10
- // The entry script to hand over to, or null to stay in this package. `ownBin` is this package's bin/dalan.mjs.
11
- export function followTarget({ ownBin, env = process.env }) {
10
+ // The entry script to hand over to, or null to stay in this package. `ownBin` is this package's bin/dalan.mjs; `argv` is the
11
+ // command line after the script. An explicit --home names a home other than the default one, so this package runs it.
12
+ export function followTarget({ ownBin, env = process.env, argv = [] }) {
12
13
  if (env.DALAN_NO_FOLLOW === '1' || env.DALAN_FOLLOWED === '1') return null;
14
+ if (argv.some(arg => arg === '--home' || arg.startsWith('--home='))) return null;
13
15
  const home = env.DALAN_HOME ? path.resolve(env.DALAN_HOME) : readDefaultHome(env);
14
16
  if (!home) return null;
15
17
  const target = real(path.join(home, 'current', 'bin', 'dalan.mjs')), own = real(ownBin);
@@ -110,9 +110,10 @@ const EXPLAIN = {
110
110
  };
111
111
  export function explainRouteError(error) {
112
112
  const code = typeof error?.code === 'string' && (FROZEN_CODES.includes(error.code) || error.code === 'runtime_missing') ? error.code : null;
113
- if (!code) return { code: null, line: safeDiagnostic(String(error?.message ?? error), 240), fix: null };
114
- const action = error.nextAction ?? null;
115
- const fix = action ? [action.label, action.instructions, action.href].filter(Boolean).join(' - ') : null;
113
+ // Gozar's next step is shown as text for every code, including one Dalan does not know yet; Dalan never acts on it.
114
+ const action = error?.nextAction ?? null;
115
+ const fix = action ? [action.label, action.instructions, action.href].filter(value => typeof value === 'string' && value.length > 0).map(value => safeDiagnostic(value, 240)).join(' - ') || null : null;
116
+ if (!code) return { code: null, line: safeDiagnostic(String(error?.message ?? error), 240), fix };
116
117
  const detail = code === 'runtime_missing' ? error.message : `${EXPLAIN[code]}${error.message && !EXPLAIN[code].includes(error.message) ? ` (${safeDiagnostic(error.message, 160)})` : ''}`;
117
118
  return { code, line: detail, fix };
118
119
  }
@@ -6,9 +6,7 @@ import {prepareHostReceipts,assertHostReceiptIsolation,readVerifiedHostStop} fro
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { spawn } from 'node:child_process';
8
8
 
9
- // One active envelope per Unix user, shared by every bridge process. The systemd
10
- // unit name is an atomic reservation; it disappears only after its tree stops.
11
- export const HOST_UNIT = 'dot-bridge-host-check.service';
9
+ // The fixed production unit reserves one active envelope per Unix user.
12
10
  export const HOST_BUDGET_CEILINGS = Object.freeze({ cpu_ms: 120000, wall_ms: 180000, memory_bytes: 1024 ** 3, processes: 128, disk_write_bytes: 256 * 1024 ** 2, output_bytes: 1024 ** 2 });
13
11
  const minima = { cpu_ms: 50, wall_ms: 100, memory_bytes: 128 * 1024 ** 2, processes: 16, disk_write_bytes: 1024 ** 2, output_bytes: 1024 };
14
12
  const service = fileURLToPath(new URL('./host-budget-service.mjs', import.meta.url));
@@ -77,12 +75,16 @@ async function runHostBudgetAttempt({ dir, budgets, phases, maskPaths = [], sour
77
75
  'LimitCORE=0', 'UMask=0077',
78
76
  `ExecStopPost=${[process.execPath, stopRecorder,...(receipts?['--check-run-id',receipts.checkRunId,'--receipt-dir',receipts.receiptDir]:[])].map(propertyArg).join(' ')}`,
79
77
  ];
80
- const args = ['--user', '--quiet', '--wait', '--pipe', '--collect', `--unit=${HOST_UNIT}`, ...properties.map(p => `--property=${p}`), '--', process.execPath, service];
78
+ // Test suites isolate their reservation without changing the production default.
79
+ const suffix = process.env.NODE_ENV === 'production' ? undefined : process.env.DALAN_HOST_CHECK_UNIT_SUFFIX;
80
+ if (suffix && !/^[a-zA-Z0-9-]{1,80}$/.test(suffix)) throw new Error('invalid DALAN_HOST_CHECK_UNIT_SUFFIX');
81
+ const unit = `dot-bridge-host-check${suffix ? '-' + suffix : ''}.service`;
82
+ const args = ['--user', '--quiet', '--wait', '--pipe', '--collect', `--unit=${unit}`, ...properties.map(p => `--property=${p}`), '--', process.execPath, service];
81
83
  const started=performance.now();
82
84
  const child = spawn('/usr/bin/systemd-run', args, { stdio: ['pipe', 'pipe', 'pipe'] });
83
85
  onSpawned();
84
86
  child.stdin.write(serialized+'\n');
85
- let buffer = '', message = null, stopped = null, pid = null, diagnostic = '', callbackError = null, cancellationSent = false;
87
+ let buffer = '', message = null, stopped = null, pid = null, diagnostic = '', callbackError = null, cancellationSent = false, cpuExceeded = false;
86
88
  const launched = [];
87
89
  const partial = new Map();
88
90
  let partialUsage = null;
@@ -106,16 +108,20 @@ async function runHostBudgetAttempt({ dir, budgets, phases, maskPaths = [], sour
106
108
  if (event.event === 'pid') pid = event.pid;
107
109
  if (event.event === 'started' && phases.some(p => p.name === event.phase)) {
108
110
  launched.push(event.phase);
109
- if (onStarted) Promise.resolve(onStarted({ pid, phase: event.phase })).catch(e => { callbackError = e; cancel(); });
111
+ if (onStarted) Promise.resolve(onStarted({ pid, unit, phase: event.phase })).catch(e => { callbackError = e; cancel(); });
110
112
  }
111
- if (event.event === 'output_started' && onOutputStarted) Promise.resolve(onOutputStarted({ pid, phase: event.phase })).catch(e => { callbackError = e; cancel(); });
113
+ if (event.event === 'output_started' && onOutputStarted) Promise.resolve(onOutputStarted({ pid, unit, phase: event.phase })).catch(e => { callbackError = e; cancel(); });
112
114
  if (event.event === 'partial' && launched.includes(event.phase)) {
113
115
  const chunks = partial.get(event.phase) ?? [];
114
116
  chunks.push(Buffer.from(event.output, 'base64'));
115
117
  partial.set(event.phase, chunks);
116
118
  partialUsage = event.usage;
117
119
  }
118
- if (event.event === 'result') message = event.result;
120
+ if (event.event === 'result') {
121
+ // Both supervisors report here; EOF cleanup cannot undo an observed limit.
122
+ cpuExceeded ||= event.result?.error === 'budget exceeded: cpu';
123
+ message = event.result;
124
+ }
119
125
  if (event.event === 'stopped') stopped = event.stop;
120
126
  } catch { diagnostic = 'invalid supervisor response'; }
121
127
  }
@@ -129,10 +135,10 @@ async function runHostBudgetAttempt({ dir, budgets, phases, maskPaths = [], sour
129
135
  if (callbackError) throw callbackError;
130
136
  // ExecStopPost runs after systemd has killed/reaped every process in the unit,
131
137
  // even on OOM, RuntimeMaxSec, or loss of the main supervisor. No PID sweep or
132
- // application TTL can release a still-running reservation.
138
+ // application TTL can certify a still-running tree as stopped.
133
139
  const stopEvidence=resolveHostStopEvidence(receipts,stopped);
134
140
  const stop = { verified: stopEvidence?.verified === true, reason: stopEvidence?.verified ? 'systemd_control_group_stopped' : 'service_stop_not_observed', service_result: stopped?.result ?? null, invocation_id: stopEvidence?.invocationId ?? stopped?.invocation_id ?? null, remaining_pids: stopEvidence?.remaining_pids ?? stopped?.remaining_pids ?? null, oom_kill: stopped?.oom_kill ?? null };
135
- let error = message?.error ?? null;
141
+ let error = cpuExceeded ? 'budget exceeded: cpu' : message?.error ?? null;
136
142
  if (stopped?.oom_kill > 0 || stopped?.result === 'oom-kill') error = 'budget exceeded: memory';
137
143
  else if (stopped?.result === 'timeout') error = 'budget exceeded: wall';
138
144
  else if (stopped && !message) error = stopped.result === 'signal' ? 'supervisor interrupted' : `host preparation failed: ${diagnostic.trim() || stopped.exit_status || 'supervisor exited without a receipt'}`;
@@ -145,5 +151,5 @@ async function runHostBudgetAttempt({ dir, budgets, phases, maskPaths = [], sour
145
151
  const bytes = Buffer.concat(phaseResults.map(p => p.bytes)).subarray(0, budgets.output_bytes);
146
152
  const notStarted=provesHostNotStarted({spawnError:exit.error,pid,stopped}); // stderr is not trusted for this decision.
147
153
  const usage = message?.usage ? { ...partialUsage, ...message.usage } : partialUsage;
148
- return { dependencies: dependencies ? {lock_sha256:dependencies.lock_sha256,manifest_sha256:dependencies.manifest_sha256,runtime:dependencies.runtime} : null, exit: error ? { code: 125 } : message?.exit ?? { code: 125 }, error, budgets, usage, usage_complete: !!message?.usage && !!message?.phases?.length && stopped?.result !== 'timeout' && !stopped?.oom_kill, bytes, phases: phaseResults, stop, notStarted, timedOut: error === 'budget exceeded: wall', cancelled: !!message?.cancelled, truncated: error === 'budget exceeded: output', duration_ms: Math.round(performance.now()-started) };
154
+ return { unit, dependencies: dependencies ? {lock_sha256:dependencies.lock_sha256,manifest_sha256:dependencies.manifest_sha256,runtime:dependencies.runtime} : null, exit: error ? { code: 125 } : message?.exit ?? { code: 125 }, error, budgets, usage, usage_complete: !!message?.usage && !!message?.phases?.length && stopped?.result !== 'timeout' && !stopped?.oom_kill, bytes, phases: phaseResults, stop, notStarted, timedOut: error === 'budget exceeded: wall', cancelled: !!message?.cancelled, truncated: error === 'budget exceeded: output', duration_ms: Math.round(performance.now()-started) };
149
155
  }
@@ -20,10 +20,10 @@ export function hostCheckAuthorization(repo, checkId, expectedSpec = null) {
20
20
  return { spec };
21
21
  }
22
22
 
23
- export function hostCheckRefusal(assignment={}, repo=null, checkId=null, expectedSpec=null) {
23
+ export function hostCheckRefusal(assignment={}, repo=null, checkId=null, expectedSpec=null,excludedPathsAbsent=false) {
24
24
  const scope=assignment.scope_paths;
25
25
  const narrow=Array.isArray(scope)&&scope.length&&!scope.some(p=>p.replace(/^\.\//,'').replace(/\/$/,'')==='.');
26
- if(narrow||assignment.scope_excluded?.length) {
26
+ if(narrow||(assignment.scope_excluded?.length&&!excludedPathsAbsent)) {
27
27
  return 'scope_paths_read_isolation_unavailable: this executor exposes the whole checkout; a check needs an owner-approved repository-wide read grant';
28
28
  }
29
29
  if(sensitivePolicyPaths().error) return 'sensitive_policy_unavailable: restore a valid mode-0600 submission policy before running host checks';
@@ -2,12 +2,11 @@ import fs from 'node:fs';
2
2
  import {spawnSync} from 'node:child_process';
3
3
  import {readHostStart,writeHostReverify,readVerifiedHostStop,validBootId} from './host-budget-receipts.mjs';
4
4
  import {readCgroupProcesses} from './host-cgroup.mjs';
5
- import {HOST_UNIT} from './host-budget.mjs';
6
5
 
7
6
  const currentBootId=()=>fs.readFileSync('/proc/sys/kernel/random/boot_id','utf8').trim();
8
7
  // Only "inactive" or "failed" shows the unit is gone. Any other answer, error or timeout counts as still active.
9
- function hostUnitInactive() {
10
- const r=spawnSync('/usr/bin/systemctl',['--user','is-active',HOST_UNIT],{encoding:'utf8',timeout:5000});
8
+ function hostUnitInactive(unit) {
9
+ const r=spawnSync('/usr/bin/systemctl',['--user','is-active',unit],{encoding:'utf8',timeout:5000});
11
10
  return !r.error&&['inactive','failed'].includes((r.stdout??'').trim());
12
11
  }
13
12
  // A missing cgroup directory means no process remains. Any other read error propagates and keeps the stop unverified.
@@ -32,7 +31,10 @@ export function reverifyHostStop({receiptDir,checkRunId},{bootId=currentBootId,u
32
31
  if(!validBootId(now)) return null;
33
32
  let basis;
34
33
  if(now!==start.boot_id) basis='boot_changed';
35
- else if(typeof start.cgroup==='string'&&unitInactive()===true) {
34
+ else if(typeof start.cgroup==='string') {
35
+ // The trusted start receipt records the exact unit, including legacy names.
36
+ const unit=start.cgroup.split('/').at(-1);
37
+ if(!/^dot-bridge-host-check(?:-[a-zA-Z0-9-]+)?\.service$/.test(unit)||unitInactive(unit)!==true) return null;
36
38
  const remaining=scan('/sys/fs/cgroup'+start.cgroup);
37
39
  if(Array.isArray(remaining)&&remaining.length===0) basis='cgroup_empty';
38
40
  }
@@ -129,8 +129,10 @@ function runIsolatedCheck(check,checkoutDir,runnerRoot,repoName) {
129
129
  fs.mkdirSync(sourceCopyDir,{mode:0o700});
130
130
  const masked=sensitiveMasks(checkoutDir,repoName,sourceCopyDir);
131
131
  const request={checkout_dir:checkoutDir,runner_root:root,argv:check.argv,github_repo:repoName,maskPaths:masked.paths,sourceExemptions:masked.sourceExemptions};
132
- const env={PATH:'/usr/bin:/bin',HOME:path.join(root,'home'),TMPDIR:path.join(root,'tmp'),LANG:'C.UTF-8',LC_ALL:'C.UTF-8',TZ:'UTC',NODE_ENV:'production',DALAN_WORKSPACE_ROOT:path.join(root,'workspace'),DALAN_INTEGRATOR_SCRATCH_ROOT:buildScratch};
132
+ const testSuffix=process.env.NODE_ENV!=='production'&&process.env.DALAN_HOST_CHECK_UNIT_SUFFIX;
133
+ const env={PATH:'/usr/bin:/bin',HOME:path.join(root,'home'),TMPDIR:path.join(root,'tmp'),LANG:'C.UTF-8',LC_ALL:'C.UTF-8',TZ:'UTC',NODE_ENV:testSuffix?'test':'production',DALAN_WORKSPACE_ROOT:path.join(root,'workspace'),DALAN_INTEGRATOR_SCRATCH_ROOT:buildScratch};
133
134
  if(readEnv('DALAN_HOST_CHECKS')==='1') env.DALAN_HOST_CHECKS='1';
135
+ if(testSuffix) env.DALAN_HOST_CHECK_UNIT_SUFFIX=testSuffix;
134
136
  if(process.env.XDG_RUNTIME_DIR) env.XDG_RUNTIME_DIR=process.env.XDG_RUNTIME_DIR;
135
137
  if(process.env.DBUS_SESSION_BUS_ADDRESS) env.DBUS_SESSION_BUS_ADDRESS=process.env.DBUS_SESSION_BUS_ADDRESS;
136
138
  fs.mkdirSync(env.HOME,{recursive:true,mode:0o700});
package/src/server.mjs CHANGED
@@ -15,7 +15,7 @@ import path from 'node:path';
15
15
  import os from 'node:os';
16
16
  import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto';
17
17
  import { loadWorkers, hasInstalledDatabase, legacyMarkerPath, seedWorkerRepos, resolveWorker, hasCapability, assertTarget, submitTarget } from './workers.mjs';
18
- import { Store, nonterminalOutcome, validateProtocol, loadRedeliveryLimits, resumeNudge } from './store.mjs';
18
+ import { Store, QUESTION_PURPOSES, nonterminalOutcome, validateProtocol, loadRedeliveryLimits, resumeNudge } from './store.mjs';
19
19
  import {protocolArtifactChunk} from './protocol-artifact-commands.mjs';
20
20
  import { sendWebhook, validSecret } from './webhooks.mjs';
21
21
  import { checkAlerts, publishAlert, redactNote } from './alerts.mjs';
@@ -34,7 +34,7 @@ import { compileWorkOrder, reasonsFromError, strongest } from './work-order.mjs'
34
34
  import { assertNoDeclaredConsumer, unprovenSource } from './consumers.mjs';
35
35
  import { preflightPR } from './pr-preflight.mjs';
36
36
  import { admitImplementation } from './check-readiness.mjs';
37
- import { parseExecution, parseRequiredCapabilities, admitHostExecution, withEvidence } from './execution.mjs';
37
+ import { parseExecution, parseRequiredCapabilities, admitHostExecution, admitAdapterCapabilities, ADAPTER_CAPABILITY_NAMES, withEvidence } from './execution.mjs';
38
38
  import { loadCapacity } from './projects.mjs';
39
39
  import { authConfig, assertPublicRouteAuth, isLoopbackBindHost, protectedResource, challenge, verifyBearer, needScope } from './auth.mjs';
40
40
  import { beginMcpOutcome, recordMcpResponse, pathShape, uaToken } from './mcp-outcome.mjs';
@@ -180,7 +180,7 @@ if(!t3ToolsEnabled)for(const [worker,profile] of workers.workers)if(profile.capa
180
180
  log({kind:'t3_tools_disabled',worker,setting:'DALAN_ENABLE_T3_TOOLS=1'});
181
181
  console.error(`dalan: startup WARNING: worker "${worker}" has t3 capability but reverse-control tools are off; set DALAN_ENABLE_T3_TOOLS=1`);
182
182
  }
183
- if(t3ToolsEnabled)for(const [worker,profile] of workers.workers)if(profile.capabilities.has('t3')) console.error(`dalan: startup NOTICE: worker "${worker}" holds the t3 capability: it can list, read and send to any T3 thread and project on this computer. Grant it only to your own harness.`);
183
+ if(t3ToolsEnabled)for(const [worker,profile] of workers.workers)if(profile.capabilities.has('t3')) console.error(`dalan: startup NOTICE: worker "${worker}" holds the t3 capability: its T3 authority is limited by live job destinations and tool grants.`);
184
184
  const startupPolicy=currentRepoPolicy();
185
185
  for(const worker of workers.workers.keys()) if(startupPolicy.repoPolicy(worker)?.repos.length===0) {
186
186
  const blocked=store.db.prepare("SELECT count(*) n FROM assignments WHERE target_worker=? AND status='queued' AND json_type(payload,'$.inputs[0].github_repo')='text'").get(worker).n;
@@ -322,6 +322,19 @@ function id(value,name='request_id') { const s=str(value,name,128); if(!/^[-\w]{
322
322
  function authorize(received,expected,label) { const a=Buffer.from(received||''),b=Buffer.from(expected); if(a.length!==b.length||!timingSafeEqual(a,b)) throw new Error(`invalid ${label}`); }
323
323
  function adminOwner(req,idValue) { store.owner(id(idValue),req.headers['x-owner-capability']); }
324
324
  function adminOperator(req) { authorize(req.headers['x-operator-key'],operatorKey,'operator key'); }
325
+ const questionPurpose=value=>{
326
+ if(value===undefined) return 'clarification';
327
+ if(!QUESTION_PURPOSES.includes(value)) throw new Error(`invalid purpose: use ${QUESTION_PURPOSES.join(' or ')}`);
328
+ return value;
329
+ };
330
+ // Any question with a purpose other than clarification is answered by a person holding the operator key. The owner
331
+ // capability alone, which a parent model may hold, is refused before anything is stored.
332
+ function requireOperatorForHumanQuestion(req,requestId,questionId) {
333
+ const purpose=store.questionPurpose(requestId,questionId);
334
+ if(purpose===null||purpose==='clarification') return;
335
+ try { adminOperator(req); }
336
+ catch { throw new Error(`FORBIDDEN: question ${questionId} on ${requestId} has purpose ${purpose}, reserved for a human; answering it needs the operator key, not the owner capability alone`); }
337
+ }
325
338
 
326
339
  const event = {
327
340
  name: 'assignment.available', description: 'An assignment or lightweight message is available. Claim assignments by request_id; read messages by message_id. Use list_pending after missed events.',
@@ -343,7 +356,7 @@ const tools = [
343
356
  { name:'get',description:'Read assignment, available_checks, cancellation, progress, report and delivery facts.',inputSchema:schema({request_id:string},['request_id']) },
344
357
  { name:'ack_message',description:'Acknowledge a lightweight message after reading it; no claim or finish is needed.',inputSchema:schema({message_id:string},['message_id']) },
345
358
  { name:'progress',description:'Append progress. Set blocker:true or start note with BLOCKED: or QUESTION: to forward a question to the owner thread. A note over 4096 bytes is cut.',inputSchema:schema({request_id:string,claim_id:string,note:message,blocker:bool},['request_id','claim_id','note']) },
346
- { name:'ask_question',description:'Ask an identified question under the current grant. The owner answers this question explicitly; ordinary notes do not answer it. Consume its answer before reporting completed.',inputSchema:schema({request_id:string,claim_id:string,question_id:{type:'string',minLength:1,maxLength:128},text:{type:'string',minLength:1,maxLength:4096}},['request_id','claim_id','question_id','text']) },
359
+ { name:'ask_question',description:'Ask an identified question under the current grant. The owner answers this question explicitly; ordinary notes do not answer it. Consume its answer before reporting completed. Set purpose to human_decision (a choice only a human may make), authentication (a sign-in only a human can complete) or tool_permission (a permission only a human may grant) when only a human may answer; no model can answer such a question for them.',inputSchema:schema({request_id:string,claim_id:string,question_id:{type:'string',minLength:1,maxLength:128},text:{type:'string',minLength:1,maxLength:4096},purpose:{type:'string',enum:['clarification','human_decision','authentication','tool_permission']}},['request_id','claim_id','question_id','text']) },
347
360
  { name:'consume_answer',description:'Read and durably consume the identified question answer under its original current grant. Refuses unanswered or stale-epoch questions.',inputSchema:schema({request_id:string,claim_id:string,question_id:{type:'string',minLength:1,maxLength:128}},['request_id','claim_id','question_id']) },
348
361
  { name:'finish',description:'Store a terminal worker report; completion is not owner acceptance. summary is optional: when absent it is the first line of result, and one over 4096 bytes is cut.',inputSchema:schema({request_id:string,claim_id:string,outcome:{type:'string',enum:['completed','blocked','failed']},summary:message,result:{type:'string',maxLength:262144},artifact_ids:{type:'array',items:string,maxItems:8}},['request_id','claim_id','outcome','result']) },
349
362
  { name:'list_files',description:"List files in this assignment's checked-out repository workspace. Read-only; scoped to the assignment. When truncated is true, pass next_cursor as cursor to get the next page.",inputSchema:schema({request_id:string,claim_id:string,path:string,limit:{type:'integer',minimum:1,maximum:200},cursor:{type:'string',maxLength:1024}},['request_id','claim_id']) },
@@ -419,6 +432,7 @@ const disabled=new Set(['list_files','read_file','apply_patch','run_check','work
419
432
  const readTools=new Set(['list_pending','get','list_files','read_file','workspace_result','list_tools','call_tool_read']);
420
433
  const t3ReadTools=new Set(['t3_thread_list','t3_thread_read','t3_thread_wait']);
421
434
  const t3Tools=new Set([...t3ReadTools,'t3_thread_create','t3_thread_send','t3_thread_set']);
435
+ if(t3ToolsEnabled)toolRegistry.initializeT3Grants([...t3Tools],workers.workers.keys());
422
436
  const notifyTools=new Set(['notify_owner']);
423
437
  // T3 tools use the existing scopes to preserve the current grant behavior.
424
438
  const scopeFor=name=>t3ReadTools.has(name)||readTools.has(name)?'dalan.read':'dalan.work';
@@ -741,7 +755,31 @@ async function dispatchTool(name,a,principal,notifyMeta) {
741
755
  return T3_READ_TOOLS_OFF;
742
756
  }
743
757
  const t3Arguments=name==='t3_thread_wait'?{...a,timeoutMs:Math.min(a.timeoutMs??90_000,90_000)}:a;
744
- const result=notifyTools.has(name) ? await notifyLedger.send(principal.worker,str(a.text,'text',1000),notificationKey,idempotencyKey=>publishAlert('Dalan message',a.text,log,{requirePublisher:true,idempotencyKey})) : await (await import('./t3-control.mjs')).runT3Tool(name,t3Arguments);
758
+ let result;
759
+ if(t3Tools.has(name)) {
760
+ const control=await import('./t3-control.mjs');
761
+ const t3=await import('./t3.mjs');
762
+ const authorize=()=>{
763
+ const threads=toolRegistry.t3Threads(name,principal);
764
+ if(name!=='t3_thread_list' && !threads.has(a.threadId)) throw new RegistryError('tool_unavailable','tool unavailable');
765
+ return threads;
766
+ };
767
+ // Linearization point: this synchronous live-grant read follows the last await before
768
+ // send/set invokes the CLI. A revoke committed before it refuses the effect. No claim
769
+ // is made about revokes after CLI dispatch cancelling an external effect.
770
+ authorize();
771
+ if(name==='t3_thread_list') {
772
+ const data=await t3.callT3(t3.listArgs({cwd:a.cwd,project:a.projectId,status:a.status,workspace_mode:a.workspaceMode}));
773
+ const threads=authorize();
774
+ result=control.compactThreadList({...data,threads:(data.threads??[]).filter(t=>threads.has(t.id))});
775
+ result._audit_ids={threadIds:result.threads.map(t=>t.id),projectIds:result.projects.map(p=>p.id)};
776
+ } else {
777
+ result=await control.runT3Tool(name,t3Arguments);
778
+ // Wait/read results require current authority. Writes linearize at dispatch:
779
+ // revocation afterward cannot turn a successful effect into a denied receipt.
780
+ if(t3ReadTools.has(name)) authorize();
781
+ }
782
+ } else result=await notifyLedger.send(principal.worker,str(a.text,'text',1000),notificationKey,idempotencyKey=>publishAlert('Dalan message',a.text,log,{requirePublisher:true,idempotencyKey}));
745
783
  t3Audit.appendT3Audit(store.db,audit,principal.subject,'success',result);
746
784
  if(result && typeof result==='object' && Object.hasOwn(result,'_audit_ids')) { const {_audit_ids,...publicResult}=result; return publicResult; }
747
785
  return result;
@@ -855,7 +893,7 @@ async function dispatchTool(name,a,principal,notifyMeta) {
855
893
  return {...receipt,...repaired.marks};
856
894
  }
857
895
  case 'ask_question': {
858
- const requestId=id(a.request_id),question=str(a.question_id,'question_id',128),text=str(a.text,'text',4096),receipt=store.askQuestion(requestId,id(a.claim_id,'claim_id'),question,text,subject,worker,commandContext('ask_question',{question,text}),connectionId);
896
+ const requestId=id(a.request_id),question=str(a.question_id,'question_id',128),text=str(a.text,'text',4096),purpose=questionPurpose(a.purpose),receipt=store.askQuestion(requestId,id(a.claim_id,'claim_id'),question,text,subject,worker,commandContext('ask_question',{question,text,...(purpose==='clarification'?{}:{purpose})}),connectionId,purpose);
859
897
  notifyAttachedWaiter(requestId);
860
898
  return receipt;
861
899
  }
@@ -1102,9 +1140,10 @@ const adminServer=http.createServer(async(req,res)=>{
1102
1140
  excludeSensitive:body.exclude_sensitive===true,sensitiveScopeOverride:body.sensitive_scope_override??null,target:target??'dot'},{
1103
1141
  render:renderAssignment,
1104
1142
  admitExecution:(p,r)=>{
1105
- if(r.requiredCapabilities&&r.jobExecution!=='host') throw new Error(`invalid required_capabilities: only execution=host jobs can require bridge capabilities (this job has execution=${r.jobExecution})`);
1143
+ const adapterRequired=r.jobExecution==='host'?r.requiredCapabilities?.filter(name=>ADAPTER_CAPABILITY_NAMES.includes(name)):r.requiredCapabilities;
1144
+ admitAdapterCapabilities(workers.workers.get(storedTarget??target??'dot')?.adapter,adapterRequired,catalogProfile);
1106
1145
  // No usable executor, or a required capability the backend does not declare verified: never degraded to a run without it.
1107
- if(r.jobExecution==='host'&&(p.execution_scope==='implementation'||r.requiredCapabilities)) admitHostExecution(r.requiredCapabilities);
1146
+ if(r.jobExecution==='host'&&(p.execution_scope==='implementation'||r.requiredCapabilities)) admitHostExecution(r.requiredCapabilities?.filter(name=>!ADAPTER_CAPABILITY_NAMES.includes(name)));
1108
1147
  },
1109
1148
  validate:(p,{warnings})=>validateSubmissionAsync(p,{sensitiveScopeOverride:body.sensitive_scope_override??null,warnings,excludeSensitive:body.exclude_sensitive===true,review:body.review===true,worker:storedTarget??target??'dot'}),
1110
1149
  admitReadiness:p=>{
@@ -1124,7 +1163,7 @@ const adminServer=http.createServer(async(req,res)=>{
1124
1163
  if(!dryRun&&(order.verdict==='reject'||order.verdict==='clarify'||order.blocking)) throw Object.assign(order.refusal,{verdict:order.verdict,reasons:order.reasons,bytes:order.bytes});
1125
1164
  payload=order.payload;
1126
1165
  }
1127
- const {environmentId}=(dryRun&&order&&order.verdict!=='admissible')?{}:await destination.validate(delivery);
1166
+ const {environmentId,generation}=(dryRun&&order&&order.verdict!=='admissible')?{}:await destination.validate(delivery);
1128
1167
  // An awaited repository/destination lookup may outlive a host policy edit.
1129
1168
  assertRepoAllowed(storedTarget??target??'dot',existingRequest?.assignment??payload);
1130
1169
  if(dryRun) store.checkRetry(submitted,delivery,environmentId,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision);
@@ -1142,7 +1181,7 @@ const adminServer=http.createServer(async(req,res)=>{
1142
1181
  const readiness=order?.check_readiness??null;
1143
1182
  const preflight=order?.preflight??null;
1144
1183
  const defaultValidity=order?.defaultValidity??null;
1145
- const result=store.submit(payload,delivery,environmentId,owner,body.review===true,preflight,body.background===true?'background':'normal',meta,(()=>{const r=renderAssignment(submitted);return payload.brief!==r.brief||JSON.stringify(payload.scope_paths)!==JSON.stringify(r.scope_paths);})()?submitted:payload,body.max_queued??null,target,explicitExecution,workers.defaultExecution,requiredCapabilities,defaultValidity?.valid_until??null,commandKey,supersedes,destinationRevision);
1184
+ const result=store.submit(payload,delivery,environmentId,owner,body.review===true,preflight,body.background===true?'background':'normal',meta,(()=>{const r=renderAssignment(submitted);return payload.brief!==r.brief||JSON.stringify(payload.scope_paths)!==JSON.stringify(r.scope_paths);})()?submitted:payload,body.max_queued??null,target,explicitExecution,workers.defaultExecution,requiredCapabilities,defaultValidity?.valid_until??null,commandKey,supersedes,destinationRevision,null,generation??null);
1146
1185
  // Only a committed first replacement wakes the TARGET's already-attached waiter.
1147
1186
  if(supersedes&&!result.duplicate) {
1148
1187
  const targetId=supersedes.target_id,waiter=waiters.get(targetId);
@@ -1165,6 +1204,8 @@ const adminServer=http.createServer(async(req,res)=>{
1165
1204
  const got=maskedForOwner(withAvailableChecks(store.get(requestId)));
1166
1205
  if(url.searchParams.get('peek')!=='1') store.recordConsumed(requestId,'get');
1167
1206
  if(protocolServices&&store.isProtocolJob(requestId))got.protocol_stop=protocolServices.observation(requestId);
1207
+ // The owner needs the current revision to build a keyed, revision-checked command such as `dalan answer`. It is null for a job with no protocol revisions.
1208
+ got.protocol_revision=store.isProtocolJob(requestId)?store.protocolRevision(requestId):null;
1168
1209
  if(!workspaceEnabled||got.assignment?.execution_scope!=='implementation'||got.available_checks_error==='repository_policy_denied') return json(res,200,got);
1169
1210
  try { return json(res,200,{...got,check_metadata:workspace.checkMetadataFor(got.assignment,got.target_worker)}); }
1170
1211
  catch(error) { return json(res,200,{...got,check_metadata:null,check_metadata_error:publicErrorText(error,'check metadata')}); }
@@ -1219,7 +1260,7 @@ const adminServer=http.createServer(async(req,res)=>{
1219
1260
  const action=url.pathname.slice(7);
1220
1261
  if(action==='add') return json(res,200,toolRegistry.register(body.spec));
1221
1262
  if(action==='remove') return json(res,200,toolRegistry.remove(body.name));
1222
- if(action==='grant') { toolRegistry.grant(body.name,body.worker); return json(res,200,{name:body.name,worker:body.worker,granted:true}); }
1263
+ if(action==='grant') { toolRegistry.grant(body.name,body.worker,body.scope); return json(res,200,{name:body.name,worker:body.worker,granted:true}); }
1223
1264
  if(action==='revoke') { toolRegistry.revoke(body.name,body.worker); return json(res,200,{name:body.name,worker:body.worker,granted:false}); }
1224
1265
  } catch(error) { if(error instanceof RegistryError) throw new Error(`${error.code}: ${error.message}`); throw error; }
1225
1266
  }
@@ -1242,7 +1283,7 @@ const adminServer=http.createServer(async(req,res)=>{
1242
1283
  return json(res,200,store.integrated(id(body.id),body.reason===undefined||body.reason===null?null:str(body.reason,'reason',512)));
1243
1284
  }
1244
1285
  if(url.pathname==='/note'&&req.method==='POST') { const requestId=id(body.id); adminOwner(req,requestId); return json(res,200,store.note(requestId,body.text)); }
1245
- if(url.pathname==='/answer'&&req.method==='POST') { const requestId=id(body.id); adminOwner(req,requestId);return json(res,200,store.answerQuestion(requestId,str(body.question_id,'question_id',128),str(body.text,'text',4096),{key:body.command_key,revision:body.expected_revision},req.headers['x-owner-capability'])); }
1286
+ if(url.pathname==='/answer'&&req.method==='POST') { const requestId=id(body.id); adminOwner(req,requestId);const questionId=str(body.question_id,'question_id',128); requireOperatorForHumanQuestion(req,requestId,questionId);return json(res,200,store.answerQuestion(requestId,questionId,str(body.text,'text',4096),{key:body.command_key,revision:body.expected_revision},req.headers['x-owner-capability'])); }
1246
1287
  if(url.pathname==='/questions'&&req.method==='GET') { const requestId=id(url.searchParams.get('id'));adminOwner(req,requestId);return json(res,200,{request_id:requestId,questions:store.questions(requestId)}); }
1247
1288
  if(url.pathname==='/tell'&&req.method==='POST') return json(res,200,store.tell(str(body.text,'text',4096),body.worker===undefined&&workers.workers.has('dot')?'dot':submitTarget(workers,body.worker)??assertTarget(workers,'dot')));
1248
1289
  if(url.pathname==='/untell'&&req.method==='POST') return json(res,200,store.untell(id(body.message_id,'message_id'),body.worker===undefined?null:assertTarget(workers,body.worker)));
@@ -1478,6 +1519,15 @@ if(workspace) {
1478
1519
  setInterval(()=>{if(t3PostHandler.hasHeld())t3PostHandler.flushDue().catch(()=>{});},60000).unref();
1479
1520
  setInterval(maintain,500).unref(); maintain();
1480
1521
  setInterval(runDrain,500).unref(); runDrain();
1522
+ // A wake held because its parent was interrupted goes back to the queue once the parent runs again (see the T3 destination).
1523
+ let releasingHeld=false;
1524
+ const releaseHeldWakes=async()=>{
1525
+ if(releasingHeld||!store.heldDeliveries(1).length) return; releasingHeld=true;
1526
+ try { const destination=await destinations.for('t3'); if((await destination.releaseHeld()).length) runDrain(); }
1527
+ catch(error) { log({kind:'held_release_error',reason:String(error?.message??error).slice(0,300)}); }
1528
+ finally { releasingHeld=false; }
1529
+ };
1530
+ setInterval(releaseHeldWakes,Number(readEnv('DALAN_T3_HELD_RECHECK_MS'))||15000).unref();
1481
1531
  reconcileTick().catch(e=>log({kind:'reconciliation_error',reason:e.message}));
1482
1532
  setInterval(()=>reconcileTick().catch(e=>log({kind:'reconciliation_error',reason:e.message})),60000).unref();
1483
1533
  const retain=()=>{try{const r=retainLifecycle(store);if(r.rolled_up)log({kind:'lifecycle_rollup',...r});}catch(error){log({kind:'lifecycle_rollup_error',reason:error.message});}};
@@ -86,13 +86,24 @@ export function launchctl(args, { spawn = spawnSync, env = process.env } = {}) {
86
86
  }
87
87
  const uidOf = seams => (seams.uid ?? process.getuid?.());
88
88
  const domainOf = seams => `user/${uidOf(seams)}`;
89
- export const isLoaded = (label, seams = {}) => launchctl(['print', `${domainOf(seams)}/${label}`], seams).status === 0;
89
+ // Only launchctl's explicit missing-service diagnostic establishes absence.
90
+ export function queryAgent(label, seams = {}) {
91
+ const result = launchctl(['print', `${domainOf(seams)}/${label}`], seams);
92
+ const diagnostic = String(result.stderr || result.stdout).trim();
93
+ const absent = result.status > 0 && diagnostic.includes(`Could not find service "${label}" in domain`);
94
+ return { ...result, state: result.status === 0 ? 'loaded' : absent ? 'absent' : 'unknown' };
95
+ }
96
+ export function isLoaded(label, seams = {}) {
97
+ const result = queryAgent(label, seams);
98
+ if (result.state === 'unknown') fail(`Cannot determine whether launchd service ${label} is loaded; leaving its plist unchanged. launchctl print failed (exit ${result.status}): ${String(result.stderr || result.stdout).trim().slice(0, 500)}`);
99
+ return result.state === 'loaded';
100
+ }
90
101
  const must = (result, what) => { if (result.status !== 0) fail(`${what} failed (exit ${result.status}): ${String(result.stderr || result.stdout).trim().slice(0, 500)}`); };
91
102
 
92
103
  // Load the agent from its plist, then ask launchd to start it: on macOS 26 a bootstrapped agent can stay loaded and never spawn.
93
- export function loadAgent({ label, plistFile }, seams = {}) {
104
+ export function loadAgent({ label, plistFile, knownAbsent = false }, seams = {}) {
94
105
  const domain = domainOf(seams);
95
- if (!isLoaded(label, seams)) must(launchctl(['bootstrap', domain, plistFile], seams), `launchctl bootstrap ${domain} ${plistFile}`);
106
+ if (knownAbsent || !isLoaded(label, seams)) must(launchctl(['bootstrap', domain, plistFile], seams), `launchctl bootstrap ${domain} ${plistFile}`);
96
107
  const kick = launchctl(['kickstart', `${domain}/${label}`], seams);
97
108
  return { kicked: kick.status === 0, detail: kick.status === 0 ? '' : String(kick.stderr).trim() };
98
109
  }
@@ -120,13 +131,18 @@ export function controlLaunchd(receipt, action, seams = {}) {
120
131
  }
121
132
 
122
133
  // ---- plist files ------------------------------------------------------------------------------------------------------------------------
123
- // Write a generated plist. A plist that already has exactly this text is left alone (returns false). A different one that carries our marker
124
- // is replaced; anything else is refused so a hand-made agent is never overwritten.
125
- export function writeAgentFile(file, text) {
134
+ // Read-only ownership/collision check. Return whether the generated plist needs writing.
135
+ export function preflightAgentFile(file, text) {
126
136
  let existing = null;
127
137
  try { const info = fs.lstatSync(file); if (!info.isFile() || info.isSymbolicLink()) fail(`${file} is not a regular file; refusing to replace it`); existing = fs.readFileSync(file, 'utf8'); } catch (error) { if (error.code !== 'ENOENT') throw error; }
128
138
  if (existing === text) return false;
129
139
  if (existing !== null && !existing.includes(MARKER)) fail(`${file} already exists and was not generated by dalan; refusing to overwrite it`);
140
+ return true;
141
+ }
142
+
143
+ // Recheck at write time too, so a collision introduced after preflight is still refused.
144
+ export function writeAgentFile(file, text) {
145
+ if (!preflightAgentFile(file, text)) return false;
130
146
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o755 });
131
147
  const temp = `${file}.${process.pid}.tmp`;
132
148
  fs.writeFileSync(temp, text, { mode: 0o644 });
@@ -145,9 +161,11 @@ export function setUpdateAgent({ receipt, home, node, enabled }, seams = {}) {
145
161
  const { update } = launchdLabels(receipt.unit), file = path.join(receipt.unit_dir, `${update}.plist`);
146
162
  if (enabled) {
147
163
  fs.mkdirSync(path.join(home, 'logs'), { recursive: true, mode: 0o700 });
148
- const changed = writeAgentFile(file, updatePlist({ unit: receipt.unit, node: receipt.node ?? node, home }));
164
+ const text = updatePlist({ unit: receipt.unit, node: receipt.node ?? node, home });
165
+ const changed = preflightAgentFile(file, text);
149
166
  if (changed) unloadAgent({ label: update }, seams);
150
- if (!isLoaded(update, seams)) must(launchctl(['bootstrap', domainOf(seams), file], seams), `launchctl bootstrap ${file}`);
167
+ writeAgentFile(file, text);
168
+ if (changed || !isLoaded(update, seams)) must(launchctl(['bootstrap', domainOf(seams), file], seams), `launchctl bootstrap ${file}`);
151
169
  } else {
152
170
  unloadAgent({ label: update }, seams);
153
171
  fs.rmSync(file, { force: true });
@@ -157,6 +175,8 @@ export function setUpdateAgent({ receipt, home, node, enabled }, seams = {}) {
157
175
 
158
176
  export function removeAgents({ unit, unit_dir: dir }, seams = {}) {
159
177
  const { service, update } = launchdLabels(unit), removed = [];
178
+ // An unknown job must not allow even the other job's plist to be removed.
179
+ for (const label of [update, service]) isLoaded(label, seams);
160
180
  for (const label of [update, service]) {
161
181
  if (unloadAgent({ label }, seams)) removed.push(`unloaded ${label}`);
162
182
  const file = path.join(dir, `${label}.plist`);
@@ -2,6 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { DatabaseSync } from 'node:sqlite';
5
+ import { loadCapacity } from './projects.mjs';
5
6
  import { loadEffectiveOwnerWorkers, parseWorkers, updateWorkerRepoPolicy, workerRepoMigrationFile } from './workers.mjs';
6
7
 
7
8
  function reenrollmentIntent(files, workers) {
@@ -45,9 +46,16 @@ export function migrateWorkers({ home, sources, sourceDbs = [], workspaceWorkers
45
46
  const workers = {};
46
47
  const grants = new Map();
47
48
  const deniedRepositories = [];
49
+ let limits = null;
48
50
  for (const source of sources) {
49
51
  const file = path.resolve(source);
50
52
  if (!fs.existsSync(file) && !fs.existsSync(workerRepoMigrationFile(file))) throw new Error(`no worker policy at ${file}`);
53
+ const sourceLimits = path.join(path.dirname(file), 'limits.json');
54
+ if (fs.existsSync(sourceLimits)) {
55
+ const capacity = loadCapacity(sourceLimits);
56
+ if (limits && limits.max_claimed_outer_assignments !== capacity) throw new Error('conflicting capacity limits in sources');
57
+ limits = { max_claimed_outer_assignments: capacity };
58
+ }
51
59
  const profile = loadEffectiveOwnerWorkers(file);
52
60
  deniedRepositories.push(...profile.deniedRepoGrants.map(item => ({ source: file, ...item })));
53
61
  for (const [name, worker] of profile.workers) {
@@ -80,8 +88,10 @@ export function migrateWorkers({ home, sources, sourceDbs = [], workspaceWorkers
80
88
  const config = path.join(home, '.config/dalan');
81
89
  const workersFile = path.join(config, 'workers.json');
82
90
  const manifestFile = path.join(config, 'service-migration.json');
91
+ const limitsFile = limits ? path.join(config, 'limits.json') : null;
83
92
  try {
84
93
  fs.mkdirSync(config, { recursive: true, mode: 0o700 });
94
+ if (limits) fs.writeFileSync(limitsFile, JSON.stringify(limits, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
85
95
  fs.writeFileSync(workersFile, JSON.stringify(value, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
86
96
  for (const [name, repos] of grants) for (const repo of repos) updateWorkerRepoPolicy(workersFile, name, 'allow', repo);
87
97
  fs.writeFileSync(manifestFile, JSON.stringify(manifest, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
@@ -89,7 +99,7 @@ export function migrateWorkers({ home, sources, sourceDbs = [], workspaceWorkers
89
99
  fs.rmSync(home, { recursive: true, force: true });
90
100
  throw error;
91
101
  }
92
- return { home, workers_file: workersFile, migration_manifest: manifestFile,
102
+ return { home, workers_file: workersFile, migration_manifest: manifestFile, limits, limits_file: limitsFile,
93
103
  workers: [...grants].map(([worker, repos]) => ({ worker, repos, workspaceAllowed: workers[worker].workspaceAllowed })),
94
104
  default_execution: 'none', reenrollment_required: true, denied_repositories: deniedRepositories };
95
105
  }
@@ -108,6 +118,6 @@ export function migrationMain(args = process.argv.slice(4)) {
108
118
  else workspaceWorkers.push(args[i]);
109
119
  }
110
120
  const result = migrateWorkers({ home, sources, sourceDbs, workspaceWorkers });
111
- process.stdout.write(json ? JSON.stringify(result) + '\n' : `Created ${result.workers.length} workers in ${result.home}; execution defaults to none. Re-enrol connectors, subscriptions and destination approvals using ${result.migration_manifest}. No sign-ins or jobs were copied.${result.denied_repositories.length ? ` Denied unaudited additions: ${result.denied_repositories.map(item => `${item.worker}: ${item.repos.join(', ')}`).join('; ')}.` : ''}\n`);
121
+ process.stdout.write(json ? JSON.stringify(result) + '\n' : `Created ${result.workers.length} workers in ${result.home}; execution defaults to none. Capacity limits: ${result.limits ? result.limits.max_claimed_outer_assignments : 'default (1; no limits file)'}. Re-enrol connectors, subscriptions and destination approvals using ${result.migration_manifest}. No sign-ins or jobs were copied.${result.denied_repositories.length ? ` Denied unaudited additions: ${result.denied_repositories.map(item => `${item.worker}: ${item.repos.join(', ')}`).join('; ')}.` : ''}\n`);
112
122
  return result;
113
123
  }