@tnunamak/dalan 0.8.1 → 0.8.2

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 (124) hide show
  1. package/CHANGELOG.md +59 -2
  2. package/CONTRIBUTING.md +2 -0
  3. package/README.md +8 -12
  4. package/bin/dalan.mjs +25 -4
  5. package/bin/dot-acp-agent.mjs +572 -76
  6. package/bin/dot-alert.mjs +9 -3
  7. package/bin/dot-deadman.mjs +3 -1
  8. package/bin/dot-heartbeat.mjs +14 -7
  9. package/bin/dot-pr-reviewer.mjs +3 -31
  10. package/bin/dot-worker.mjs +121 -34
  11. package/contracts/adapter-qualification.schema.json +94 -7
  12. package/docs/chatgpt-worker-onboarding.md +1 -1
  13. package/docs/codex-to-muse.md +2 -2
  14. package/docs/connect-chatgpt.md +1 -1
  15. package/docs/connection-longevity.md +2 -2
  16. package/docs/dalan-upgrade.md +8 -5
  17. package/docs/deadman.md +4 -0
  18. package/docs/design/authority-matrix.md +18 -0
  19. package/docs/design/failure-table.md +87 -0
  20. package/docs/design/identities.md +22 -0
  21. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  22. package/docs/design/reuse-ledger.md +75 -0
  23. package/docs/design/target-architecture-v2.md +434 -0
  24. package/docs/local-agent-mcp.md +14 -0
  25. package/docs/local-agent-requester.md +2 -1
  26. package/docs/manual-setup.md +1 -1
  27. package/docs/operations.md +77 -14
  28. package/docs/pull-workers.md +11 -1
  29. package/docs/service-setup.md +10 -10
  30. package/docs/t3-integration.md +4 -2
  31. package/docs/t3-reverse-control.md +5 -5
  32. package/docs/test-suite-isolation.md +7 -6
  33. package/docs/trials/chatgpt-agent.md +47 -0
  34. package/docs/trials/claude-code-requester.md +68 -0
  35. package/docs/trials/muse.md +46 -0
  36. package/docs/usage.md +21 -7
  37. package/docs/worker-clients.md +1 -1
  38. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  39. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  40. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  41. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  42. package/package.json +4 -3
  43. package/packages/job-core/protocol/canonical.mjs +45 -7
  44. package/packages/job-core/transitions.mjs +4 -2
  45. package/scripts/upgrade-drain.mjs +96 -8
  46. package/scripts/worker-bridge-setup.mjs +215 -120
  47. package/src/ack-ledger.mjs +7 -1
  48. package/src/acp-bridge.mjs +256 -28
  49. package/src/admin-socket.mjs +32 -3
  50. package/src/alerts.mjs +17 -8
  51. package/src/answer-journal-retention.mjs +82 -0
  52. package/src/answer-journal.mjs +6 -4
  53. package/src/as-store.mjs +51 -6
  54. package/src/as.mjs +27 -5
  55. package/src/catalog-switch-inventory.mjs +70 -0
  56. package/src/check-response.mjs +4 -1
  57. package/src/cli-help.mjs +14 -3
  58. package/src/cli-name.mjs +13 -1
  59. package/src/connect-cli.mjs +159 -4
  60. package/src/deadman.mjs +8 -5
  61. package/src/delivery.mjs +2 -19
  62. package/src/destinations/index.mjs +75 -14
  63. package/src/drain-runner.mjs +5 -1
  64. package/src/follow-current.mjs +3 -1
  65. package/src/get-summary.mjs +11 -2
  66. package/src/git-env.mjs +1 -1
  67. package/src/gozar-routes.mjs +313 -94
  68. package/src/host-budget-storage.py +56 -6
  69. package/src/host-budget.mjs +98 -15
  70. package/src/host-execution-policy.mjs +17 -6
  71. package/src/legacy-names.mjs +0 -2
  72. package/src/lifecycle.mjs +44 -9
  73. package/src/loopback-probe.mjs +46 -0
  74. package/src/mcp-outcome.mjs +3 -1
  75. package/src/mcp-sse.mjs +2 -1
  76. package/src/mcp-stdio.mjs +192 -30
  77. package/src/patch-apply.mjs +212 -7
  78. package/src/phase-trace.mjs +73 -0
  79. package/src/prepared-go-modules.mjs +127 -0
  80. package/src/prepared-node-modules.mjs +225 -38
  81. package/src/prepared-pnpm.mjs +276 -0
  82. package/src/prepared-store-prune.mjs +52 -0
  83. package/src/projects.mjs +59 -7
  84. package/src/protocol-artifact-commands.mjs +28 -0
  85. package/src/protocol-finish.mjs +3 -2
  86. package/src/publication-authority.mjs +22 -0
  87. package/src/publish-plan.mjs +2 -2
  88. package/src/pull-queue.mjs +55 -20
  89. package/src/read-api.mjs +127 -0
  90. package/src/redaction.mjs +173 -0
  91. package/src/rejections.mjs +19 -3
  92. package/src/route-custody.mjs +90 -0
  93. package/src/route-publication.mjs +50 -0
  94. package/src/route-setup.mjs +184 -0
  95. package/src/schema-subset.mjs +5 -3
  96. package/src/server.mjs +503 -98
  97. package/src/service-launchd.mjs +5 -1
  98. package/src/service-update-lock.mjs +7 -4
  99. package/src/service-update-runtime.mjs +64 -19
  100. package/src/service-update.mjs +193 -48
  101. package/src/service.mjs +276 -77
  102. package/src/setup.mjs +48 -25
  103. package/src/signal.mjs +1 -1
  104. package/src/status-evidence.mjs +18 -5
  105. package/src/store.mjs +876 -120
  106. package/src/submission-policy.mjs +257 -56
  107. package/src/t3-control.mjs +1 -1
  108. package/src/t3.mjs +14 -8
  109. package/src/terminal-safe.mjs +9 -7
  110. package/src/tool-registry.mjs +134 -41
  111. package/src/try-exposure.mjs +53 -86
  112. package/src/try-hosted.mjs +257 -70
  113. package/src/try.mjs +48 -22
  114. package/src/work-order.mjs +11 -6
  115. package/src/worker-instructions.mjs +26 -4
  116. package/src/worker-runs.mjs +35 -0
  117. package/src/workers.mjs +34 -7
  118. package/src/workspace.mjs +354 -54
  119. package/systemd/dot-deadman.service +3 -1
  120. package/docs/dot-pr-reviewer.config.example.json +0 -9
  121. package/docs/pr-head-reviewer.md +0 -70
  122. package/src/pr-head-reviewer.mjs +0 -596
  123. package/systemd/dot-pr-reviewer.service +0 -11
  124. package/systemd/dot-pr-reviewer.timer +0 -10
package/bin/dot-alert.mjs CHANGED
@@ -3,7 +3,13 @@
3
3
  // so scheduled agents can alert the owner without handling the notification token themselves.
4
4
  // Usage: dalan-alert "title" "message"
5
5
  import { publishAlert } from '../src/alerts.mjs';
6
- const [title, message] = process.argv.slice(2);
7
- if (!title || !message) { console.error('usage: dalan-alert TITLE MESSAGE'); process.exit(2); }
8
- await publishAlert(title, message, () => {}, { requirePublisher: true });
6
+ const args = process.argv.slice(2);
7
+ const [title, message] = args;
8
+ if (args.length !== 2 || !title.trim() || !message.trim()) { console.error('usage: dalan-alert TITLE MESSAGE'); process.exit(2); }
9
+ try {
10
+ await publishAlert(title, message, () => {}, { requirePublisher: true });
11
+ } catch (error) {
12
+ console.error('Delivery unconfirmed; do not assume repeating this alert is deduplicated.');
13
+ throw error;
14
+ }
9
15
  console.log('sent');
@@ -36,7 +36,8 @@ async function heartbeat() {
36
36
  if (target.search || target.hash) throw new Error('heartbeat base URL cannot include a query or fragment');
37
37
  const health = JSON.parse(fs.readFileSync(file, 'utf8'));
38
38
  const observed = Date.parse(health.observed_at);
39
- if (health.healthy !== true || !Number.isFinite(observed) || Date.now() - observed > 90_000 || observed > Date.now() + 30_000) {
39
+ const now = Date.now();
40
+ if (health.healthy !== true || !Number.isFinite(observed) || now - observed > 90_000 || observed > now + 30_000) {
40
41
  throw new Error('bridge health evidence is absent, unhealthy, or stale');
41
42
  }
42
43
  target.pathname = `${target.pathname.replace(/\/+$/, '')}/heartbeat`;
@@ -49,6 +50,7 @@ async function heartbeat() {
49
50
  }
50
51
 
51
52
  try {
53
+ if (command === 'heartbeat' && args.length) throw new Error('usage: dalan-deadman heartbeat');
52
54
  loadEnv();
53
55
  if (command === 'heartbeat') await heartbeat();
54
56
  else if(command==='status') {
@@ -8,22 +8,29 @@ import { execFile } from 'node:child_process';
8
8
  import { promisify } from 'node:util';
9
9
  import { fileURLToPath } from 'node:url';
10
10
  import { bridgeHealth } from '../src/host-health.mjs';
11
+ import { adminSocketPath } from '../src/admin-socket.mjs';
11
12
 
12
13
  const root = defaultPath(os.homedir(),'.local/share/dot-bridge');
13
14
  const healthFile = readEnv('DALAN_HEALTH_FILE') || path.join(root, 'health.json');
14
15
  const temporary = `${healthFile}.${process.pid}`;
15
16
  try {
16
- const health = await bridgeHealth({ socketPath: path.join(root, 'admin.sock'), drainerFile: readEnv('DALAN_DRAINER_HEALTH_FILE') });
17
+ const health = await bridgeHealth({ socketPath: adminSocketPath(root), drainerFile: readEnv('DALAN_DRAINER_HEALTH_FILE') });
17
18
  fs.writeFileSync(temporary, JSON.stringify(health) + '\n', { mode: 0o600 });
18
19
  fs.renameSync(temporary, healthFile);
19
- const { stdout } = await promisify(execFile)(process.execPath, [fileURLToPath(new URL('./dot-deadman.mjs', import.meta.url)), 'heartbeat'], {
20
- env: { ...process.env, DOT_BRIDGE_HEALTH_FILE: healthFile }, timeout: 10000,
21
- });
22
- process.stdout.write(stdout);
23
20
  } catch {
24
21
  fs.rmSync(temporary, { force: true });
25
- // Remove stale positive evidence; a failed local check must not ping externally.
26
22
  fs.rmSync(healthFile, { force: true });
27
- console.error('dalan-heartbeat: health check or external heartbeat failed');
23
+ console.error('dalan-heartbeat: local health check failed');
28
24
  process.exitCode = 1;
29
25
  }
26
+ if (!process.exitCode) {
27
+ try {
28
+ const { stdout } = await promisify(execFile)(process.execPath, [fileURLToPath(new URL('./dot-deadman.mjs', import.meta.url)), 'heartbeat'], {
29
+ env: { ...process.env, DOT_BRIDGE_HEALTH_FILE: healthFile }, timeout: 10000,
30
+ });
31
+ process.stdout.write(stdout);
32
+ } catch {
33
+ console.error('dalan-heartbeat: external heartbeat failed');
34
+ process.exitCode = 1;
35
+ }
36
+ }
@@ -1,32 +1,4 @@
1
1
  #!/usr/bin/env node
2
- // Submit one read-only review per open PR head that has no worker review yet. Deterministic; see docs/pr-head-reviewer.md.
3
- import { loadConfig, realDeps, run, acquireLock, paths, parseOnly } from '../src/pr-head-reviewer.mjs';
4
-
5
- const usage = `usage: dalan-pr-reviewer [--dry-run] [--only OWNER/REPO#N] [--max N] [--ignore-capacity] [--config FILE] [--state-dir DIR]
6
- --dry-run print what would be submitted; submit and write nothing
7
- --only OWNER/REPO#N consider only that PR (still deduped and gated)
8
- --max N submit at most N this run (default: config max_submits_per_run)
9
- --ignore-capacity with --dry-run only: preview candidates even when no lane is free`;
10
- const args = process.argv.slice(2), has = f => args.includes(f), opt = f => { const i = args.indexOf(f); return i < 0 ? null : args[i + 1]; };
11
- try {
12
- const known = new Set(['--dry-run', '--only', '--max', '--ignore-capacity', '--config', '--state-dir', '--help']);
13
- const values = new Set(['--only', '--max', '--config', '--state-dir']);
14
- for (let i = 0; i < args.length; i++) { if (!known.has(args[i])) throw new Error(`unknown argument ${args[i]}`); if (values.has(args[i])) i++; }
15
- if (has('--help')) { console.log(usage); process.exit(0); }
16
- const dryRun = has('--dry-run');
17
- if (has('--ignore-capacity') && !dryRun) throw new Error('--ignore-capacity requires --dry-run');
18
- let only = null;
19
- // A present --only with a missing or malformed value must fail, never fall through to every open PR.
20
- if (args.includes('--only')) only = parseOnly(opt('--only'));
21
- const max = opt('--max') === null ? null : Number(opt('--max'));
22
- if (max !== null && !(Number.isInteger(max) && max >= 0)) throw new Error('--max expects a non-negative integer');
23
- const cfg = loadConfig(opt('--config') ?? paths.config), stateDir = opt('--state-dir') ?? paths.stateDir;
24
- const release = dryRun ? () => {} : acquireLock(stateDir);
25
- if (!release) { console.error('dalan-pr-reviewer: another run is active'); process.exit(0); }
26
- try {
27
- await run({ cfg, deps: realDeps(cfg), stateDir, dryRun, only, maxSubmits: max, ignoreCapacity: has('--ignore-capacity'), print: line => console.log(line) });
28
- } finally { release(); }
29
- } catch (error) {
30
- console.error(`dalan-pr-reviewer: ${error.message}`);
31
- process.exit(1);
32
- }
2
+ // Retired. This stub keeps the `dalan-pr-reviewer` command for one release, so an upgrade leaves no dangling command.
3
+ console.error('dalan-pr-reviewer: the PR-head reviewer was retired from Dalan in this release; fleet tooling owns PR-head reviews.');
4
+ process.exit(2);
@@ -5,6 +5,9 @@ import http from 'node:http';
5
5
  import net from 'node:net';
6
6
  import { DatabaseSync } from 'node:sqlite';
7
7
  import { prepareNodeModules } from '../src/prepared-node-modules.mjs';
8
+ import { prepareGoModules, pruneGoStore } from '../src/prepared-go-modules.mjs';
9
+ import { preparePnpm } from '../src/prepared-pnpm.mjs';
10
+ import { pruneNodeStore } from '../src/prepared-store-prune.mjs';
8
11
  import fs from 'node:fs';
9
12
  import os from 'node:os';
10
13
  import path from 'node:path';
@@ -23,7 +26,7 @@ import { readLines } from '../src/request-log.mjs';
23
26
  import { lintChecksFile, formatChecksReport } from '../src/check-lint.mjs';
24
27
  import { parseExecution, parseRequiredCapabilities, hostReadiness, hostBackend } from '../src/execution.mjs';
25
28
  import { RESOURCE_LIMITS_UNAVAILABLE } from '../src/host-execution-policy.mjs';
26
- import { summarizeRejections } from '../src/rejections.mjs';
29
+ import { summarizeRejections, formatRejections } from '../src/rejections.mjs';
27
30
  import { VERDICT_EXIT, formatVerdict } from '../src/work-order.mjs';
28
31
  import { connectCommand } from '../src/connect-cli.mjs';
29
32
  import { runAuthCheck } from '../src/auth-check.mjs';
@@ -31,12 +34,12 @@ import { initAsFiles, rotateKeys } from '../src/as-files.mjs';
31
34
  import { docsUrl } from '../src/docs-url.mjs';
32
35
  import { workerPrompt } from '../src/worker-prompt.mjs';
33
36
  import { stoppedTrialFix } from '../src/try-command.mjs';
34
- import { formatGetSummary, formatWaitLine } from '../src/get-summary.mjs';
37
+ import { formatGetSummary, formatGetEndNote, formatWaitLine } from '../src/get-summary.mjs';
35
38
  import { cliCommand } from '../src/cli-name.mjs';
36
- import { applyPatch, listPatchFiles, patchMatchesWorktree, worktreeRoot } from '../src/patch-apply.mjs';
39
+ import { applyPatch, listPatchFiles, materialize, readMaterializeGrant, patchMatchesWorktree, worktreeRoot } from '../src/patch-apply.mjs';
37
40
  import { terminalSafe, jsonTerminalSafe } from '../src/terminal-safe.mjs';
38
41
  import { loadOwnerWorkers, parseWorkers, submitTarget, updateWorkerRepoPolicy, writeGenericProfile, writeLegacyMarker, readWorkerRepoHistory, seedWorkerRepos, inspectGrantAudit, ensureWorkerRelationship, AUDIT_INTEGRITY_HINT } from '../src/workers.mjs';
39
- import { adminSocketPathError } from '../src/admin-socket.mjs';
42
+ import { adminSocketPathError, adminSocketPath } from '../src/admin-socket.mjs';
40
43
  import { answerThroughJournal } from '../src/answer-journal.mjs';
41
44
  // An answer reply that takes longer than this counts as lost; the journaled envelope is sent again.
42
45
  const ANSWER_TIMEOUT_MS=30000;
@@ -48,7 +51,7 @@ console.error=(...parts)=>writeStderr(...parts.map(part=>typeof part==='string'?
48
51
 
49
52
  let endNote=null;
50
53
  const args = process.argv.slice(2), command = args.shift(), json = args.includes('--json');
51
- const home=os.homedir(), root=defaultPath(home,'.local/share/dot-bridge'), socket=path.join(root,'admin.sock'), receipts=path.join(root,'receipts');
54
+ const home=os.homedir(), root=defaultPath(home,'.local/share/dot-bridge'), socket=adminSocketPath(root), receipts=path.join(root,'receipts');
52
55
  function missingProfileWarning(worker,policy) {
53
56
  if(policy?.source==='admitted-history')return `worker "${worker}" uses a persisted exact repository list; no identity profile was created`;
54
57
  return `worker "${worker}" has no workers.json; repository jobs are denied until an explicit repository allow-list is configured (docs/operations.md#legacy-repository-policy-migration)`;
@@ -65,8 +68,8 @@ const FIRST_JOB_URL=docsUrl('docs/manual-setup.md','submit-finish-and-read-the-r
65
68
  // --json output keeps `dalan`, so scripts see the same text as before.
66
69
  const cli=json?'dalan':cliCommand(process.argv[1]);
67
70
  // Every option a command reads. An option it does not know is refused, so a typo is not ignored in silence.
68
- const SUBMIT_FLAGS=['--stdin','--json','--review','--wait','--dry-run','--queue-anyway','--refuse-defer','--allow-scope-prune','--fix-scope','--background','--allow-main','--exclude-sensitive'];
69
- const SUBMIT_VALUES=['--eligible','--policy','--file','--brief','--worker','--thread','--deliver','--timeout','--execution','--require-capability','--objective-key','--revision','--task-kind','--source','--revises','--sensitive-scope-override','--defer-if-queued','--producer-thread'];
71
+ const SUBMIT_FLAGS=['--stdin','--json','--review','--wait','--dry-run','--queue-anyway','--refuse-defer','--allow-scope-prune','--fix-scope','--background','--caller-waiting','--allow-main','--exclude-sensitive'];
72
+ const SUBMIT_VALUES=['--eligible','--policy','--file','--brief','--worker','--thread','--deliver','--timeout','--execution','--require-capability','--objective-key','--revision','--task-kind','--source','--revises','--follows','--sensitive-scope-override','--defer-if-queued','--producer-thread'];
70
73
  const SUBMIT_OPTIONS=[...SUBMIT_FLAGS,...SUBMIT_VALUES];
71
74
  function refuseUnknownOptions(name,{flags=[],values=[]}) {
72
75
  for(let i=0;i<args.length;i++) {
@@ -89,7 +92,7 @@ function bridgeNotRunning(error) {
89
92
  if(selected) return Object.assign(error,{message:`cannot reach the bridge: no bridge is running for DALAN_HOME=${selected} (${cause})`,fix:[`start the bridge for this home the way you set it up (${docsUrl('docs/manual-setup.md','owner-and-requester-setup')}), then run this command again`]});
90
93
  return Object.assign(error,{message:`cannot reach the bridge: DALAN_HOME is not set and no bridge is running in ${home} (${cause})`,fix:[`export DALAN_HOME=DIR for the bridge home you made, or start a trial bridge with: ${cli} try`]});
91
94
  }
92
- function request(route, method = 'GET', payload, headers={}, timeoutMs=0) {
95
+ function request(route, method = 'GET', payload, headers={}, timeoutMs=30000) {
93
96
  return new Promise((resolve, reject) => {
94
97
  const bytes = payload ? JSON.stringify(payload) : '';
95
98
  const transportFailure=error=>reject(Object.assign(error.syscall==='connect'&&['ENOENT','ECONNREFUSED'].includes(error.code)?bridgeNotRunning(error):error,{kind:'transport'}));
@@ -112,7 +115,40 @@ function request(route, method = 'GET', payload, headers={}, timeoutMs=0) {
112
115
  });
113
116
  }
114
117
 
115
- function download(id,output) { return new Promise((resolve,reject)=>{ const socketPathError=adminSocketPathError(socket); if(socketPathError) return reject(socketPathError); const req=http.request({socketPath:socket,path:'/artifact?id='+encodeURIComponent(id),headers:{'x-owner-capability':receiptForArtifact(id).token}},res=>{if(res.statusCode!==200){let body='';res.on('data',b=>body+=b);res.on('end',()=>reject(new Error(JSON.parse(body).error)));return;}const bytes=[];res.on('data',b=>bytes.push(b));res.on('end',()=>{const data=Buffer.concat(bytes),digest=createHash('sha256').update(data).digest('hex');if(digest!==res.headers['x-artifact-sha256']) return reject(new Error('artifact digest mismatch'));fs.writeFileSync(output,data,{flag:'wx',mode:0o600});resolve({artifact_id:id,output,bytes:data.length,sha256:digest});});});req.on('error',reject);req.end();}); }
118
+ function download(id,output,ownerHeaders) {
119
+ return new Promise((resolve,reject)=>{
120
+ const socketPathError=adminSocketPathError(socket);
121
+ if(socketPathError) return reject(socketPathError);
122
+ if(!artifactIdPattern.test(id)) return reject(new Error('invalid artifact ID'));
123
+ const req=http.request({socketPath:socket,path:'/artifact?id='+encodeURIComponent(id),headers:ownerHeaders??{'x-owner-capability':receiptForArtifact(id).token}},res=>{
124
+ if(res.statusCode!==200){
125
+ let body='', tooLarge=false;
126
+ res.on('data',chunk=>{
127
+ if(tooLarge) return;
128
+ body+=chunk;
129
+ if(body.length>8192){ body=''; tooLarge=true; }
130
+ });
131
+ res.on('end',()=>{
132
+ let error;
133
+ try { error=JSON.parse(body)?.error; } catch { /* status fallback */ }
134
+ reject(new Error(typeof error==='string'&&error.trim() ? error : `HTTP ${res.statusCode}`));
135
+ });
136
+ return;
137
+ }
138
+ const bytes=[];
139
+ res.on('data',b=>bytes.push(b));
140
+ res.on('end',()=>{
141
+ const data=Buffer.concat(bytes),digest=createHash('sha256').update(data).digest('hex');
142
+ if(digest!==res.headers['x-artifact-sha256']) return reject(new Error('artifact digest mismatch'));
143
+ try { fs.writeFileSync(output,data,{flag:'wx',mode:0o600}); }
144
+ catch (error) { return reject(error); }
145
+ resolve({artifact_id:id,output,bytes:data.length,sha256:digest});
146
+ });
147
+ });
148
+ req.on('error',reject);
149
+ req.end();
150
+ });
151
+ }
116
152
  const artifactIdPattern=/^art_[-\w]{8,128}$/;
117
153
  function receiptForArtifact(id) { if(!artifactIdPattern.test(id)) throw new Error('invalid artifact ID');let requestId;try{requestId=fs.readFileSync(path.join(root,'artifact-index',id),'utf8').trim();}catch{throw new Error('artifact owner unknown; run dalan get REQUEST_ID or wait REQUEST_ID first');}return receipt(requestId); }
118
154
  function canonical(value) { if(Array.isArray(value)) return value.map(canonical); if(value&&typeof value==='object') return Object.fromEntries(Object.keys(value).sort().map(k=>[k,canonical(value[k])])); return value; }
@@ -134,12 +170,12 @@ function acpReceipt(id) {
134
170
  if(secret.length<32) return null;
135
171
  return {request_id:id,token:createHmac('sha256',secret).update(id).digest('hex'),acp:true};
136
172
  }
137
- function writeReceipt(id, token, body, delivery, review=false, background=false, meta=null, producer=null, routing=null, destinationRevisions=null, revises=null) {
173
+ function writeReceipt(id, token, body, delivery, review=false, background=false, meta=null, producer=null, routing=null, destinationRevisions=null, revises=null, follows=null, callerWaiting=false) {
138
174
  fs.mkdirSync(receipts,{recursive:true,mode:0o700});
139
175
  const file=receiptPath(id);
140
176
  try {
141
177
  const fd=fs.openSync(file,'wx',0o600);
142
- try { fs.writeSync(fd,JSON.stringify({request_id:id,token,body,delivery,...(delivery.startsWith('t3:')?{thread:delivery.slice(3)}:{}),...(review?{review:true}:{}),...(background?{background:true}:{}),...(meta?{meta}:{}),...(producer?{producer}:{}),...(routing?{routing,destination_revisions:destinationRevisions??{}}:{}),...(revises?{revises}:{})})+'\n'); fs.fsyncSync(fd); }
178
+ try { fs.writeSync(fd,JSON.stringify({request_id:id,token,body,delivery,...(delivery.startsWith('t3:')?{thread:delivery.slice(3)}:{}),...(review?{review:true}:{}),...(background?{background:true}:{}),...(meta?{meta}:{}),...(producer?{producer}:{}),...(routing?{routing,destination_revisions:destinationRevisions??{}}:{}),...(revises?{revises}:{}),...(follows?{follows}:{}),...(callerWaiting?{caller_waiting:true}:{})})+'\n'); fs.fsyncSync(fd); }
143
179
  finally { fs.closeSync(fd); }
144
180
  } catch(e) { if(e.code!=='EEXIST') throw e; }
145
181
  const dir=fs.openSync(receipts,'r'); try { fs.fsyncSync(dir); } finally { fs.closeSync(dir); }
@@ -149,7 +185,7 @@ function operator() { const file=defaultPath(home,'.config/dot-bridge/operator.k
149
185
  async function waitForAssignment(id, timeout) {
150
186
  const seconds=timeout===null?300:Number(timeout);
151
187
  if(!Number.isInteger(seconds)||seconds<1||seconds>3600) throw new Error('wait timeout must be an integer from 1 to 3600 seconds');
152
- return request(`/wait?id=${encodeURIComponent(id)}&timeout=${seconds}`,'GET',null,{'x-owner-capability':receipt(id).token});
188
+ return request(`/wait?id=${encodeURIComponent(id)}&timeout=${seconds}`,'GET',null,{'x-owner-capability':receipt(id).token},0); // The server owns the long-poll deadline.
153
189
  }
154
190
  // Records which request owns each artifact so `artifact ART_ID` can find the owner receipt. Called by get and wait.
155
191
  function indexArtifacts(requestId,result) {
@@ -224,8 +260,8 @@ function producerReceipts(producer,cache) {
224
260
  }
225
261
  // A failure worth retrying: the bridge restarting (transport) or unavailable (5xx).
226
262
  const transient=e=>e.kind==='transport'||e.http_status>=500;
227
- // /owner-states reads without recording an owner read. An older bridge lacks it; /get then works, but each finished task
228
- // it sees is recorded as consumed once. A 4xx for one request (unknown, not owned) marks it unknown; anything else throws.
263
+ // /owner-states is explicitly non-consuming. A bridge lacking it might also
264
+ // silently ignore /get's peek parameter; do not probe it with an actual receipt.
229
265
  async function ownerStates(items,legacy) {
230
266
  if(!legacy.on) try {
231
267
  let out=null;
@@ -236,14 +272,7 @@ async function ownerStates(items,legacy) {
236
272
  return out;
237
273
  }
238
274
  catch(e) { if(e.http_status!==404) throw e; legacy.on=true; }
239
- const states=[];
240
- for(const x of items) {
241
- let got; try { got=await request('/get?id='+encodeURIComponent(x.id),'GET',null,{'x-owner-capability':x.token}); }
242
- catch(e) { if(transient(e)) throw e; states.push({request_id:x.id,error:'unreadable'}); continue; }
243
- if(typeof got.status!=='string') { states.push({request_id:x.id,error:'unreadable'}); continue; }
244
- const blockers=(got.progress??[]).map(p=>p.note).filter(n=>/^\s*(?:BLOCKED:|QUESTION:)/im.test(n));
245
- states.push({request_id:x.id,status:got.status,blocker_count:blockers.length,last_blocker:blockers.at(-1)??null});
246
- }
275
+ const states=items.map(x=>({request_id:x.id,error:'unreadable'}));
247
276
  const s=await request('/status');
248
277
  // Only evidence holds refill: a pause or an owner-confirmed break (not an inferred break, not an estimated limit).
249
278
  const held=s.paused?'paused':s.worker_break?.active&&s.worker_break.source==='owner'?'worker_break':null;
@@ -300,8 +329,10 @@ async function waitDrained() {
300
329
  if(!Number.isInteger(v)||v<0||v>100) throw new Error(`${flag} must be an integer from 0 to 100`);
301
330
  limits[key]=v;
302
331
  }
303
- const intervalMs=Number(process.env.DOT_DRAINED_INTERVAL_MS||15000);
304
- const unreachableMs=Number(process.env.DOT_DRAINED_UNREACHABLE_MS||600000);
332
+ const intervalMs=Number(process.env.DOT_DRAINED_INTERVAL_MS ?? 15000);
333
+ if(!Number.isSafeInteger(intervalMs)||intervalMs<1||intervalMs>2147483647) throw new Error('DOT_DRAINED_INTERVAL_MS must be a positive integer no greater than 2147483647');
334
+ const unreachableMs=Number(process.env.DOT_DRAINED_UNREACHABLE_MS ?? 600000);
335
+ if(!Number.isSafeInteger(unreachableMs)||unreachableMs<1||unreachableMs>2147483647) throw new Error('DOT_DRAINED_UNREACHABLE_MS must be a positive integer no greater than 2147483647');
305
336
  // One waiter per producer: a second one exits at once, so the hook and a forgetful agent cannot stack them.
306
337
  fs.mkdirSync(drainedDir,{recursive:true,mode:0o700});
307
338
  const file=drainedPidfile(producer), mine={pid:process.pid,token:randomBytes(8).toString('hex'),producer,started_at:new Date().toISOString()};
@@ -356,8 +387,10 @@ async function main() {
356
387
  const [action,relationshipId,...extra]=args.filter(a=>a!=='--json');
357
388
  const headers={'x-operator-key':operator()};
358
389
  if(action==='list'&&!relationshipId&&!extra.length) result=await request('/relationships','GET',null,headers);
390
+ else if(action==='publish'&&relationshipId&&(extra.length===1&&extra[0]==='--revoke'||extra.length>=1&&extra.length%2===0&&extra.every((a,i)=>i%2?true:a==='--grant')))
391
+ result=await request('/relationships/publish','POST',{relationship_id:relationshipId,grant:extra[0]==='--revoke'?null:extra.filter((_,i)=>i%2).map(String)},headers);
359
392
  else if(action==='end'&&relationshipId&&!extra.length) result=await request('/relationships/end','POST',{relationship_id:relationshipId},headers);
360
- else throw new Error('usage: dalan relationships list | end RELATIONSHIP_ID [--json]');
393
+ else throw new Error('usage: dalan relationships list | end RELATIONSHIP_ID | publish RELATIONSHIP_ID (--grant org:NAME|repo:OWNER/NAME)... | publish RELATIONSHIP_ID --revoke [--json]');
361
394
  break;
362
395
  }
363
396
  case 'grants': {
@@ -411,6 +444,8 @@ async function main() {
411
444
  }
412
445
  case 'submit': {
413
446
  refuseUnknownOptions('submit',{flags:SUBMIT_FLAGS,values:SUBMIT_VALUES});
447
+ let callerWaiting = args.includes('--caller-waiting');
448
+ if (callerWaiting && args.includes('--background')) throw new Error('--caller-waiting cannot be combined with --background');
414
449
  const thread = option('--thread'), requestedDelivery = option('--deliver'), file = option('--file');
415
450
  if (thread && requestedDelivery) throw new Error('submit accepts either --thread or --deliver, not both');
416
451
  const delivery = requestedDelivery ?? (thread ? `t3:${thread}` : 'none');
@@ -464,6 +499,9 @@ async function main() {
464
499
  if(args.includes('--revises')&&(!option('--revises')||option('--revises').startsWith('--'))) throw new Error('--revises requires the request ID of the job this one corrects');
465
500
  const revisesGiven=option('--revises')??null;
466
501
  if(revisesGiven&&routing) throw new Error('--revises needs one worker: it cannot be combined with --eligible or --policy');
502
+ const followsGiven=option('--follows')??null;
503
+ if(args.includes('--follows')&&(!followsGiven||followsGiven.startsWith('--'))) throw new Error('--follows requires a finished predecessor request ID');
504
+ if(followsGiven&&(routing||revisesGiven)) throw new Error('--follows cannot be combined with routing or --revises');
467
505
  const dryRun=args.includes('--dry-run'), queueAnyway=args.includes('--queue-anyway'), refuseDefer=args.includes('--refuse-defer');
468
506
  if(dryRun&&queueAnyway) throw new Error('--dry-run stores nothing; it cannot be combined with --queue-anyway');
469
507
  if(dryRun&&args.includes('--wait')) throw new Error('--dry-run stores nothing; it cannot be combined with --wait');
@@ -483,18 +521,22 @@ async function main() {
483
521
  }
484
522
  }
485
523
  const token=randomBytes(32).toString('hex');
486
- const write=()=>writeReceipt(id,token,JSON.stringify(body),delivery,review,background,{...given,source:given.source??'agent'},producerId(),routing,destinationRevisions,revisesGiven);
524
+ const write=()=>writeReceipt(id,token,JSON.stringify(body),delivery,review,background,{...given,source:given.source??'agent'},producerId(),routing,destinationRevisions,revisesGiven,followsGiven,callerWaiting);
487
525
  let saved;
488
526
  if(dryRun) {
489
527
  try { saved=receipt(id); }
490
- catch(error) { if(error.code!=='ENOENT') throw error; saved={request_id:id,token,delivery,body:input,...(routing?{routing,destination_revisions:destinationRevisions}:{})}; }
528
+ catch(error) { if(error.code!=='ENOENT') throw error; saved={request_id:id,token,delivery,background,body:input,...(routing?{routing,destination_revisions:destinationRevisions}:{}),...(followsGiven?{follows:followsGiven}:{})}; }
491
529
  } else saved=write();
530
+ if (callerWaiting && saved.token !== token && saved.caller_waiting !== true)
531
+ throw Object.assign(new Error('--caller-waiting cannot be added to a saved request; reconcile the saved request before submitting a new request ID'), {local_code:'receipt_conflict'});
532
+ callerWaiting ||= saved.caller_waiting === true;
533
+ if (callerWaiting && background) throw new Error('--caller-waiting cannot be combined with --background');
492
534
  if(!routing&&saved.routing) {routing=saved.routing;destinationRevisions=saved.destination_revisions??{};}
493
535
  let fresh=!dryRun&&saved.token===token;
494
536
  // Receipts written by earlier releases may carry the old spelling of a source; compare the normalized form.
495
537
  const savedMeta=()=>{ try { return normalizeMeta(saved.meta); } catch { return {}; } };
496
538
  const conflicts=()=>{ const savedDelivery=saved.delivery ?? (saved.thread ? `t3:${saved.thread}` : null);
497
- return JSON.stringify(canonical(saved.routing??null))!==JSON.stringify(canonical(routing))||JSON.stringify(canonical(saved.destination_revisions??{}))!==JSON.stringify(canonical(destinationRevisions))||JSON.stringify(canonical(JSON.parse(saved.body)))!==JSON.stringify(canonical(body))||savedDelivery!==delivery||!!saved.review!==review||!!saved.background!==background||metaFields.some(k=>savedMeta()[k]!=null&&given[k]!==null&&savedMeta()[k]!==given[k])||saved.revises!=null&&revisesGiven!==null&&saved.revises!==revisesGiven; };
539
+ return JSON.stringify(canonical(saved.routing??null))!==JSON.stringify(canonical(routing))||JSON.stringify(canonical(saved.destination_revisions??{}))!==JSON.stringify(canonical(destinationRevisions))||JSON.stringify(canonical(JSON.parse(saved.body)))!==JSON.stringify(canonical(body))||savedDelivery!==delivery||!!saved.review!==review||!!saved.background!==background||metaFields.some(k=>savedMeta()[k]!=null&&given[k]!==null&&savedMeta()[k]!==given[k])||saved.revises!=null&&revisesGiven!==null&&saved.revises!==revisesGiven||followsGiven!==null&&(saved.follows??null)!==followsGiven; };
498
540
  const conflict=()=>Object.assign(new Error('request_id conflict with local receipt'),{local_code:'receipt_conflict'});
499
541
  // A refused submit stores no assignment, so its receipt guards nothing. Replace it instead of refusing a corrected retry.
500
542
  if(dryRun&&conflicts()) throw conflict();
@@ -507,7 +549,8 @@ async function main() {
507
549
  // A retry inherits what the receipt recorded for any flag it omits, so replaying a drainer request by hand stays one request.
508
550
  const meta=Object.fromEntries(metaFields.map(k=>[k,given[k]??savedMeta()[k]??(k==='source'?'agent':null)]));
509
551
  const revisesId=revisesGiven??saved.revises??null;
510
- const send=()=>request(dryRun?'/submit-preview':'/submit', 'POST', { ...(worker?{worker}:{}), ...(routing?{routing,destination_revisions:destinationRevisions}:{}), delivery, assignment: body, owner_token:saved.token, review, ...(background?{background:true}:{}), meta, ...(revisesId?{revises:{prior_id:revisesId,prior_token:receipt(revisesId).token}}:{}), ...(args.includes('--sensitive-scope-override')?{sensitive_scope_override:option('--sensitive-scope-override')}:{}), ...(args.includes('--allow-main')?{allow_main:true}:{}), ...(args.includes('--exclude-sensitive')?{exclude_sensitive:true}:{}), ...(execution?{execution}:{}), ...(requiredCapabilities?{required_capabilities:requiredCapabilities}:{}), ...(dryRun?{dry_run:true}:{...(refuseDefer?{refuse_defer:true}:{}),...(queueAnyway?{queue_anyway:true}:{})}), ...(args.includes('--defer-if-queued')?{defer_queued:Number(option('--defer-if-queued'))}:{}) },args.includes('--allow-main')?{'x-operator-key':operator()}:{});
552
+ const followsId=followsGiven??saved.follows??null;
553
+ const send=()=>request(dryRun?'/submit-preview':'/submit', 'POST', { ...(worker?{worker}:{}), ...(routing?{routing,destination_revisions:destinationRevisions}:{}), delivery, assignment: body, owner_token:saved.token, review, ...(background?{background:true}:{}), ...(callerWaiting?{caller_waiting:true}:{}), meta, ...(revisesId?{revises:{prior_id:revisesId,prior_token:receipt(revisesId).token}}:{}), ...(followsId?{follows:{prior_id:followsId,prior_token:receipt(followsId).token}}:{}), ...(args.includes('--sensitive-scope-override')?{sensitive_scope_override:option('--sensitive-scope-override')}:{}), ...(args.includes('--allow-main')?{allow_main:true}:{}), ...(args.includes('--exclude-sensitive')?{exclude_sensitive:true}:{}), ...(execution?{execution}:{}), ...(requiredCapabilities?{required_capabilities:requiredCapabilities}:{}), ...(dryRun?{dry_run:true}:{...(refuseDefer?{refuse_defer:true}:{}),...(queueAnyway?{queue_anyway:true}:{})}), ...(args.includes('--defer-if-queued')?{defer_queued:Number(option('--defer-if-queued'))}:{}) },args.includes('--allow-main')?{'x-operator-key':operator()}:{});
511
554
  try {
512
555
  try { result=await send(); }
513
556
  catch(error) {
@@ -559,7 +602,7 @@ async function main() {
559
602
  console.error(`worker activity: ${a.tool_calls} call${a.tool_calls===1?'':'s'}${a.last_tool?`, last ${a.last_tool} at ${a.last_tool_at.slice(11,19)}Z (${age<90?age+'s':age<5400?Math.round(age/60)+'m':Math.round(age/3600)+'h'} ago)`:''}${a.first_workspace_tool_at?'':', no workspace tool'}${a.last_tool_error?`, last error: ${a.last_tool_error}`:''}`); }
560
603
  // On a terminal, a person reads the output: show the short human view. Piped output stays the JSON document.
561
604
  if(!json&&!id.startsWith('msg_')&&process.stdout.isTTY) { result=formatGetSummary(result,{id,cli}); plainOutput=true; }
562
- else if(!json&&!id.startsWith('msg_')&&result?.status==='finished') endNote=`decide: ${cli} decide ${id} ${decideWords}`;
605
+ else if(!json&&!id.startsWith('msg_')) endNote=formatGetEndNote(result,{id,cli,decideWords});
563
606
  break; }
564
607
  case 'cancel-if-queued': { const id=args[0]; if(!id||id.startsWith('-')) throw new Error('cancel-if-queued requires request id'); result=await request('/cancel-if-queued','POST',{id},{'x-owner-capability':receipt(id).token}); break; }
565
608
  case 'artifact': { const artifactId=args[0],output=option('--output');if(!artifactId||!output) throw new Error('artifact requires ID --output PATH');result=await download(artifactId,output);break; }
@@ -628,6 +671,7 @@ async function main() {
628
671
  break;
629
672
  }
630
673
  case 'resume': result=await request('/resume','POST',{}, {'x-operator-key':operator()}); break;
674
+ case 'quiesce': { const modes=args.filter(x=>x!=='--json'&&!x.startsWith('-')),mode=modes[0]; if(modes.length!==1||!['on','off','status'].includes(mode)||args.some(x=>x.startsWith('-')&&x!=='--json')) throw new Error('quiesce takes on, off or status (optional --json)'); result=mode==='status'?await request('/quiesce','GET',null,{'x-operator-key':operator()}):await request('/quiesce','POST',{on:mode==='on'},{'x-operator-key':operator()}); break; }
631
675
  case 'claims': { if(args.some(a=>a!=='--json')) throw new Error('claims accepts only --json'); result=await request('/claims','GET',null,{'x-operator-key':operator()}); break; }
632
676
  case 'abandon': { const id=args[0]; if(!id||id.startsWith('-')) throw new Error('abandon requires request id'); if(args.includes('--reason')&&!option('--reason')) throw new Error('--reason requires text'); result=await request('/abandon','POST',{id,...(args.includes('--reason')?{reason:option('--reason')}:{})},{'x-operator-key':operator()}); break; }
633
677
  case 'accept': case 'reject': { const id=args[0]; if(!id||id.startsWith('-')) throw new Error(`${command} requires request id`); if(args.includes('--note')&&!option('--note')) throw new Error('--note requires text'); result=await request(`/${command}`,'POST',{id,...(args.includes('--note')?{note:option('--note')}:{})},{'x-owner-capability':receipt(id).token}); break; }
@@ -639,6 +683,35 @@ async function main() {
639
683
  if(!json&&process.stdout.isTTY) { result=`Recorded ${id} as ${decision}.`; plainOutput=true; }
640
684
  break;
641
685
  }
686
+ case 'materialize': {
687
+ const id=args[0], flags=args.slice(1), parsed=new Map();
688
+ const usage='usage: dalan materialize ID [--dir PATH] [--approve] [--dry-run] [--json]';
689
+ for(let i=0;i<flags.length;i++) {
690
+ const flag=flags[i];
691
+ if(!['--dir','--approve','--dry-run','--json'].includes(flag) || parsed.has(flag)) throw new Error(usage);
692
+ const value=flag==='--dir' ? flags[++i] : true;
693
+ if(!value || (flag==='--dir' && value.startsWith('--'))) throw new Error(usage);
694
+ parsed.set(flag,value);
695
+ }
696
+ if(!/^[-\w]{8,128}$/.test(id??'') || parsed.has('--dry-run') && parsed.has('--approve')) throw new Error(usage);
697
+ readMaterializeGrant(defaultPath(home,'.config/dot-bridge/materialize.json'));
698
+ const headers={'x-owner-capability':receipt(id).token};
699
+ result=await materialize({id, got:await request('/get?id='+encodeURIComponent(id)+'&peek=1','GET',null,headers), grantFile:defaultPath(home,'.config/dot-bridge/materialize.json'),
700
+ dir:path.resolve(parsed.get('--dir')||process.cwd()), dryRun:parsed.has('--dry-run'), approve:parsed.has('--approve'),
701
+ recheck:()=>request('/get?id='+encodeURIComponent(id)+'&peek=1','GET',null,headers),
702
+ download:async art=>{
703
+ const temp=fs.mkdtempSync(path.join(os.tmpdir(),'dalan-download-')), file=path.join(temp,'patch.diff');
704
+ try { await download(art.artifact_id,file,headers); return fs.readFileSync(file); }
705
+ finally { fs.rmSync(temp,{recursive:true,force:true}); }
706
+ }});
707
+ delete result.published; if(!result.pr_url) delete result.branch; delete result.reason;
708
+ if(!json) {
709
+ const message=result.pr_url ? 'Draft pull request: '+result.pr_url : (parsed.has('--dry-run')?'Dry run only: ':'Not published: ')+result.decision.reason+'; branch '+result.decision.branch;
710
+ result=[result.repo+' at '+result.base_sha, message, ...result.files.map(file=>' '+file)].join('\n');
711
+ plainOutput=true;
712
+ }
713
+ break;
714
+ }
642
715
  case 'apply': {
643
716
  const id=args[0]; if(!id||id.startsWith('-')) throw new Error('apply requires request id (optional --dir PATH, default the current directory; --release gives up an uncertain apply)');
644
717
  if(args.includes('--dir')&&!option('--dir')) throw new Error('--dir requires a path');
@@ -755,7 +828,7 @@ async function main() {
755
828
  const { DatabaseSync }=await import('node:sqlite'), db=new DatabaseSync(defaultPath(home,'.local/share/dot-bridge/bridge.db'),{readOnly:true});
756
829
  const accepted=db.prepare('SELECT count(*) n FROM assignments WHERE created_at>=?').get(new Date(sinceMs).toISOString()).n; db.close();
757
830
  result={since:new Date(sinceMs).toISOString(),accepted,refused:summary.refused,refused_fraction:summary.refused+accepted?Math.round(summary.refused/(summary.refused+accepted)*1000)/1000:null,classes:summary.classes,by_kind:summary.by_kind};
758
- if(!args.includes('--json')) { result=[`submits since ${result.since}: ${accepted} accepted, ${summary.refused} refused (${result.refused_fraction===null?'n/a':Math.round(result.refused_fraction*100)+'%'})`,...summary.classes.map(c=>`${String(c.count).padStart(6)} ${c.reason} (${c.distinct_requests} requests) e.g. ${c.example.slice(0,120)}`)].join('\n'); plainOutput=true; }
831
+ if(!args.includes('--json')) { result=formatRejections(summary,{since:result.since,accepted}); plainOutput=true; }
759
832
  break;
760
833
  }
761
834
  // Built-in authorization server. init writes local files only (no running bridge needed); connect talks to the owner socket.
@@ -788,9 +861,23 @@ async function main() {
788
861
  case 'reconcile': { const id=args[0]; if(!id) throw new Error('reconcile requires id'); const adopt=args.includes('--adopt'); let ownerToken; if(adopt) ownerToken=writeReceipt(id,randomBytes(32).toString('hex'),'', '').token; result=await request('/reconcile','POST',{id,adopt,owner_token:ownerToken},{'x-operator-key':operator()}); break; }
789
862
  case 'verify-stops': { const id=args.find(a=>a!=='--json'); result=await request('/verify-stops','POST',id?{id}:{},{'x-operator-key':operator()}); break; }
790
863
  case 'prepare-deps': {
791
- const positional=args.filter(a=>!['--json','--replace-invalid'].includes(a));
792
- if(positional.length!==1||positional[0].startsWith('-')) throw new Error('usage: dalan prepare-deps SOURCE_DIRECTORY [--json] [--replace-invalid]');
793
- result=prepareNodeModules(positional[0],{replaceInvalid:args.includes('--replace-invalid')});
864
+ const usage='usage: dalan prepare-deps SOURCE_DIRECTORY [--go|--pnpm] [--json] [--replace-invalid] | dalan prepare-deps --prune [--keep N] [--json]';
865
+ if(args.includes('--prune')) {
866
+ const at=args.indexOf('--keep'),keep=at<0?4:Number(args[at+1]);
867
+ if(args.some((a,i)=>!['--prune','--json','--keep'].includes(a)&&!(at>=0&&i===at+1))||!Number.isInteger(keep)||keep<1) throw new Error(usage);
868
+ result={...pruneNodeStore({keep}),go:pruneGoStore({keep})};
869
+ break;
870
+ }
871
+ const positional=args.filter(a=>!['--json','--replace-invalid','--go','--pnpm'].includes(a));
872
+ if(positional.length!==1||positional[0].startsWith('-')) throw new Error(usage);
873
+ const replaceInvalid=args.includes('--replace-invalid');
874
+ // --go prepares the Go module cache (and the toolchain go.mod asks for); --pnpm (or a pnpm-lock.yaml without a package-lock.json) the pnpm trees; otherwise the npm tree.
875
+ const source=positional[0],has=name=>fs.existsSync(path.join(source,name));
876
+ if(args.includes('--go')) result=prepareGoModules(source,{replaceInvalid});
877
+ else if(args.includes('--pnpm')||(has('pnpm-lock.yaml')&&!has('package-lock.json'))) result=preparePnpm(source,{replaceInvalid});
878
+ else result=prepareNodeModules(source,{replaceInvalid});
879
+ // Keep the shared store that was just written bounded: the newest entries stay, and nothing under a day old is touched.
880
+ try { if(args.includes('--go')) pruneGoStore({}); else pruneNodeStore({}); } catch {}
794
881
  break;
795
882
  }
796
883
  case 'doctor': {
@@ -30,7 +30,8 @@
30
30
  },
31
31
  "observed_on": {
32
32
  "type": "string",
33
- "format": "date"
33
+ "format": "date",
34
+ "pattern": "^\\d{4}-\\d{2}-\\d{2}$"
34
35
  },
35
36
  "pins": {
36
37
  "type": "object",
@@ -42,11 +43,36 @@
42
43
  "sdk",
43
44
  "catalog_fingerprint"
44
45
  ],
45
- "additionalProperties": {
46
- "type": [
47
- "string",
48
- "null"
49
- ]
46
+ "additionalProperties": false,
47
+ "properties": {
48
+ "dalan_commit": {
49
+ "type": "string",
50
+ "minLength": 1
51
+ },
52
+ "requester_ref": {
53
+ "type": "string",
54
+ "minLength": 1
55
+ },
56
+ "worker_host_ref": {
57
+ "type": "string",
58
+ "minLength": 1
59
+ },
60
+ "protocol": {
61
+ "type": "string",
62
+ "minLength": 1
63
+ },
64
+ "sdk": {
65
+ "type": [
66
+ "string",
67
+ "null"
68
+ ]
69
+ },
70
+ "catalog_fingerprint": {
71
+ "type": [
72
+ "string",
73
+ "null"
74
+ ]
75
+ }
50
76
  }
51
77
  },
52
78
  "roles": {
@@ -166,5 +192,66 @@
166
192
  "type": "string"
167
193
  }
168
194
  }
169
- }
195
+ },
196
+ "allOf": [
197
+ {
198
+ "if": {
199
+ "properties": {
200
+ "qualification": {
201
+ "properties": {
202
+ "state": {
203
+ "const": "passed_for_declared_scope"
204
+ }
205
+ },
206
+ "required": [
207
+ "state"
208
+ ]
209
+ }
210
+ },
211
+ "required": [
212
+ "qualification"
213
+ ]
214
+ },
215
+ "then": {
216
+ "properties": {
217
+ "pins": {
218
+ "properties": {
219
+ "catalog_fingerprint": {
220
+ "type": "string",
221
+ "minLength": 1
222
+ }
223
+ }
224
+ },
225
+ "capabilities": {
226
+ "items": {
227
+ "if": {
228
+ "properties": {
229
+ "required": {
230
+ "const": true
231
+ }
232
+ },
233
+ "required": [
234
+ "required"
235
+ ]
236
+ },
237
+ "then": {
238
+ "properties": {
239
+ "observed": {
240
+ "const": "passed"
241
+ }
242
+ }
243
+ }
244
+ }
245
+ },
246
+ "qualification": {
247
+ "properties": {
248
+ "run_refs": {
249
+ "minItems": 1
250
+ }
251
+ }
252
+ }
253
+ }
254
+ }
255
+ }
256
+ ]
170
257
  }
@@ -8,7 +8,7 @@ The owner completes the setup and first-job checks below on the intended account
8
8
 
9
9
  - Confirm that the intended account/workspace can add a custom remote MCP server, authorize it with OAuth, and invoke its tools in the intended cloud conversation. OpenAI says account/workspace policies govern custom MCP access; stop if the controls are absent rather than changing a subscription or policy. [Connection guide](https://developers.openai.com/plugins/deploy/connect-chatgpt#add-the-mcp-server)
10
10
  - Background runs, schedules, push wake and continuous execution are separate capabilities and not prerequisites for this manual smoke; ordinary chat access does not prove any of them.
11
- - Have the owner complete the [public-service owner setup](service-setup.md#owner-setup) (`dalan service install --worker NAME --route tailscale`). Retain the same service home, worker profile and private `resource-url` file throughout this recipe. Use an existing dedicated worker profile with no T3 capability and no allowed repositories. `NAME` below means that exact profile name, not the account display name. Do not change the profile to make a failed test pass.
11
+ - Have the owner complete the [public-service owner setup](service-setup.md#owner-setup) (`dalan service install --worker NAME`). Retain the same service home, worker profile and private `resource-url` file throughout this recipe. Use an existing dedicated worker profile with no T3 capability and no allowed repositories. `NAME` below means that exact profile name, not the account display name. Do not change the profile to make a failed test pass.
12
12
  - Use the existing public **HTTPS resource URL**, including its secret path and `/mcp`, from `<bridge-home>/resource-url` (mode 0600); never substitute the host root or an authorization endpoint. Prefer standard public port 443 for the trial. This is a conservative deployment choice, not a claim that OpenAI forbids other ports. OpenAI documents public HTTPS and authentication discovery for this path. [Endpoint requirements](https://developers.openai.com/plugins/deploy/connect-chatgpt#prepare-the-endpoint)
13
13
  - Before account linking, have the owner verify the public surface from outside the private network: path-suffixed resource/authorization discovery returns 200; tokenless MCP returns 401; unsuffixed discovery, root and `/admin` return 404. The existing [live-trial public check](https://github.com/tnunamak/dalan/blob/main/scripts/live-trial/README.md#3-verify-from-outside-the-tailnet) reads the resource URL from a private file. Reuse its check, but not its job: that job is not this smoke.
14
14
 
@@ -16,11 +16,11 @@ This first job uses no repository and runs no checks. Use a dedicated worker nam
16
16
 
17
17
  ## 1. Start and expose the bridge
18
18
 
19
- Install Dalan, then install the service with a dedicated worker named `muse`. `tailscale` publishes through Tailscale Funnel, which your tailnet administrator must allow (see [service setup](service-setup.md#install-and-connect-your-agent)); `dalan setup` lists the other routes.
19
+ Install Dalan, then install the service with a dedicated worker named `muse`. Gozar shows the available routes and any steps that need your approval.
20
20
 
21
21
  ```sh
22
22
  npm install -g @tnunamak/dalan
23
- dalan service install --worker muse --route tailscale
23
+ dalan service install --worker muse
24
24
  dalan status
25
25
  dalan doctor --auth
26
26
  ```
@@ -8,7 +8,7 @@ A client you have not listed here follows the same flow: give it the complete MC
8
8
 
9
9
  ## Owner setup
10
10
 
11
- 1. Follow the [service setup](service-setup.md): `dalan service install --worker NAME --route tailscale` creates the public HTTPS address. Use the service's worker name wherever this guide says `NAME`.
11
+ 1. Follow the [service setup](service-setup.md): `dalan service install --worker NAME` creates the public HTTPS address. Use the service's worker name wherever this guide says `NAME`.
12
12
 
13
13
  ```sh
14
14
  dalan status