@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
package/src/auth.mjs ADDED
@@ -0,0 +1,166 @@
1
+ import { defaultPath } from './paths.mjs';
2
+ import { readEnv } from './env.mjs';
3
+ import { ADVERTISED_SCOPES, advertisedScopeNames, canonicalScopes, legacyScopeNames, wireScope } from './scopes.mjs';
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { createPublicKey, verify } from 'node:crypto';
8
+
9
+ const decode=s=>Buffer.from(s,'base64url');
10
+ export function authConfig(file=readEnv('DALAN_OAUTH_FILE')||defaultPath(os.homedir(),'.config/dot-bridge/oauth.env'), requireMode=true) {
11
+ if(requireMode && readEnv('DALAN_AUTH_MODE')!=='oauth') return null;
12
+ if(!requireMode && !fs.existsSync(file)) return null;
13
+ if(!fs.existsSync(file)||(fs.statSync(file).mode&0o777)!==0o600) throw new Error('OAuth config missing or not mode 0600');
14
+ const values=Object.fromEntries(fs.readFileSync(file,'utf8').split('\n').filter(x=>x.includes('=')).map(line=>{const n=line.indexOf('=');return [line.slice(0,n),line.slice(n+1)];}));
15
+ for(const key of ['OAUTH_ISSUER','OAUTH_AUDIENCE','OAUTH_JWKS_URI','OAUTH_ALLOWED_SUBJECTS']) if(!values[key]) throw new Error(`OAuth ${key} missing`);
16
+ // A misspelled value must not silently keep the legacy scope names the operator meant to leave.
17
+ if(values.OAUTH_SCOPE_NAMES!==undefined&&!['legacy','neutral'].includes(values.OAUTH_SCOPE_NAMES)) throw new Error('OAuth OAUTH_SCOPE_NAMES must be legacy or neutral');
18
+ const testHttp=process.env.NODE_ENV!=='production'&&readEnv('DALAN_TEST_OAUTH')==='1';
19
+ if((!testHttp&&(new URL(values.OAUTH_ISSUER).protocol!=='https:'||new URL(values.OAUTH_JWKS_URI).protocol!=='https:'))||new URL(values.OAUTH_ISSUER).origin!==new URL(values.OAUTH_JWKS_URI).origin||new URL(values.OAUTH_AUDIENCE).protocol!=='https:') throw new Error('invalid OAuth origins');
20
+ return values;
21
+ }
22
+ // Fail closed: the public MCP route may run unauthenticated only when a test or dev run opts in explicitly.
23
+ // The insecure development flags are loopback-only: a development env file copied onto a public host
24
+ // must not start an unauthenticated public route. options.bindHost is the effective listener host;
25
+ // an unknown host is treated as non-loopback.
26
+ export const LOOPBACK_BIND_HOSTS=['127.0.0.1','::1','localhost'];
27
+ export function isLoopbackBindHost(host) {
28
+ return typeof host==='string' && LOOPBACK_BIND_HOSTS.includes(host.toLowerCase());
29
+ }
30
+ export function assertPublicRouteAuth(config,env=process.env,options={}) {
31
+ if(config) return;
32
+ const insecureFlags=['DALAN_DEV_ALLOW_UNAUTHENTICATED','DALAN_ALLOW_INSECURE_PUBLIC'].filter(name=>env.NODE_ENV!=='production'&&readEnv(name,env)==='1');
33
+ if(insecureFlags.length) {
34
+ // A same-host proxy or tunnel would make the unauthenticated loopback listener public.
35
+ if(readEnv('DALAN_TRUST_PROXY',env)==='1') throw new Error(`refusing to start the public route unauthenticated with ${insecureFlags.join(' and ')} while DALAN_TRUST_PROXY=1: a reverse proxy or tunnel would expose it; unset the flag and use DALAN_AUTH_MODE=builtin or oauth`);
36
+ if(isLoopbackBindHost(options.bindHost)) return;
37
+ throw new Error(`refusing to start the public route unauthenticated with ${insecureFlags.join(' and ')} on a non-loopback bind: ${insecureFlags.join(' and ')} is allowed only when the bind host is loopback (DALAN_BIND_HOST=127.0.0.1, ::1 or localhost); unset the flag or bind to loopback`);
38
+ }
39
+ throw new Error('refusing to start the public route without OAuth: set DALAN_AUTH_MODE=builtin or oauth (DALAN_DEV_ALLOW_UNAUTHENTICATED=1 is for non-production fixtures only)');
40
+ }
41
+ export function protectedResource(config,resource=config.OAUTH_AUDIENCE) {return {resource,authorization_servers:[config.OAUTH_ISSUER],scopes_supported:advertisedScopeNames(config),bearer_methods_supported:['header']};}
42
+ export function challenge(config,scope) {
43
+ const explicit=!config.builtin&&scope===undefined&&config.OAUTH_CHALLENGE_SCOPE!==undefined;
44
+ const value=explicit?config.OAUTH_CHALLENGE_SCOPE:wireScope(scope??config.OAUTH_CHALLENGE_SCOPE??'dalan.read',legacyScopeNames(config));
45
+ return `Bearer realm="dalan", resource_metadata="${config.OAUTH_RESOURCE_METADATA??new URL('/.well-known/oauth-protected-resource',config.OAUTH_AUDIENCE)}", scope="${value}"`;
46
+ }
47
+ // Each verifier owns process-local entries by URI. Unknown-key refreshes have a
48
+ // separate cooldown: a normal cache fill does not delay the first key rotation.
49
+ export function createBearerVerifier({fetch:fetchJwks=globalThis.fetch,now=Date.now,cacheTtlMs=300000,kidRefreshCooldownMs=30000,timeoutMs=3000}={}) {
50
+ for(const value of [cacheTtlMs,kidRefreshCooldownMs,timeoutMs]) {
51
+ if(!Number.isFinite(value)||value<=0) throw new Error('invalid verifier timing');
52
+ }
53
+ const entries=new Map();
54
+ const elapsed=start=>Math.max(0,Math.round(performance.now()-start));
55
+ const signingKey=(keys,kid)=>keys?.find(k=>k&&k.kid===kid&&k.kty==='RSA'&&k.use!=='enc');
56
+
57
+ async function refresh(uri,entry) {
58
+ if(entry.pending) return entry.pending;
59
+ entry.pending=(async()=>{
60
+ const signal=AbortSignal.timeout(timeoutMs);
61
+ let status;
62
+ try {
63
+ const response=await fetchJwks(uri,{signal});
64
+ status=response.status;
65
+ if(!response.ok) return {outcome:'http_error',status};
66
+ const jwks=await response.json();
67
+ if(!jwks||!Array.isArray(jwks.keys)) return {outcome:'invalid_response',status};
68
+ entry.keys=jwks.keys;
69
+ entry.expiresAt=now()+cacheTtlMs;
70
+ return {outcome:'fetched',status,keys:entry.keys};
71
+ } catch(error) {
72
+ return {outcome:signal.aborted?'timeout':error instanceof SyntaxError?'invalid_response':'fetch_error',status};
73
+ }
74
+ })();
75
+ try {return await entry.pending;} finally {entry.pending=null;}
76
+ }
77
+
78
+ async function getKey(uri,kid,trace) {
79
+ const start=performance.now();
80
+ trace.jwks_outcome='pending';
81
+ let entry=entries.get(uri);
82
+ if(!entry) {
83
+ entry={keys:null,expiresAt:0,pending:null,lastKidRefreshAt:-Infinity};
84
+ entries.set(uri,entry);
85
+ }
86
+ try {
87
+ const fresh=entry.keys&&now()<entry.expiresAt;
88
+ const cached=fresh&&signingKey(entry.keys,kid);
89
+ if(cached) {trace.jwks_outcome='cache_hit';return cached;}
90
+ // Join a refresh already in flight before applying the miss cooldown.
91
+ let outcome;
92
+ if(entry.pending) {
93
+ outcome=await entry.pending;
94
+ trace.jwks_outcome=outcome.keys?'coalesced':outcome.outcome;
95
+ } else {
96
+ if(fresh) {
97
+ if(now()-entry.lastKidRefreshAt<kidRefreshCooldownMs) {
98
+ trace.jwks_outcome='refresh_throttled';
99
+ throw new Error('signing key unavailable');
100
+ }
101
+ entry.lastKidRefreshAt=now();
102
+ }
103
+ outcome=await refresh(uri,entry);
104
+ trace.jwks_outcome=outcome.outcome;
105
+ }
106
+ if(outcome.status!==undefined) trace.jwks_http_status=outcome.status;
107
+ if(!outcome.keys) throw new Error('JWKS unavailable');
108
+ const key=signingKey(outcome.keys,kid);
109
+ if(!key) {
110
+ entry.lastKidRefreshAt=now();
111
+ throw new Error('signing key unavailable');
112
+ }
113
+ return key;
114
+ } finally {trace.jwks_duration_ms=elapsed(start);}
115
+ }
116
+
117
+ return async function verifyBearer(header,config,trace={}) {
118
+ const start=performance.now();
119
+ // Preserve explicit in-progress fields if the connection closes during I/O.
120
+ Object.assign(trace,{auth_outcome:'pending',auth_reason:null,auth_duration_ms:null,
121
+ jwks_outcome:'not_attempted',jwks_duration_ms:null,jwks_http_status:null});
122
+ let reason='invalid_token';
123
+ try {
124
+ reason='missing_bearer';
125
+ if(typeof header!=='string'||!header.startsWith('Bearer ')) throw new Error('missing bearer token');
126
+ reason='invalid_token';
127
+ const parts=header.slice(7).split('.');
128
+ if(parts.length!==3) throw new Error('invalid bearer token');
129
+ let meta,claims;
130
+ try {meta=JSON.parse(decode(parts[0]));claims=JSON.parse(decode(parts[1]));} catch {throw new Error('invalid bearer token');}
131
+ if(!meta||!claims||typeof meta!=='object'||typeof claims!=='object') throw new Error('invalid bearer token');
132
+ reason='unsupported_signature';
133
+ if(meta.alg!=='RS256'||typeof meta.kid!=='string') throw new Error('unsupported bearer signature');
134
+ let jwk;
135
+ try {jwk=await getKey(config.OAUTH_JWKS_URI,meta.kid,trace);} catch(error) {
136
+ reason=error.message==='signing key unavailable'?'signing_key_unavailable':'jwks_unavailable';
137
+ throw error;
138
+ }
139
+ reason='invalid_signature';
140
+ let valid;
141
+ try {valid=verify('RSA-SHA256',Buffer.from(parts[0]+'.'+parts[1]),createPublicKey({key:jwk,format:'jwk'}),decode(parts[2]));} catch {throw new Error('invalid bearer signature');}
142
+ if(!valid) throw new Error('invalid bearer signature');
143
+ // One class per refusal, so a log line says why a client was turned away. Never the token or its claims.
144
+ const seconds=Math.floor(now()/1000),aud=claims.aud;
145
+ const refuse=why=>{reason=why;throw new Error('invalid bearer claims');};
146
+ if(claims.iss!==config.OAUTH_ISSUER) refuse('wrong_issuer');
147
+ if(!(aud===config.OAUTH_AUDIENCE||Array.isArray(aud)&&aud.includes(config.OAUTH_AUDIENCE))) refuse('wrong_audience');
148
+ if(!Number.isInteger(claims.exp)) refuse('malformed_claims');
149
+ if(claims.exp<=seconds) refuse('expired');
150
+ if(claims.nbf>seconds) refuse('not_yet_valid');
151
+ if(!claims.sub||!config.OAUTH_ALLOWED_SUBJECTS.split(',').includes(claims.sub)) refuse('unknown_subject');
152
+ reason='invalid_scope';
153
+ const scopes=canonicalScopes(String(claims.scope||'').split(' '));
154
+ if(!ADVERTISED_SCOPES.some(scope=>scopes.has(scope))) throw new Error('invalid bearer scope');
155
+ trace.auth_outcome='success';
156
+ trace.auth_reason='verified';
157
+ return {subject:claims.sub,scopes,issuer:claims.iss,client_id:claims.azp??claims.client_id,connection_id:claims.connection_id};
158
+ } catch(error) {
159
+ trace.auth_outcome='failure';
160
+ trace.auth_reason=reason;
161
+ throw error;
162
+ } finally {trace.auth_duration_ms=elapsed(start);}
163
+ };
164
+ }
165
+ export const verifyBearer=createBearerVerifier();
166
+ export function needScope(principal,scope) {if(!principal.scopes.has(scope)) throw new Error('insufficient_scope');}
@@ -0,0 +1,22 @@
1
+ import http from 'node:http';
2
+
3
+ // Limits on receiving requests do not limit tool execution or the lifetime of an SSE response.
4
+ export function createBuiltinHttpServer(handler) {
5
+ const server = http.createServer({ headersTimeout: 10000, requestTimeout: 30000, keepAliveTimeout: 5000, connectionsCheckingInterval: 1000 }, (req, res) => {
6
+ const writeHead = res.writeHead;
7
+ res.writeHead = function (...args) {
8
+ const headers = typeof args[1] === 'string' ? args[2] : args[1];
9
+ let contentType = this.getHeader('content-type');
10
+ const entries = Array.isArray(headers) ? Array.from({ length: headers.length / 2 }, (_, i) => [headers[i * 2], headers[i * 2 + 1]]) : Object.entries(headers ?? {});
11
+ for (const [name, value] of entries) if (name.toLowerCase() === 'content-type') contentType = value;
12
+ const result = writeHead.apply(this, args);
13
+ if (/^text\/event-stream(?:;|$)/i.test(String(contentType ?? ''))) this.setTimeout(0);
14
+ return result;
15
+ };
16
+ return handler(req, res);
17
+ });
18
+ server.maxConnections = 128;
19
+ // T3 waits may take 120 seconds. Leave a minute for dispatch and delivery.
20
+ server.setTimeout(180000, socket => socket.destroy());
21
+ return server;
22
+ }
@@ -0,0 +1,38 @@
1
+ // Coverage comes from complete check output before preview truncation. Exit 77
2
+ // also marks incomplete coverage when a command supplied no segment detail.
3
+ function coverage(output,exitCode) {
4
+ const names=new Set();let unnamed=0;
5
+ const add=value=>{
6
+ const label=value.trim(),script=label.match(/(?:^|[\/\s])(scripts\/[^\r\n]*?\.mjs)(?=\s|$)/);
7
+ names.add(script?script[1]:label);
8
+ };
9
+ for(const match of output.matchAll(/^SKIP #\d+\/\d+: (.+)$/gm)) add(match[1]);
10
+ for(const match of output.matchAll(/^SKIP host executor journey:[ \t]*([^\r\n]*)\r?$/gm)) {
11
+ const name=match[1].replace(/(?:^|[ \t]+)\([^\r\n]*\)[ \t]*$/,'').trim();
12
+ if(name) add(name);else unnamed++;
13
+ }
14
+ for(const match of output.matchAll(/^SKIP (?!#\d+\/\d+:|host executor journey:)(.+)$/gm)) add(match[1]);
15
+ for(const match of output.matchAll(/^(?:ok|not ok) \d+ - (.+?) # SKIP(?: .*)?$/gm)) add(match[1]);
16
+ let reported=null;
17
+ for(const match of output.matchAll(/^TEST SEGMENTS: \d+ total, \d+ passed, \d+ failed, (\d+) skipped$/gm)) {
18
+ const n=Number(match[1]);if(Number.isSafeInteger(n)) reported=Math.max(reported??0,n);
19
+ }
20
+ // The aggregate already includes unnamed lines from its child segments.
21
+ // A contradictory zero summary must still leave an observed skip visible.
22
+ const count=Math.max(names.size,reported??names.size+unnamed,unnamed?1:0,exitCode===77?1:0);
23
+ return {skipped_segments:count,skipped_segment_names:[...names]};
24
+ }
25
+
26
+ export function withCheckCoverage(row,output) {
27
+ const evidence=row.evidence;
28
+ const skips=output!==undefined?coverage(output,row.exit_code)
29
+ :Number.isSafeInteger(evidence?.skipped_segments)&&evidence.skipped_segments>=0?{skipped_segments:evidence.skipped_segments,skipped_segment_names:evidence.skipped_segment_names??[]}
30
+ :coverage(row.output_preview??'',row.exit_code);
31
+ const check_summary=skips.skipped_segments?`${row.check_id}: ${skips.skipped_segments} skipped segment${skips.skipped_segments===1?'':'s'}: ${skips.skipped_segment_names.join(', ')||'segment name unavailable'}`:null;
32
+ let status=row.status;
33
+ if(skips.skipped_segments&&status==='completed') {
34
+ const failed=![0,77].includes(row.exit_code)||row.timed_out||row.cancelled||evidence?.cancelled||(row.phase??evidence?.phase)==='install';
35
+ status=failed?'failed':'skipped';
36
+ }
37
+ return {...row,...skips,check_summary,status,evidence:evidence?{...evidence,...skips,check_summary}:evidence};
38
+ }
@@ -0,0 +1,88 @@
1
+ // Owner-side drift lint for check definitions: what each check's argv names, and ids that sound like a test file the argv leaves out.
2
+ import { spawnSync } from 'node:child_process';
3
+ import fs from 'node:fs';
4
+ import { ownerChecks, normalizeCheck, argvTestFiles, testFileName, mirrorPath } from './projects.mjs';
5
+ import { gitEnv } from './git-env.mjs';
6
+
7
+ const stemTokens = file => {
8
+ const base = file.split('/').pop().replace(/\.(?:test|spec)\.[cm]?[jt]sx?$|_test\.(?:py|go|sh)$|\.py$/, '').replace(/^test_/, '');
9
+ return base.split(/[-_.]+/).filter(Boolean).filter((t, i) => !(i === 0 && /^v\d+$/.test(t)));
10
+ };
11
+ const contiguous = (hay, needle) => needle.length > 0 && hay.some((_, i) => needle.every((t, j) => hay[i + j] === t));
12
+ // A test file the id names: its stem tokens sit inside the id's tokens, or (two or more id tokens) the id sits inside the stem.
13
+ export function filesNamedById(id, treeFiles) {
14
+ const idTokens = id.split(/[-_.]+/).filter(Boolean);
15
+ return treeFiles.filter(f => {
16
+ if (!testFileName.test(f)) return false;
17
+ const stem = stemTokens(f);
18
+ if (!stem.length) return false;
19
+ if (stem.length === 1) return stem[0] === id;
20
+ return contiguous(idTokens, stem) || (idTokens.length >= 2 && contiguous(stem, idTokens));
21
+ });
22
+ }
23
+
24
+ // Does the argv run this file? A word names it by path suffix or by glob (`tests/*.test.mjs`); `cd dir && ... ../x/a.test.ts` style
25
+ // relative paths match on the same basename, so a file the command reaches from another directory is not reported as missing.
26
+ export function argvCovers(argv, file) {
27
+ const base = file.split('/').pop();
28
+ for (const el of argv) for (const raw of String(el).split(/[\s'"=;&|()<>]+/)) {
29
+ const w = raw.replace(/^(?:\.\.?\/)+/, '');
30
+ if (!w || w.startsWith('-')) continue;
31
+ if (!w.includes('*')) { if (w === file || file.endsWith(`/${w}`) || w.split('/').pop() === base) return true; continue; }
32
+ const re = new RegExp(`(?:^|/)${w.split('*').map(x => x.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('[^/]*')}$`);
33
+ if (re.test(file)) return true;
34
+ }
35
+ return false;
36
+ }
37
+
38
+ // Tracked files in the mirror: HEAD plus the most recently committed ref (a mirror's HEAD can lag the branch work happens on). null with no mirror.
39
+ export function mirrorTree(repo) {
40
+ let mirror;
41
+ try { mirror = mirrorPath(repo); } catch { return null; }
42
+ if (!fs.existsSync(mirror)) return null;
43
+ const git = args => spawnSync('git', ['-C', mirror, ...args], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, env: gitEnv() });
44
+ const newest = git(['for-each-ref', '--count=1', '--sort=-committerdate', '--format=%(refname)']).stdout.trim();
45
+ const files = new Set();
46
+ let ok = false;
47
+ for (const ref of ['HEAD', newest].filter(Boolean)) {
48
+ const out = git(['ls-tree', '-r', '--name-only', ref]);
49
+ if (out.status === 0) { ok = true; for (const f of out.stdout.split('\n')) if (f) files.add(f); }
50
+ }
51
+ return ok ? [...files] : null;
52
+ }
53
+
54
+ export function lintChecksFile({ tree = mirrorTree } = {}) {
55
+ const repos = [];
56
+ for (const [repo, source] of Object.entries(ownerChecks())) {
57
+ const treeFiles = tree(repo);
58
+ const checks = [];
59
+ for (const [id, def] of Object.entries(source?.checks || {})) {
60
+ const entry = { id, test_files: [], warnings: [], errors: [] };
61
+ try {
62
+ const spec = normalizeCheck(def, id);
63
+ entry.test_files = spec.test_paths ?? argvTestFiles(spec.argv);
64
+ // A check whose argv names no test file runs a whole suite (go test, npm test, make): there is nothing to compare.
65
+ if (treeFiles && entry.test_files.length && id !== 'default')
66
+ for (const f of filesNamedById(id, treeFiles)) if (!argvCovers(spec.argv, f)) entry.warnings.push(`id suggests ${f}, which argv does not run`);
67
+ } catch (error) { entry.errors.push(error.message); }
68
+ checks.push(entry);
69
+ }
70
+ repos.push({ repo, tree_checked: treeFiles !== null, checks });
71
+ }
72
+ return repos;
73
+ }
74
+
75
+ export function formatChecksReport(repos) {
76
+ const lines = [];
77
+ let warnings = 0, errors = 0;
78
+ for (const r of repos) {
79
+ lines.push(`${r.repo}${r.tree_checked ? '' : ' (no local mirror: id/file name lint skipped)'}`);
80
+ for (const c of r.checks) {
81
+ lines.push(` ${c.id}: ${c.test_files.length ? c.test_files.join(' ') : '(argv names no test files)'}`);
82
+ for (const w of c.warnings) { lines.push(` WARNING: ${w}`); warnings++; }
83
+ for (const e of c.errors) { lines.push(` ERROR: ${e}`); errors++; }
84
+ }
85
+ }
86
+ lines.push(`${warnings} warning(s), ${errors} error(s)`);
87
+ return lines.join('\n');
88
+ }
@@ -0,0 +1,112 @@
1
+ import { gitEnv } from './git-env.mjs';
2
+ import fs from 'node:fs';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { assignmentInput, mirrorPath, checkSpecsAt, prepareGithubRepo } from './projects.mjs';
5
+ import { hostCheckAuthorization } from './host-execution-policy.mjs';
6
+
7
+ // The check sandbox ro-binds the host /usr and puts /usr/bin on PATH, so presence in /usr/bin on the host is the honest signal.
8
+ const sandboxBinDirs = ['/usr/bin'];
9
+ const lockfileNames = ['package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', 'uv.lock', 'poetry.lock', 'Cargo.lock', 'go.sum'];
10
+
11
+ const testDir = /(?:^|\/)(?:test|tests|__tests__|spec)(?:\/|$)/;
12
+ const testFile = /\.(?:test|spec)\.[^/]+$|_test\.[^/]+$|(?:^|\/)test_[^/]+\.py$|^scripts\/[^/]*-(?:test|e2e)\.mjs$/;
13
+ const regressionAsk = /\bregression[- ]tests?\b/i;
14
+ const regressionNegated = /\b(?:no|not|without|never|don't|do not|skip)\b[^.\n]{0,40}\bregression[- ]tests?\b/i;
15
+
16
+ const clean = p => p === './...' ? p : p.replace(/^\.\//, '').replace(/\/$/, '');
17
+
18
+ export const isConventionalTest = file => testDir.test(file) || testFile.test(file);
19
+
20
+ // A scope entry is a test path by convention, when it equals, contains or sits inside a path the check links to its tests,
21
+ // or when it is a directory whose tree at base_sha already holds a conventional test file (colocated tests: src/x.test.ts, pkg/x_test.go).
22
+ export function isTestScopePath(entry, linked = null, treeFiles = null) {
23
+ const p = clean(entry);
24
+ if (isConventionalTest(p)) return true;
25
+ if (treeFiles && p !== './...') { const files = typeof treeFiles === 'function' ? treeFiles() : treeFiles; if (files.some(f => (p === '.' || p === '' || f.startsWith(`${p}/`)) && isConventionalTest(f))) return true; }
26
+ // `./...` (Go) runs tests beside the code in every package, so any directory in scope can hold the new test.
27
+ if ((linked || []).includes('./...') && !/\.[^/]+$/.test(p.split('/').pop())) return true;
28
+ return (linked || []).map(clean).filter(l => l && !l.endsWith('...')).some(l => p === '.' || p === l || p.startsWith(`${l}/`) || l.startsWith(`${p}/`));
29
+ }
30
+
31
+ export function asksForRegressionTest(text) {
32
+ return regressionAsk.test(text || '') && !regressionNegated.test(text || '');
33
+ }
34
+
35
+ // Returns null when fine, else the error message naming the rule.
36
+ export function regressionTestRule(assignment, linkedPaths = null, treeFiles = null) {
37
+ if (assignment.execution_scope !== 'implementation' || !asksForRegressionTest(assignment.expected_output)) return null;
38
+ const scope = assignment.scope_paths || [];
39
+ if (scope.some(p => isTestScopePath(p, linkedPaths, treeFiles))) return null;
40
+ return `regression_test_scope: expected_output asks for a regression test but no scope_paths entry is a test path (conventional test/, tests/, __tests__/, spec/, *.test.*, *.spec.*, *_test.*, test_*.py, scripts/*-test.mjs, scripts/*-e2e.mjs, a directory that already holds such a test${linkedPaths ? `, or linked test paths: ${linkedPaths.join(', ')}` : ''}); add the test file or its directory to scope_paths`;
41
+ }
42
+
43
+ const versionParts = v => v.split('.').map(n => Number.parseInt(n, 10) || 0);
44
+ export function versionAtLeast(have, need) {
45
+ const a = versionParts(have), b = versionParts(need);
46
+ for (let i = 0; i < Math.max(a.length, b.length); i++) if ((a[i] || 0) !== (b[i] || 0)) return (a[i] || 0) > (b[i] || 0);
47
+ return true;
48
+ }
49
+
50
+ function hostBinary(name, dirs) {
51
+ return dirs.some(dir => { try { const f = `${dir}/${name}`; return fs.statSync(f).isFile() && (fs.accessSync(f, fs.constants.X_OK), true); } catch { return false; } });
52
+ }
53
+
54
+ // Every file path at the pinned commit; read only when a scope directory needs the colocated-test lookup.
55
+ function repoFiles(mirror, sha) {
56
+ const r = spawnSync('git', ['-C', mirror, 'ls-tree', '-r', '-z', '--name-only', sha], { encoding: 'utf8', timeout: 10000, maxBuffer: 64 * 1024 * 1024, env: gitEnv() });
57
+ if (r.error || r.status !== 0) throw new Error(`BLOCKED: cannot list files at ${sha.slice(0, 12)} for the regression-test rule`);
58
+ return r.stdout.split('\0').filter(Boolean);
59
+ }
60
+
61
+ function inRepo(mirror, sha, file) {
62
+ return spawnSync('git', ['-C', mirror, 'cat-file', '-e', `${sha}:${file}`], { timeout: 10000, env: gitEnv() }).status === 0;
63
+ }
64
+
65
+ // Static probe of one check's prerequisites. Returns {unmet: string[], skipped: [{what, reason}]}.
66
+ export function probePrerequisites(spec, { mirror, sha, binDirs = sandboxBinDirs, nodeVersion = process.versions.node }) {
67
+ const unmet = [], skipped = [], p = spec.prerequisites;
68
+ if (!p) skipped.push({ what: `prerequisites of ${spec.id}`, reason: spec.prerequisites_reason });
69
+ else {
70
+ for (const bin of p.binaries || []) if (!hostBinary(bin, binDirs)) unmet.push(`binary ${bin} not found in ${binDirs.join(':')}`);
71
+ if (p.lockfile) {
72
+ const wanted = p.lockfile === true ? lockfileNames : [p.lockfile];
73
+ if (!wanted.some(f => inRepo(mirror, sha, f))) unmet.push(p.lockfile === true ? `no lockfile at ${sha.slice(0, 12)} (looked for ${wanted.join(', ')})` : `lockfile ${p.lockfile} missing at ${sha.slice(0, 12)}`);
74
+ }
75
+ if (p.runtime) {
76
+ const [name, need] = p.runtime.split('>=');
77
+ if (name === 'node') { if (!versionAtLeast(nodeVersion, need)) unmet.push(`runtime node ${nodeVersion} is older than required >=${need}`); }
78
+ else skipped.push({ what: `runtime ${p.runtime}`, reason: 'host version probe exists for node only' });
79
+ }
80
+ }
81
+ if (spec.readiness_argv) skipped.push({ what: `readiness_argv of ${spec.id}`, reason: 'declared but not run at admission: running a repository-declared command needs the sandboxed checkout, and it is unsafe on the host' });
82
+ return { unmet, skipped };
83
+ }
84
+
85
+ // Admission gate for a new implementation assignment. Metadata comes from the pinned base_sha, the same way availableChecksFor reads it.
86
+ // Only the default check blocks; unmet prerequisites of other checks come back as warnings.
87
+ // The host-prerequisite probes (binaries in /usr/bin, lockfile, runtime) exist because the bridge runs the check. With execution
88
+ // none or worker nobody on this host runs it, so those probes do not apply and an unreadable check file does not block the job.
89
+ export function admitImplementation(assignment, options = {}) {
90
+ if (assignment.execution_scope !== 'implementation') return null;
91
+ const { execution = 'host', worker, ...probeOptions } = options;
92
+ const input = assignmentInput(assignment);
93
+ const mirror = fs.existsSync(mirrorPath(input.github_repo,{worker})) ? mirrorPath(input.github_repo,{worker}) : prepareGithubRepo(input,{worker});
94
+ let specs;
95
+ try { specs = checkSpecsAt(input.github_repo, mirror, input.base_sha); }
96
+ catch (error) { if (execution === 'host') throw new Error(`BLOCKED: check metadata unreadable at ${input.base_sha.slice(0, 12)}: ${error.message}`); specs = {}; }
97
+ let tree = null;
98
+ const treeFiles = () => tree ??= repoFiles(mirror, input.base_sha);
99
+ const rule = regressionTestRule(assignment, specs.default?.test_paths ?? null, treeFiles);
100
+ if (rule) throw new Error(rule);
101
+ if (execution !== 'host') return { probed: [], warnings: [], skipped: [{ what: 'host check prerequisites', reason: `execution=${execution}: the bridge host runs no check for this job` }] };
102
+ const blocking = [], warnings = [], skipped = [], probed = [];
103
+ const defaultRunnable = !hostCheckAuthorization(input.github_repo, 'default').refusal;
104
+ for (const [id, spec] of Object.entries(specs)) {
105
+ const result = probePrerequisites(spec, { mirror, sha: input.base_sha, ...probeOptions });
106
+ probed.push(id);
107
+ skipped.push(...result.skipped);
108
+ for (const item of result.unmet) (id === 'default' && defaultRunnable ? blocking : warnings).push(`${id}: ${item}`);
109
+ }
110
+ if (blocking.length) throw new Error(`BLOCKED: check prerequisites unmet: ${blocking.join('; ')}`);
111
+ return { probed, warnings, skipped };
112
+ }
@@ -0,0 +1,19 @@
1
+ // Scheduling affects only how long callers wait, never the check's execution timeout.
2
+ export const CHECK_RESPONSE_MS = 20000;
3
+ export async function checkResponse(work, running, {
4
+ responseMs = CHECK_RESPONSE_MS,
5
+ schedule = setTimeout,
6
+ cancel = clearTimeout,
7
+ } = {}) {
8
+ if (!Number.isFinite(responseMs) || responseMs < 0)
9
+ throw new TypeError('responseMs must be a non-negative finite number');
10
+ let timer;
11
+ try {
12
+ return await Promise.race([
13
+ work,
14
+ new Promise(resolve => { timer = schedule(() => resolve(running), responseMs); }),
15
+ ]);
16
+ } finally {
17
+ if (timer !== undefined) cancel(timer);
18
+ }
19
+ }
@@ -0,0 +1,18 @@
1
+ // A ChildProcess can emit `error` while its PID is still alive (for example, a failed signal).
2
+ // Only `close` proves a started process ended. Spawn failure has no PID and needs no wait.
3
+ export function waitForChildExit(child, { onError = () => {}, onClose = () => {} } = {}) {
4
+ return new Promise(resolve => {
5
+ let settled = false;
6
+ const finish = (...args) => {
7
+ if (settled) return;
8
+ settled = true;
9
+ onClose(...args);
10
+ resolve();
11
+ };
12
+ child.once('close', (...args) => finish(...args));
13
+ child.once('error', error => {
14
+ onError(error);
15
+ if (!Number.isInteger(child.pid) || child.pid <= 0) finish();
16
+ });
17
+ });
18
+ }
@@ -0,0 +1,94 @@
1
+ // A trial's child processes (the public-route ssh, the bridge) are listed in a registry outside every trial home. If the trial's own
2
+ // process is killed without cleanup, the children keep running; the next trial sweeps the registry and ends them only after the
3
+ // recorded owner is confirmed gone and the child's recorded identity still matches.
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { processCommand } from './process-inspection.mjs';
8
+
9
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
10
+ export const childRegistry = (env = process.env) => path.join(env.XDG_CACHE_HOME || path.join(env.HOME || os.homedir(), '.cache'), 'dalan', 'trial-children');
11
+
12
+ // Kept for callers that need only a command string. Cleanup uses the three-state processCommand result below.
13
+ export const commandOf = pid => {
14
+ const identity = processCommand(pid);
15
+ return identity.state === 'present' ? identity.command : null;
16
+ };
17
+
18
+ const inspect = (processCmd, pid) => {
19
+ try {
20
+ const result = processCmd(pid);
21
+ if (result && typeof result === 'object' && ['present', 'absent', 'unknown'].includes(result.state)) return result;
22
+ // Older injected inspectors returned a command string or null. A null result cannot prove absence.
23
+ if (typeof result === 'string' && result) return { state: 'present', command: result, start: null };
24
+ } catch { /* a failed inspection is unknown */ }
25
+ return { state: 'unknown' };
26
+ };
27
+
28
+ const childMatches = (identity, record) => {
29
+ if (identity.state === 'absent') return 'gone';
30
+ if (identity.state !== 'present' || !record.cmd) return 'unknown';
31
+ if (record.cmd !== identity.command) return 'different';
32
+ if (record.start && !identity.start) return 'unknown';
33
+ if (record.start && record.start !== identity.start) return 'different';
34
+ return 'same';
35
+ };
36
+
37
+ // Records one child. Returns a function that removes its record after the child exits.
38
+ export function registerChild({ registry, child, processCmd = processCommand, owner = process.pid }) {
39
+ if (!Number.isInteger(child?.pid)) return () => {};
40
+ const file = path.join(registry, `${child.pid}.json`);
41
+ try {
42
+ fs.mkdirSync(registry, { recursive: true, mode: 0o700 });
43
+ const childIdentity = inspect(processCmd, child.pid);
44
+ const ownerIdentity = inspect(processCmd, owner);
45
+ fs.writeFileSync(file, JSON.stringify({
46
+ pid: child.pid,
47
+ cmd: childIdentity.state === 'present' ? childIdentity.command : null,
48
+ start: childIdentity.state === 'present' ? childIdentity.start ?? null : null,
49
+ owner,
50
+ ownerCmd: ownerIdentity.state === 'present' ? ownerIdentity.command : null,
51
+ ownerStart: ownerIdentity.state === 'present' ? ownerIdentity.start ?? null : null,
52
+ }), { mode: 0o600 });
53
+ } catch { return () => {}; }
54
+ return () => fs.rmSync(file, { force: true });
55
+ }
56
+
57
+ // Ends listed children only after the recorded owner is known to be gone or its PID has a different start identity.
58
+ export async function sweepChildren({ registry, processCmd = processCommand, kill = (pid, sig) => process.kill(pid, sig), clock = { sleep }, graceMs = 2000 }) {
59
+ let names = [];
60
+ try { names = fs.readdirSync(registry).filter(n => n.endsWith('.json')); } catch { return []; }
61
+ const ended = [];
62
+ for (const name of names) {
63
+ const file = path.join(registry, name);
64
+ let record;
65
+ try { record = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { continue; }
66
+ if (!record || typeof record !== 'object' || Array.isArray(record)) continue;
67
+
68
+ if (!Number.isInteger(record.owner)) continue;
69
+ const owner = inspect(processCmd, record.owner);
70
+ const ownerGone = owner.state === 'absent';
71
+ const ownerReused = owner.state === 'present' && Boolean(record.ownerStart) && Boolean(owner.start) && owner.start !== record.ownerStart;
72
+ if (!ownerGone && !ownerReused) continue;
73
+
74
+ let childState = childMatches(inspect(processCmd, record.pid), record);
75
+ if (childState === 'unknown') continue;
76
+ if (childState === 'same') {
77
+ try { kill(record.pid, 'SIGTERM'); } catch { /* inspect again: a signal error does not prove exit */ }
78
+ for (let waited = 0; waited < graceMs; waited += 100) {
79
+ await clock.sleep(100);
80
+ childState = childMatches(inspect(processCmd, record.pid), record);
81
+ if (childState !== 'same') break;
82
+ }
83
+ if (childState === 'same') {
84
+ try { kill(record.pid, 'SIGKILL'); } catch { /* inspect again before releasing the record */ }
85
+ childState = childMatches(inspect(processCmd, record.pid), record);
86
+ }
87
+ if (childState === 'same' || childState === 'unknown') continue;
88
+ ended.push(record.pid);
89
+ }
90
+ // An absent or reused child PID has no process left that this record can safely own.
91
+ fs.rmSync(file, { force: true });
92
+ }
93
+ return ended;
94
+ }
@@ -0,0 +1,51 @@
1
+ import { canonicalValue as canonical, canonicalJson as json, assertClaimAuthority, decide } from '../packages/job-core/index.mjs';
2
+
3
+ // Parent transaction owns native mutation, revision and immutable receipt.
4
+ const fail=c=>{throw Object.assign(new Error(c),{code:c});};
5
+ const str=v=>typeof v==='string'&&v.length>0&&v.length<=512;
6
+ const nat=v=>Number.isSafeInteger(v)&&v>=0;
7
+ export function migrateClaimCommands(db) {
8
+ if(!db.isTransaction)fail('transaction_required');
9
+ db.exec(`CREATE TABLE IF NOT EXISTS claim_command_revisions(job TEXT PRIMARY KEY,revision INTEGER NOT NULL);
10
+ CREATE TABLE IF NOT EXISTS claim_command_receipts(job TEXT NOT NULL,command_key TEXT NOT NULL,
11
+ identity TEXT NOT NULL,result TEXT NOT NULL,PRIMARY KEY(job,command_key));`);
12
+ }
13
+ export function createClaimCommands({db,authorize,clock=Date.now,maxLeaseMs=3600000}) {
14
+ if(typeof authorize!=='function'||!nat(maxLeaseMs)||maxLeaseMs===0)fail('invalid_configuration');
15
+ const tx=()=>{if(!db.isTransaction)fail('transaction_required');};
16
+ const revision=job=>db.prepare('SELECT revision FROM claim_command_revisions WHERE job=?').get(job)?.revision??null;
17
+ function initialize(job,value) {
18
+ tx();if(!str(job)||!nat(value))fail('invalid_revision');
19
+ const current=revision(job);
20
+ if(current!==null&&current!==value)fail('revision_conflict');
21
+ if(current===null)db.prepare('INSERT INTO claim_command_revisions VALUES(?,?)').run(job,value);
22
+ return value;
23
+ }
24
+ function advance(job,expected) {
25
+ tx();if(!nat(expected)||expected>=Number.MAX_SAFE_INTEGER)fail('invalid_revision');
26
+ const result=db.prepare('UPDATE claim_command_revisions SET revision=revision+1 WHERE job=? AND revision=?').run(job,expected);
27
+ if(result.changes!==1)fail('revision_conflict');
28
+ return expected+1;
29
+ }
30
+ function execute(command,mutate) {
31
+ tx();
32
+ const {job,subject,worker,claim,epoch,operation,key,expectedRevision,args}=command;
33
+ if(![job,subject,worker,claim,operation,key].every(str)||!nat(epoch)||epoch<1||!nat(expectedRevision)||typeof mutate!=='function')fail('invalid_command');
34
+ const now=clock();if(!nat(now))fail('invalid_clock');
35
+ const authority=authorize({job,subject,worker,claim,epoch,operation,now});
36
+ assertClaimAuthority({job,subject,worker,claim,epoch},authority,now);
37
+ const identity=json(command);
38
+ const old=db.prepare('SELECT identity,result FROM claim_command_receipts WHERE job=? AND command_key=?').get(job,key);
39
+ if(old){if(old.identity!==identity)fail('command_conflict');return JSON.parse(old.result);}
40
+ const decision=decide({revision:revision(job)},{expectedRevision,operation,args},{now,maxLeaseMs});
41
+ const {leaseUntil}=decision;
42
+ // No arbitrary worker callback: parent injects the trusted Store mutation.
43
+ const nextRevision=advance(job,decision.effects[0].expectedRevision);
44
+ const value=mutate({command,now,revision:nextRevision,...(leaseUntil===undefined?{}:{leaseUntil})});
45
+ if(value&&typeof value.then==='function')fail('async_mutation_forbidden');
46
+ const result={value:canonical(value??null),revision:nextRevision,...(leaseUntil===undefined?{}:{leaseUntil})};
47
+ db.prepare('INSERT INTO claim_command_receipts VALUES(?,?,?,?)').run(job,key,identity,json(result));
48
+ return result;
49
+ }
50
+ return {initialize,revision,advance,execute};
51
+ }