@tnunamak/dalan 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/CONTRIBUTING.md +4 -0
  3. package/PROTOCOL.md +8 -0
  4. package/README.md +68 -28
  5. package/bin/dalan.mjs +1 -1
  6. package/bin/dot-worker.mjs +115 -16
  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 +4 -3
  12. package/docs/pull-workers.md +1 -0
  13. package/docs/relationships.md +13 -0
  14. package/docs/service-setup.md +40 -17
  15. package/docs/setup-reference.md +1 -1
  16. package/docs/t3-integration.md +2 -0
  17. package/docs/t3-question-relationship.md +43 -0
  18. package/docs/t3-reverse-control.md +12 -8
  19. package/docs/t3-wake-fence-r4.md +42 -0
  20. package/docs/test-suite-isolation.md +205 -0
  21. package/docs/usage.md +14 -2
  22. package/docs/worker-clients.md +3 -1
  23. package/package.json +6 -3
  24. package/qualification/README.md +13 -0
  25. package/qualification/mcp.json +121 -0
  26. package/qualification/protocol-v0.json +127 -0
  27. package/src/admin-socket.mjs +2 -1
  28. package/src/answer-journal.mjs +200 -0
  29. package/src/auth-check.mjs +8 -2
  30. package/src/claim-command-ledger.mjs +3 -2
  31. package/src/cli-help.mjs +19 -10
  32. package/src/destinations/index.mjs +6 -0
  33. package/src/destinations/none.mjs +3 -0
  34. package/src/destinations/t3.mjs +63 -6
  35. package/src/execution.mjs +20 -2
  36. package/src/follow-current.mjs +4 -2
  37. package/src/gozar-routes.mjs +4 -3
  38. package/src/host-budget.mjs +17 -11
  39. package/src/host-execution-policy.mjs +2 -2
  40. package/src/host-stop-reverify.mjs +6 -4
  41. package/src/inbox.mjs +13 -3
  42. package/src/integrator.mjs +3 -1
  43. package/src/lifecycle.mjs +60 -2
  44. package/src/patch-apply.mjs +74 -13
  45. package/src/server.mjs +210 -34
  46. package/src/service-launchd.mjs +28 -8
  47. package/src/service-migrate-workers.mjs +12 -2
  48. package/src/service.mjs +52 -16
  49. package/src/status-summary.mjs +3 -0
  50. package/src/store.mjs +300 -34
  51. package/src/submission-policy.mjs +8 -4
  52. package/src/t3.mjs +21 -2
  53. package/src/tool-registry.mjs +54 -8
  54. package/src/workers.mjs +22 -3
  55. package/src/workspace.mjs +94 -15
@@ -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
  }
package/src/service.mjs CHANGED
@@ -7,13 +7,15 @@ import { createHash, randomBytes } from 'node:crypto';
7
7
  import { fileURLToPath } from 'node:url';
8
8
  import { isIP } from 'node:net';
9
9
  import { defaultPath } from './paths.mjs';
10
+ import { socketPathLimit } from './admin-socket.mjs';
10
11
  import { initAsFiles, writeAtomic } from './as-files.mjs';
11
12
  import { parseWorkers } from './workers.mjs';
13
+ import { loadCapacity } from './projects.mjs';
12
14
  import { parseArgs } from '../scripts/live-trial/common.mjs';
13
15
  import { buildQuery, ensureDurableRoute, explainRouteError, describeCandidate, describeDisclosure, gozarHomeFor, registerExternalService, resolveGozar, resolveRouteWord } from './gozar-routes.mjs';
14
16
  import { autoUpdateUnits, setAutoUpdate } from './service-auto-update.mjs';
15
17
  import { serviceHomeFor, readDefaultHome, recordDefaultHome, forgetDefaultHome, DEFAULT_SERVICE_HOME } from './default-home.mjs';
16
- import { launchdLabels, launchAgentsDir, servicePlist, writeAgentFile, loadAgent, unloadAgent, removeAgents, lintPlist } from './service-launchd.mjs';
18
+ import { launchdLabels, launchAgentsDir, servicePlist, updatePlist, preflightAgentFile, writeAgentFile, loadAgent, unloadAgent, removeAgents, lintPlist, isLoaded } from './service-launchd.mjs';
17
19
 
18
20
  const REPO = path.resolve(fileURLToPath(new URL('..', import.meta.url)));
19
21
  const SAFE_PATH = /^[A-Za-z0-9_@+=:,./-]+$/;
@@ -193,7 +195,7 @@ function profileFor(home, workers) {
193
195
 
194
196
  const POLICY_HOME_FILES = new Set([
195
197
  'service-migration.json', 'workers.json', 'workers-audit.jsonl', 'workers-audit-checkpoint.sqlite',
196
- 'workers-audit-checkpoint.sqlite-wal', 'workers-audit-checkpoint.sqlite-shm', 'workers-repos.json',
198
+ 'workers-audit-checkpoint.sqlite-wal', 'workers-audit-checkpoint.sqlite-shm', 'workers-repos.json', 'limits.json',
197
199
  ]);
198
200
  const WORKSPACE_RUNTIME_DIRS = new Set(['artifacts', 'caches', 'host-receipts', 'mirrors', 'run', 'worktrees']);
199
201
  const WORKSPACE_RUNTIME_FILES = new Map([['github-askpass', 0o700]]);
@@ -247,6 +249,11 @@ function checkHomeScope(home, configDir, o, workers) {
247
249
  if (configInfo.isSymbolicLink() || !configInfo.isDirectory()) fail(`${configDir} must be a real directory`);
248
250
  const receiptFile = path.join(configDir, 'service-install.json');
249
251
  const entries = fs.readdirSync(configDir);
252
+ if (entries.includes('limits.json')) {
253
+ const file = path.join(configDir, 'limits.json'), info = fs.lstatSync(file);
254
+ if (!info.isFile() || info.isSymbolicLink() || (typeof process.getuid === 'function' && info.uid !== process.getuid()) || (info.mode & 0o777) !== 0o600) fail(`${file} must be a private regular file`);
255
+ loadCapacity(file);
256
+ }
250
257
  const hasReceipt = entries.includes('service-install.json');
251
258
  if (!hasReceipt && rootEntries.some(name => !['.config', '.local', '.tmp', 'resource-url', 'logs'].includes(name))) fail(`${home} contains update data without a service receipt`);
252
259
  if (hasReceipt) {
@@ -371,18 +378,21 @@ export async function installService(o, seams = {}) {
371
378
  if (!path.isAbsolute(o.home) || !SAFE_PATH.test(o.home)) fail('--home must be an absolute service-safe path');
372
379
  assertRealDirectoryPath(path.dirname(o.home), { owner: true });
373
380
  assertRealDirectoryPath(o.home, { owner: true });
374
- let gozar = null;
381
+ // Every check up to the route allocation below only reads. A public route is allocated after the last of them passes, so a
382
+ // read-only preflight refusal leaves no route behind. Later writes or startup can still fail.
383
+ const adminSocket = path.join(defaultPath(o.home, '.local/share/dot-bridge'), 'admin.sock');
384
+ const socketBytes = Buffer.byteLength(adminSocket), socketLimit = socketPathLimit(platform);
385
+ if (socketBytes > socketLimit) fail(`--home is too long: the bridge's admin socket ${adminSocket} would be ${socketBytes} bytes, and the limit on ${mac ? 'macOS' : 'Linux'} is ${socketLimit} bytes. Use a shorter --home.`);
386
+ let gozar = null, allocate = false;
375
387
  if (o.auto) {
376
- // The one-command install: reuse the port and address a previous run recorded, or pick a free port and ask Gozar for the address.
388
+ // The one-command install: reuse the port and address a previous run recorded, or pick a free port now and ask Gozar for
389
+ // the address once every check has passed.
377
390
  const prior = readReceipt(o.home);
378
391
  if (prior?.origin && prior.port) o = { ...o, origin: prior.origin, port: prior.port, target: parseTarget(prior.target) };
379
392
  else {
380
393
  const port = await (seams.freePort ?? firstFreePort)(8789);
381
- gozar = seams.gozar ?? await resolveGozar();
382
- const wanted = buildQuery({ home: gozarHomeFor(env), target: `127.0.0.1:${port}`, usage: { kind: 'durable', routeId: 'dalan-main' }, route: o.route, address: 'stable' });
383
- const { query, pick } = await resolveRouteWord({ gozar, query: wanted });
384
- const view = await ensureDurableRoute({ gozar, query, pick, consent: seams.consent ?? (async () => fail('A durable route needs your approval; run `dalan setup --route NAME` first, then retry.')) });
385
- o = { ...o, origin: parseOrigin(view.origin), port, target: parseTarget(`127.0.0.1:${port}`) };
394
+ o = { ...o, origin: null, port, target: parseTarget(`127.0.0.1:${port}`) };
395
+ allocate = true;
386
396
  }
387
397
  }
388
398
  const target = parseTarget(typeof o.target === 'string' ? o.target : `${o.target?.host}:${o.target?.port}`);
@@ -411,9 +421,14 @@ export async function installService(o, seams = {}) {
411
421
  Object.assign(files, autoUpdateUnits({ home: o.home, unit: name, node }).files);
412
422
  }
413
423
  let replaceLegacyUnit = false;
424
+ let updateNeedsReplace = false;
414
425
  // Check every collision before creating the bridge home or the first unit file.
415
- for (const [filename, text] of mac ? [] : Object.entries(files)) {
426
+ if (mac && autoUpdate && !o.writeUnitsOnly) {
427
+ updateNeedsReplace = preflightAgentFile(path.join(unitDir, `${labels.update}.plist`), updatePlist({ unit: name, node, home: o.home }));
428
+ }
429
+ for (const [filename, text] of Object.entries(files)) {
416
430
  const file = path.join(unitDir, filename);
431
+ if (mac) { preflightAgentFile(file, text); continue; }
417
432
  if (fs.existsSync(file) && (!fs.lstatSync(file).isFile() || fs.readFileSync(file, 'utf8') !== text)) {
418
433
  const actual = fs.lstatSync(file).isFile() ? fs.readFileSync(file, 'utf8') : '';
419
434
  const oldRepo = actual.match(/^WorkingDirectory=(.+)$/m)?.[1];
@@ -425,6 +440,10 @@ export async function installService(o, seams = {}) {
425
440
  else fail(`${file} already exists with different contents; refusing to overwrite it`);
426
441
  }
427
442
  }
443
+ if (mac && !o.writeUnitsOnly && preflightAgentFile(path.join(unitDir, `${labels.service}.plist`), files[`${labels.service}.plist`])) {
444
+ isLoaded(labels.service, seams.launchd);
445
+ }
446
+ if (updateNeedsReplace) isLoaded(labels.update, seams.launchd);
428
447
  if (o.writeUnitsOnly) {
429
448
  if (replaceLegacyUnit) fail('rerun without --write-units-only to enroll an existing service for updates');
430
449
  if (mac) for (const [filename, text] of Object.entries(files)) writeAgentFile(path.join(unitDir, filename), text); else writeUnits(unitDir, files);
@@ -434,9 +453,22 @@ export async function installService(o, seams = {}) {
434
453
  assertGozarStatePath(env);
435
454
  const needsEnrollmentRestart = replaceLegacyUnit || !!previous && (!previous.repo || previous.enrollment_pending === true);
436
455
  const spawn = seams.spawn ?? spawnSync;
437
- if (!mac) runCommand('systemctl', ['--user', 'show-environment'], { env, spawn });
456
+ if (!mac) {
457
+ try { runCommand('systemctl', ['--user', 'show-environment'], { env, spawn }); }
458
+ catch (error) { fail(`the user systemd manager is not reachable (${error.message}). Run \`systemctl --user status\` to see why; a login session or \`loginctl enable-linger\` may be needed.`); }
459
+ }
460
+ let allocated = null;
461
+ if (allocate) {
462
+ const wanted = buildQuery({ home: gozarHomeFor(env), target: o.target.value, usage: { kind: 'durable', routeId: 'dalan-main' }, route: o.route, address: 'stable' });
463
+ const { query, pick } = await resolveRouteWord({ gozar, query: wanted });
464
+ const view = await ensureDurableRoute({ gozar, query, pick, consent: seams.consent ?? (async () => fail('A durable route needs your approval; run `dalan setup --route NAME` first, then retry.')) });
465
+ o = { ...o, origin: parseOrigin(view.origin) };
466
+ // Gozar's reply does not say whether this call created the route or reused one that already existed (from `dalan setup`, or
467
+ // another install), so a failure below never closes it. The receipt keeps its handle, and `dalan service uninstall` releases it.
468
+ allocated = view.handle ?? null;
469
+ }
438
470
  fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
439
- if (!homeScope.hasReceipt) writePrivate(receiptFile, `${JSON.stringify({ ...installReceipt(o.home, configDir, o, profile.workers), repo, node, unit_dir: unitDir, auto_update: autoUpdate, platform, route: o.route ?? null }, null, 2)}\n`);
471
+ if (!homeScope.hasReceipt) writePrivate(receiptFile, `${JSON.stringify({ ...installReceipt(o.home, configDir, o, profile.workers), repo, node, unit_dir: unitDir, auto_update: autoUpdate, platform, route: o.route ?? null, ...(allocated ? { route_handle: allocated } : {}) }, null, 2)}\n`);
440
472
  if (!hasCurrent) fs.symlinkSync(repo, current);
441
473
  const homeFiles = prepareHome(o, profile);
442
474
  if (needsEnrollmentRestart) {
@@ -450,10 +482,12 @@ export async function installService(o, seams = {}) {
450
482
  if (mac) {
451
483
  fs.mkdirSync(path.join(o.home, 'logs'), { recursive: true, mode: 0o700 });
452
484
  const plistFile = path.join(unitDir, `${labels.service}.plist`);
453
- const changed = writeAgentFile(plistFile, files[`${labels.service}.plist`]);
454
- if (lintPlist(plistFile, seams) === false) fail(`${plistFile} is not a valid property list`);
485
+ const changed = preflightAgentFile(plistFile, files[`${labels.service}.plist`]);
455
486
  if (changed) unloadAgent({ label: labels.service }, seams.launchd);
456
- loadAgent({ label: labels.service, plistFile }, seams.launchd);
487
+ writeAgentFile(plistFile, files[`${labels.service}.plist`]);
488
+ if (lintPlist(plistFile, seams) === false) fail(`${plistFile} is not a valid property list`);
489
+ const { kicked, detail } = loadAgent({ label: labels.service, plistFile, knownAbsent: changed }, seams.launchd);
490
+ if (!kicked) fail(`launchctl kickstart ${labels.service} failed: ${detail}`);
457
491
  } else {
458
492
  writeUnits(unitDir, files);
459
493
  runCommand('systemctl', ['--user', 'daemon-reload'], { env, spawn });
@@ -499,7 +533,9 @@ export async function uninstallService({ home }, seams = {}) {
499
533
  const removed = [];
500
534
  const unitDir = receipt.unit_dir;
501
535
  if (!unitDir || !path.isAbsolute(unitDir)) fail('the service receipt names no unit directory');
502
- if (receipt.auto_update) { try { await setAutoUpdate({ home, enabled: false }, { ...seams, env, platform }); removed.push('automatic updates off'); } catch (error) { removed.push(`update job not removed: ${error.message}`); } }
536
+ // Verify both jobs before removing either plist or disabling automatic updates.
537
+ if (mac) for (const label of Object.values(launchdLabels(receipt.unit))) isLoaded(label, seams.launchd);
538
+ if (receipt.auto_update) { try { await setAutoUpdate({ home, enabled: false }, { ...seams, env, platform }); removed.push('automatic updates off'); } catch (error) { if (mac) throw error; removed.push(`update job not removed: ${error.message}`); } }
503
539
  if (mac) removed.push(...removeAgents({ unit: receipt.unit, unit_dir: unitDir }, seams.launchd));
504
540
  else {
505
541
  const spawn = seams.spawn ?? spawnSync, name = receipt.unit;
@@ -41,6 +41,9 @@ export function formatStatusSummary(status, { home, url = null, trial = false, n
41
41
  const paused = status?.paused === true;
42
42
  const lines = [`Bridge: ${paused ? 'running, paused' : 'running'}${url ? ` on ${url}` : ''} (${trial ? 'trial home' : 'home'} ${home})${paused && status.pause_reason ? `. Pause reason: ${status.pause_reason}` : ''}`,
43
43
  ...(workers.length ? workers.map(w => w.text) : ['Workers: none yet'])];
44
+ // A wake held because its parent stopped is invisible in the queue counts: it left the send queue and waits for the parent.
45
+ const held = Number.isInteger(status?.held_wakes) ? status.held_wakes : 0;
46
+ if (held > 0) lines.push(`${held} held wake${held === 1 ? '' : 's'}: the parent thread stopped, so the wake waits until it runs again (see: ${cli} inbox --all)`);
44
47
  const total = workers.reduce((n, w) => n + w.total, 0) || (status?.counts ?? []).reduce((n, c) => n + c.count, 0);
45
48
  const next = paused ? `resume handing out jobs: ${cli} resume`
46
49
  : workers.some(w => w.queued) ? `send your worker the queued job (to connect a worker first, see ${CONNECT_URL}); list your jobs: ${cli} inbox --all`