@tnunamak/dalan 0.8.0 → 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 (130) hide show
  1. package/CHANGELOG.md +70 -1
  2. package/CONTRIBUTING.md +2 -0
  3. package/PROTOCOL.md +6 -0
  4. package/README.md +8 -12
  5. package/bin/dalan.mjs +25 -4
  6. package/bin/dot-acp-agent.mjs +572 -76
  7. package/bin/dot-alert.mjs +9 -3
  8. package/bin/dot-deadman.mjs +3 -1
  9. package/bin/dot-heartbeat.mjs +14 -7
  10. package/bin/dot-pr-reviewer.mjs +3 -31
  11. package/bin/dot-worker.mjs +215 -40
  12. package/contracts/adapter-qualification.schema.json +94 -7
  13. package/docs/chatgpt-worker-onboarding.md +1 -1
  14. package/docs/codex-to-muse.md +2 -2
  15. package/docs/connect-chatgpt.md +1 -1
  16. package/docs/connection-longevity.md +2 -2
  17. package/docs/dalan-upgrade.md +8 -5
  18. package/docs/deadman.md +4 -0
  19. package/docs/design/authority-matrix.md +18 -0
  20. package/docs/design/failure-table.md +87 -0
  21. package/docs/design/identities.md +22 -0
  22. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  23. package/docs/design/reuse-ledger.md +75 -0
  24. package/docs/design/target-architecture-v2.md +434 -0
  25. package/docs/local-agent-mcp.md +14 -0
  26. package/docs/local-agent-requester.md +3 -2
  27. package/docs/manual-setup.md +1 -1
  28. package/docs/operations.md +78 -14
  29. package/docs/pull-workers.md +11 -0
  30. package/docs/relationships.md +13 -0
  31. package/docs/service-setup.md +10 -10
  32. package/docs/t3-integration.md +6 -2
  33. package/docs/t3-reverse-control.md +5 -5
  34. package/docs/t3-wake-fence-r4.md +1 -1
  35. package/docs/test-suite-isolation.md +8 -6
  36. package/docs/trials/chatgpt-agent.md +47 -0
  37. package/docs/trials/claude-code-requester.md +68 -0
  38. package/docs/trials/muse.md +46 -0
  39. package/docs/usage.md +35 -9
  40. package/docs/worker-clients.md +1 -1
  41. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  42. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  43. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  44. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  45. package/package.json +4 -3
  46. package/packages/job-core/protocol/canonical.mjs +45 -7
  47. package/packages/job-core/transitions.mjs +4 -2
  48. package/scripts/upgrade-drain.mjs +96 -8
  49. package/scripts/worker-bridge-setup.mjs +215 -120
  50. package/src/ack-ledger.mjs +7 -1
  51. package/src/acp-bridge.mjs +256 -28
  52. package/src/admin-socket.mjs +32 -3
  53. package/src/alerts.mjs +17 -8
  54. package/src/answer-journal-retention.mjs +82 -0
  55. package/src/answer-journal.mjs +6 -4
  56. package/src/as-store.mjs +51 -6
  57. package/src/as.mjs +27 -5
  58. package/src/catalog-switch-inventory.mjs +70 -0
  59. package/src/check-response.mjs +4 -1
  60. package/src/claim-command-ledger.mjs +3 -2
  61. package/src/cli-help.mjs +29 -10
  62. package/src/cli-name.mjs +13 -1
  63. package/src/connect-cli.mjs +159 -4
  64. package/src/deadman.mjs +8 -5
  65. package/src/delivery.mjs +2 -19
  66. package/src/destinations/index.mjs +75 -14
  67. package/src/drain-runner.mjs +5 -1
  68. package/src/follow-current.mjs +3 -1
  69. package/src/get-summary.mjs +11 -2
  70. package/src/git-env.mjs +1 -1
  71. package/src/gozar-routes.mjs +313 -94
  72. package/src/host-budget-storage.py +56 -6
  73. package/src/host-budget.mjs +98 -15
  74. package/src/host-execution-policy.mjs +17 -6
  75. package/src/inbox.mjs +13 -3
  76. package/src/legacy-names.mjs +0 -2
  77. package/src/lifecycle.mjs +104 -11
  78. package/src/loopback-probe.mjs +46 -0
  79. package/src/mcp-outcome.mjs +3 -1
  80. package/src/mcp-sse.mjs +2 -1
  81. package/src/mcp-stdio.mjs +192 -30
  82. package/src/patch-apply.mjs +285 -19
  83. package/src/phase-trace.mjs +73 -0
  84. package/src/prepared-go-modules.mjs +127 -0
  85. package/src/prepared-node-modules.mjs +225 -38
  86. package/src/prepared-pnpm.mjs +276 -0
  87. package/src/prepared-store-prune.mjs +52 -0
  88. package/src/projects.mjs +59 -7
  89. package/src/protocol-artifact-commands.mjs +28 -0
  90. package/src/protocol-finish.mjs +3 -2
  91. package/src/publication-authority.mjs +22 -0
  92. package/src/publish-plan.mjs +2 -2
  93. package/src/pull-queue.mjs +55 -20
  94. package/src/read-api.mjs +127 -0
  95. package/src/redaction.mjs +173 -0
  96. package/src/rejections.mjs +19 -3
  97. package/src/route-custody.mjs +90 -0
  98. package/src/route-publication.mjs +50 -0
  99. package/src/route-setup.mjs +184 -0
  100. package/src/schema-subset.mjs +5 -3
  101. package/src/server.mjs +619 -88
  102. package/src/service-launchd.mjs +5 -1
  103. package/src/service-update-lock.mjs +7 -4
  104. package/src/service-update-runtime.mjs +64 -19
  105. package/src/service-update.mjs +193 -48
  106. package/src/service.mjs +276 -77
  107. package/src/setup.mjs +48 -25
  108. package/src/signal.mjs +1 -1
  109. package/src/status-evidence.mjs +18 -5
  110. package/src/status-summary.mjs +3 -0
  111. package/src/store.mjs +1086 -127
  112. package/src/submission-policy.mjs +257 -56
  113. package/src/t3-control.mjs +1 -1
  114. package/src/t3.mjs +14 -8
  115. package/src/terminal-safe.mjs +9 -7
  116. package/src/tool-registry.mjs +134 -41
  117. package/src/try-exposure.mjs +53 -86
  118. package/src/try-hosted.mjs +257 -70
  119. package/src/try.mjs +48 -22
  120. package/src/work-order.mjs +11 -6
  121. package/src/worker-instructions.mjs +26 -4
  122. package/src/worker-runs.mjs +35 -0
  123. package/src/workers.mjs +49 -4
  124. package/src/workspace.mjs +354 -54
  125. package/systemd/dot-deadman.service +3 -1
  126. package/docs/dot-pr-reviewer.config.example.json +0 -9
  127. package/docs/pr-head-reviewer.md +0 -70
  128. package/src/pr-head-reviewer.mjs +0 -596
  129. package/systemd/dot-pr-reviewer.service +0 -11
  130. 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}`;
package/src/inbox.mjs CHANGED
@@ -2,14 +2,23 @@
2
2
  // bin/dot-worker.mjs does the reads. Nothing here, or in the batch read behind it, records an owner read.
3
3
 
4
4
  import { terminalSafeLine } from './terminal-safe.mjs';
5
- export const inboxGroups=['finished_unread','question','undecided','cancelled_unread'];
5
+ export const inboxGroups=['finished_unread','question','undecided','cancelled_unread','held_wake'];
6
6
  export const decideWords='accepted|applied|useful_no_change|useful_negative|not_useful';
7
7
  const firstLine=text=>{ const line=String(text).split('\n').find(l=>l.trim())?.trim()??''; return line.length>100?line.slice(0,97)+'...':line; };
8
8
 
9
- // One owner-states row to an inbox item, or null when the owner has nothing to do for it.
9
+ // One owner-states row to an inbox item, or null when the owner has nothing to do for it. A wake held because the parent
10
+ // stopped is not owner work: it marks the item the request already has, and only a request with no other item gets its own
11
+ // held_wake line, so the owner can see why a result or question did not reach the parent.
10
12
  export function inboxItem(state) {
11
13
  const v=state.inbox;
12
14
  if(!v||state.error) return null;
15
+ const item=ownerItem(state,v), held=v.held_wake;
16
+ if(!held) return item;
17
+ const wake_held={kind:held.kind,reason:held.reason,detail:held.detail,since:held.since};
18
+ if(item) return {...item,wake_held};
19
+ return {group:'held_wake',request_id:state.request_id,worker:v.target_worker,title:firstLine(v.brief),status:state.status,wake_held,updated_at:held.since,next:[`dalan get ${state.request_id}`]};
20
+ }
21
+ function ownerItem(state,v) {
13
22
  const base={request_id:state.request_id,worker:v.target_worker,title:firstLine(v.brief)};
14
23
  const failure=v.failure_type?{failure_type:v.failure_type,failure_type_source:v.failure_type_source}:{};
15
24
  const get=`dalan get ${state.request_id}`;
@@ -47,7 +56,8 @@ export function formatInbox(inbox) {
47
56
  if(!inbox.total) return hidden?`inbox empty\n${hidden}`:'inbox empty';
48
57
  const lines=[];
49
58
  for(const g of inboxGroups) for(const i of inbox.items.filter(x=>x.group===g)) {
50
- const why=i.group==='cancelled_unread'?` (${i.reason??'cancelled'})`:i.group==='question'?` ${i.text}`:'';
59
+ const held=i.wake_held?` [wake held: ${i.wake_held.reason}${i.wake_held.detail?`, ${i.wake_held.detail}`:''}; it sends when the parent runs again]`:'';
60
+ const why=(i.group==='cancelled_unread'?` (${i.reason??'cancelled'})`:i.group==='question'?` ${i.text}`:'')+held;
51
61
  lines.push(terminalSafeLine(`${g} ${i.request_id} ${i.worker} ${i.status} ${i.updated_at??''} ${i.title}${why} -> ${i.next.join(' | ')}`));
52
62
  }
53
63
  lines.push(`${inbox.total} item${inbox.total===1?'':'s'}: ${inboxGroups.map(g=>`${inbox.counts[g]} ${g}`).join(', ')}${hidden?`; ${hidden}`:''}`);
@@ -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
@@ -1,7 +1,12 @@
1
1
  // Append-only lifecycle events: one row per state change, written in the same transaction as the change.
2
2
  // Metrics derive from these rows only; anything the rows cannot show is reported as unknown with a reason, never as zero.
3
3
  import { fromStoredSource, canonicalObjectiveKey, canonicalKindSql, canonicalKindLabel } from './objectives.mjs';
4
- export const lifecycleTypes=['queued','claimed','working','waiting','blocked','completed','consumed','accepted','integrated','abandoned','cancelled','delivery_sent','delivery_uncertain','reconciled','check_started','check_passed','check_failed','check_skipped'];
4
+ // The control vocabulary: what an owner or operator asked to stop, release or withdraw. Each event names the scope it
5
+ // acted on (scope) and whether that effect is known (outcome). A request to something outside the store is 'unknown'
6
+ // until an observation says otherwise; 'done' means the store itself made the change in the same transaction.
7
+ export const controlTypes=['detach','interrupt_foreground','withdraw_work','revoke_grant'];
8
+ export const controlOutcomes=['done','confirmed','unknown'];
9
+ export const lifecycleTypes=['queued','claimed','working','waiting','blocked','completed','consumed','accepted','integrated','abandoned','cancelled','delivery_sent','delivery_uncertain','reconciled','check_started','check_passed','check_failed','check_skipped','wake_held',...controlTypes];
5
10
  export const retentionDays=90;
6
11
  // Two consecutive claim activity events no more than this far apart count as working time (see docs/usage.md, "Metrics").
7
12
  export const activeGapMs=20*60000;
@@ -14,7 +19,8 @@ export const progressType=(note,blocker=false)=>blocker||/^\s*BLOCKED:/im.test(n
14
19
  // Retention deletes go through one guarded path: the trigger admits a DELETE only for rows older than the cutoff that
15
20
  // retainLifecycle sets and clears inside its own transaction. This guards against accidental writes, not against a
16
21
  // process that can rewrite the schema.
17
- export const lifecycleSchema=`CREATE TABLE IF NOT EXISTS lifecycle_events (id INTEGER PRIMARY KEY AUTOINCREMENT, request_id TEXT NOT NULL, claim_id TEXT, epoch INTEGER, type TEXT NOT NULL CHECK(type IN (${lifecycleTypes.map(t=>`'${t}'`).join(',')})), at TEXT NOT NULL, actor TEXT NOT NULL, source TEXT NOT NULL CHECK(source IN ('live','backfill')), reason TEXT);
22
+ const lifecycleTableBody=`id INTEGER PRIMARY KEY AUTOINCREMENT, request_id TEXT NOT NULL, claim_id TEXT, epoch INTEGER, type TEXT NOT NULL CHECK(type IN (${lifecycleTypes.map(t=>`'${t}'`).join(',')})), at TEXT NOT NULL, actor TEXT NOT NULL, source TEXT NOT NULL CHECK(source IN ('live','backfill')), reason TEXT`;
23
+ export const lifecycleSchema=`CREATE TABLE IF NOT EXISTS lifecycle_events (${lifecycleTableBody});
18
24
  CREATE INDEX IF NOT EXISTS lifecycle_events_request ON lifecycle_events(request_id,id);
19
25
  CREATE INDEX IF NOT EXISTS lifecycle_events_type_at ON lifecycle_events(type,at);
20
26
  CREATE TABLE IF NOT EXISTS lifecycle_daily (day TEXT NOT NULL, type TEXT NOT NULL, kind TEXT NOT NULL, count INTEGER NOT NULL, PRIMARY KEY(day,type,kind));
@@ -23,6 +29,58 @@ export const lifecycleSchema=`CREATE TABLE IF NOT EXISTS lifecycle_events (id IN
23
29
  CREATE TRIGGER IF NOT EXISTS lifecycle_events_no_update BEFORE UPDATE ON lifecycle_events BEGIN SELECT RAISE(ABORT, 'lifecycle events are append-only'); END;
24
30
  CREATE TRIGGER IF NOT EXISTS lifecycle_events_no_delete BEFORE DELETE ON lifecycle_events WHEN NOT EXISTS (SELECT 1 FROM lifecycle_retention WHERE id=1 AND cutoff IS NOT NULL AND old.at<cutoff) BEGIN SELECT RAISE(ABORT, 'lifecycle events are append-only'); END;`;
25
31
 
32
+ // Migration 72. Control events carry the scope they acted on and an outcome. A table made by an earlier release also
33
+ // lists the old types in its CHECK, and SQLite cannot widen a CHECK in place, so that table is rebuilt: same rows, same
34
+ // ids, and the stored text of its indexes and triggers is carried over unchanged. A table made by this release
35
+ // (a fresh database) already lists every type and only gains the two columns.
36
+ export function addControlColumns(db) {
37
+ const table=db.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name='lifecycle_events'").get();
38
+ if(!table) return;
39
+ const has=name=>!!db.prepare("SELECT 1 FROM pragma_table_info('lifecycle_events') WHERE name=?").get(name);
40
+ // A table is current only when its CHECK lists every type this release writes. Naming one type is not enough: a table
41
+ // built part-way through this change can list wake_held and still lack another.
42
+ if(lifecycleTypes.every(t=>table.sql.includes(`'${t}'`))) {
43
+ for(const name of ['scope','outcome']) if(!has(name)) db.exec(`ALTER TABLE lifecycle_events ADD COLUMN ${name} TEXT`);
44
+ return;
45
+ }
46
+ const attached=db.prepare("SELECT type,name,sql FROM sqlite_master WHERE tbl_name='lifecycle_events' AND type IN ('index','trigger') AND sql IS NOT NULL").all();
47
+ const columns=db.prepare("SELECT name FROM pragma_table_info('lifecycle_events')").all().map(c=>c.name);
48
+ const wanted=['id','request_id','claim_id','epoch','type','at','actor','source','reason','worker'];
49
+ const missing=wanted.filter(c=>!columns.includes(c));
50
+ if(missing.length) throw new Error(`lifecycle_events is missing ${missing.join(', ')}; cannot widen its type list`);
51
+ // The rebuild copies a fixed list of columns. A column it does not know would be dropped with its data, so refuse
52
+ // before any DDL runs and leave the database as it was.
53
+ const known=[...wanted,'scope','outcome'];
54
+ const unknown=columns.filter(c=>!known.includes(c));
55
+ if(unknown.length) throw new Error(`lifecycle_events has columns this release does not know: ${unknown.join(', ')}; refusing to rebuild it because that would drop their data`);
56
+ const copied=known.filter(c=>columns.includes(c));
57
+ for(const a of attached) db.exec(`DROP ${a.type.toUpperCase()} ${a.name}`);
58
+ db.exec('ALTER TABLE lifecycle_events RENAME TO lifecycle_events_pre71');
59
+ db.exec(`CREATE TABLE lifecycle_events (${lifecycleTableBody}, worker TEXT NOT NULL DEFAULT 'unknown', scope TEXT, outcome TEXT)`);
60
+ db.exec(`INSERT INTO lifecycle_events(${copied.join(',')}) SELECT ${copied.join(',')} FROM lifecycle_events_pre71 ORDER BY id`);
61
+ // AUTOINCREMENT remembers the highest id ever issued, which can be above the highest id still stored once retention
62
+ // has removed old events. Copying explicit ids restarts it at the copied max, so carry the old mark over or ids repeat.
63
+ const issued=db.prepare("SELECT seq FROM sqlite_sequence WHERE name='lifecycle_events_pre71'").get()?.seq??0;
64
+ db.exec('DROP TABLE lifecycle_events_pre71');
65
+ const kept=db.prepare("SELECT seq FROM sqlite_sequence WHERE name='lifecycle_events'").get()?.seq??0;
66
+ if(Math.max(issued,kept)>0) {
67
+ if(db.prepare("SELECT 1 FROM sqlite_sequence WHERE name='lifecycle_events'").get()) db.prepare("UPDATE sqlite_sequence SET seq=? WHERE name='lifecycle_events'").run(Math.max(issued,kept));
68
+ else db.prepare("INSERT INTO sqlite_sequence(name,seq) VALUES('lifecycle_events',?)").run(Math.max(issued,kept));
69
+ }
70
+ for(const a of attached) db.exec(a.sql);
71
+ }
72
+
73
+ // What a control verb controlled and what it left alone, as text for the owner. ref is the stored scope.
74
+ export function controlScopeText(type,{ref,claimed=false}={}) {
75
+ if(type==='withdraw_work') return {ref,controlled:'the job: its authority is withdrawn, so a result sent after this is kept as audit evidence and not accepted',
76
+ not_controlled:claimed?'worker compute: the worker may still run and report late; nothing here proves it stopped':'nothing was running, so there was no worker compute to stop'};
77
+ if(type==='detach') return {ref,controlled:'the claim: it is released and the job goes back to the queue, and the old claim id stops working',
78
+ not_controlled:'the worker session: it is not stopped, and it may still run until it sees the claim is gone'};
79
+ if(type==='interrupt_foreground') return {ref,controlled:'a request to interrupt the foreground run',not_controlled:'whether the run stopped: the outcome stays unknown until an observation confirms it'};
80
+ if(type==='revoke_grant') return {ref,controlled:'the grant: no new call is admitted under it',not_controlled:'a call already in flight under the grant'};
81
+ throw new Error(`unknown control type ${type}`);
82
+ }
83
+
26
84
  export const checkOutcome=(job,run)=>{
27
85
  const base=`check_id=${job.check_id};check_run_id=${job.id}`;
28
86
  const skipped=job.skipped_segments??run?.skipped_segments??(run?.exit_code===77?1:0);
@@ -54,8 +112,9 @@ export function backfillLifecycle(db) {
54
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);
55
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));
56
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.
57
116
  const claim=byClaimId.get(r.claim_id)??{claim_id:r.claim_id,epoch:null};
58
- 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}`);
59
118
  if(r.outcome==='blocked') add(r.request_id,'blocked',r.created_at,claim);
60
119
  }
61
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()) {
@@ -79,7 +138,7 @@ export function backfillLifecycle(db) {
79
138
  // Events older than the retention window become per-day counts by type and kind, then leave the event table.
80
139
  export function retainLifecycle(store,days=retentionDays) { return store.transaction(()=>{
81
140
  const db=store.db, cutoff=new Date(store.nowMs()-days*86400000).toISOString();
82
- 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
83
142
  ON CONFLICT(day,type,kind) DO UPDATE SET count=count+excluded.count`).run(cutoff);
84
143
  db.prepare('UPDATE lifecycle_retention SET cutoff=? WHERE id=1').run(cutoff);
85
144
  const deleted=db.prepare('DELETE FROM lifecycle_events WHERE at<?').run(cutoff).changes;
@@ -125,7 +184,7 @@ function laneUtilization(store,laneCapacity,nowMs,firstEventMs,rolledUpBefore) {
125
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);
126
185
  const queuedNow=new Set(db.prepare("SELECT request_id FROM assignments WHERE status='queued'").all().map(a=>a.request_id));
127
186
  const timelines=new Map();
128
- 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); }
129
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]
130
189
  const deltas=[], work=[], pickups=[];
131
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]); };
@@ -168,7 +227,15 @@ function laneUtilization(store,laneCapacity,nowMs,firstEventMs,rolledUpBefore) {
168
227
 
169
228
  export function lifecycleMetrics(store,{since=null,laneCapacity=store.limits.laneCapacity??6}={}) {
170
229
  const db=store.db, nowMs=store.nowMs();
171
- 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
+ }
172
239
  const sinceMs=since===null?nowMs-defaultWindowMs:Date.parse(since), sinceText=new Date(sinceMs).toISOString();
173
240
  if(sinceMs>=nowMs) throw new Error('since must be in the past');
174
241
  const rolledUpBefore=db.prepare('SELECT rolled_up_before FROM lifecycle_retention WHERE id=1').get().rolled_up_before;
@@ -206,6 +273,18 @@ export function lifecycleMetrics(store,{since=null,laneCapacity=store.limits.lan
206
273
  const duration=value=>rolledUp?unknown('rolled up'):metric(value,'ms');
207
274
  const windowed=rows.filter(inWindow);
208
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
+ }
209
288
  const backfilled=windowed.some(e=>e.source==='backfill');
210
289
  // Throughput: completed (terminal worker report) events per UTC day and kind, plus daily roll-ups when the window reaches them.
211
290
  const perDay=new Map();
@@ -231,10 +310,15 @@ export function lifecycleMetrics(store,{since=null,laneCapacity=store.limits.lan
231
310
  const repeated=name=>coverage.keyed?{value:repeat[name].value,unit:'count',n:coverage.keyed,by_source:repeat[name].by_source}:unknown(noKey);
232
311
  // Owner acceptance of requests whose terminal report landed in the window. The latest verdict wins.
233
312
  const verdicts={accepted:0,rejected:0,consumed_only:0,unknown:0};
234
- for(const [requestId,events] of timelines) {
235
- 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;
236
316
  const verdict=events.filter(e=>e.type==='accepted'||e.type==='consumed'&&/^rejected/.test(e.reason??'')).at(-1);
237
- 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]++;
238
322
  }
239
323
  const finished=Object.values(verdicts).reduce((a,b)=>a+b,0);
240
324
  const passed=count('check_passed'), failed=count('check_failed'), skipped=count('check_skipped');
@@ -270,12 +354,21 @@ export function lifecycleMetrics(store,{since=null,laneCapacity=store.limits.lan
270
354
  rework:repeated('rework'),
271
355
  duplicates:repeated('duplicates'),
272
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'),
273
- // Output filed after cancel. Not a completion: throughput counts results only; late reports before migration 42 stay counted as completed.
274
- 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'),
275
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')},
276
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')},
277
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'),
278
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
+ }])),
279
372
  notes,
280
373
  };
281
374
  }