@tnunamak/dalan 0.8.1 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/CHANGELOG.md +59 -2
  2. package/CONTRIBUTING.md +2 -0
  3. package/README.md +8 -12
  4. package/bin/dalan.mjs +25 -4
  5. package/bin/dot-acp-agent.mjs +572 -76
  6. package/bin/dot-alert.mjs +9 -3
  7. package/bin/dot-deadman.mjs +3 -1
  8. package/bin/dot-heartbeat.mjs +14 -7
  9. package/bin/dot-pr-reviewer.mjs +3 -31
  10. package/bin/dot-worker.mjs +121 -34
  11. package/contracts/adapter-qualification.schema.json +94 -7
  12. package/docs/chatgpt-worker-onboarding.md +1 -1
  13. package/docs/codex-to-muse.md +2 -2
  14. package/docs/connect-chatgpt.md +1 -1
  15. package/docs/connection-longevity.md +2 -2
  16. package/docs/dalan-upgrade.md +8 -5
  17. package/docs/deadman.md +4 -0
  18. package/docs/design/authority-matrix.md +18 -0
  19. package/docs/design/failure-table.md +87 -0
  20. package/docs/design/identities.md +22 -0
  21. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  22. package/docs/design/reuse-ledger.md +75 -0
  23. package/docs/design/target-architecture-v2.md +434 -0
  24. package/docs/local-agent-mcp.md +14 -0
  25. package/docs/local-agent-requester.md +2 -1
  26. package/docs/manual-setup.md +1 -1
  27. package/docs/operations.md +77 -14
  28. package/docs/pull-workers.md +11 -1
  29. package/docs/service-setup.md +10 -10
  30. package/docs/t3-integration.md +4 -2
  31. package/docs/t3-reverse-control.md +5 -5
  32. package/docs/test-suite-isolation.md +7 -6
  33. package/docs/trials/chatgpt-agent.md +47 -0
  34. package/docs/trials/claude-code-requester.md +68 -0
  35. package/docs/trials/muse.md +46 -0
  36. package/docs/usage.md +21 -7
  37. package/docs/worker-clients.md +1 -1
  38. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  39. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  40. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  41. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  42. package/package.json +4 -3
  43. package/packages/job-core/protocol/canonical.mjs +45 -7
  44. package/packages/job-core/transitions.mjs +4 -2
  45. package/scripts/upgrade-drain.mjs +96 -8
  46. package/scripts/worker-bridge-setup.mjs +215 -120
  47. package/src/ack-ledger.mjs +7 -1
  48. package/src/acp-bridge.mjs +256 -28
  49. package/src/admin-socket.mjs +32 -3
  50. package/src/alerts.mjs +17 -8
  51. package/src/answer-journal-retention.mjs +82 -0
  52. package/src/answer-journal.mjs +6 -4
  53. package/src/as-store.mjs +51 -6
  54. package/src/as.mjs +27 -5
  55. package/src/catalog-switch-inventory.mjs +70 -0
  56. package/src/check-response.mjs +4 -1
  57. package/src/cli-help.mjs +14 -3
  58. package/src/cli-name.mjs +13 -1
  59. package/src/connect-cli.mjs +159 -4
  60. package/src/deadman.mjs +8 -5
  61. package/src/delivery.mjs +2 -19
  62. package/src/destinations/index.mjs +75 -14
  63. package/src/drain-runner.mjs +5 -1
  64. package/src/follow-current.mjs +3 -1
  65. package/src/get-summary.mjs +11 -2
  66. package/src/git-env.mjs +1 -1
  67. package/src/gozar-routes.mjs +313 -94
  68. package/src/host-budget-storage.py +56 -6
  69. package/src/host-budget.mjs +98 -15
  70. package/src/host-execution-policy.mjs +17 -6
  71. package/src/legacy-names.mjs +0 -2
  72. package/src/lifecycle.mjs +44 -9
  73. package/src/loopback-probe.mjs +46 -0
  74. package/src/mcp-outcome.mjs +3 -1
  75. package/src/mcp-sse.mjs +2 -1
  76. package/src/mcp-stdio.mjs +192 -30
  77. package/src/patch-apply.mjs +212 -7
  78. package/src/phase-trace.mjs +73 -0
  79. package/src/prepared-go-modules.mjs +127 -0
  80. package/src/prepared-node-modules.mjs +225 -38
  81. package/src/prepared-pnpm.mjs +276 -0
  82. package/src/prepared-store-prune.mjs +52 -0
  83. package/src/projects.mjs +59 -7
  84. package/src/protocol-artifact-commands.mjs +28 -0
  85. package/src/protocol-finish.mjs +3 -2
  86. package/src/publication-authority.mjs +22 -0
  87. package/src/publish-plan.mjs +2 -2
  88. package/src/pull-queue.mjs +55 -20
  89. package/src/read-api.mjs +127 -0
  90. package/src/redaction.mjs +173 -0
  91. package/src/rejections.mjs +19 -3
  92. package/src/route-custody.mjs +90 -0
  93. package/src/route-publication.mjs +50 -0
  94. package/src/route-setup.mjs +184 -0
  95. package/src/schema-subset.mjs +5 -3
  96. package/src/server.mjs +503 -98
  97. package/src/service-launchd.mjs +5 -1
  98. package/src/service-update-lock.mjs +7 -4
  99. package/src/service-update-runtime.mjs +64 -19
  100. package/src/service-update.mjs +193 -48
  101. package/src/service.mjs +276 -77
  102. package/src/setup.mjs +48 -25
  103. package/src/signal.mjs +1 -1
  104. package/src/status-evidence.mjs +18 -5
  105. package/src/store.mjs +876 -120
  106. package/src/submission-policy.mjs +257 -56
  107. package/src/t3-control.mjs +1 -1
  108. package/src/t3.mjs +14 -8
  109. package/src/terminal-safe.mjs +9 -7
  110. package/src/tool-registry.mjs +134 -41
  111. package/src/try-exposure.mjs +53 -86
  112. package/src/try-hosted.mjs +257 -70
  113. package/src/try.mjs +48 -22
  114. package/src/work-order.mjs +11 -6
  115. package/src/worker-instructions.mjs +26 -4
  116. package/src/worker-runs.mjs +35 -0
  117. package/src/workers.mjs +34 -7
  118. package/src/workspace.mjs +354 -54
  119. package/systemd/dot-deadman.service +3 -1
  120. package/docs/dot-pr-reviewer.config.example.json +0 -9
  121. package/docs/pr-head-reviewer.md +0 -70
  122. package/src/pr-head-reviewer.mjs +0 -596
  123. package/systemd/dot-pr-reviewer.service +0 -11
  124. package/systemd/dot-pr-reviewer.timer +0 -10
@@ -28,7 +28,9 @@ if sys.argv[1] != '--inside':
28
28
  config_fd=os.memfd_create('dot-host-config')
29
29
  guest_config = dict(config)
30
30
  if config['dependencies']:
31
- guest_config['dependencies'] = {key: value for key, value in config['dependencies'].items() if key != 'treePath'}
31
+ guest_config['dependencies'] = {key: value for key, value in config['dependencies'].items() if key not in ('treePath', 'workspaceTrees')}
32
+ if config.get('goModules'):
33
+ guest_config['goModules'] = {key: value for key, value in config['goModules'].items() if key != 'treePath'}
32
34
  os.write(config_fd,json.dumps(guest_config).encode())
33
35
  os.lseek(config_fd,0,0)
34
36
  extra_fds=[config_fd]
@@ -46,8 +48,25 @@ if sys.argv[1] != '--inside':
46
48
  '--dir', '/home', '--symlink', '/budget/home', '/home/worker']
47
49
  if os.path.isdir(npm):
48
50
  command += ['--ro-bind', npm, '/runtime/npm']
51
+ # Tools cache and bundle under node_modules (vite's config bundle goes to .vite-temp and aborts the run without it). Where a prepared tree
52
+ # carries one of these empty mount points, a small tmpfs goes over it: the tree stays read-only, the writes vanish with the sandbox, and
53
+ # each tmpfs is capped (its pages count against the cgroup memory budget). Names match SCRATCH_DIRS in prepared-node-modules.mjs.
54
+ def scratch(tree_path, dest):
55
+ mounts = []
56
+ for name in ('.cache', '.vite', '.vite-temp', '.vitest', '.vitest-cache'):
57
+ source = os.path.join(tree_path, name)
58
+ if os.path.isdir(source) and not os.path.islink(source):
59
+ mounts += ['--size', str(16 * 1024 * 1024), '--tmpfs', dest + '/' + name]
60
+ return mounts
49
61
  if config['dependencies']:
50
- command += ['--ro-bind', config['dependencies']['treePath'], '/budget/workspace/node_modules']
62
+ command += ['--ro-bind', config['dependencies']['treePath'], '/budget/workspace/node_modules', *scratch(config['dependencies']['treePath'], '/budget/workspace/node_modules')]
63
+ # A workspace's own node_modules (versions that conflict with the root's) sits beside its source, read-only like the root tree.
64
+ for tree in config['dependencies'].get('workspaceTrees', []):
65
+ dest = '/budget/workspace/' + tree['path'] + '/node_modules'
66
+ command += ['--ro-bind', tree['treePath'], dest, *scratch(tree['treePath'], dest)]
67
+ # The prepared Go module cache (modules plus the toolchain go.mod asks for) is the sandbox's GOMODCACHE, read-only.
68
+ if config.get('goModules'):
69
+ command += ['--ro-bind', config['goModules']['treePath'], '/budget/cache/go/pkg/mod']
51
70
  # Empty sensitive files and host-approved source overlays stay read-only.
52
71
  for name in config['maskPaths']:
53
72
  empty=os.memfd_create('dot-host-mask')
@@ -75,6 +94,7 @@ if sys.argv[1] != '--inside':
75
94
  '--setenv', 'PATH', '/budget/bin:/runtime:/usr/bin:/bin', '--setenv', 'HOME', '/home/worker', '--setenv', 'TMPDIR', '/tmp',
76
95
  '--setenv', 'XDG_CACHE_HOME', '/cache/xdg', '--setenv', 'npm_config_cache', '/cache/npm', '--setenv', 'UV_CACHE_DIR', '/cache/uv',
77
96
  '--setenv', 'CARGO_HOME', '/cache/cargo', '--setenv', 'GOPATH', '/cache/go', '--setenv', 'GOMODCACHE', '/cache/go/pkg/mod',
97
+ '--setenv', 'GOPROXY', 'off', '--setenv', 'GOFLAGS', '-mod=readonly',
78
98
  '--', '/usr/bin/python3', '/supervisor.py', '--inside', str(read_fd)]
79
99
  child = subprocess.Popen(command, pass_fds=[read_fd,*extra_fds], stdin=sys.stdin)
80
100
  os.close(read_fd)
@@ -134,7 +154,9 @@ def inspect():
134
154
  global error
135
155
  used = usage()
136
156
  which = ('disk_write' if used['disk_write_bytes'] >= budgets['disk_write_bytes'] else
137
- 'memory' if fields('memory.events').get('max', 0) else
157
+ # memory.events 'max' only counts reclaim at the limit (page cache, for example); the run goes on.
158
+ # Only a kernel OOM kill means the memory budget was exceeded.
159
+ 'memory' if fields('memory.events').get('oom_kill', 0) else
138
160
  'processes' if fields('pids.events').get('max', 0) else
139
161
  'cpu' if used['cpu_ms'] >= budgets['cpu_ms'] else None)
140
162
  if which and error is None:
@@ -164,12 +186,40 @@ try:
164
186
  archive.extractall('/workspace', filter='data')
165
187
  dependencies = config['dependencies']
166
188
  if dependencies:
167
- for name, key in [('package-lock.json', 'lock_sha256'), ('package.json', 'manifest_sha256')]:
189
+ if dependencies.get('kind') == 'pnpm':
190
+ checks = [('pnpm-lock.yaml', dependencies['lock_sha256']), ('package.json', dependencies['manifest_sha256'])]
191
+ if os.path.lexists('/workspace/package-lock.json'):
192
+ raise ValueError('dependencies_invalid: copied lock appeared after admission')
193
+ # pnpm-workspace.yaml is optional: an absent file must hash as empty, like the empty bytes the host recorded.
194
+ data = b''
195
+ if os.path.lexists('/workspace/pnpm-workspace.yaml'):
196
+ with open('/workspace/pnpm-workspace.yaml', 'rb') as stream:
197
+ data = stream.read()
198
+ if hashlib.sha256(data).hexdigest() != dependencies['workspace_yaml_sha256']:
199
+ raise ValueError('dependencies_invalid: copied dependency inputs changed')
200
+ else:
201
+ checks = [('package-lock.json', dependencies['lock_sha256']), ('package.json', dependencies['manifest_sha256'])]
202
+ if os.path.lexists('/workspace/pnpm-lock.yaml'):
203
+ raise ValueError('dependencies_invalid: copied lock appeared after admission')
204
+ checks += [(name + '/package.json', digest) for name, digest in dependencies.get('workspaces', {}).items()]
205
+ checks += list(dependencies.get('local_files', {}).items())
206
+ for name, digest in checks:
168
207
  with open('/workspace/' + name, 'rb') as stream:
169
- if hashlib.sha256(stream.read()).hexdigest() != dependencies[key]:
208
+ if hashlib.sha256(stream.read()).hexdigest() != digest:
170
209
  raise ValueError('dependencies_invalid: copied dependency inputs changed')
171
- elif os.path.lexists('/workspace/package-lock.json'):
210
+ elif os.path.lexists('/workspace/package-lock.json') or os.path.lexists('/workspace/pnpm-lock.yaml'):
172
211
  raise ValueError('dependencies_invalid: copied lock appeared after admission')
212
+ go_modules = config.get('goModules')
213
+ if go_modules:
214
+ for name, key in [('go.mod', 'go_mod_sha256'), ('go.sum', 'go_sum_sha256')]:
215
+ data = b''
216
+ if os.path.lexists('/workspace/' + name):
217
+ with open('/workspace/' + name, 'rb') as stream:
218
+ data = stream.read()
219
+ if hashlib.sha256(data).hexdigest() != go_modules[key]:
220
+ raise ValueError('dependencies_invalid: copied Go module inputs changed')
221
+ elif os.path.lexists('/workspace/go.mod'):
222
+ raise ValueError('dependencies_invalid: copied go.mod appeared after admission')
173
223
  for name in ['npm', 'npx']:
174
224
  file = '/budget/bin/' + name
175
225
  with open(file, 'w') as stream:
@@ -1,13 +1,31 @@
1
1
  import { readEnv } from './env.mjs';
2
2
  import fs from 'node:fs';
3
3
  import {resolvePreparedNodeModules} from './prepared-node-modules.mjs';
4
+ import {resolvePreparedGoModules} from './prepared-go-modules.mjs';
5
+ import {resolvePreparedPnpm} from './prepared-pnpm.mjs';
4
6
  import path from 'node:path';
5
7
  import {prepareHostReceipts,assertHostReceiptIsolation,readVerifiedHostStop} from './host-budget-receipts.mjs';
6
8
  import { fileURLToPath } from 'node:url';
7
9
  import { spawn } from 'node:child_process';
10
+ import { setTimeout as delay } from 'node:timers/promises';
11
+ import { createHash, randomUUID } from 'node:crypto';
8
12
 
9
13
  // The fixed production unit reserves one active envelope per Unix user.
10
- export const HOST_BUDGET_CEILINGS = Object.freeze({ cpu_ms: 120000, wall_ms: 180000, memory_bytes: 1024 ** 3, processes: 128, disk_write_bytes: 256 * 1024 ** 2, output_bytes: 1024 ** 2 });
14
+ // The 4 GiB memory ceiling covers the heaviest measured suite-class workload. The metric is the cgroup's peak, which counts page cache and
15
+ // tmpfs pages, so it runs well above the largest single process: a vitest suite on my-two-cents peaked at 2.2 GiB (1.2 GiB resident) on
16
+ // 2026-11-26, and the full suite at over 3.1 GiB when stopped. One unit runs per user at a time.
17
+ export const HOST_BUDGET_CEILINGS = Object.freeze({ cpu_ms: 120000, wall_ms: 180000, memory_bytes: 4 * 1024 ** 3, processes: 192, disk_write_bytes: 512 * 1024 ** 2, output_bytes: 1024 ** 2 });
18
+ // The 512 MiB disk ceiling (the tmpfs also holds the candidate copy) covers a cold Go build: the build cache of a mid-size module
19
+ // (clawmeter: 143 MB cached, about the same again in $WORK) did not fit in 256 MiB, measured 2026-11-26. A check asks for what it needs.
20
+ // A workload the kernel OOM-killed is not restarted at once: the same workload
21
+ // on the same unit fails fast with reason "oom" until this delay passes, so a
22
+ // caller's restart loop cannot re-kill it second after second. The production
23
+ // unit is shared by every job of a Unix user, so the key includes the workload:
24
+ // one job's memory kill must not fail another job's check.
25
+ export const HOST_CHECK_OOM_RETRY_DELAY_MS = 60_000;
26
+ export const HOST_CHECK_BUSY_WAIT_MS = 120_000;
27
+ const oomKilledReservations = new Map();
28
+ let processUnitSuffix;
11
29
  const minima = { cpu_ms: 50, wall_ms: 100, memory_bytes: 128 * 1024 ** 2, processes: 16, disk_write_bytes: 1024 ** 2, output_bytes: 1024 };
12
30
  const service = fileURLToPath(new URL('./host-budget-service.mjs', import.meta.url));
13
31
  const stopRecorder = fileURLToPath(new URL('./host-budget-stop.mjs', import.meta.url));
@@ -35,37 +53,93 @@ const propertyArg = value => '"' + value.replaceAll('%', '%%').replaceAll('\\',
35
53
 
36
54
  export const provesHostNotStarted = ({ spawnError, pid, stopped }) => !!(spawnError && !pid && !stopped);
37
55
 
56
+ function markOomKilledReservation(key, at) {
57
+ for (const [reservation, killedAt] of oomKilledReservations) if (at - killedAt >= HOST_CHECK_OOM_RETRY_DELAY_MS) oomKilledReservations.delete(reservation);
58
+ oomKilledReservations.set(key, at);
59
+ }
60
+
61
+ // Nothing was launched: the caller marks the check failed with reason "oom"
62
+ // instead of handing the same workload back to the kernel that just killed it.
63
+ function deferredOomReservation({ unit, budgets, killedAt, at }) {
64
+ return { unit, dependencies: null, exit: { code: 125 }, budgets, usage: null, usage_complete: false, bytes: Buffer.alloc(0), phases: [],
65
+ error: `oom: ${unit} was kernel-killed and is not restarted at once (retry after ${Math.ceil((killedAt + HOST_CHECK_OOM_RETRY_DELAY_MS - at) / 1000)}s)`,
66
+ stop: { verified: false, reason: 'oom', service_result: 'oom-kill', invocation_id: null, remaining_pids: null, oom_kill: null },
67
+ notStarted: true, timedOut: false, cancelled: false, truncated: false, duration_ms: 0 };
68
+ }
69
+
70
+ function hostCheckBusyWaitMs() {
71
+ const override = process.env.NODE_ENV === 'production' ? undefined : process.env.HOST_CHECK_BUSY_WAIT_MS;
72
+ const value = override === undefined || override === '' ? NaN : Number(override);
73
+ return Number.isSafeInteger(value) && value >= 0 ? Math.min(value, HOST_CHECK_BUSY_WAIT_MS) : HOST_CHECK_BUSY_WAIT_MS;
74
+ }
75
+
76
+ async function waitForHostAdmission(until, cancelled) {
77
+ while (!cancelled()) {
78
+ const remaining = until - performance.now();
79
+ if (remaining <= 0) return;
80
+ await delay(Math.min(50, Math.ceil(remaining)));
81
+ }
82
+ }
83
+
84
+ const busyBeforeStart = Symbol('busyBeforeStart');
85
+
38
86
  export async function runHostBudget(options) {
39
- let spawned=false;
40
- try { return await runHostBudgetAttempt(options,()=>{spawned=true;}); }
41
- catch(error) { if(spawned) error.hostInvoked=true;throw error; }
87
+ let spawned=false, waitStarted, busyRetries=0;
88
+ const cancelled = options.cancelled ?? (() => false);
89
+ const busyWait = hostCheckBusyWaitMs();
90
+ try {
91
+ for (;;) {
92
+ const result = await runHostBudgetAttempt(options,()=>{spawned=true;});
93
+ if (!result[busyBeforeStart]) return busyRetries ? {...result,busy_retries:busyRetries} : result;
94
+ delete result[busyBeforeStart];
95
+ waitStarted ??= performance.now();
96
+ const deadline = waitStarted + busyWait;
97
+ await waitForHostAdmission(Math.min(deadline,performance.now()+1000+Math.random()*2000),cancelled);
98
+ if (cancelled()) return {...result,cancelled:true,busy_retries:busyRetries};
99
+ if (performance.now() >= deadline) {
100
+ return {...result,error:`${result.error} (waited ${Math.round(performance.now()-waitStarted)} ms)`,busy_retries:busyRetries};
101
+ }
102
+ busyRetries++;
103
+ }
104
+ } catch(error) { if(spawned) error.hostInvoked=true;throw error; }
42
105
  }
43
106
 
44
- async function runHostBudgetAttempt({ dir, budgets, phases, maskPaths = [], sourceExemptions = [], checkRunId, receiptDir, cancelled = () => false, onStarted, onOutputStarted, enabled = readEnv('DALAN_HOST_CHECKS') === '1' }, onSpawned) {
107
+ async function runHostBudgetAttempt({ dir, budgets, phases, maskPaths = [], sourceExemptions = [], checkRunId, receiptDir, cancelled = () => false, onStarted, onOutputStarted, enabled = readEnv('DALAN_HOST_CHECKS') === '1', now = () => performance.now() }, onSpawned) {
45
108
  if (!enabled) throw new Error('host_execution_disabled: set DALAN_HOST_CHECKS=1 to opt in');
46
109
  if (process.platform !== 'linux') throw new Error(`host budget backend unavailable on ${process.platform}`);
47
110
  budgets = parseHostBudget(budgets);
48
- if (!Array.isArray(phases) || !phases.length || phases.length > 2 || phases.some(p => !['install', 'check'].includes(p.name) || !Array.isArray(p.argv) || !p.argv.length || p.argv.some(a => typeof a !== 'string' || a.includes('\0')))) throw new Error('invalid host phases');
111
+ const validOrder = Array.isArray(phases) && (
112
+ (phases.length === 1 && phases[0]?.name === 'check') ||
113
+ (phases.length === 2 && phases[0]?.name === 'install' && phases[1]?.name === 'check'));
114
+ const validArgv = phase => Array.isArray(phase.argv) && typeof phase.argv[0] === 'string' &&
115
+ phase.argv[0].trim().length > 0 && phase.argv.every(arg => typeof arg === 'string' && !arg.includes('\0'));
116
+ // Bound the serialized plan instead of inventing a separate argument-count limit.
117
+ if (!validOrder || !phases.every(validArgv) || Buffer.byteLength(JSON.stringify(phases)) > 65536)
118
+ throw new Error('invalid host phases');
49
119
  const receipts=prepareHostReceipts({checkRunId,receiptDir});
50
120
  const workingDir=fs.realpathSync(dir);
51
- const dependencies=resolvePreparedNodeModules(workingDir);
52
- const protectedPaths=['node_modules','package.json','package-lock.json'];
121
+ const dependencies=resolvePreparedNodeModules(workingDir)??resolvePreparedPnpm(workingDir);
122
+ const goModules=resolvePreparedGoModules(workingDir);
123
+ const protectedPaths=['node_modules','package.json','package-lock.json','pnpm-lock.yaml','pnpm-workspace.yaml','go.mod','go.sum',...Object.keys(dependencies?.workspaces??{}).flatMap(name=>[`${name}/node_modules`,`${name}/package.json`]),...Object.keys(dependencies?.local_files??{})];
53
124
  const overlaps=(a,b)=>a===b||a.startsWith(b+'/')||b.startsWith(a+'/');
54
125
  for(const name of [...maskPaths,...sourceExemptions.map(entry=>entry.path)]) {
55
126
  if(typeof name!=='string'||!name||path.posix.normalize(name)!==name||name.startsWith('/')||name==='..'||name.startsWith('../')||protectedPaths.some(p=>overlaps(name,p))) throw new Error('dependencies_invalid: overlay overlaps dependency inputs');
56
127
  }
57
128
  if(dependencies) for(const entry of sourceExemptions) {
58
- const host=fs.realpathSync(entry.hostPath), tree=fs.realpathSync(dependencies.treePath);
59
- if(host===tree||host.startsWith(tree+path.sep)||tree.startsWith(host+path.sep)) throw new Error('dependencies_invalid: overlay exposes dependency tree');
129
+ const host=fs.realpathSync(entry.hostPath);
130
+ for(const treePath of [dependencies.treePath,...dependencies.workspaceTrees.map(tree=>tree.treePath)]) {
131
+ const tree=fs.realpathSync(treePath);
132
+ if(host===tree||host.startsWith(tree+path.sep)||tree.startsWith(host+path.sep)) throw new Error('dependencies_invalid: overlay exposes dependency tree');
133
+ }
60
134
  }
61
135
  if(receipts) {
62
136
  assertHostReceiptIsolation(receipts.receiptDir,[workingDir,'/usr','/lib','/lib64','/etc/alternatives',process.execPath,
63
137
  path.resolve(path.dirname(process.execPath),'../lib/node_modules/npm'),service,stopRecorder,
64
138
  cgroupReader,processSignaler,
65
139
  fileURLToPath(new URL('./host-budget-storage.py',import.meta.url)),fileURLToPath(new URL('./host-budget-seccomp.py',import.meta.url)),
66
- ...sourceExemptions.map(entry=>entry.hostPath),...(dependencies?[dependencies.treePath]:[])]);
140
+ ...sourceExemptions.map(entry=>entry.hostPath),...(dependencies?[dependencies.treePath,...dependencies.workspaceTrees.map(tree=>tree.treePath)]:[]),...(goModules?[goModules.treePath]:[])]);
67
141
  }
68
- const config = { dir: workingDir, budgets, phases, maskPaths, sourceExemptions, dependencies, node: process.execPath, ...(receipts?{receipts}:{}) };
142
+ const config = { dir: workingDir, budgets, phases, maskPaths, sourceExemptions, dependencies, goModules, node: process.execPath, ...(receipts?{receipts}:{}) };
69
143
  const serialized = JSON.stringify(config);
70
144
  if (Buffer.byteLength(serialized) > 65536) throw new Error('host budget configuration exceeds 64 KiB');
71
145
  const properties = [
@@ -75,10 +149,14 @@ async function runHostBudgetAttempt({ dir, budgets, phases, maskPaths = [], sour
75
149
  'LimitCORE=0', 'UMask=0077',
76
150
  `ExecStopPost=${[process.execPath, stopRecorder,...(receipts?['--check-run-id',receipts.checkRunId,'--receipt-dir',receipts.receiptDir]:[])].map(propertyArg).join(' ')}`,
77
151
  ];
78
- // Test suites isolate their reservation without changing the production default.
79
- const suffix = process.env.NODE_ENV === 'production' ? undefined : process.env.DALAN_HOST_CHECK_UNIT_SUFFIX;
152
+ // Only a process started with NODE_ENV=production uses the fixed unit. Any other process (a test, a bare script run) uses
153
+ // the suffix its suite set, or else a unit of its own, so it can never occupy the unit the live bridge needs.
154
+ const suffix = process.env.NODE_ENV === 'production' ? undefined : (process.env.DALAN_HOST_CHECK_UNIT_SUFFIX || (processUnitSuffix ??= `proc-${process.pid}-${randomUUID()}`));
80
155
  if (suffix && !/^[a-zA-Z0-9-]{1,80}$/.test(suffix)) throw new Error('invalid DALAN_HOST_CHECK_UNIT_SUFFIX');
81
156
  const unit = `dot-bridge-host-check${suffix ? '-' + suffix : ''}.service`;
157
+ const oomKey = `${unit}#${createHash('sha256').update(JSON.stringify({ dir: workingDir, phases, budgets })).digest('hex')}`;
158
+ const oomKilledAt = oomKilledReservations.get(oomKey);
159
+ if (oomKilledAt !== undefined && now() - oomKilledAt < HOST_CHECK_OOM_RETRY_DELAY_MS) return deferredOomReservation({ unit, budgets, killedAt: oomKilledAt, at: now() });
82
160
  const args = ['--user', '--quiet', '--wait', '--pipe', '--collect', `--unit=${unit}`, ...properties.map(p => `--property=${p}`), '--', process.execPath, service];
83
161
  const started=performance.now();
84
162
  const child = spawn('/usr/bin/systemd-run', args, { stdio: ['pipe', 'pipe', 'pipe'] });
@@ -138,6 +216,7 @@ async function runHostBudgetAttempt({ dir, budgets, phases, maskPaths = [], sour
138
216
  // application TTL can certify a still-running tree as stopped.
139
217
  const stopEvidence=resolveHostStopEvidence(receipts,stopped);
140
218
  const stop = { verified: stopEvidence?.verified === true, reason: stopEvidence?.verified ? 'systemd_control_group_stopped' : 'service_stop_not_observed', service_result: stopped?.result ?? null, invocation_id: stopEvidence?.invocationId ?? stopped?.invocation_id ?? null, remaining_pids: stopEvidence?.remaining_pids ?? stopped?.remaining_pids ?? null, oom_kill: stopped?.oom_kill ?? null };
219
+ if ((stopped?.oom_kill ?? 0) > 0 || stopped?.result === 'oom-kill') markOomKilledReservation(oomKey, now());
141
220
  let error = cpuExceeded ? 'budget exceeded: cpu' : message?.error ?? null;
142
221
  if (stopped?.oom_kill > 0 || stopped?.result === 'oom-kill') error = 'budget exceeded: memory';
143
222
  else if (stopped?.result === 'timeout') error = 'budget exceeded: wall';
@@ -151,5 +230,9 @@ async function runHostBudgetAttempt({ dir, budgets, phases, maskPaths = [], sour
151
230
  const bytes = Buffer.concat(phaseResults.map(p => p.bytes)).subarray(0, budgets.output_bytes);
152
231
  const notStarted=provesHostNotStarted({spawnError:exit.error,pid,stopped}); // stderr is not trusted for this decision.
153
232
  const usage = message?.usage ? { ...partialUsage, ...message.usage } : partialUsage;
154
- return { unit, dependencies: dependencies ? {lock_sha256:dependencies.lock_sha256,manifest_sha256:dependencies.manifest_sha256,runtime:dependencies.runtime} : null, exit: error ? { code: 125 } : message?.exit ?? { code: 125 }, error, budgets, usage, usage_complete: !!message?.usage && !!message?.phases?.length && stopped?.result !== 'timeout' && !stopped?.oom_kill, bytes, phases: phaseResults, stop, notStarted, timedOut: error === 'budget exceeded: wall', cancelled: !!message?.cancelled, truncated: error === 'budget exceeded: output', duration_ms: Math.round(performance.now()-started) };
233
+ // Recognize only the systemd admission refusal, with no supervisor bytes or stop evidence.
234
+ // Never use this diagnosis to mark a started check stopped or retry it.
235
+ const busy = Number.isInteger(exit.code) && exit.code !== 0 && !exit.signal && received === 0 && !stopEvidence &&
236
+ diagnostic.includes('Failed to start transient service unit:') && diagnostic.includes('already loaded or has a fragment file');
237
+ return { ...(busy ? {[busyBeforeStart]:true} : {}), unit, dependencies: dependencies ? {lock_sha256:dependencies.lock_sha256,manifest_sha256:dependencies.manifest_sha256,runtime:dependencies.runtime,...(dependencies.kind?{kind:dependencies.kind,workspace_yaml_sha256:dependencies.workspace_yaml_sha256}:{}),...(dependencies.workspaces?{workspaces:dependencies.workspaces}:{})} : null, go_modules: goModules ? {go_mod_sha256:goModules.go_mod_sha256,go_sum_sha256:goModules.go_sum_sha256,runtime:goModules.runtime} : null, exit: error ? { code: 125 } : message?.exit ?? { code: 125 }, error, budgets, usage, usage_complete: !!message?.usage && !!message?.phases?.length && stopped?.result !== 'timeout' && !stopped?.oom_kill, bytes, phases: phaseResults, stop, notStarted, timedOut: error === 'budget exceeded: wall', cancelled: !!message?.cancelled, truncated: error === 'budget exceeded: output', duration_ms: Math.round(performance.now()-started) };
155
238
  }
@@ -1,6 +1,6 @@
1
1
  import { readEnv } from './env.mjs';
2
- import { sensitivePolicyPaths } from './submission-policy.mjs';
3
- import { ownerCheck } from './projects.mjs';
2
+ import { isSensitiveRepoPath, sensitivePolicyPaths } from './submission-policy.mjs';
3
+ import { assignmentNamedCheck, isNamedCheck, ownerCheck } from './projects.mjs';
4
4
  import { parseHostBudget } from './host-budget.mjs';
5
5
  import { hostCheckPairAllowed } from './host-check-allowlist.mjs';
6
6
  import fs from 'node:fs';
@@ -9,13 +9,24 @@ export const RESOURCE_LIMITS_UNAVAILABLE='resource_limits_unavailable: host chec
9
9
 
10
10
  const same = (left, right) => JSON.stringify(left) === JSON.stringify(right);
11
11
 
12
- export function hostCheckAuthorization(repo, checkId, expectedSpec = null) {
13
- if (!hostCheckPairAllowed(repo, checkId)) return { refusal: 'host_check_not_allowlisted: owner allowlist does not permit this repository/check pair' };
12
+ export function hostCheckAuthorization(repo, checkId, expectedSpec = null, assignment = null) {
13
+ const named=isNamedCheck(checkId)&&Array.isArray(assignment?.checks)&&assignment.checks.length>0;
14
+ if (!hostCheckPairAllowed(repo, named?'named':checkId)) return { refusal: named?
15
+ 'host_check_not_allowlisted: allow (repo, named) to run requester-declared checks' :
16
+ 'host_check_not_allowlisted: owner allowlist does not permit this repository/check pair' };
14
17
  let spec;
15
- try { spec = ownerCheck(repo, checkId); } catch { return { refusal: 'host_check_owner_definition_unavailable: owner check configuration is invalid or unavailable' }; }
18
+ try { spec = ownerCheck(repo, named?'default':checkId); } catch { return { refusal: 'host_check_owner_definition_unavailable: owner check configuration is invalid or unavailable' }; }
16
19
  if (!spec) return { refusal: 'host_check_owner_definition_required: this check has no current owner-configured definition' };
17
20
  if (!spec.host_budget) return { refusal: 'host_budget_missing: declare host_budget in owner configuration' };
18
21
  try { parseHostBudget(spec.host_budget); } catch { return { refusal: 'host_budget_missing: declare a valid host_budget in owner configuration' }; }
22
+ if (named) {
23
+ const policy=sensitivePolicyPaths();
24
+ if (policy.error) return { refusal: 'sensitive_policy_unavailable: restore a valid mode-0600 submission policy before running host checks' };
25
+ spec=assignmentNamedCheck(assignment,checkId,spec);
26
+ if (!spec || isSensitiveRepoPath(spec.test_paths[0],policy.paths) ||
27
+ assignment.scope_excluded?.some(entry=>entry.path===spec.test_paths[0]))
28
+ return { refusal: 'invalid_named_check: a current non-sensitive named check is required' };
29
+ }
19
30
  if (expectedSpec && !same(spec, expectedSpec)) return { refusal: 'host_check_definition_changed: owner definition changed after resolution' };
20
31
  return { spec };
21
32
  }
@@ -29,7 +40,7 @@ export function hostCheckRefusal(assignment={}, repo=null, checkId=null, expecte
29
40
  if(sensitivePolicyPaths().error) return 'sensitive_policy_unavailable: restore a valid mode-0600 submission policy before running host checks';
30
41
  if(readEnv('DALAN_HOST_CHECKS')!=='1') return RESOURCE_LIMITS_UNAVAILABLE;
31
42
  if(repo!==null&&checkId!==null) {
32
- const authorization=hostCheckAuthorization(repo,checkId,expectedSpec);
43
+ const authorization=hostCheckAuthorization(repo,checkId,expectedSpec,assignment);
33
44
  if(authorization.refusal) return authorization.refusal;
34
45
  }
35
46
  if(process.platform!=='linux') return `resource_limits_unavailable: no enforced host budget backend on ${process.platform}`;
@@ -4,5 +4,3 @@
4
4
  export const legacyFixLoopName = 'dot-fix';
5
5
  // Directory of the fix ledger that `dalan backfill-objectives` reads when no path is given.
6
6
  export const legacyFixLedgerPath = `.local/share/${legacyFixLoopName}/ledger.jsonl`;
7
- // Earlier name of the `report_thread_id` key in the PR-head reviewer config. Still read; `report_thread_id` wins when both are set.
8
- export const legacyReportThreadKey = 'lead_thread_id';
package/src/lifecycle.mjs CHANGED
@@ -112,8 +112,9 @@ export function backfillLifecycle(db) {
112
112
  for(const c of claims.values()) add(c.request_id,'claimed',c.claimed_at,c,c.epoch>1?'current epoch only; earlier epochs unknown':null);
113
113
  for(const p of db.prepare('SELECT request_id,note,created_at FROM progress ORDER BY id').all()) add(p.request_id,progressType(p.note),p.created_at,inClaim(p.request_id,p.created_at));
114
114
  for(const r of db.prepare('SELECT request_id,claim_id,outcome,late,created_at FROM reports').all()) {
115
+ if(r.late) continue; // Historical late reports are evidence, not terminal lifecycle transitions.
115
116
  const claim=byClaimId.get(r.claim_id)??{claim_id:r.claim_id,epoch:null};
116
- add(r.request_id,'completed',r.created_at,claim,`outcome=${r.outcome}${r.late?';late':''}`);
117
+ add(r.request_id,'completed',r.created_at,claim,`outcome=${r.outcome}`);
117
118
  if(r.outcome==='blocked') add(r.request_id,'blocked',r.created_at,claim);
118
119
  }
119
120
  for(const n of db.prepare("SELECT request_id,kind,state,attempt_started_at,last_reconciled_at,uncertain_reason FROM notifications WHERE kind IN ('t3','blocker','watch') AND attempt_started_at IS NOT NULL AND state IN ('delivered','uncertain')").all()) {
@@ -137,7 +138,7 @@ export function backfillLifecycle(db) {
137
138
  // Events older than the retention window become per-day counts by type and kind, then leave the event table.
138
139
  export function retainLifecycle(store,days=retentionDays) { return store.transaction(()=>{
139
140
  const db=store.db, cutoff=new Date(store.nowMs()-days*86400000).toISOString();
140
- db.prepare(`INSERT INTO lifecycle_daily(day,type,kind,count) SELECT substr(e.at,1,10),e.type,${kindSql},count(*) FROM lifecycle_events e LEFT JOIN assignments a ON a.request_id=e.request_id WHERE e.at<? GROUP BY 1,2,3
141
+ db.prepare(`INSERT INTO lifecycle_daily(day,type,kind,count) SELECT substr(e.at,1,10),e.type,${kindSql},count(*) FROM lifecycle_events e LEFT JOIN assignments a ON a.request_id=e.request_id WHERE e.at<? AND NOT (e.type='completed' AND e.source='backfill' AND COALESCE(e.reason,'') LIKE '%;late') GROUP BY 1,2,3
141
142
  ON CONFLICT(day,type,kind) DO UPDATE SET count=count+excluded.count`).run(cutoff);
142
143
  db.prepare('UPDATE lifecycle_retention SET cutoff=? WHERE id=1').run(cutoff);
143
144
  const deleted=db.prepare('DELETE FROM lifecycle_events WHERE at<?').run(cutoff).changes;
@@ -183,7 +184,7 @@ function laneUtilization(store,laneCapacity,nowMs,firstEventMs,rolledUpBefore) {
183
184
  const rows=db.prepare(`SELECT request_id,type,at,epoch,source,actor FROM lifecycle_events WHERE request_id IN (SELECT request_id FROM lifecycle_events WHERE at>=? UNION SELECT request_id FROM assignments WHERE status IN ('queued','claimed')) ORDER BY request_id,at,id`).all(startText);
184
185
  const queuedNow=new Set(db.prepare("SELECT request_id FROM assignments WHERE status='queued'").all().map(a=>a.request_id));
185
186
  const timelines=new Map();
186
- for(const row of rows) { row.ms=Date.parse(row.at); (timelines.get(row.request_id)??timelines.set(row.request_id,[]).get(row.request_id)).push(row); }
187
+ for(const row of rows) { if(row.type==='completed'&&row.source==='backfill'&&row.reason?.endsWith(';late')) continue; row.ms=Date.parse(row.at); (timelines.get(row.request_id)??timelines.set(row.request_id,[]).get(row.request_id)).push(row); }
187
188
  // delta = [ms, queued, claims, stale (queued longer than the pickup budget), completion marker, worker active (a claim event by the worker within activeGapMs), owner break]
188
189
  const deltas=[], work=[], pickups=[];
189
190
  const queuedSpan=(from,to)=>{ deltas.push([from,1,0,0,0],[to,-1,0,0,0]); if(to-from>pickupBudgetMs) deltas.push([from+pickupBudgetMs,0,0,1,0],[to,0,0,-1,0]); };
@@ -226,7 +227,15 @@ function laneUtilization(store,laneCapacity,nowMs,firstEventMs,rolledUpBefore) {
226
227
 
227
228
  export function lifecycleMetrics(store,{since=null,laneCapacity=store.limits.laneCapacity??6}={}) {
228
229
  const db=store.db, nowMs=store.nowMs();
229
- if(since!==null&&(!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(since)||!Number.isFinite(Date.parse(since)))) throw new Error('since must be an RFC 3339 time with offset');
230
+ if (since !== null) {
231
+ const match = typeof since === 'string' && /^(\d{4})-(\d{2})-(\d{2})T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.exec(since);
232
+ const [,y,m,d] = match || [];
233
+ const year = Number(y), month = Number(m), day = Number(d);
234
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
235
+ const lastDay = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
236
+ if (!match || !(day >= 1 && day <= lastDay) || !Number.isFinite(Date.parse(since)))
237
+ throw new Error('since must be an RFC 3339 time with offset');
238
+ }
230
239
  const sinceMs=since===null?nowMs-defaultWindowMs:Date.parse(since), sinceText=new Date(sinceMs).toISOString();
231
240
  if(sinceMs>=nowMs) throw new Error('since must be in the past');
232
241
  const rolledUpBefore=db.prepare('SELECT rolled_up_before FROM lifecycle_retention WHERE id=1').get().rolled_up_before;
@@ -264,6 +273,18 @@ export function lifecycleMetrics(store,{since=null,laneCapacity=store.limits.lan
264
273
  const duration=value=>rolledUp?unknown('rolled up'):metric(value,'ms');
265
274
  const windowed=rows.filter(inWindow);
266
275
  const count=type=>windowed.filter(e=>e.type===type).length;
276
+ const kindTrack=new Map();
277
+ const track=kind=>kindTrack.get(kind)??kindTrack.set(kind,{
278
+ n:0,outcomes:{completed:0,blocked:0,failed:0},checks:{passed:0,failed:0,skipped:0},acceptance:{accepted:0,rejected:0,unknown:0}
279
+ }).get(kind);
280
+ for(const e of windowed) {
281
+ if(e.type==='completed') {
282
+ const row=track(e.kind), outcome=/^outcome=(completed|blocked|failed)(?:;|$)/.exec(e.reason??'')?.[1];
283
+ if(outcome) row.outcomes[outcome]++;
284
+ } else if(e.type==='check_passed'||e.type==='check_failed'||e.type==='check_skipped') {
285
+ track(e.kind).checks[e.type.slice('check_'.length)]++;
286
+ }
287
+ }
267
288
  const backfilled=windowed.some(e=>e.source==='backfill');
268
289
  // Throughput: completed (terminal worker report) events per UTC day and kind, plus daily roll-ups when the window reaches them.
269
290
  const perDay=new Map();
@@ -289,10 +310,15 @@ export function lifecycleMetrics(store,{since=null,laneCapacity=store.limits.lan
289
310
  const repeated=name=>coverage.keyed?{value:repeat[name].value,unit:'count',n:coverage.keyed,by_source:repeat[name].by_source}:unknown(noKey);
290
311
  // Owner acceptance of requests whose terminal report landed in the window. The latest verdict wins.
291
312
  const verdicts={accepted:0,rejected:0,consumed_only:0,unknown:0};
292
- for(const [requestId,events] of timelines) {
293
- if(!events.some(e=>e.type==='completed'&&inWindow(e))) continue;
313
+ for(const events of timelines.values()) {
314
+ const done=events.find(e=>e.type==='completed'&&inWindow(e));
315
+ if(!done) continue;
294
316
  const verdict=events.filter(e=>e.type==='accepted'||e.type==='consumed'&&/^rejected/.test(e.reason??'')).at(-1);
295
- verdicts[verdict?verdict.type==='accepted'?'accepted':'rejected':events.some(e=>e.type==='consumed')?'consumed_only':'unknown']++;
317
+ const label=verdict?verdict.type==='accepted'?'accepted':'rejected':events.some(e=>e.type==='consumed')?'consumed_only':'unknown';
318
+ verdicts[label]++;
319
+ const row=track(done.kind);
320
+ row.n++;
321
+ if(label!=='consumed_only') row.acceptance[label]++;
296
322
  }
297
323
  const finished=Object.values(verdicts).reduce((a,b)=>a+b,0);
298
324
  const passed=count('check_passed'), failed=count('check_failed'), skipped=count('check_skipped');
@@ -328,12 +354,21 @@ export function lifecycleMetrics(store,{since=null,laneCapacity=store.limits.lan
328
354
  rework:repeated('rework'),
329
355
  duplicates:repeated('duplicates'),
330
356
  objective_coverage:coverage.total?{value:Math.round(coverage.keyed/coverage.total*1000)/1000,unit:'ratio',keyed:coverage.keyed,total:coverage.total,by_source:coverage.by_source}:unknown('no assignment was submitted in the window'),
331
- // Output filed after cancel. Not a completion: throughput counts results only; late reports before migration 42 stay counted as completed.
332
- late_evidence:metric(db.prepare('SELECT count(*) n FROM late_evidence WHERE created_at>=?').get(sinceText).n,'count'),
357
+ // Pre-migration late reports and current late evidence are separate storage paths.
358
+ late_evidence:metric(db.prepare('SELECT (SELECT count(*) FROM late_evidence WHERE created_at>=?) + (SELECT count(*) FROM reports WHERE late=1 AND created_at>=?) n').get(sinceText,sinceText).n,'count'),
333
359
  orphaned_claims:{current:metric(store.claims().filter(c=>c.expired).length,'count'),lease_expired_takeovers:metric(windowed.filter(e=>e.type==='abandoned'&&/^lease_expired\b/.test(e.reason??'')).length,'count'),abandoned:metric(count('abandoned'),'count')},
334
360
  checks:{passed:metric(passed,'count'),failed:metric(failed,'count'),skipped:metric(skipped,'count'),pass_rate:ratio(passed,passed+failed+skipped,'ratio','no check passed, failed or skipped in the window'),started:metric(count('check_started'),'count')},
335
361
  acceptance:{finished:metric(finished,'count'),accepted:metric(verdicts.accepted,'count'),rejected:metric(verdicts.rejected,'count'),consumed_only:metric(verdicts.consumed_only,'count'),unknown:metric(verdicts.unknown,'count'),
336
362
  accept_rate:ratio(verdicts.accepted,verdicts.accepted+verdicts.rejected,'ratio','no owner accept or reject in the window'),integrated:metric(count('integrated'),'count')},
363
+ // Only unrolled events retain outcome and verdict detail. Consumed-only is still included in n.
364
+ by_kind:Object.fromEntries([...kindTrack].map(([kind,row])=>[kind,{
365
+ n:metric(row.n,'count'),
366
+ outcomes:Object.fromEntries(Object.entries(row.outcomes).map(([key,value])=>[key,metric(value,'count')])),
367
+ checks:{...Object.fromEntries(Object.entries(row.checks).map(([key,value])=>[key,metric(value,'count')])),
368
+ pass_rate:ratio(row.checks.passed,row.checks.passed+row.checks.failed+row.checks.skipped,'ratio','no check passed, failed or skipped in the window')},
369
+ acceptance:{...Object.fromEntries(Object.entries(row.acceptance).map(([key,value])=>[key,metric(value,'count')])),
370
+ accept_rate:ratio(row.acceptance.accepted,row.acceptance.accepted+row.acceptance.rejected,'ratio','no owner accept or reject in the window')},
371
+ }])),
337
372
  notes,
338
373
  };
339
374
  }
@@ -0,0 +1,46 @@
1
+ import http from 'node:http';
2
+
3
+ // A bridge that stops answering leaves no trace in its own request log: a request that never reaches a handler is never logged.
4
+ // The probe asks the bridge's own loopback listener a question on a timer and records how long the answer took, plus how late the
5
+ // timer itself fired (the event loop's lag). A stall then shows up in the log and in `dalan status --json` as a number.
6
+ const answered = (url, timeoutMs) => new Promise(resolve => {
7
+ const req = http.get(url, { agent: false, timeout: timeoutMs }, res => { res.resume(); res.once('end', () => resolve({ status: res.statusCode })); res.once('error', error => resolve({ error: error.code ?? 'error' })); });
8
+ req.once('timeout', () => { req.destroy(); resolve({ error: 'timeout' }); });
9
+ req.once('error', error => resolve({ error: error.code ?? 'error' }));
10
+ });
11
+
12
+ export function createLoopbackProbe({
13
+ url, log, intervalMs = 30000, slowMs = 1000, timeoutMs = 30000, heartbeatEvery = 10, keep = 120,
14
+ request = answered, clock = () => Number(process.hrtime.bigint()) / 1e6, wall = () => new Date().toISOString(),
15
+ } = {}) {
16
+ const samples = [];
17
+ let timer = null, expectedAt = null, count = 0, running = false;
18
+ const record = sample => { samples.push(sample); if (samples.length > keep) samples.shift(); };
19
+ const percentile = (values, p) => values.length ? [...values].sort((a, b) => a - b)[Math.min(values.length - 1, Math.floor(values.length * p))] : null;
20
+ async function tick() {
21
+ const lagMs = expectedAt === null ? 0 : Math.max(0, Math.round(clock() - expectedAt));
22
+ if (running) return; running = true;
23
+ try {
24
+ const started = clock();
25
+ const result = await request(typeof url === 'function' ? url() : url, timeoutMs);
26
+ const ms = Math.round(clock() - started);
27
+ const sample = { at: wall(), ms, lag_ms: lagMs, ...(result.error ? { error: result.error } : { status: result.status }) };
28
+ record(sample); count++;
29
+ if (result.error || ms >= slowMs || lagMs >= slowMs) log({ kind: 'loopback_probe_slow', ms, lag_ms: lagMs, ...(result.error ? { error: result.error } : { status: result.status }) });
30
+ else if (count % heartbeatEvery === 0) {
31
+ const recent = samples.slice(-heartbeatEvery);
32
+ log({ kind: 'loopback_probe', samples: recent.length, p50_ms: percentile(recent.map(s => s.ms), 0.5), max_ms: Math.max(...recent.map(s => s.ms)), max_lag_ms: Math.max(...recent.map(s => s.lag_ms)) });
33
+ }
34
+ } finally { running = false; expectedAt = clock() + intervalMs; }
35
+ }
36
+ return {
37
+ start() { if (timer === null) { expectedAt = clock() + intervalMs; timer = setInterval(() => { tick().catch(() => {}); }, intervalMs); timer.unref(); } return this; },
38
+ stop() { if (timer !== null) { clearInterval(timer); timer = null; } },
39
+ tick,
40
+ // For `dalan status --json`: the last answer, and the worst of the samples kept (about an hour at the default interval).
41
+ snapshot() {
42
+ const last = samples.at(-1) ?? null;
43
+ return { interval_ms: intervalMs, samples: samples.length, last, worst_ms: samples.length ? Math.max(...samples.map(s => s.ms)) : null, worst_lag_ms: samples.length ? Math.max(...samples.map(s => s.lag_ms)) : null, failures: samples.filter(s => s.error).length };
44
+ },
45
+ };
46
+ }
@@ -4,6 +4,8 @@ import { redactNote } from './alerts.mjs';
4
4
 
5
5
  const responses = new WeakMap();
6
6
 
7
+ // `worker` is the configured worker name the verified connection maps to (set after auth; null before it), so a call can be
8
+ // attributed to one worker. It is a name from the owner's workers.json, never a client-provided string.
7
9
  // The caller's class, never its text: a User-Agent can hold anything, including a credential, so only a name from this fixed
8
10
  // list is logged ("other" for the rest, null when absent). That is enough to tell an Anthropic or OpenAI caller from a generic one.
9
11
  const UA_CLASSES = [['Claude-User', /^claude-user/i], ['ClaudeBot', /^claudebot/i], ['anthropic-ai', /^anthropic-ai/i], ['ChatGPT-User', /^chatgpt-user/i], ['OAI-SearchBot', /^oai-searchbot/i],
@@ -24,7 +26,7 @@ export function beginMcpOutcome(req, res, log, toolNames, authRequired) {
24
26
  const state = {
25
27
  call_id: randomUUID(), started_at: new Date().toISOString(),
26
28
  http_method: ['POST', 'GET', 'DELETE', 'PUT', 'PATCH', 'HEAD', 'OPTIONS'].includes(req.method) ? req.method : 'other',
27
- rpc_method: null, tool: null, request_id: null, phase: authRequired ? 'auth' : 'body', auth_outcome: authRequired ? 'pending' : 'disabled',
29
+ rpc_method: null, tool: null, request_id: null, worker: null, phase: authRequired ? 'auth' : 'body', auth_outcome: authRequired ? 'pending' : 'disabled',
28
30
  auth_reason: null, auth_duration_ms: null, jwks_outcome: 'not_attempted',
29
31
  jwks_duration_ms: null, jwks_http_status: null,
30
32
  rpc_error_code: null, tool_error: null, tool_error_message: null, response_bytes: 0,
package/src/mcp-sse.mjs CHANGED
@@ -22,7 +22,8 @@ export function beginMcpEventStream(res, { heartbeatMs = 20_000, setIntervalFn =
22
22
  res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache, no-transform' });
23
23
  const heartbeat = () => {
24
24
  if (!active || res.destroyed) { stop(); return; }
25
- res.write(HEARTBEAT);
25
+ try { res.write(HEARTBEAT); }
26
+ catch { stop(); res.destroy(); return; }
26
27
  writtenBytes += Buffer.byteLength(HEARTBEAT);
27
28
  };
28
29
  heartbeat();