@tnunamak/dalan 0.0.0-stage → 0.6.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 (199) hide show
  1. package/CHANGELOG.md +176 -0
  2. package/CONTRIBUTING.md +26 -0
  3. package/LICENSE +204 -0
  4. package/PROTOCOL.md +351 -0
  5. package/README.md +215 -2
  6. package/SECURITY.md +30 -0
  7. package/bin/dalan.mjs +43 -0
  8. package/bin/dot-acp-agent.mjs +377 -0
  9. package/bin/dot-alert.mjs +9 -0
  10. package/bin/dot-deadman.mjs +82 -0
  11. package/bin/dot-heartbeat.mjs +29 -0
  12. package/bin/dot-pr-reviewer.mjs +32 -0
  13. package/bin/dot-worker.mjs +764 -0
  14. package/docs/chatgpt-worker-onboarding.md +112 -0
  15. package/docs/claude-worker-onboarding.md +113 -0
  16. package/docs/codex-to-muse.md +175 -0
  17. package/docs/connect-chatgpt.md +83 -0
  18. package/docs/connection-longevity.md +43 -0
  19. package/docs/dalan-upgrade.md +246 -0
  20. package/docs/deadman.md +61 -0
  21. package/docs/dot-pr-reviewer.config.example.json +9 -0
  22. package/docs/durability-audit.md +27 -0
  23. package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
  24. package/docs/keycloak-oauth-setup.md +30 -0
  25. package/docs/local-agent-mcp.md +41 -0
  26. package/docs/manual-setup.md +135 -0
  27. package/docs/mirror-fetch.md +97 -0
  28. package/docs/operations.md +799 -0
  29. package/docs/operator-duties.md +68 -0
  30. package/docs/owner-integrator.md +27 -0
  31. package/docs/portable-auth-profile.md +107 -0
  32. package/docs/pr-head-reviewer.md +70 -0
  33. package/docs/pr-preflight.md +28 -0
  34. package/docs/pull-queue.md +131 -0
  35. package/docs/pull-workers.md +94 -0
  36. package/docs/redaction.md +27 -0
  37. package/docs/service-setup.md +219 -0
  38. package/docs/setup-reference.md +80 -0
  39. package/docs/t3-connector-icon.png +0 -0
  40. package/docs/t3-integration.md +51 -0
  41. package/docs/t3-result-retry-delivery.md +41 -0
  42. package/docs/t3-reverse-control.md +107 -0
  43. package/docs/usage.md +443 -0
  44. package/docs/worker-clients.md +290 -0
  45. package/integrations/t3/acp-kit/src/capability.mjs +25 -0
  46. package/integrations/t3/acp-kit/src/errors.mjs +13 -0
  47. package/integrations/t3/acp-kit/src/index.mjs +5 -0
  48. package/integrations/t3/acp-kit/src/lock.mjs +155 -0
  49. package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
  50. package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
  51. package/package.json +67 -4
  52. package/packages/job-core/README.md +18 -0
  53. package/packages/job-core/index.mjs +2 -0
  54. package/packages/job-core/package.json +8 -0
  55. package/packages/job-core/protocol/canonical.mjs +11 -0
  56. package/packages/job-core/protocol/v0/command.schema.json +1154 -0
  57. package/packages/job-core/protocol/v0/event.schema.json +77 -0
  58. package/packages/job-core/protocol/v0/reply.schema.json +59 -0
  59. package/packages/job-core/transitions.mjs +25 -0
  60. package/scripts/daily-selfcheck.mjs +135 -0
  61. package/scripts/dalan-try-selfcheck.mjs +29 -0
  62. package/scripts/lib/expose-tailscale.mjs +408 -0
  63. package/scripts/live-trial/common.mjs +272 -0
  64. package/scripts/monitor-targets.mjs +44 -0
  65. package/scripts/upgrade-drain.mjs +39 -0
  66. package/scripts/worker-bridge-setup.mjs +925 -0
  67. package/src/ack-ledger.mjs +37 -0
  68. package/src/acp-bridge.mjs +418 -0
  69. package/src/acp-context.mjs +138 -0
  70. package/src/admin-socket.mjs +14 -0
  71. package/src/alerts.mjs +147 -0
  72. package/src/artifact-journal.mjs +75 -0
  73. package/src/as-files.mjs +347 -0
  74. package/src/as-store.mjs +456 -0
  75. package/src/as.mjs +538 -0
  76. package/src/auth.mjs +166 -0
  77. package/src/builtin-http.mjs +22 -0
  78. package/src/check-coverage.mjs +38 -0
  79. package/src/check-lint.mjs +88 -0
  80. package/src/check-readiness.mjs +112 -0
  81. package/src/check-response.mjs +19 -0
  82. package/src/child-exit.mjs +18 -0
  83. package/src/child-registry.mjs +94 -0
  84. package/src/claim-command-ledger.mjs +51 -0
  85. package/src/cli-help.mjs +186 -0
  86. package/src/cli-name.mjs +16 -0
  87. package/src/connect-cli.mjs +126 -0
  88. package/src/consumers.mjs +61 -0
  89. package/src/deadman.mjs +329 -0
  90. package/src/delivery.mjs +19 -0
  91. package/src/demo-worker.mjs +150 -0
  92. package/src/destinations/index.mjs +23 -0
  93. package/src/destinations/none.mjs +15 -0
  94. package/src/destinations/t3.mjs +109 -0
  95. package/src/diagnostic.mjs +78 -0
  96. package/src/docs-url.mjs +9 -0
  97. package/src/drain-runner.mjs +9 -0
  98. package/src/drained-owner.mjs +26 -0
  99. package/src/drained-slot.mjs +70 -0
  100. package/src/drained.mjs +40 -0
  101. package/src/durable-waiters.mjs +236 -0
  102. package/src/env.mjs +19 -0
  103. package/src/execution.mjs +112 -0
  104. package/src/failure-type.mjs +28 -0
  105. package/src/get-summary.mjs +32 -0
  106. package/src/git-env.mjs +15 -0
  107. package/src/host-budget-receipts.mjs +154 -0
  108. package/src/host-budget-seccomp.py +33 -0
  109. package/src/host-budget-service.mjs +54 -0
  110. package/src/host-budget-stop.mjs +26 -0
  111. package/src/host-budget-storage.py +259 -0
  112. package/src/host-budget.mjs +149 -0
  113. package/src/host-cgroup.mjs +23 -0
  114. package/src/host-check-allowlist.mjs +42 -0
  115. package/src/host-execution-policy.mjs +38 -0
  116. package/src/host-health.mjs +34 -0
  117. package/src/host-stop-reverify.mjs +44 -0
  118. package/src/inbox.mjs +55 -0
  119. package/src/integrator.mjs +322 -0
  120. package/src/job-retention.mjs +69 -0
  121. package/src/legacy-names.mjs +8 -0
  122. package/src/lifecycle.mjs +291 -0
  123. package/src/limits.mjs +31 -0
  124. package/src/loopback.mjs +9 -0
  125. package/src/mcp-outcome.mjs +79 -0
  126. package/src/mcp-sse.mjs +62 -0
  127. package/src/mcp-stdio.mjs +191 -0
  128. package/src/mirror-fetch-lock.py +164 -0
  129. package/src/mirror-fetch.mjs +174 -0
  130. package/src/notify-ledger.mjs +82 -0
  131. package/src/objectives.mjs +129 -0
  132. package/src/owner-report-artifact.mjs +66 -0
  133. package/src/patch-apply.mjs +84 -0
  134. package/src/path-syntax.mjs +16 -0
  135. package/src/paths.mjs +67 -0
  136. package/src/pr-head-reviewer.mjs +596 -0
  137. package/src/pr-preflight.mjs +51 -0
  138. package/src/prepared-node-modules.mjs +129 -0
  139. package/src/process-inspection.mjs +36 -0
  140. package/src/projects.mjs +480 -0
  141. package/src/protocol-artifact-commands.mjs +52 -0
  142. package/src/protocol-delivery-driver.mjs +167 -0
  143. package/src/protocol-finish.mjs +100 -0
  144. package/src/protocol-owner-command.mjs +35 -0
  145. package/src/protocol-owner-mutations.mjs +22 -0
  146. package/src/protocol-owner-waiters.mjs +67 -0
  147. package/src/protocol-retention.mjs +52 -0
  148. package/src/protocol-services.mjs +61 -0
  149. package/src/protocol-stop-observer.mjs +131 -0
  150. package/src/publish-plan.mjs +245 -0
  151. package/src/pull-queue.mjs +159 -0
  152. package/src/redaction.mjs +763 -0
  153. package/src/rejections.mjs +18 -0
  154. package/src/request-log.mjs +102 -0
  155. package/src/restore-check.mjs +90 -0
  156. package/src/result-binding.mjs +65 -0
  157. package/src/route-setting.mjs +24 -0
  158. package/src/runtime-check.mjs +13 -0
  159. package/src/sandbox-supervisor.mjs +105 -0
  160. package/src/schema-subset.mjs +186 -0
  161. package/src/scopes.mjs +15 -0
  162. package/src/server.mjs +1468 -0
  163. package/src/service-migrate-workers.mjs +113 -0
  164. package/src/service.mjs +388 -0
  165. package/src/setup.mjs +63 -0
  166. package/src/shutdown-signal.mjs +12 -0
  167. package/src/signal-sandbox-processes.py +56 -0
  168. package/src/signal.mjs +119 -0
  169. package/src/status-evidence.mjs +47 -0
  170. package/src/status-summary.mjs +54 -0
  171. package/src/store.mjs +3069 -0
  172. package/src/submission-policy.mjs +623 -0
  173. package/src/subscription-storage.mjs +64 -0
  174. package/src/t3-audit.mjs +120 -0
  175. package/src/t3-control.mjs +102 -0
  176. package/src/t3-transport.mjs +158 -0
  177. package/src/t3.mjs +209 -0
  178. package/src/terminal-safe.mjs +19 -0
  179. package/src/tool-registry.mjs +453 -0
  180. package/src/try-command.mjs +11 -0
  181. package/src/try-exposure.mjs +908 -0
  182. package/src/try-hosted-clients.mjs +46 -0
  183. package/src/try-hosted.mjs +444 -0
  184. package/src/try-selfcheck.mjs +168 -0
  185. package/src/try.mjs +635 -0
  186. package/src/webhooks.mjs +86 -0
  187. package/src/work-order.mjs +265 -0
  188. package/src/worker-instructions.mjs +26 -0
  189. package/src/worker-prompt.mjs +4 -0
  190. package/src/workers.mjs +632 -0
  191. package/src/workspace.mjs +1065 -0
  192. package/systemd/dot-bridge-heartbeat.service +18 -0
  193. package/systemd/dot-bridge-heartbeat.timer +10 -0
  194. package/systemd/dot-bridge-selfcheck.service +12 -0
  195. package/systemd/dot-bridge-selfcheck.timer +11 -0
  196. package/systemd/dot-bridge.service +17 -0
  197. package/systemd/dot-deadman.service +30 -0
  198. package/systemd/dot-pr-reviewer.service +11 -0
  199. package/systemd/dot-pr-reviewer.timer +10 -0
@@ -0,0 +1,764 @@
1
+ #!/usr/bin/env node
2
+ import { defaultPath,workspaceRoot,rootWarnings } from '../src/paths.mjs';
3
+ import { readEnv } from '../src/env.mjs';
4
+ import http from 'node:http';
5
+ import net from 'node:net';
6
+ import { DatabaseSync } from 'node:sqlite';
7
+ import { prepareNodeModules } from '../src/prepared-node-modules.mjs';
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { randomBytes, randomUUID, createHash, createHmac } from 'node:crypto';
12
+ import { explainStatus } from '../src/status-evidence.mjs';
13
+ import { formatStatusSummary } from '../src/status-summary.mjs';
14
+ import { explainMetrics } from '../src/lifecycle.mjs';
15
+ import { normalizeMeta, metaFields, deriveObjectives } from '../src/objectives.mjs';
16
+ import { legacyFixLedgerPath } from '../src/legacy-names.mjs';
17
+ import { buildInbox, formatInbox, parseWhen, decideWords } from '../src/inbox.mjs';
18
+ import { decideDrained, drainedExitCodes, terminal } from '../src/drained.mjs';
19
+ import { takeSlot, releaseSlot } from '../src/drained-slot.mjs';
20
+ import { liveWaiter } from '../src/drained-owner.mjs';
21
+ import { resolveHelp } from '../src/cli-help.mjs';
22
+ import { readLines } from '../src/request-log.mjs';
23
+ import { lintChecksFile, formatChecksReport } from '../src/check-lint.mjs';
24
+ import { parseExecution, parseRequiredCapabilities, hostReadiness, hostBackend } from '../src/execution.mjs';
25
+ import { RESOURCE_LIMITS_UNAVAILABLE } from '../src/host-execution-policy.mjs';
26
+ import { summarizeRejections } from '../src/rejections.mjs';
27
+ import { VERDICT_EXIT, formatVerdict } from '../src/work-order.mjs';
28
+ import { connectCommand } from '../src/connect-cli.mjs';
29
+ import { initAsFiles, rotateKeys } from '../src/as-files.mjs';
30
+ import { docsUrl } from '../src/docs-url.mjs';
31
+ import { workerPrompt } from '../src/worker-prompt.mjs';
32
+ import { stoppedTrialFix } from '../src/try-command.mjs';
33
+ import { formatGetSummary, formatWaitLine } from '../src/get-summary.mjs';
34
+ import { cliCommand } from '../src/cli-name.mjs';
35
+ import { applyPatch } from '../src/patch-apply.mjs';
36
+ import { terminalSafe, jsonTerminalSafe } from '../src/terminal-safe.mjs';
37
+ import { loadOwnerWorkers, parseWorkers, submitTarget, updateWorkerRepoPolicy, writeGenericProfile, writeLegacyMarker, readWorkerRepoHistory, seedWorkerRepos, inspectGrantAudit, AUDIT_INTEGRITY_HINT } from '../src/workers.mjs';
38
+ import { adminSocketPathError } from '../src/admin-socket.mjs';
39
+
40
+ // Every line this command writes to stderr can quote a worker's report, error or path. JSON lines stay JSON; the rest is made inert.
41
+ const writeStderr=console.error.bind(console);
42
+ const jsonLine=text=>{ if(!text.startsWith('{')) return false; try { JSON.parse(text); return true; } catch { return false; } };
43
+ console.error=(...parts)=>writeStderr(...parts.map(part=>typeof part==='string'?(jsonLine(part)?jsonTerminalSafe(part):terminalSafe(part)):part));
44
+
45
+ let endNote=null;
46
+ const args = process.argv.slice(2), command = args.shift(), json = args.includes('--json');
47
+ const home=os.homedir(), root=defaultPath(home,'.local/share/dot-bridge'), socket=path.join(root,'admin.sock'), receipts=path.join(root,'receipts');
48
+ function missingProfileWarning(worker,policy) {
49
+ if(policy?.source==='admitted-history')return `worker "${worker}" uses a persisted exact repository list; no identity profile was created`;
50
+ 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)`;
51
+ }
52
+ // The bridge's public origin from its authorization server settings, without any path (the MCP path holds a secret).
53
+ function bridgeOrigin() {
54
+ try { return new URL(JSON.parse(fs.readFileSync(defaultPath(home,'.config/dot-bridge/as.json'),'utf8')).public_url).origin; } catch { return null; }
55
+ }
56
+ function option(name) { const i = args.indexOf(name); return i < 0 ? null : args[i + 1]; }
57
+ const shellQuote=value=>`'${String(value).replaceAll("'","'\\''")}'`;
58
+ // first-job.json, a complete valid job, and the full submit walk-through live in the manual setup.
59
+ const FIRST_JOB_URL=docsUrl('docs/manual-setup.md','submit-finish-and-read-the-result'), JOB_EXAMPLE_URL=FIRST_JOB_URL;
60
+ // The commands that plain output tells the user to run next use the form they ran: `npx @tnunamak/dalan`, `dalan` or node and a path.
61
+ // --json output keeps `dalan`, so scripts see the same text as before.
62
+ const cli=json?'dalan':cliCommand(process.argv[1]);
63
+ // Every option a command reads. An option it does not know is refused, so a typo is not ignored in silence.
64
+ const SUBMIT_FLAGS=['--stdin','--json','--review','--wait','--dry-run','--queue-anyway','--refuse-defer','--allow-scope-prune','--fix-scope','--background','--allow-main','--exclude-sensitive'];
65
+ const SUBMIT_VALUES=['--eligible','--policy','--file','--brief','--worker','--thread','--deliver','--timeout','--execution','--require-capability','--objective-key','--revision','--task-kind','--source','--sensitive-scope-override','--defer-if-queued','--producer-thread'];
66
+ const SUBMIT_OPTIONS=[...SUBMIT_FLAGS,...SUBMIT_VALUES];
67
+ function refuseUnknownOptions(name,{flags=[],values=[]}) {
68
+ for(let i=0;i<args.length;i++) {
69
+ if(values.includes(args[i])) { i++; continue; }
70
+ if(args[i].startsWith('-')&&!flags.includes(args[i])) throw new Error(`${name}: unknown option ${JSON.stringify(args[i])}. See the options with: dalan ${name} --help`);
71
+ }
72
+ }
73
+ // Whether a bridge listens on the admin socket. Only connects; sends nothing.
74
+ function socketListening(file) {
75
+ return new Promise(resolve => {
76
+ const probe=net.connect(file); const done=value=>{probe.destroy();resolve(value);};
77
+ probe.setTimeout(1000,()=>done(false)); probe.once('connect',()=>done(true)); probe.once('error',()=>done(false));
78
+ });
79
+ }
80
+ // The admin socket is missing or nobody listens on it: the bridge for this home is not running. Say so, and how to start it.
81
+ function bridgeNotRunning(error) {
82
+ const selected=process.env.DALAN_HOME, trialHome=selected&&fs.existsSync(path.join(home,'.dalan-trial'));
83
+ const cause=`connect ${error.code} ${socket}`;
84
+ if(trialHome) return Object.assign(error,{message:`cannot reach the bridge: the trial bridge in ${home} is not running (${cause})`,fix:[`start it in another terminal, then run this command again: ${cli} try --home ${shellQuote(home)}`]});
85
+ 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`]});
86
+ 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`]});
87
+ }
88
+ function request(route, method = 'GET', payload, headers={}) {
89
+ return new Promise((resolve, reject) => {
90
+ const bytes = payload ? JSON.stringify(payload) : '';
91
+ const transportFailure=error=>reject(Object.assign(error.syscall==='connect'&&['ENOENT','ECONNREFUSED'].includes(error.code)?bridgeNotRunning(error):error,{kind:'transport'}));
92
+ const socketPathError=adminSocketPathError(socket); if(socketPathError) return reject(socketPathError);
93
+ const req = http.request({ socketPath: socket, path: route, method, headers: { 'content-type': 'application/json', 'content-length': Buffer.byteLength(bytes),...headers } }, res => {
94
+ let out = '';
95
+ res.on('data', b => out += b);
96
+ res.on('error',transportFailure);
97
+ res.on('aborted',()=>transportFailure(new Error('admin response aborted')));
98
+ res.on('end', () => {
99
+ let value;
100
+ try { value=JSON.parse(out); }
101
+ catch { return transportFailure(new Error('invalid admin response')); }
102
+ if(res.statusCode<200||res.statusCode>=300) reject(Object.assign(new Error(value?.error||`HTTP ${res.statusCode}`),{kind:'http',http_status:res.statusCode,...(res.statusCode>=500&&value?.reason?{code:value.code??null,reason:value.reason}:{}),...(Array.isArray(value?.suggested_scope_paths)?{suggested_scope_paths:value.suggested_scope_paths}:{}),...(value?.verdict?{verdict:value.verdict,reasons:value.reasons,bytes:value.bytes,...(value.retry_after_seconds?{retry_after_seconds:value.retry_after_seconds}:{})}:{})}));
103
+ else resolve(value);
104
+ });
105
+ });
106
+ req.on('error',transportFailure); req.end(bytes);
107
+ });
108
+ }
109
+
110
+ 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();}); }
111
+ const artifactIdPattern=/^art_[-\w]{8,128}$/;
112
+ 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); }
113
+ 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; }
114
+ function receiptPath(id) { if(!/^[-\w]{8,128}$/.test(id)) throw Object.assign(new Error(`invalid request ID ${JSON.stringify(String(id).slice(0,140))}: a request ID has 8 to 128 letters, digits, _ or -`),{fix:[`check the ID, or list your jobs with: ${cli} inbox --all`]}); return path.join(receipts,createHash('sha256').update(id).digest('hex')+'.json'); }
115
+ function receipt(id) {
116
+ let text;
117
+ try { text=fs.readFileSync(receiptPath(id),'utf8'); }
118
+ catch(e) { if(e.code!=='ENOENT') throw e; const acp=acpReceipt(id); if(acp) return acp;
119
+ // Every job this home submitted has a receipt, so a missing one means the ID is mistyped or the job came from another home.
120
+ throw Object.assign(new Error(`no job "${id}" in this bridge home: ${home} has no receipt for it`),{code:'ENOENT',local_code:'unknown_request',fix:[`check the ID and DALAN_HOME, or list your jobs with: ${cli} inbox --all`]}); }
121
+ const value=JSON.parse(text); if(value.request_id!==id) throw new Error('receipt mismatch'); return value;
122
+ }
123
+ // A row the ACP adapter (T3 worker provider) submitted has no CLI receipt: its owner token is HMAC(acp-secret, request id).
124
+ // Deriving it lets the T3 parent get, download, accept and reject that row. The bridge still checks the token.
125
+ function acpReceipt(id) {
126
+ const file=process.env.DOT_ACP_SECRET_FILE||defaultPath(home,'.config/dot-bridge/acp-secret');
127
+ let secret;
128
+ try { if((fs.statSync(file).mode&0o777)!==0o600) return null; secret=fs.readFileSync(file,'utf8').trim(); } catch { return null; }
129
+ if(secret.length<32) return null;
130
+ return {request_id:id,token:createHmac('sha256',secret).update(id).digest('hex'),acp:true};
131
+ }
132
+ function writeReceipt(id, token, body, delivery, review=false, background=false, meta=null, producer=null, routing=null, destinationRevisions=null) {
133
+ fs.mkdirSync(receipts,{recursive:true,mode:0o700});
134
+ const file=receiptPath(id);
135
+ try {
136
+ const fd=fs.openSync(file,'wx',0o600);
137
+ 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??{}}:{})})+'\n'); fs.fsyncSync(fd); }
138
+ finally { fs.closeSync(fd); }
139
+ } catch(e) { if(e.code!=='EEXIST') throw e; }
140
+ const dir=fs.openSync(receipts,'r'); try { fs.fsyncSync(dir); } finally { fs.closeSync(dir); }
141
+ return receipt(id);
142
+ }
143
+ function operator() { const file=defaultPath(home,'.config/dot-bridge/operator.key'); const mode=fs.statSync(file).mode&0o777; if(mode!==0o600) throw new Error('operator key must be mode 0600'); return fs.readFileSync(file,'utf8').trim(); }
144
+ async function waitForAssignment(id, timeout) {
145
+ const seconds=timeout===null?300:Number(timeout);
146
+ if(!Number.isInteger(seconds)||seconds<1||seconds>3600) throw new Error('wait timeout must be an integer from 1 to 3600 seconds');
147
+ return request(`/wait?id=${encodeURIComponent(id)}&timeout=${seconds}`,'GET',null,{'x-owner-capability':receipt(id).token});
148
+ }
149
+ // Records which request owns each artifact so `artifact ART_ID` can find the owner receipt. Called by get and wait.
150
+ function indexArtifacts(requestId,result) {
151
+ try { indexArtifactIds(requestId,result); } catch(e) { console.error(`dalan: could not index artifacts: ${e.message}`); }
152
+ }
153
+ function indexArtifactIds(requestId,result) {
154
+ const index=path.join(root,'artifact-index');fs.mkdirSync(index,{recursive:true,mode:0o700});
155
+ for(const entry of [...(result.artifacts||[]).map(x=>({artifact_id:x.id})),...(result.artifact_ids||[]).map(x=>({artifact_id:x})),...(result.checks||[]).map(x=>({artifact_id:x.output_artifact_id})),result.report?.workspace_evidence?.patch_artifact,...(result.report?.workspace_evidence?.artifacts||[]).map(x=>({artifact_id:x.id})),...(result.report?.workspace_evidence?.checks||[]).map(x=>({artifact_id:x.output_artifact_id}))]){
156
+ const id=entry?.artifact_id; if(!id) continue;
157
+ // Ids come from the bridge response. Never let one pick a path or abort the command that already got its result.
158
+ if(typeof id!=='string'||!artifactIdPattern.test(id)) { console.error(`dalan: skipped invalid artifact id in response: ${JSON.stringify(String(id).slice(0,40))}`); continue; }
159
+ try { fs.writeFileSync(path.join(index,id),requestId+'\n',{mode:0o600}); } catch(e) { console.error(`dalan: could not index artifact ${id}: ${e.message}`); }
160
+ }
161
+ }
162
+ // stdout stays the JSON result; a timeout also gets one plain line on stderr, because exit 124 alone does not say what to do.
163
+ function waitTimeoutNote(id,result) {
164
+ if(result?.status!=='timeout') return;
165
+ const seconds=option('--timeout')===null?300:Number(option('--timeout'));
166
+ console.error(`dalan: wait timed out after ${seconds} s: job ${id} is not finished yet (a worker may not have claimed it). Wait longer with: ${cli} wait ${id} --timeout 3600, or check it with: ${cli} get ${id}`);
167
+ }
168
+ function waitExitCode(status) {
169
+ if(status==='finished') return 0;
170
+ if(status==='blocker'||status==='question') return 3;
171
+ if(status==='cancelled') return 4;
172
+ if(status==='worker_break') return 5;
173
+ if(status==='timeout') return 124;
174
+ throw new Error(`unexpected wait status ${status}`);
175
+ }
176
+ // Per-tool calls and response bytes from the request log's mcp_outcome lines in the 1h/6h/24h before sinceMs. Reads
177
+ // complete (newline-terminated) lines only: a line being appended can be half-visible; skips lines that do not parse.
178
+ async function requestLogUsage(file,sinceMs) {
179
+ const spans=[['1h',3600000],['6h',21600000],['24h',86400000]], windows=Object.fromEntries(spans.map(([name])=>[name,{response_bytes:0,calls:0,by_tool:{}}]));
180
+ const log={file,lines:0,outcomes:0,skipped:0,first_at:null};
181
+ const take=line=>{
182
+ if(!line) return; log.lines++;
183
+ if(!line.includes('"mcp_outcome"')) return;
184
+ let entry; try { entry=JSON.parse(line); } catch { log.skipped++; return; }
185
+ const at=Date.parse(entry.at);
186
+ if(entry.kind!=='mcp_outcome'||!Number.isFinite(at)) return;
187
+ if(log.first_at===null||at<Date.parse(log.first_at)) log.first_at=new Date(at).toISOString();
188
+ if(typeof entry.tool!=='string'||!/^[a-z0-9_]{1,64}$/.test(entry.tool)||!Number.isInteger(entry.response_bytes)||entry.response_bytes<0) return;
189
+ log.outcomes++;
190
+ for(const [name,ms] of spans) if(at>=sinceMs-ms&&at<sinceMs) {
191
+ const w=windows[name], t=w.by_tool[entry.tool]??={calls:0,bytes:0};
192
+ t.calls++; t.bytes+=entry.response_bytes; w.calls++; w.response_bytes+=entry.response_bytes;
193
+ }
194
+ };
195
+ for (const line of readLines(file)) take(line);
196
+ // A window that starts before the log's first outcome is partial.
197
+ for(const [name,ms] of spans) if(log.first_at===null||Date.parse(log.first_at)>sinceMs-ms) windows[name].partial=true;
198
+ return {windows,log};
199
+ }
200
+ // The agent session a submit belongs to, so `wait --drained` can find that session's own work. Explicit flag first, then the
201
+ // harness session id (Claude Code sets CLAUDE_CODE_SESSION_ID, Codex sets CODEX_THREAD_ID in shell commands). Only the flag is
202
+ // validated strictly; an odd environment value is ignored, so it can never break a submit.
203
+ const producerPattern=/^[A-Za-z0-9._:%-]{1,256}$/;
204
+ function producerId() {
205
+ const flag=option('--producer-thread');
206
+ if(flag!==null) { if(!producerPattern.test(flag)) throw new Error('invalid --producer-thread'); return flag; }
207
+ return [process.env.CLAUDE_CODE_SESSION_ID,process.env.CODEX_THREAD_ID].find(v=>v&&producerPattern.test(v))??null;
208
+ }
209
+ const drainedDir=defaultPath(home,'.local/state/dot-bridge/drained');
210
+ function drainedPidfile(producer) { return path.join(drainedDir,createHash('sha256').update(producer).digest('hex').slice(0,32)+'.json'); }
211
+ // Producer receipts. A parsed receipt never changes, so it is read once; one still being written is retried next time.
212
+ function producerReceipts(producer,cache) {
213
+ let names=[]; try { names=fs.readdirSync(receipts); } catch {}
214
+ for(const name of names) if(!cache.has(name)) {
215
+ let r; try { r=JSON.parse(fs.readFileSync(path.join(receipts,name),'utf8')); } catch { continue; }
216
+ cache.set(name,r&&typeof r==='object'&&(producer===null||r.producer===producer||r.thread===producer)?{id:r.request_id,token:r.token}:null);
217
+ }
218
+ return [...cache.values()].filter(Boolean);
219
+ }
220
+ // A failure worth retrying: the bridge restarting (transport) or unavailable (5xx).
221
+ const transient=e=>e.kind==='transport'||e.http_status>=500;
222
+ // /owner-states reads without recording an owner read. An older bridge lacks it; /get then works, but each finished task
223
+ // it sees is recorded as consumed once. A 4xx for one request (unknown, not owned) marks it unknown; anything else throws.
224
+ async function ownerStates(items,legacy) {
225
+ if(!legacy.on) try {
226
+ let out=null;
227
+ for(let i=0;i===0||i<items.length;i+=500) { // the route takes at most 500 items
228
+ const part=await request('/owner-states','POST',{items:items.slice(i,i+500).map(x=>({id:x.id,capability:x.token}))});
229
+ out=out?{...part,states:[...out.states,...part.states]}:part;
230
+ }
231
+ return out;
232
+ }
233
+ catch(e) { if(e.http_status!==404) throw e; legacy.on=true; }
234
+ const states=[];
235
+ for(const x of items) {
236
+ let got; try { got=await request('/get?id='+encodeURIComponent(x.id),'GET',null,{'x-owner-capability':x.token}); }
237
+ catch(e) { if(transient(e)) throw e; states.push({request_id:x.id,error:'unreadable'}); continue; }
238
+ if(typeof got.status!=='string') { states.push({request_id:x.id,error:'unreadable'}); continue; }
239
+ const blockers=(got.progress??[]).map(p=>p.note).filter(n=>/^\s*(?:BLOCKED:|QUESTION:)/im.test(n));
240
+ states.push({request_id:x.id,status:got.status,blocker_count:blockers.length,last_blocker:blockers.at(-1)??null});
241
+ }
242
+ const s=await request('/status');
243
+ // Only evidence holds refill: a pause or an owner-confirmed break (not an inferred break, not an estimated limit).
244
+ const held=s.paused?'paused':s.worker_break?.active&&s.worker_break.source==='owner'?'worker_break':null;
245
+ return {states,refill:{held}};
246
+ }
247
+ // A peek at the owner's receipts: finished results nobody read, questions, and cancellations. Records no owner read.
248
+ // With --mark-read it records the owner read, without fetching results, for the listed ids or for items older than --before.
249
+ async function inbox() {
250
+ const all=args.includes('--all'), explicit=option('--producer');
251
+ if(args.includes('--producer')&&(explicit===null||!producerPattern.test(explicit))) throw new Error('invalid --producer');
252
+ const markRead=args.includes('--mark-read'), valued=['--producer','--since','--before'];
253
+ const ids=args.filter((a,i)=>!a.startsWith('-')&&!valued.includes(args[i-1]));
254
+ const before=args.includes('--before')?option('--before'):null;
255
+ if(args.includes('--before')&&!markRead) throw new Error('--before only applies to --mark-read');
256
+ if(ids.length&&!markRead) throw new Error(`unexpected argument '${ids[0]}' (request IDs go after --mark-read)`);
257
+ if(markRead&&!ids.length&&before===null) throw new Error('--mark-read needs request IDs or --before TIME (Nh, Nd or RFC3339); it never marks everything');
258
+ if(markRead&&ids.length&&before!==null) throw new Error('--mark-read takes request IDs or --before, not both');
259
+ if(markRead&&before==='all') throw new Error('--before needs a time (Nh, Nd or RFC3339), not all');
260
+ const sinceText=args.includes('--since')?option('--since'):'72h', cutoff=parseWhen(sinceText), beforeCutoff=before===null?null:parseWhen(before);
261
+ const detectedProducer=explicit??producerId();
262
+ const scopeAll=all||(!markRead&&!detectedProducer);
263
+ const producer=scopeAll||(markRead&&ids.length)?null:detectedProducer;
264
+ if(!scopeAll&&!producer&&!(markRead&&ids.length)) throw new Error('inbox needs --producer ID (or CLAUDE_CODE_SESSION_ID / CODEX_THREAD_ID), or --all for every receipt on this host');
265
+ const legacy={on:false}, receiptsInScope=producerReceipts(producer,new Map());
266
+ if(markRead&&ids.length) {
267
+ const byId=new Map(receiptsInScope.map(r=>[r.id,r])), missing=ids.filter(x=>!byId.has(x));
268
+ if(missing.length) throw new Error(`no receipt on this host for ${missing.join(', ')}`);
269
+ return markInboxRead(ids.map(x=>byId.get(x)));
270
+ }
271
+ const read=await ownerStates(receiptsInScope,legacy);
272
+ if(legacy.on) throw new Error('this bridge predates dalan inbox; update and restart it');
273
+ if(!markRead) return buildInbox(read.states,scopeAll?'all':producer,{cutoff});
274
+ const due=buildInbox(read.states,all?'all':producer).items.filter(i=>i.group!=='question'&&i.group!=='undecided'&&Date.parse(i.updated_at)<beforeCutoff);
275
+ const byId=new Map(receiptsInScope.map(r=>[r.id,r]));
276
+ return markInboxRead(due.map(i=>byId.get(i.request_id)));
277
+ }
278
+ async function markInboxRead(items) {
279
+ let marked=0, unknown=[];
280
+ for(let i=0;i<items.length;i+=500) {
281
+ let part; try { part=await request('/owner-mark-read','POST',{items:items.slice(i,i+500).map(x=>({id:x.id,capability:x.token}))}); }
282
+ catch(e) { if(e.http_status===404) throw new Error('this bridge predates dalan inbox --mark-read; update and restart it'); throw e; }
283
+ marked+=part.marked; unknown.push(...part.results.filter(r=>r.error).map(r=>r.request_id));
284
+ }
285
+ return {marked,requested:items.length,...(unknown.length?{unknown}:{})};
286
+ }
287
+ async function waitDrained() {
288
+ const producer=producerId();
289
+ if(!producer) throw new Error('wait --drained needs --producer-thread ID (or CLAUDE_CODE_SESSION_ID / CODEX_THREAD_ID)');
290
+ const seconds=option('--timeout')===null?1740:Number(option('--timeout'));
291
+ if(!Number.isInteger(seconds)||seconds<1||seconds>86400) throw new Error('wait --drained timeout must be an integer from 1 to 86400 seconds');
292
+ const limits={};
293
+ for(const [flag,key,fallback] of [['--max-claimed','maxClaimed',0],['--max-queued','maxQueued',1]]) {
294
+ const v=option(flag)===null?fallback:Number(option(flag));
295
+ if(!Number.isInteger(v)||v<0||v>100) throw new Error(`${flag} must be an integer from 0 to 100`);
296
+ limits[key]=v;
297
+ }
298
+ const intervalMs=Number(process.env.DOT_DRAINED_INTERVAL_MS||15000);
299
+ const unreachableMs=Number(process.env.DOT_DRAINED_UNREACHABLE_MS||600000);
300
+ // One waiter per producer: a second one exits at once, so the hook and a forgetful agent cannot stack them.
301
+ fs.mkdirSync(drainedDir,{recursive:true,mode:0o700});
302
+ const file=drainedPidfile(producer), mine={pid:process.pid,token:randomBytes(8).toString('hex'),producer,started_at:new Date().toISOString()};
303
+ const other=takeSlot(file,mine,{isLive:liveWaiter});
304
+ if(other) return {status:'already_running',producer,pid:other.pid,started_at:other.started_at};
305
+ const release=()=>releaseSlot(file,mine);
306
+ process.once('exit',release);
307
+ for(const signal of ['SIGTERM','SIGINT','SIGHUP']) process.once(signal,()=>{ release(); process.exit(128+({SIGTERM:15,SIGINT:2,SIGHUP:1})[signal]); });
308
+ const cache=new Map(), memo={baseline:new Map(),startTerminal:new Set(),lastHeld:undefined}, legacy={on:false}, done=new Map();
309
+ const deadline=Date.now()+seconds*1000;
310
+ let failingSince=null;
311
+ for(;;) {
312
+ let read=null;
313
+ try { read=await ownerStates(producerReceipts(producer,cache).filter(x=>!done.has(x.id)),legacy); failingSince=null; }
314
+ catch(e) {
315
+ // Keep waiting through a bridge restart; give up with a JSON line only after a sustained outage.
316
+ if(!transient(e)) return {status:'error',producer,error:e.message};
317
+ failingSince??=Date.now();
318
+ if(Date.now()-failingSince>=unreachableMs) return {status:'bridge_unreachable',producer,error:e.message};
319
+ }
320
+ if(read) {
321
+ // Terminal tasks stay terminal; they are never read from the bridge again.
322
+ for(const s of read.states) if(terminal.has(s.status)) done.set(s.request_id,s.status);
323
+ const unknown=read.states.filter(s=>s.error).map(s=>s.request_id);
324
+ const states=[...read.states.filter(s=>!s.error&&!terminal.has(s.status)),...[...done].map(([id,status])=>({request_id:id,status,blocker_count:0,last_blocker:null}))];
325
+ let outcome=decideDrained(states,read.refill,memo,limits);
326
+ // Nothing readable and nothing finished (e.g. the bridge lost these requests): not a refill signal; hold to the timeout.
327
+ if(outcome?.status==='drained'&&unknown.length&&!outcome.finished.length&&!states.some(s=>!terminal.has(s.status))) outcome=null;
328
+ const extra={producer,...(unknown.length?{unknown}:{}),...(legacy.on?{legacy_reads:true}:{})};
329
+ if(outcome) return {...outcome,...extra};
330
+ if(Date.now()>=deadline) return {status:'timeout',in_flight:{queued:states.filter(s=>s.status==='queued').length,claimed:states.filter(s=>s.status==='claimed').length},...extra};
331
+ } else if(Date.now()>=deadline) return {status:'timeout',producer,error:'bridge unreachable'};
332
+ await new Promise(r=>setTimeout(r,Math.min(intervalMs,Math.max(0,deadline-Date.now()))));
333
+ }
334
+ }
335
+ async function main() {
336
+ let result, waitOutput=false, plainOutput=false;
337
+ const help=resolveHelp([command,...args]);
338
+ if(help){ if(help.stream==='stdout') console.log(help.text); else console.error(help.text); process.exitCode=help.code; return; }
339
+ switch (command) {
340
+ case 'paths': {
341
+ const selectors={'--workspace-root':()=>workspaceRoot(home),'--config-root':()=>defaultPath(home,'.config/dot-bridge'),'--data-root':()=>root,'--state-root':()=>defaultPath(home,'.local/state/dot-bridge')};
342
+ if(args.some(arg=>arg!=='--json'&&!Object.hasOwn(selectors,arg))||args.filter(arg=>Object.hasOwn(selectors,arg)).length>1)throw new Error('usage: dalan paths [--json | --workspace-root | --config-root | --data-root | --state-root]');
343
+ const selector=args.find(arg=>Object.hasOwn(selectors,arg));
344
+ const warnings=rootWarnings(home);
345
+ if(!json||selector)for(const warning of warnings) console.error(`dalan: WARNING root_passed_over ${warning.area}: using ${JSON.stringify(warning.chosen)}; passed over ${JSON.stringify(warning.passed_over)}; missing ${JSON.stringify(warning.missing)}`);
346
+ if(selector) {result=selectors[selector]();plainOutput=true;}
347
+ else result={config_dir:selectors['--config-root'](),data_dir:root,state_dir:selectors['--state-root'](),workspace_root:workspaceRoot(home),...(json?{warnings}:{})};
348
+ break;
349
+ }
350
+ case 'worker': {
351
+ const [action,name,repo,...extra]=args.filter(a=>a!=='--json');
352
+ if(args.filter(a=>a==='--json').length>1) throw new Error('usage: dalan worker allow|deny NAME OWNER/REPO [--json] | worker list [NAME] [--json]');
353
+ const file=readEnv('DALAN_WORKERS_FILE')||defaultPath(home,'.config/dot-bridge/workers.json');
354
+ if(action==='migrate-repos') {
355
+ if(name!==undefined)throw new Error('usage: dalan worker migrate-repos [--json]; stop the service first');
356
+ // Read existing history without opening Store or migrating its schema.
357
+ const db=new DatabaseSync(path.join(root,'bridge.db'),{readOnly:true});
358
+ // Name both inputs: a HOME and a DALAN_WORKERS_FILE from different bridges would seed one bridge's history into the other.
359
+ try {loadOwnerWorkers(file);result={...seedWorkerRepos(file,db),database:path.join(root,'bridge.db'),workers_file:file};} finally {db.close();}
360
+ break;
361
+ }
362
+ if(action==='list') {
363
+ if(repo!==undefined||extra.length) throw new Error('usage: dalan worker list [NAME] [--json]');
364
+ const profile=loadOwnerWorkers(file);
365
+ const names=name===undefined?[...profile.workers.keys()]:[name];
366
+ const history=readWorkerRepoHistory(path.join(path.dirname(file),'workers-audit.jsonl'),{workersFile:file});
367
+ const grantAudit=fs.existsSync(file)?inspectGrantAudit(file):{unaudited:[],integrity_error:null},unauditedGrants=grantAudit.unaudited;
368
+ const integrityNote=grantAudit.integrity_error?`${grantAudit.integrity_error}. ${AUDIT_INTEGRITY_HINT}`:null;
369
+ const policies=names.map(worker=>{
370
+ if(!profile.workers.has(worker)) throw new Error(`unknown worker "${worker}"; configured workers: ${[...profile.workers.keys()].join(', ')}`);
371
+ const policy=profile.repoPolicy(worker);
372
+ const changes=history.events.filter(event=>event.worker===worker),changeCount=history.complete?changes.length:null;
373
+ const unaudited=unauditedGrants.find(item=>item.worker===worker)?.repos;
374
+ return {worker,...policy,...(unaudited?{unaudited_grants:unaudited}:{}),...(integrityNote?{audit_integrity_error:integrityNote}:{}),changes:changes.slice(-20),change_count:changeCount,changes_truncated:!history.complete||changes.length>20,
375
+ ...(history.error?{changes_error:history.error}:{}),...(!fs.existsSync(file)?{warning:missingProfileWarning(worker,policy)}:{})};
376
+ });
377
+ if(!json) { result=policies.map(policy=>`${policy.worker}: ${policy.mode}${policy.repos?.length?` (${policy.repos.join(', ')})`:''}${policy.warning?` WARNING: ${policy.warning}`:''}${policy.changes.map(event=>`\n ${event.at} uid=${event.actor.host_uid}: ${event.before.repos?.join(', ')||'(none)'} -> ${event.after.repos?.join(', ')||'(none)'}`).join('')}${policy.changes_truncated?`\n showing ${policy.changes.length} retained changes; ${policy.change_count===null?'older history count unknown':`${policy.change_count} recorded changes in total`}`:''}${policy.changes_error?`\n WARNING: ${policy.changes_error}`:''}${policy.audit_integrity_error?`\n WARNING: ${policy.audit_integrity_error}`:''}`).join('\n')||'No workers configured.'; plainOutput=true; }
378
+ else result={workers:policies};
379
+ break;
380
+ }
381
+ if(!['allow','deny'].includes(action)||!name||!repo||extra.length) throw new Error('usage: dalan worker allow|deny NAME OWNER/REPO [--json]');
382
+ result=updateWorkerRepoPolicy(file,name,action,repo);
383
+ if(!json) { result=`${name}: ${result.mode}${result.repos?.length?` (${result.repos.join(', ')})`:''}${result.denied?.length?` except ${result.denied.join(', ')}`:''}${result.reset_to_audited?.length?`\nthe audit log failed its checkpoint, so workers.json was reset to the audited grants; allow again: ${result.reset_to_audited.map(item=>`${item.worker}${item.repos.length?` (${item.repos.join(', ')})`:''}`).join('; ')}`:''}`; plainOutput=true; }
384
+ break;
385
+ }
386
+ case 'submit': {
387
+ refuseUnknownOptions('submit',{flags:SUBMIT_FLAGS,values:SUBMIT_VALUES});
388
+ const thread = option('--thread'), requestedDelivery = option('--deliver'), file = option('--file');
389
+ if (thread && requestedDelivery) throw new Error('submit accepts either --thread or --deliver, not both');
390
+ const delivery = requestedDelivery ?? (thread ? `t3:${thread}` : 'none');
391
+ if (delivery !== 'none' && !/^t3:[A-Za-z0-9._:%-]{8,1024}$/.test(delivery)) throw new Error('invalid delivery; expected none or t3:<thread-id>');
392
+ const jobFix=(message,...fix)=>Object.assign(new Error(message),{fix});
393
+ const stdin=args.includes('--stdin'), briefGiven=args.includes('--brief'), briefText=option('--brief');
394
+ if (!file && !stdin && !briefGiven) throw jobFix('submit needs a job: pass --file PATH, --stdin or --brief TEXT', `for the first job: ${cli} submit --worker local --execution none --deliver none --file first-job.json`, `first-job.json is in ${FIRST_JOB_URL}`, `or for a text-only question: ${cli} submit --worker local --brief "your question"`);
395
+ if ([file,stdin,briefGiven].filter(Boolean).length>1) throw jobFix('submit reads one job: pass exactly one of --file PATH, --stdin and --brief TEXT, not several', 'run the same command again with only one of them');
396
+ if (briefGiven&&(briefText===undefined||briefText===null||SUBMIT_OPTIONS.includes(briefText)||!briefText.trim())) throw jobFix('--brief needs the text of the job, and it is empty or missing', `pass the text after --brief, in quotes: ${cli} submit --brief "your question"`);
397
+ let input;
398
+ if (briefGiven) {
399
+ // A text-only job: the text is the brief exactly as typed, with no repository and no file access.
400
+ input = JSON.stringify({ schema_version: 1, request_id: `req_${randomUUID()}`, brief: briefText, inputs: [], expected_output: 'A plain-text answer.', execution_scope: 'read-only' });
401
+ } else {
402
+ try { input = file ? fs.readFileSync(file, 'utf8') : fs.readFileSync(0, 'utf8'); }
403
+ catch(e) { if(!file) throw e; throw jobFix(`cannot read the job file ${JSON.stringify(file)}: ${e.code==='ENOENT'?'no such file':e.code==='EISDIR'?'it is a directory':e.message}`, 'check the path, then run the same dalan submit command again'); }
404
+ }
405
+ const source=briefGiven?'the --brief job':file?`the job file ${JSON.stringify(file)}`:'the job on standard input';
406
+ let body;
407
+ try { body=JSON.parse(input); }
408
+ catch(e) { throw jobFix(`${source} is not valid JSON: ${e.message}`, 'correct the JSON, then run the same dalan submit command again', `a valid example: ${JOB_EXAMPLE_URL}`); }
409
+ if(!body||typeof body!=='object'||Array.isArray(body)) throw jobFix(`${source} is not a job: it must be a JSON object`, `a valid example: ${JOB_EXAMPLE_URL}`);
410
+ if(typeof body.request_id!=='string'||!/^[-\w]{8,128}$/.test(body.request_id)) throw jobFix('the job has no valid request_id: request_id is required and must be 8-128 letters, digits, _ or -', 'add "request_id": "req_" followed by a new UUID; make one with: node -e "console.log(require(\'node:crypto\').randomUUID())"');
411
+ // A dry run leaves this to the bridge, which answers it with a typed verdict.
412
+ if(!Array.isArray(body.inputs)&&!args.includes('--dry-run')) throw jobFix('the job has no inputs array: inputs must be an array', 'add "inputs": [] when the job has no repository input');
413
+ const id=body.request_id, review=args.includes('--review'), background=args.includes('--background'), worker=option('--worker');
414
+ if(args.includes('--worker')&&(!worker||worker.startsWith('--'))) throw new Error('--worker requires a name');
415
+ if(args.includes('--eligible')&&args.includes('--policy'))throw new Error('use either --eligible or --policy');
416
+ let routing=null,destinationRevisions={};
417
+ if(args.includes('--eligible')) {
418
+ const list=option('--eligible');if(!list||list.startsWith('--'))throw new Error('--eligible requires a comma-separated worker list');
419
+ routing={version:1,allowed_workers:list.split(','),fan_out:1,...(body.valid_until?{deadline_at:body.valid_until}:{})};
420
+ }
421
+ if(args.includes('--policy')) {
422
+ const file=option('--policy');if(!file||file.startsWith('--'))throw new Error('--policy requires a JSON file');
423
+ const value=JSON.parse(fs.readFileSync(file,'utf8'));
424
+ if(value?.routing&&Object.keys(value).some(key=>!['routing','destination_revisions'].includes(key)))throw new Error('unsupported policy file field');
425
+ routing=value.routing??value;destinationRevisions=value.destination_revisions??{};
426
+ }
427
+ if(routing&&worker)throw new Error('--worker cannot be combined with --eligible or --policy');
428
+ // Execution capability (none|worker|host) and required backend capabilities travel beside the assignment, like --worker.
429
+ const execution=option('--execution'), requireCaps=option('--require-capability');
430
+ if(args.includes('--execution')) parseExecution(execution);
431
+ if(args.includes('--require-capability')&&(!requireCaps||requireCaps.startsWith('--'))) throw new Error('--require-capability requires a comma-separated list');
432
+ const requiredCapabilities=requireCaps?parseRequiredCapabilities(requireCaps.split(',')):null;
433
+ if(review&&body.execution_scope===undefined) body.execution_scope='implementation';
434
+ for(const flag of ['--objective-key','--revision','--task-kind','--source']) if(args.includes(flag)&&(!option(flag)||option(flag).startsWith('--'))) throw new Error(`${flag} requires a value`);
435
+ // Objective identity travels beside the assignment, never inside it; a plain dalan submit is an agent's.
436
+ const given=normalizeMeta({objective_key:option('--objective-key'),revision:option('--revision'),task_kind:option('--task-kind'),source:option('--source')});
437
+ const dryRun=args.includes('--dry-run'), queueAnyway=args.includes('--queue-anyway'), refuseDefer=args.includes('--refuse-defer');
438
+ if(dryRun&&queueAnyway) throw new Error('--dry-run stores nothing; it cannot be combined with --queue-anyway');
439
+ if(dryRun&&args.includes('--wait')) throw new Error('--dry-run stores nothing; it cannot be combined with --wait');
440
+ if(args.includes('--defer-if-queued')&&!(Number.isSafeInteger(Number(option('--defer-if-queued')))&&Number(option('--defer-if-queued'))>=1)) throw new Error('--defer-if-queued requires a positive integer');
441
+ // Refuse a new local request before creating its durable owner receipt. The server repeats this check from its current
442
+ // workers.json, so a stale CLI profile cannot authorize an assignment.
443
+ if(!dryRun&&!fs.existsSync(receiptPath(id))) {
444
+ const policy=loadOwnerWorkers(readEnv('DALAN_WORKERS_FILE')||defaultPath(home,'.config/dot-bridge/workers.json'));
445
+ const targets=routing?.allowed_workers??[submitTarget(policy,worker??undefined)??'dot'],inputs=body.inputs;
446
+ for(const target of targets) {
447
+ if(routing&&!policy.workers.has(target))throw new Error('unknown eligible worker '+target);
448
+ if(Array.isArray(inputs)&&inputs.some(input=>input?.github_repo!==undefined)) {
449
+ const repoName=inputs[0]?.github_repo;
450
+ if(inputs.length!==1) throw new Error('one repository input per job; submit separate jobs for multiple repositories');
451
+ if(typeof repoName!=='string'||!policy.allowsRepo(target,repoName)) throw new Error(`repository ${typeof repoName==='string'?repoName:'(invalid repository)'} is not allowed for worker "${target}"; update it with dalan worker allow ${target} OWNER/REPO, or choose another worker`);
452
+ }
453
+ }
454
+ }
455
+ const token=randomBytes(32).toString('hex');
456
+ const write=()=>writeReceipt(id,token,JSON.stringify(body),delivery,review,background,{...given,source:given.source??'agent'},producerId(),routing,destinationRevisions);
457
+ let saved;
458
+ if(dryRun) {
459
+ try { saved=receipt(id); }
460
+ catch(error) { if(error.code!=='ENOENT') throw error; saved={request_id:id,token,delivery,body:input,...(routing?{routing,destination_revisions:destinationRevisions}:{})}; }
461
+ } else saved=write();
462
+ if(!routing&&saved.routing) {routing=saved.routing;destinationRevisions=saved.destination_revisions??{};}
463
+ let fresh=!dryRun&&saved.token===token;
464
+ // Receipts written by earlier releases may carry the old spelling of a source; compare the normalized form.
465
+ const savedMeta=()=>{ try { return normalizeMeta(saved.meta); } catch { return {}; } };
466
+ const conflicts=()=>{ const savedDelivery=saved.delivery ?? (saved.thread ? `t3:${saved.thread}` : null);
467
+ 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]); };
468
+ const conflict=()=>Object.assign(new Error('request_id conflict with local receipt'),{local_code:'receipt_conflict'});
469
+ // A refused submit stores no assignment, so its receipt guards nothing. Replace it instead of refusing a corrected retry.
470
+ if(dryRun&&conflicts()) throw conflict();
471
+ if(!dryRun&&conflicts()) {
472
+ const admission=await request('/admission?id='+encodeURIComponent(id)).catch(()=>null);
473
+ if(admission?.exists!==false) throw conflict();
474
+ fs.unlinkSync(receiptPath(id));saved=write();fresh=saved.token===token;
475
+ if(conflicts()) throw conflict();
476
+ }
477
+ // A retry inherits what the receipt recorded for any flag it omits, so replaying a drainer request by hand stays one request.
478
+ const meta=Object.fromEntries(metaFields.map(k=>[k,given[k]??savedMeta()[k]??(k==='source'?'agent':null)]));
479
+ 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, ...(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()}:{});
480
+ try {
481
+ try { result=await send(); }
482
+ catch(error) {
483
+ // Default: refuse with the exact scope fix. The bridge's suggested_scope_paths (brief files outside scope_paths added, unknown
484
+ // scope paths dropped) are applied and the submit retried once only with --allow-scope-prune (--fix-scope is its old spelling).
485
+ // The refused first submit stored nothing, so the same request_id and receipt stay valid.
486
+ if(!(error.kind==='http'&&error.http_status===400&&error.suggested_scope_paths)) throw error;
487
+ const was=body.scope_paths||[], added=error.suggested_scope_paths.filter(p=>!was.includes(p)), removed=was.filter(p=>!error.suggested_scope_paths.includes(p));
488
+ const change=`${added.length?`added ${added.join(', ')}`:''}${added.length&&removed.length?'; ':''}${removed.length?`removed ${removed.join(', ')}`:''}`;
489
+ if(!args.includes('--allow-scope-prune')&&!args.includes('--fix-scope')) {
490
+ error.fix=[...(added.length?[`add these to scope_paths: ${added.join(', ')} (the brief names them; or remove the mentions from the brief)`]:[]),
491
+ ...(removed.length?[`remove these from scope_paths: ${removed.join(', ')} (not in the repository tree at the pinned revision; to have the job CREATE a new file, list it in output_paths instead)`]:[]),
492
+ `corrected scope_paths: ${JSON.stringify(error.suggested_scope_paths)}`,
493
+ 'or rerun with --allow-scope-prune to let submit apply this scope change and retry once'];
494
+ throw error;
495
+ }
496
+ body.scope_paths=error.suggested_scope_paths;
497
+ console.error(`dalan: --allow-scope-prune: changed scope_paths (${change}) and retried once`);
498
+ result=await send();
499
+ }
500
+ } catch(error) {
501
+ if(dryRun&&error.kind==='http'&&error.http_status===404) throw new Error('bridge does not support the safe /submit-preview route; no submission was attempted');
502
+ if(error.kind==='http'&&error.http_status===400&&!error.fix&&!error.verdict&&/^invalid assignment\b/.test(error.message)) error.fix=['correct the job, then run the same dalan submit command again',`a valid example: ${JOB_EXAMPLE_URL}`];
503
+ // Refused (400): the bridge stored nothing, so a receipt this call created goes too.
504
+ if(fresh&&error.kind==='http'&&(error.http_status===400||error.http_status===409&&error.verdict==='defer')) try { fs.unlinkSync(receiptPath(id)); } catch {}
505
+ throw error;
506
+ }
507
+ for(const w of result?.submission_warnings??[]) console.error(`dalan: WARNING: ${w}`);
508
+ if(dryRun) { if(!json) console.error(formatVerdict(result)); process.exitCode=VERDICT_EXIT[result.verdict]??0; break; }
509
+ if(args.includes('--wait')) { result=await waitForAssignment(id,option('--timeout')); indexArtifacts(id,result); waitOutput=true; process.exitCode=waitExitCode(result.status); if(!json) waitTimeoutNote(id,result); }
510
+ // Discovery labels are not capabilities. Report only the persisted, validated binding.
511
+ const producer=typeof saved.producer==='string'&&producerPattern.test(saved.producer)?saved.producer:null;
512
+ const binding=producer===null?'missing':producer!==producerId()?'different':'saved';
513
+ const recovery={producer,get:`${cli} get ${id}`,...(producer?{inbox:`${cli} inbox --producer ${producer}`}:{}),
514
+ binding,wake:args.includes('--wait')?'wait_returned':delivery==='none'?'not_registered_by_this_submit':'delivery_destination'};
515
+ if(json) result={...result,recovery};
516
+ // Human mode: one plain next step on stderr, so stdout stays the JSON document. --json carries the full recovery record.
517
+ else endNote=`${briefGiven?`Request ID: ${id}\nSend your worker: ${workerPrompt(id)}\n`:''}Next: ${recovery.wake==='wait_returned'?`read the result with: ${recovery.get}`:recovery.wake==='delivery_destination'?`the result goes to ${delivery}; check it any time with: ${recovery.get}`:`send your worker the job, then run: ${cli} wait ${id} (check it any time with: ${recovery.get})`}${recovery.inbox?`. List your jobs with: ${recovery.inbox}`:''}`;
518
+ // On a terminal, a person reads the output: show the human lines instead of the JSON receipt. Piped output stays
519
+ // the JSON document, so scripts that read submit's standard output keep working; --json always prints it.
520
+ if(!json&&!waitOutput&&process.stdout.isTTY) { result=`Request ID: ${id}${briefGiven?`\nSend your worker: ${workerPrompt(id)}`:''}`; plainOutput=true; endNote=endNote.split('\n').filter(l=>!l.startsWith('Request ID: ')&&!l.startsWith('Send your worker: ')).join('\n'); }
521
+ break;
522
+ }
523
+ case 'get': { refuseUnknownOptions('get',{flags:['--json']}); const id=args[0]; if(!id||id.startsWith('-')) throw new Error(`get needs a request ID: ${cli} get REQUEST_ID (list your jobs with: ${cli} inbox --all)`); const headers=id.startsWith('msg_')?{}:{'x-owner-capability':receipt(id).token}; result=await request('/get?id='+encodeURIComponent(id),'GET',null,headers); if(!id.startsWith('msg_')) indexArtifacts(id,result);
524
+ // Human mode: one extra line on stderr so stdout stays the JSON document.
525
+ if(!json&&result?.claim?.activity) { const a=result.claim.activity, age=a.last_tool_at?Math.max(0,Math.round((Date.now()-Date.parse(a.last_tool_at))/1000)):null;
526
+ 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}`:''}`); }
527
+ // On a terminal, a person reads the output: show the short human view. Piped output stays the JSON document.
528
+ if(!json&&!id.startsWith('msg_')&&process.stdout.isTTY) { result=formatGetSummary(result,{id,cli}); plainOutput=true; }
529
+ else if(!json&&!id.startsWith('msg_')&&result?.status==='finished') endNote=`decide: ${cli} decide ${id} ${decideWords}`;
530
+ break; }
531
+ 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; }
532
+ 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; }
533
+ case 'cancel': { const id=args[0]; if(!id) throw new Error('cancel requires request id'); result=await request('/cancel','POST',{id,reason:option('--reason')},{'x-owner-capability':receipt(id).token}); break; }
534
+ case 'status': {
535
+ refuseUnknownOptions('status',{flags:['--json','--explain']});
536
+ result = await request('/status');
537
+ if (args.includes('--explain')) {
538
+ let metrics = null;
539
+ try { metrics = await request('/metrics'); if (!metrics?.window) metrics = null; } catch { /* an older bridge has no /metrics */ }
540
+ const explanation = explainStatus(result) + '\n' + (metrics ? explainMetrics(metrics) : 'metrics=unavailable');
541
+ if (json) result = { ...result, explanation, ...(metrics ? { metrics } : {}) };
542
+ else { result = explanation; plainOutput = true; }
543
+ } else if (!json) { result = formatStatusSummary(result, { home, url: bridgeOrigin(), trial: fs.existsSync(path.join(home, '.dalan-trial')), cli, envHome: process.env.DALAN_HOME }); plainOutput = true; }
544
+ break;
545
+ }
546
+ case 'tool': {
547
+ const rest=args.filter(a=>a!=='--json'),[action,name,workerArg,...extra]=rest;
548
+ const usage='usage: dalan tool add --file PATH | remove NAME | list | grant NAME WORKER | revoke NAME WORKER [--json]';
549
+ const headers={'x-operator-key':operator()};
550
+ if(action==='list'&&rest.length===1) result=await request('/tools','GET',null,headers);
551
+ else if(action==='add'&&name==='--file'&&workerArg&&!extra.length) result=await request('/tools/add','POST',{spec:JSON.parse(fs.readFileSync(workerArg,'utf8'))},headers);
552
+ else if(action==='remove'&&name&&workerArg===undefined) result=await request('/tools/remove','POST',{name},headers);
553
+ else if((action==='grant'||action==='revoke')&&name&&workerArg&&!extra.length) result=await request('/tools/'+action,'POST',{name,worker:workerArg},headers);
554
+ else throw new Error(usage);
555
+ if(!json&&action==='list') { result=result.tools.length?result.tools.map(t=>`${t.name} [${t.class}${t.enabled?'':', disabled'}] ${t.schema_hash.slice(0,12)} workers: ${t.workers.join(', ')||'none'}${t.uncertain?`, ${t.uncertain} message(s) may have been delivered and are not retried`:''}`).join('\n'):'no registered tools'; plainOutput=true; }
556
+ break;
557
+ }
558
+ case 'inbox': { result=await inbox(); if(!json) { result='marked' in result?`marked ${result.marked} read${result.unknown?` (${result.unknown.length} not owned: ${result.unknown.join(', ')})`:''}`:formatInbox(result); plainOutput=true; } break; }
559
+ case 'wait': { refuseUnknownOptions('wait',{flags:['--json','--drained'],values:['--timeout','--producer-thread','--max-claimed','--max-queued']}); if(args.includes('--drained')) { result=await waitDrained(); waitOutput=true; process.exitCode=drainedExitCodes[result.status]; break; } const id=args[0]; if(!id||id.startsWith('-')) throw new Error(`wait needs a request ID: ${cli} wait REQUEST_ID (list your jobs with: ${cli} inbox --all)`); result=await waitForAssignment(id,option('--timeout')); indexArtifacts(id,result); waitOutput=true; process.exitCode=waitExitCode(result.status); if(!json&&process.stdout.isTTY) { result=formatWaitLine(result,{id,cli,seconds:option('--timeout')===null?300:Number(option('--timeout'))}); plainOutput=true; } else if(!json) waitTimeoutNote(id,result); break; }
560
+ case 'note': { if(args.some(a=>a.startsWith('-')&&a!=='--json')) throw new Error('note accepts only --json as an option'); const [id,...parts]=args.filter(a=>a!=='--json'),text=parts.join(' '); if(!id||!text) throw new Error('note requires request id and text'); result=await request('/note','POST',{id,text},{'x-owner-capability':receipt(id).token}); break; }
561
+ case 'questions': { const ids=args.filter(a=>a!=='--json');if(ids.length!==1||ids[0].startsWith('-')) throw new Error('questions requires one request id (optional --json)');result=await request('/questions?id='+encodeURIComponent(ids[0]),'GET',null,{'x-owner-capability':receipt(ids[0]).token});break; }
562
+ case 'answer': { if(args.some(a=>a.startsWith('-')&&a!=='--json')) throw new Error('answer accepts only --json as an option');const [id,questionId,...parts]=args.filter(a=>a!=='--json'),text=parts.join(' ');if(!id||!questionId||!text) throw new Error('answer requires request id, question id and text');result=await request('/answer','POST',{id,question_id:questionId,text},{'x-owner-capability':receipt(id).token});break; }
563
+ case 'tell': { const worker=option('--worker'),rest=args.filter((a,i)=>a!=='--worker'&&args[i-1]!=='--worker');if(rest.some(a=>a.startsWith('-')&&a!=='--json')) throw new Error('tell accepts --worker NAME and --json');const text=rest.filter(a=>a!=='--json').join(' ');if(!text) throw new Error('tell requires text');result=await request('/tell','POST',{text,...(worker?{worker}:{})});break; }
564
+ case 'untell': { const worker=option('--worker'),rest=args.filter((a,i)=>a!=='--worker'&&args[i-1]!=='--worker'&&a!=='--json');if(rest.length!==1||rest[0].startsWith('-')) throw new Error('untell requires message ID (optional --worker NAME, --json)');result=await request('/untell','POST',{message_id:rest[0],...(worker?{worker}:{})});break; }
565
+ case 'audit': { const since=option('--since'); result=await request('/audit'+(since?'?since='+encodeURIComponent(since):''),'GET',null,{'x-operator-key':operator()}); break; }
566
+ case 'pause': { const reason=option('--reason'); if(!reason) throw new Error('pause requires --reason'); result=await request('/pause','POST',{reason},{'x-operator-key':operator()}); break; }
567
+ case 'break': {
568
+ if(args.some((a,i)=>a.startsWith('--')&&!['--json','--clear','--reason','--since'].includes(a)&&!['--reason','--since'].includes(args[i-1]))) throw new Error('break accepts only --reason TEXT, --since RFC3339, --clear and --json');
569
+ if(args.includes('--clear')) { if(args.includes('--reason')||args.includes('--since')) throw new Error('break --clear takes no --reason or --since'); result=await request('/break','POST',{clear:true},{'x-operator-key':operator()}); break; }
570
+ const reason=option('--reason'); if(!reason||reason.startsWith('--')) throw new Error('break requires --reason TEXT (or --clear)');
571
+ if(args.includes('--since')&&(!option('--since')||option('--since').startsWith('--'))) throw new Error('--since requires an RFC 3339 time');
572
+ result=await request('/break','POST',{reason,...(option('--since')?{since:option('--since')}:{})},{'x-operator-key':operator()}); break;
573
+ }
574
+ case 'learned': {
575
+ if(args.some(a=>!['--json','--clear'].includes(a))) throw new Error('learned accepts only --clear and --json');
576
+ result=args.includes('--clear')?await request('/learned','POST',{clear:true},{'x-operator-key':operator()}):await request('/learned','GET',null,{'x-operator-key':operator()}); break;
577
+ }
578
+ case 'breaks': { if(args.some(a=>a!=='--json')) throw new Error('breaks accepts only --json'); result=await request('/breaks','GET',null,{'x-operator-key':operator()}); break; }
579
+ case 'break-usage-backfill': {
580
+ if(args.some((a,i)=>a.startsWith('--')&&!['--json','--id','--log'].includes(a)&&!['--id','--log'].includes(args[i-1]))) throw new Error('break-usage-backfill accepts only --id N, --log PATH and --json');
581
+ const breakId=Number(option('--id')), logFile=option('--log')??defaultPath(home,'.local/state/dot-bridge/requests.jsonl');
582
+ if(!Number.isInteger(breakId)||breakId<1) throw new Error('break-usage-backfill requires --id N');
583
+ if(args.includes('--log')&&(!option('--log')||option('--log').startsWith('--'))) throw new Error('--log requires a path');
584
+ const key=operator(), target=(await request('/breaks','GET',null,{'x-operator-key':key})).breaks.find(b=>b.id===breakId);
585
+ if(!target) throw new Error(`break ${breakId} not found`);
586
+ const scanned=await requestLogUsage(logFile,Date.parse(target.since));
587
+ result={...await request('/break-usage-backfill','POST',{id:breakId,since:target.since,windows:scanned.windows},{'x-operator-key':key}),log:scanned.log};
588
+ break;
589
+ }
590
+ case 'resume': result=await request('/resume','POST',{}, {'x-operator-key':operator()}); break;
591
+ 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; }
592
+ 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; }
593
+ 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; }
594
+ case 'decide': {
595
+ const [id,decision]=args; if(!id||id.startsWith('-')||!decision||decision.startsWith('-')) throw new Error(`decide requires ID and one of ${decideWords}`);
596
+ if(!decideWords.split('|').includes(decision)) throw new Error(`unknown decision '${decision}': use ${decideWords}`);
597
+ if(args.includes('--note')&&!option('--note')) throw new Error('--note requires text');
598
+ result=await request('/decide','POST',{id,decision,...(args.includes('--note')?{note:option('--note')}:{})},{'x-owner-capability':receipt(id).token});
599
+ if(!json&&process.stdout.isTTY) { result=`Recorded ${id} as ${decision}.`; plainOutput=true; }
600
+ break;
601
+ }
602
+ case 'apply': {
603
+ const id=args[0]; if(!id||id.startsWith('-')) throw new Error('apply requires request id (optional --dir PATH, default the current directory)');
604
+ if(args.includes('--dir')&&!option('--dir')) throw new Error('--dir requires a path');
605
+ const dir=path.resolve(option('--dir')??process.cwd()), headers={'x-owner-capability':receipt(id).token};
606
+ const got=await request('/get?id='+encodeURIComponent(id),'GET',null,headers); indexArtifacts(id,got);
607
+ const ev=got.report?.workspace_evidence, art=ev?.patch_artifact;
608
+ if(!art?.artifact_id||!art.size) throw new Error('this result has no patch artifact (nothing to apply)');
609
+ const tmp=fs.mkdtempSync(path.join(os.tmpdir(),'dot-apply-')), file=path.join(tmp,'patch.diff');
610
+ try {
611
+ await download(art.artifact_id,file);
612
+ const files=applyPatch({dir,patch:fs.readFileSync(file),sha256:art.sha256,baseSha:ev.base_sha??got.assignment?.inputs?.[0]?.base_sha});
613
+ let decided; try { decided=await request('/decide','POST',{id,decision:'applied',via:'apply'},headers); } catch(e) { throw new Error(`patch applied in ${dir}, but recording the decision failed: ${e.message}; run dalan decide ${id} applied`); }
614
+ result={request_id:id,applied:true,dir,files,decision:decided.decision};
615
+ } finally { fs.rmSync(tmp,{recursive:true,force:true}); }
616
+ if(!json) { const {files}=result; result=`applied ${files.length} file${files.length===1?'':'s'} in ${dir}; recorded decision applied for ${id}\n${files.map(f=>' '+f).join('\n')}`; plainOutput=true; }
617
+ break;
618
+ }
619
+ case 'integrate': { const id=args[0]; if(!id||id.startsWith('-')) throw new Error('integrate requires request id'); result=await request('/lifecycle','POST',{id,type:'integrated',...(option('--reason')?{reason:option('--reason')}:{})},{'x-operator-key':operator()}); break; }
620
+ case 'metrics': {
621
+ if(args.some((a,i)=>a.startsWith('--')&&!['--json','--since'].includes(a)&&args[i-1]!=='--since')) throw new Error('metrics accepts only --since RFC3339 and --json');
622
+ if(args.includes('--since')&&!option('--since')) throw new Error('--since requires an RFC 3339 time');
623
+ result=await request('/metrics'+(option('--since')?'?since='+encodeURIComponent(option('--since')):''));
624
+ if(!json) { result=explainMetrics(result).replace(/ (?=[\w/]+=)/g,'\n '); plainOutput=true; }
625
+ break;
626
+ }
627
+ case 'backfill-objectives': {
628
+ if(args.some(a=>!['--json','--dry-run'].includes(a))) throw new Error('backfill-objectives accepts only --dry-run and --json');
629
+ const key=operator(), readJson=file=>{ try { return JSON.parse(fs.readFileSync(file,'utf8')); } catch { return null; } };
630
+ const list=dir=>fs.existsSync(dir)?fs.readdirSync(dir).filter(n=>n.endsWith('.json')).map(n=>path.join(dir,n)):[];
631
+ const ledgerFile=path.join(home,legacyFixLedgerPath);
632
+ const ledger=fs.existsSync(ledgerFile)?fs.readFileSync(ledgerFile,'utf8').split('\n').filter(Boolean).flatMap(line=>{ try { return [JSON.parse(line)]; } catch { return []; } }):[];
633
+ const derived=deriveObjectives({receipts:list(receipts).map(readJson).filter(r=>r&&typeof r.body==='string'&&r.body),manifests:list(path.join(root,'manifests')).map(readJson),ledger});
634
+ const server={received:0,updated:0,already_set:0,conflict:0,not_found:0,rejected:0,by_source:{},rejected_examples:[]};
635
+ let last=null;
636
+ for(let i=0;i<derived.tuples.length||last===null;i+=200) {
637
+ last=await request('/backfill-objectives','POST',{tuples:derived.tuples.slice(i,i+200),dry_run:args.includes('--dry-run')},{'x-operator-key':key});
638
+ for(const k of ['received','updated','already_set','conflict','not_found','rejected']) server[k]+=last[k];
639
+ for(const [src,n] of Object.entries(last.by_source)) server.by_source[src]=(server.by_source[src]??0)+n;
640
+ server.rejected_examples.push(...last.rejected_examples.slice(0,20-server.rejected_examples.length));
641
+ }
642
+ const dry=args.includes('--dry-run');
643
+ // In a dry run each batch reports nulls minus its own would-be updates, so subtract the earlier batches' too.
644
+ result={dry_run:dry,derived:derived.counts,server,without_objective:dry?last.without_objective+last.updated-server.updated:last.without_objective,total:last.total};
645
+ break;
646
+ }
647
+ case 'rejections': {
648
+ // Refused submits by reason class, against submits the bridge accepted in the same window.
649
+ args.forEach((a,i)=>{ if(!['--since','--log','--json'].includes(a)&&!['--since','--log'].includes(args[i-1])) throw new Error('rejections accepts only --since RFC3339, --log PATH and --json'); });
650
+ const since=option('--since')??new Date(Date.now()-86400000).toISOString(), sinceMs=Date.parse(since);
651
+ if(!Number.isFinite(sinceMs)) throw new Error('--since requires an RFC 3339 time');
652
+ const summary=summarizeRejections(readLines(option('--log')??defaultPath(home,'.local/state/dot-bridge/requests.jsonl'),{missingOk:true}),sinceMs);
653
+ const { DatabaseSync }=await import('node:sqlite'), db=new DatabaseSync(defaultPath(home,'.local/share/dot-bridge/bridge.db'),{readOnly:true});
654
+ const accepted=db.prepare('SELECT count(*) n FROM assignments WHERE created_at>=?').get(new Date(sinceMs).toISOString()).n; db.close();
655
+ 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};
656
+ 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; }
657
+ break;
658
+ }
659
+ // Built-in authorization server. init writes local files only (no running bridge needed); connect talks to the owner socket.
660
+ case 'init': case 'as-init': {
661
+ const publicUrl=option('--public-url'), legacy=args.includes('--legacy'), name=option('--worker'), profiled=command==='init';
662
+ const flagged=['--json','--public-url','--worker','--legacy','--enable-workspace'];
663
+ const usage='usage: dalan init --public-url https://HOST (--worker NAME [--enable-workspace] | --legacy)';
664
+ if(!publicUrl||args.some((a,i)=>!flagged.includes(a)&&!['--public-url','--worker'].includes(args[i-1]))||(!profiled&&(legacy||name))) throw new Error(profiled?usage:'usage: dalan as-init --public-url https://HOST');
665
+ if(args.includes('--enable-workspace')&&(!profiled||legacy)) throw new Error('--enable-workspace requires init --worker NAME');
666
+ if(profiled&&legacy&&name) throw new Error('init takes --worker NAME or --legacy, not both');
667
+ if(profiled&&!legacy&&(!name||name.startsWith('--'))) throw new Error(`init needs --worker NAME to create the first worker profile (or --legacy for an older single-worker host); ${usage}`);
668
+ const config=defaultPath(home,'.config/dot-bridge'), workersFile=path.join(config,'workers.json');
669
+ if(profiled&&!legacy) { parseWorkers({workers:{[name]:{}}},{builtin:true}); if(fs.existsSync(workersFile)) throw new Error(`${workersFile} already exists; init does not overwrite a worker profile`); }
670
+ result=initAsFiles(config,{publicUrl,loopback:readEnv('DALAN_LOOPBACK')==='1',allowHttp:process.env.NODE_ENV!=='production'&&readEnv('DALAN_TEST_OAUTH')==='1'});
671
+ if(profiled&&!legacy) result={...result,workers_profile:{file:writeGenericProfile(workersFile,name,{workspaceAllowed:args.includes('--enable-workspace')}),worker:name,default_execution:'none'}};
672
+ else if(profiled) { writeLegacyMarker(config); result={...result,workers_profile:null,legacy_profile:path.join(config,'legacy-profile')}; console.error('dalan: --legacy wrote no workers.json; it wrote a legacy-profile marker so the server starts in legacy mode. Legacy mode (implicit default worker, t3 capability, host execution) is for older single-worker hosts; new hosts should use --worker NAME.'); }
673
+ break;
674
+ }
675
+ case 'as-rotate-keys': {
676
+ const only=args.filter(a=>a!=='--json');
677
+ if(only.some(a=>!['--jwks-only','--cookies-only'].includes(a))||only.length>1) throw new Error('usage: dalan as-rotate-keys [--jwks-only|--cookies-only]; stop the bridge, rotate, start');
678
+ result={...rotateKeys(defaultPath(home,'.config/dot-bridge'),{jwks:!only.includes('--cookies-only'),cookies:!only.includes('--jwks-only')}),restart_required:true};
679
+ break;
680
+ }
681
+ case 'connect': {
682
+ const out=await connectCommand(args,{request,operator,option,json});
683
+ result=out.result; plainOutput=out.plain===true;
684
+ break;
685
+ }
686
+ 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; }
687
+ case 'verify-stops': { const id=args.find(a=>a!=='--json'); result=await request('/verify-stops','POST',id?{id}:{},{'x-operator-key':operator()}); break; }
688
+ case 'prepare-deps': {
689
+ const positional=args.filter(a=>!['--json','--replace-invalid'].includes(a));
690
+ if(positional.length!==1||positional[0].startsWith('-')) throw new Error('usage: dalan prepare-deps SOURCE_DIRECTORY [--json] [--replace-invalid]');
691
+ result=prepareNodeModules(positional[0],{replaceInvalid:args.includes('--replace-invalid')});
692
+ break;
693
+ }
694
+ case 'doctor': {
695
+ if(args.includes('--checks')) {
696
+ // Local only: the owner's checks.json against each repo's default-branch tree (mirror). Warnings never fail the command; errors do.
697
+ const repos=lintChecksFile();
698
+ result=json?{checks:repos}:formatChecksReport(repos);plainOutput=!json;
699
+ if(repos.some(r=>r.checks.some(c=>c.errors.length))) process.exitCode=1;
700
+ break;
701
+ }
702
+ // Local only: what this host can execute and what the executor declares. No bridge call.
703
+ // The host executor's sandbox backends are Linux-only, so on macOS doctor names none of them instead of listing backends that can never run.
704
+ const macHost=process.platform==='darwin',macReason='unavailable on macOS: host checks are not available; jobs can still be delegated with --execution none (no host checks)';
705
+ const readiness=macHost?{ready:false,reason:macReason}:hostReadiness(), backend=macHost?null:hostBackend(), pasta=macHost?null:['/usr/bin/pasta','/usr/local/bin/pasta'].find(f=>fs.existsSync(f))??null;
706
+ // Doctor diagnoses a broken setup, so it runs with no bridge home selected and reports that as one finding. A home
707
+ // directory with bridge files is a bridge home (an older single-worker host), so that counts as selected.
708
+ const trialHome=path.join(home,'.local/share/dalan-trial');
709
+ // A home with no bridge configuration has no worker profile: the legacy default worker it would imply is not shown.
710
+ const hasProfile=!!readEnv('DALAN_WORKERS_FILE')||fs.existsSync(defaultPath(home,'.config/dot-bridge'));
711
+ const homeSelected=!!process.env.DALAN_HOME||hasProfile;
712
+ const noHomeYet='no bridge home here yet. To try Dalan, run: npx @tnunamak/dalan try';
713
+ const bridgeHome=homeSelected?{selected:true}:{selected:false,warning:'no bridge home selected: DALAN_HOME is not set, so this checked the host and your home directory, not a bridge home',
714
+ fix:fs.existsSync(path.join(trialHome,'.dalan-trial'))?`to check the trial bridge, run: export DALAN_HOME=${shellQuote(trialHome)}`:`${noHomeYet} (or export DALAN_HOME=DIR for a bridge home made with dalan init)`};
715
+ const running=hasProfile?await socketListening(socket):false;
716
+ const homeLine=!homeSelected?(fs.existsSync(path.join(trialHome,'.dalan-trial'))?`WARNING: ${bridgeHome.warning}. Fix: ${bridgeHome.fix}`:'No bridge home here yet. To try Dalan, run: npx @tnunamak/dalan try. For a bridge home made with dalan init, export DALAN_HOME=DIR first.')
717
+ :hasProfile?`bridge home: ${home} (${fs.existsSync(path.join(home,'.dalan-trial'))?'trial bridge':'bridge'}, ${running?'running':'not running'})`:`bridge home: ${home}: ${noHomeYet}`;
718
+ // A trial bridge lives only while `dalan try` runs, so a stopped one is the usual state after the terminal closed.
719
+ if(homeSelected&&hasProfile&&!running&&fs.existsSync(path.join(home,'.dalan-trial'))) bridgeHome.fix=stoppedTrialFix(cli,home,os.userInfo().homedir);
720
+ const workersFile=readEnv('DALAN_WORKERS_FILE')||defaultPath(home,'.config/dot-bridge/workers.json');
721
+ const doctorWorkers=loadOwnerWorkers(workersFile);
722
+ const repoPolicies=[...doctorWorkers.workers.keys()].map(worker=>({worker,...doctorWorkers.repoPolicy(worker)}));
723
+ // A worker entry that lists `"repos": []` has no grants yet, which is normal for a new worker. The text output shows it
724
+ // as a plain line, not a WARNING; --json keeps it in repository_access.warnings, because queued repository jobs wait on it.
725
+ const rawWorkers=(()=>{try{return JSON.parse(fs.readFileSync(workersFile,'utf8')).workers??{};}catch{return {};}})();
726
+ const noGrantsYet=policy=>policy.repos.length===0&&Array.isArray(rawWorkers[policy.worker]?.repos)&&rawWorkers[policy.worker].repos.length===0;
727
+ const repoNotes=repoPolicies.filter(noGrantsYet).map(policy=>`worker "${policy.worker}" has no repository grants yet, which is normal for a new worker; repository jobs are denied until you run: dalan worker allow ${policy.worker} OWNER/REPO`);
728
+ const repoWarnings=repoPolicies.filter(policy=>!noGrantsYet(policy)).flatMap(policy=>policy.repos.length===0
729
+ ? [!fs.existsSync(workersFile)&&policy.source!=='admitted-history'?missingProfileWarning(policy.worker,policy):`worker "${policy.worker}" has an empty exact repository list; repository jobs are denied. Use dalan worker allow ${policy.worker} OWNER/REPO; see docs/operations.md#legacy-repository-policy-migration`]
730
+ : !fs.existsSync(workersFile)?[missingProfileWarning(policy.worker,policy)]:[]);
731
+ const repoHistory=readWorkerRepoHistory(path.join(path.dirname(workersFile),'workers-audit.jsonl'),{workersFile});
732
+ const grantAudit=fs.existsSync(workersFile)?inspectGrantAudit(workersFile):{unaudited:[],recorded:[],history_error:null,integrity_error:null};
733
+ if(grantAudit.integrity_error) repoWarnings.push(`${grantAudit.integrity_error}. ${AUDIT_INTEGRITY_HINT}`);
734
+ repoWarnings.push(...grantAudit.unaudited.map(({worker,repos})=>`worker "${worker}" has repository grants with no audit record (${repos.join(', ')}), probably from editing workers.json by hand. The bridge records them when it next loads the file and applies them only if that record is written. Use dalan worker allow/deny to change grants.`),
735
+ ...grantAudit.recorded.map(({worker,repos,at})=>`worker "${worker}": the bridge recorded ${repos.join(', ')} at ${at} because the grant had no audit record (workers.json edited by hand, or a list that predates the audit). Confirm you intended it.`));
736
+ const t3Warnings=readEnv('DALAN_ENABLE_T3_TOOLS')==='1'?[]:[...doctorWorkers.workers].filter(([,worker])=>worker.capabilities.has('t3')).map(([worker])=>`worker "${worker}" has the t3 capability, but reverse-control tools are off; set DALAN_ENABLE_T3_TOOLS=1 (legacy: DOT_BRIDGE_ENABLE_T3_TOOLS=1) to retain them`);
737
+ result={bridge_home:bridgeHome,host_executor:{ready:readiness.ready,reason:readiness.reason,pasta,checks_disabled:readiness.reason===RESOURCE_LIMITS_UNAVAILABLE},backend,repository_access:{workers:repoPolicies,warnings:[...repoNotes,...repoWarnings],unaudited_grants:grantAudit.unaudited,audit_integrity_error:grantAudit.integrity_error,changes:repoHistory.events},t3:{enabled:readEnv('DALAN_ENABLE_T3_TOOLS')==='1',warnings:t3Warnings},
738
+ note:macHost?null:`Historical backend values come from ${backend.measured_by.script} (which measured v1). Live capabilities are unknown while the executor is disabled; execution probes report SKIP.`};
739
+ if(!json) { result=[homeLine,...(bridgeHome.fix&&homeSelected?[`fix: ${bridgeHome.fix}`]:[]),macHost?`host executor: ${macReason}`:`host executor: ${backend.name} v${backend.version}: ${readiness.ready?'ready':readiness.reason===RESOURCE_LIMITS_UNAVAILABLE?'off (optional: only jobs that run checks on this computer need it; a first job does not)':`not ready (${readiness.reason})`}`,...(macHost?[]:[`pasta (install phase network): ${pasta??'not found; the install phase fails closed'}`,...(readiness.ready?['declared capabilities:',...Object.entries(backend.capabilities).map(([name,state])=>` ${name}: ${state}`)]:['declared capabilities: not checked while host checks are off'])]),...(hasProfile?['repository access:',...repoPolicies.map(policy=>` ${policy.worker}: ${policy.mode}${policy.repos?.length?` (${policy.repos.join(', ')})`:''}${policy.denied?.length?` except ${policy.denied.join(', ')}`:''}`),...repoNotes,...[...repoWarnings,...t3Warnings].map(warning=>`WARNING: ${warning}`)]:[]),
740
+ ...(macHost?[]:[readiness.ready?'Host checks are on.':`Host checks are off. The first job does not need them; to turn them on, see ${docsUrl('docs/operations.md', 'execution-capability-and-check-evidence')}`])].join('\n'); plainOutput=true; }
741
+ break;
742
+ }
743
+ default: throw new Error(`unknown command "${command}"`);
744
+ }
745
+ console.log(plainOutput ? terminalSafe(result) : jsonTerminalSafe(waitOutput||json ? JSON.stringify(result) : JSON.stringify(result, null, 2)));
746
+ if(endNote) console.error(endNote);
747
+ }
748
+ // Human error text. A refused assignment that only failed the schema check reads like any other error: the cause, one
749
+ // fix with the example, and "nothing was queued". Byte counts are shown only when the bridge measured the brief.
750
+ function humanError(e) {
751
+ const fixFor=r=>r.code==='invalid_schema'&&r.field==='assignment'?{...r,fix:`add the missing fields; a valid example: ${JOB_EXAMPLE_URL}`}:r;
752
+ let fix=e.fix, verdict=e.verdict&&Array.isArray(e.reasons)?e:null;
753
+ let message=e.message;
754
+ if(verdict&&!fix&&e.reasons.length===1&&e.reasons[0].code==='invalid_schema'&&e.reasons[0].message===e.message) {
755
+ fix=[fixFor(e.reasons[0]).fix]; verdict=null;
756
+ // The bridge lists the fields it found missing or wrong as "brief, expected_output (a string)". Name each one.
757
+ const wrong=/; missing or wrong: (.+)$/.exec(e.message)?.[1].split(', ').map(item=>{ const [,field,need]=/^(\S+)(?: \((?:must be |an? )?(.+)\))?$/.exec(item)??[null,item,null];
758
+ return need?`${field} must be ${/^\d/.test(need)?need:`${/^[aeiou]/.test(need)?'an':'a'} ${need}`}`:`${field} is missing or invalid`; });
759
+ if(wrong?.length) message=`the job is not a valid assignment: ${wrong.join('; ')}`;
760
+ }
761
+ const bytes=e.bytes?.limits&&(e.bytes.limits.brief||e.bytes.limits.instructions)?e.bytes:undefined;
762
+ return `dalan: ${message}${e.reason?` (${e.code??'no code'}: ${e.reason.split('\n')[0]})`:''}${fix?`\n${fix.map(l=>`dalan: fix: ${l}`).join('\n')}\ndalan: nothing was queued or changed`:''}${verdict?`\n${formatVerdict({verdict:e.verdict,reasons:e.reasons.map(fixFor),bytes,retry_after_seconds:e.retry_after_seconds}).split('\n').map(l=>`dalan: ${l}`).join('\n')}`:''}`;
763
+ }
764
+ main().catch(e => { console.error(json ? JSON.stringify({ error:e.message,kind:e.kind??'local',...(e.suggested_scope_paths?{suggested_scope_paths:e.suggested_scope_paths}:{}),...(e.verdict?{verdict:e.verdict,reasons:e.reasons,bytes:e.bytes,...(e.retry_after_seconds?{retry_after_seconds:e.retry_after_seconds}:{})}:{}),...(e.fix?{fix:e.fix}:{}),...(Number.isInteger(e.http_status)?{http_status:e.http_status}:{}),...(e.local_code?{code:e.local_code}:{}),...(e.reason?{cause_code:e.code??null,reason:e.reason}:{}) }) : humanError(e)); process.exitCode = e.verdict&&e.verdict in VERDICT_EXIT ? VERDICT_EXIT[e.verdict] : 1; });