@tnunamak/dalan 0.8.1 → 0.8.3

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 +61 -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 +136 -21
  100. package/src/service-update.mjs +207 -51
  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
@@ -1,3 +1,4 @@
1
+ import { materialize } from './patch-apply.mjs';
1
2
  import { defaultPath } from './paths.mjs';
2
3
  // Bridge-facing pieces of the ACP adapter (bin/dot-acp-agent.mjs): the admin-socket client, the owner token, brief and
3
4
  // request-id rules, submit eligibility and the payload builder. Nothing here speaks ACP.
@@ -14,7 +15,7 @@ import { redactLogEntry } from './redaction.mjs';
14
15
  import { submissionLimits } from './submission-policy.mjs';
15
16
  import { readOrCreateSecret, ownerToken } from '../integrations/t3/acp-kit/src/capability.mjs';
16
17
  import { CONTINUE_PROMPT, promptText, unwrapUserRequest, isT3RuntimeBlock, parseIdentity } from '../integrations/t3/acp-kit/src/t3-envelope.mjs';
17
- import { adminSocketPathError } from './admin-socket.mjs';
18
+ import { adminSocketPathError, adminSocketPath } from './admin-socket.mjs';
18
19
 
19
20
  // Shared with external ACP adapters: integrations/t3/acp-kit.
20
21
  export { readOrCreateSecret, ownerToken, CONTINUE_PROMPT, promptText, unwrapUserRequest, isT3RuntimeBlock };
@@ -25,7 +26,7 @@ const idPattern = /^[-\w]{8,128}$/;
25
26
  export function paths(env = process.env) {
26
27
  const home = os.homedir();
27
28
  return {
28
- socket: env.DOT_ACP_SOCKET || defaultPath(home,'.local/share/dot-bridge/admin.sock'),
29
+ socket: env.DOT_ACP_SOCKET || adminSocketPath(defaultPath(home,'.local/share/dot-bridge')),
29
30
  secretFile: env.DOT_ACP_SECRET_FILE || defaultPath(home,'.config/dot-bridge/acp-secret'),
30
31
  stateDir: env.DOT_ACP_STATE_DIR || defaultPath(home,'.local/state/dot-bridge/acp'),
31
32
  };
@@ -37,9 +38,18 @@ export class BridgeError extends Error {
37
38
  }
38
39
  export const transient = e => e.kind === 'transport' || e.http_status >= 500;
39
40
 
41
+ const isReplyRecord = value => value !== null && typeof value === 'object' && !Array.isArray(value);
42
+ function validAdminVerdict(value) {
43
+ return ['admissible', 'clarify', 'reject', 'defer'].includes(value.verdict) &&
44
+ Array.isArray(value.reasons) && value.reasons.every(reason =>
45
+ isReplyRecord(reason) && typeof reason.message === 'string' && typeof reason.fix === 'string' &&
46
+ (reason.candidates === undefined || (Array.isArray(reason.candidates) &&
47
+ reason.candidates.every(candidate => typeof candidate === 'string'))));
48
+ }
49
+
40
50
  export function adminRequest(socket, route, { method = 'GET', payload, token, signal, timeoutMs } = {}) {
41
51
  const positive = (value, fallback) => Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) : fallback;
42
- const baseMs = positive(process.env.DOT_ACP_HTTP_TIMEOUT_MS, 5000);
52
+ const baseMs = positive(process.env.DOT_ACP_HTTP_TIMEOUT_MS, 20000);
43
53
  const graceMs = positive(process.env.DOT_ACP_HTTP_GRACE_MS, 1000);
44
54
  const url = new URL(route, 'http://localhost');
45
55
  const pollMs = url.pathname === '/wait' ? positive(url.searchParams.get('timeout'), 30) * 1000 : 0;
@@ -60,6 +70,11 @@ export function adminRequest(socket, route, { method = 'GET', payload, token, si
60
70
  clearTimeout(timer);
61
71
  let value;
62
72
  try { value = JSON.parse(out); } catch { return fail(new Error('invalid admin response')); }
73
+ const admission = url.pathname === '/submit' || url.pathname === '/submit-preview';
74
+ const previewSuccess = url.pathname === '/submit-preview' && res.statusCode >= 200 && res.statusCode < 300;
75
+ if (!isReplyRecord(value) || ((previewSuccess || (admission && Object.hasOwn(value, 'verdict'))) && !validAdminVerdict(value))) {
76
+ return fail(new Error('invalid admin response'));
77
+ }
63
78
  if (res.statusCode < 200 || res.statusCode >= 300) reject(Object.assign(new BridgeError(value?.error || `HTTP ${res.statusCode}`, 'http', res.statusCode), value?.verdict ? { verdict: value.verdict, reasons: value.reasons, bytes: value.bytes, retry_after_seconds: value.retry_after_seconds } : {}));
64
79
  else resolve(value);
65
80
  });
@@ -70,20 +85,54 @@ export function adminRequest(socket, route, { method = 'GET', payload, token, si
70
85
  });
71
86
  }
72
87
 
88
+ // A bridge restart closes the admin socket for about two minutes and, just before it, answers writes with bridge_quiescing.
89
+ // Neither sent anything the bridge acted on, so the call is safe to repeat: a refused connect (the socket is gone or not yet
90
+ // listening) and a bridge_quiescing answer are retried until the budget (DOT_ACP_RESTART_RETRY_MS, default 150 s) is spent.
91
+ // A read (GET) is also retried after a deadline, since repeating a read changes nothing. A write that timed out after it was
92
+ // sent is not repeated here: whether it landed is the caller's own idempotency question (request_id conflict handling).
93
+ export async function adminRequestThroughRestart(socket, route, options = {}) {
94
+ const budgetMs = Number.isFinite(Number(process.env.DOT_ACP_RESTART_RETRY_MS)) ? Number(process.env.DOT_ACP_RESTART_RETRY_MS) : 150000;
95
+ const stepMs = Number.isFinite(Number(process.env.DOT_ACP_RESTART_RETRY_STEP_MS)) ? Number(process.env.DOT_ACP_RESTART_RETRY_STEP_MS) : 2000;
96
+ const until = Date.now() + budgetMs;
97
+ const read = (options.method ?? 'GET') === 'GET';
98
+ for (;;) {
99
+ try { return await adminRequest(socket, route, options); }
100
+ catch (e) {
101
+ const unsent = ['ECONNREFUSED', 'ENOENT'].includes(e.code) || /ECONNREFUSED|ENOENT/.test(e.message ?? '');
102
+ const quiescing = /bridge_quiescing/.test(e.message ?? '');
103
+ const retry = unsent || quiescing || (read && e.kind === 'transport');
104
+ if (!retry || options.signal?.aborted || Date.now() + stepMs > until) throw e;
105
+ await new Promise(resolve => setTimeout(resolve, stepMs));
106
+ }
107
+ }
108
+ }
109
+
73
110
  // Raw artifact bytes (the admin route answers octet-stream, not JSON). Resolves null on any failure: evidence is best effort.
74
- export function adminArtifact(socket, artifactId, token, timeoutMs = 5000) {
111
+ export function adminArtifact(socket, artifactId, token, timeoutMs = 5000, wallClockMs = 30_000) {
75
112
  return new Promise(resolve => {
113
+ let timer, settled = false;
114
+ const finish = value => {
115
+ if (settled) return false;
116
+ settled = true;
117
+ clearTimeout(timer);
118
+ resolve(value);
119
+ return true;
120
+ };
76
121
  const req = http.request({ socketPath: socket, path: `/artifact?id=${encodeURIComponent(artifactId)}`, headers: { 'x-owner-capability': token } }, res => {
77
122
  const chunks = [];
78
- res.on('data', b => chunks.push(b));
79
- res.on('error', () => resolve(null));
123
+ res.on('data', b => { if (!settled) chunks.push(b); });
124
+ res.on('error', () => finish(null));
125
+ res.on('aborted', () => finish(null));
80
126
  res.on('end', () => {
127
+ if (settled) return;
81
128
  const data = Buffer.concat(chunks);
82
- resolve(res.statusCode === 200 && sha256(data) === res.headers['x-artifact-sha256'] ? data : null);
129
+ finish(res.statusCode === 200 && sha256(data) === res.headers['x-artifact-sha256'] ? data : null);
83
130
  });
84
131
  });
85
- req.on('error', () => resolve(null));
86
- req.setTimeout(timeoutMs, () => req.destroy());
132
+ req.on('error', () => finish(null));
133
+ const expire = () => { if (finish(null)) req.destroy(); };
134
+ req.setTimeout(timeoutMs, expire);
135
+ timer = setTimeout(expire, wallClockMs);
87
136
  req.end();
88
137
  });
89
138
  }
@@ -95,7 +144,16 @@ export function adminArtifact(socket, artifactId, token, timeoutMs = 5000) {
95
144
  export function parsePrompt(prompt) {
96
145
  const { id: root, text, brief } = parseIdentity(prompt, { prefix: 'dot-decision', idPattern });
97
146
  // Without a token the identity is the text after the T3 preamble, so a resend with or without a role maps to one request.
98
- return { brief, root, requestRoot: root ?? `acp-${sha256(text).slice(0, 24)}` };
147
+ const lines = brief.split('\n');
148
+ let priority = 'normal', requirements = [];
149
+ while (/^(?:priority|requires):/.test(lines[0] ?? '')) {
150
+ const line = lines.shift();
151
+ if (line.startsWith('priority:')) {
152
+ priority = line.slice(9).trim();
153
+ if (!['normal', 'background'].includes(priority)) throw new Refusal('priority must be normal or background');
154
+ } else requirements = line.slice(9).trim().split(/[,\s]+/).filter(Boolean);
155
+ }
156
+ return { brief: lines.join('\n').trim(), priority, requirements, root, requestRoot: root ?? `acp-${sha256(text).slice(0, 24)}` };
99
157
  }
100
158
  // Attempt 1 is the root itself. After a cancelled or expired row the next attempt is `<root>_r<n>` (the bridge accepts only
101
159
  // [-\w] in a request id, so the doc's `#` separator cannot be used).
@@ -117,13 +175,62 @@ export function verdictRefusal(order) {
117
175
  return new Refusal(`${lines.join(' | ')}${retry}`, failure_type, { verdict: order.verdict, reasons: order.reasons, bytes: order.bytes, failure_type_source:'bridge_work_order_verdict' });
118
176
  }
119
177
 
178
+ export function unnamedWorkerRefusal(status, worker) {
179
+ const workers = Object.entries(status.by_worker ?? {});
180
+ if (worker || workers.length <= 1) return null;
181
+ const available = workers.filter(([, state]) =>
182
+ !state?.paused && !(state?.worker_break?.active && state.worker_break.source === 'owner')
183
+ ).map(([name]) => name).sort();
184
+ return `${available.length ? 'Choose one of these available workers: '+available.join(', ')+'.' : 'No worker is currently available.'} Re-file with --worker NAME.`;
185
+ }
186
+
187
+ export function expectedWait(status, worker) {
188
+ const live = status?.by_worker?.[worker], dispatch = status?.dispatch?.by_worker?.[worker];
189
+ const count = (...values) => values.find(value => Number.isSafeInteger(value) && value >= 0) ?? null;
190
+ const queued = count(dispatch?.queued_ahead, live?.queued_normal, dispatch?.queued_normal);
191
+ const free_lanes = count(dispatch?.free_lanes, live?.free_lanes);
192
+ const state = live?.paused || dispatch?.paused || status?.paused ? 'paused' : dispatch?.state ?? live?.state ?? 'unknown';
193
+ const median = status?.median_job_minutes;
194
+ let minutes_estimate = null;
195
+ if (state !== 'paused' && free_lanes > 0 && queued !== null) {
196
+ if (queued === 0) minutes_estimate = 0;
197
+ else if (Number.isFinite(median) && median > 0) {
198
+ const estimate = Math.floor(queued / free_lanes) * median;
199
+ if (Number.isFinite(estimate)) minutes_estimate = estimate;
200
+ }
201
+ }
202
+ return {queued, free_lanes, state, minutes_estimate};
203
+ }
204
+
205
+ export function withExpectedWait(acknowledgement, status, worker) {
206
+ const workers = Object.keys(status?.by_worker ?? {});
207
+ const target = worker ?? status?.default_worker ?? (workers.length === 1 ? workers[0] : undefined);
208
+ const wait = expectedWait(status, target);
209
+ const label = wait.state === 'paused' ? 'paused' : wait.minutes_estimate === null ? 'unknown' :
210
+ wait.minutes_estimate === 0 ? '0 minutes' : `about ${Math.ceil(wait.minutes_estimate)} min`;
211
+ return `${acknowledgement}\nExpected wait: ${label}.`;
212
+ }
213
+
120
214
  // The router's checks repeated as a backstop: the worker must be able to take work now.
121
- export function bridgeRefusal(status, inFlightCap) {
215
+ export function bridgeRefusal(status, inFlightCap, worker, priority, callerWaiting=false) {
216
+ const unnamed = unnamedWorkerRefusal(status, worker);
217
+ if (unnamed) throw new Refusal(unnamed, 'worker_unavailable');
122
218
  if (status.paused) return `worker paused${status.pause_reason ? `: ${status.pause_reason}` : ''}`;
123
219
  // Only evidence holds work: an owner-confirmed break. An inferred break is silence; estimated limits are metrics.
124
220
  if (status.worker_break?.active && status.worker_break.source === 'owner') return `worker_break active since ${status.worker_break.since}`;
125
- const queued = status.counts?.find(c => c.status === 'queued')?.count ?? 0;
126
- if (queued >= inFlightCap) return `worker queue is full (${queued} queued, in-flight cap ${inFlightCap})`;
221
+ const workers = status.by_worker;
222
+ const names = Object.keys(workers ?? {});
223
+ if (worker != null && names.length && !Object.hasOwn(workers, worker)) {
224
+ return `worker_unavailable: no worker ${worker} is registered; registered: ${names.sort().join(', ')}`;
225
+ }
226
+ // Omitted targets resolve to the single configured worker or the legacy default worker.
227
+ // In a named multi-worker profile, submit still owns target validation.
228
+ const targetWorker = worker ?? status.default_worker ?? (names.length === 1 ? names[0] : 'dot');
229
+ const target = workers?.[targetWorker];
230
+ const queued = callerWaiting ? (priority === 'background' ? target?.queued_waiting_background : target?.queued_waiting) : priority === 'background' ? target?.queued_background : !workers
231
+ ? status.counts?.find(c => c.status === 'queued')?.count
232
+ : target?.queued_normal ?? (priority === undefined && worker ? target?.queued_live : undefined);
233
+ if (queued >= inFlightCap) return `worker ${targetWorker} queue is full (${queued} queued, in-flight cap ${inFlightCap})`;
127
234
  return null;
128
235
  }
129
236
 
@@ -151,6 +258,27 @@ export const withoutNote = brief => {
151
258
  const note = NOTES.find(n => brief.startsWith(`${n}\n\n`));
152
259
  return stripPacked(note ? brief.slice(note.length + 2) : brief);
153
260
  };
261
+ // Parse an explicit repository mention without granting access or performing network I/O.
262
+ export function namedRepoInputs(text, allowedRepos = []) {
263
+ if (typeof text !== 'string') return null;
264
+ const match = /(?<![A-Za-z0-9_.\/:@\\-])(?:https:\/\/github\.com\/([A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*)\/pull\/([1-9]\d*)|([A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*)@([0-9a-f]{40}|[0-9a-f]{7,39}))(?![A-Za-z0-9_\/@\\-]|\.[A-Za-z0-9])/i.exec(text);
265
+ if (!match) return null;
266
+ const [, pullRepo, pullNumber, shaRepo, revision] = match;
267
+ const repo = pullRepo ?? shaRepo;
268
+ // allowedRepos is a list of names or a function that returns the canonical name of an allowed repository, or null.
269
+ let githubRepo;
270
+ if (typeof allowedRepos === 'function') githubRepo = allowedRepos(repo);
271
+ else githubRepo = new Map(Array.from(allowedRepos, name => [String(name).toLowerCase(), name])).get(repo.toLowerCase());
272
+ if (!githubRepo) return { refused: 'repo_not_allowed', repo };
273
+ if (pullRepo) {
274
+ const pr = Number(pullNumber);
275
+ return Number.isSafeInteger(pr) ? { needs_head: true, repo: githubRepo, pr } : null;
276
+ }
277
+ if (revision.length !== 40) return { refused: 'short_sha' };
278
+ const sha = revision.toLowerCase();
279
+ return { inputs: [{ github_repo: githubRepo, base_sha: sha, head_sha: sha }] };
280
+ }
281
+
154
282
  export async function repoInputs(cwd, { repoOf = githubRepoOf } = {}) {
155
283
  if (!cwd || !fs.existsSync(cwd)) return { inputs: [] };
156
284
  if (!(await git(cwd, ['rev-parse', '--is-inside-work-tree'])).ok) return { inputs: [] };
@@ -193,12 +321,15 @@ export function sizeRefusal(message, requestBytes) {
193
321
  return `${head}: ${split}; the limit is ${fmt(limit)}; cut at least ${fmt(cut)} bytes from your request${extra > 0 ? ' (pushing your local work drops the added context)' : ''}`;
194
322
  }
195
323
  export async function prepareAssignment(request, options, env = process.env) {
324
+ return (await prepareAssignmentWithContext(request, options, env)).assignment;
325
+ }
326
+ export async function prepareAssignmentWithContext(request, options, env = process.env) {
196
327
  try {
197
- const assignment = await prepareUnexplained(request, options, env);
328
+ const prepared = await prepareUnexplained(request, options, env);
198
329
  // The bridge repeats this check; making it here too refuses before the round trip, with the same numbers.
199
- const total = Buffer.byteLength(assignment.brief);
330
+ const total = Buffer.byteLength(prepared.assignment.brief);
200
331
  if (total > submissionLimits.brief) throw new Error(`brief: ${total} UTF-8 bytes exceeds ${submissionLimits.brief}`);
201
- return assignment;
332
+ return prepared;
202
333
  } catch (error) {
203
334
  const text = sizeRefusal(error.message, Buffer.byteLength(request.brief));
204
335
  if (text) throw new Refusal(text);
@@ -212,22 +343,67 @@ async function prepareUnexplained({ cwd, ...request }, options, env) {
212
343
  const hostPath = request.brief.match(/(?<![\w:/.-])(?:~\/|\/(?:home|Users|tmp|root|var|etc|mnt|opt)\/)[^\s'"`)<>]+/);
213
344
  if (hostPath) throw new Refusal(`text-only worker: the brief names a local path (${hostPath[0].slice(0, 80)}) that the worker cannot read; paste the needed content into the brief instead`);
214
345
  }
215
- const context = env.DOT_ACP_TEXT_ONLY === '1' ? { inputs: [], note: TEXT_ONLY_NOTE } : await repoInputs(cwd, options);
346
+ const textOnly = env.DOT_ACP_TEXT_ONLY === '1';
216
347
  const build = isBuild(request.brief);
348
+ // Without an explicit list, a named repository is allowed when a build of it would be: its owner is in the configured owner
349
+ // list and no exclusion rule covers it (the same rules as buildIneligible, so a review reads what a build may read).
350
+ const named = namedRepoInputs(request.brief, options?.allowedRepos ?? (repo => buildIneligible(repo, [], env) === null ? repo : null));
351
+ const hint = 'File it as a backlog row instead, or name owner/repo@FULL_SHA';
352
+ const refuseNamed = (code, reason) => new Refusal(`${reason}. ${hint}`, 'admission_refused', {code, refused: code});
353
+ if (named?.refused) {
354
+ const reason = named.refused === 'short_sha' ? 'The named revision is abbreviated' : 'The named repository is outside the configured allowlist';
355
+ throw refuseNamed(named.refused, reason);
356
+ }
357
+ if (named?.needs_head) throw refuseNamed('unresolved_repo', 'The pull request head is not pinned');
358
+ if (named?.inputs && textOnly) throw refuseNamed('unresolved_repo', 'This worker has no repository access');
359
+ let context;
360
+ if (named?.inputs && !build) {
361
+ context = named;
362
+ } else {
363
+ context = textOnly ? { inputs: [], note: TEXT_ONLY_NOTE } : await repoInputs(cwd, options);
364
+ if (named?.inputs && build) {
365
+ const actual = context.inputs[0], requested = named.inputs[0];
366
+ // A build's path checks below inspect the local HEAD. Do not classify paths against a different tree.
367
+ if (!actual || context.packBase || context.note || actual.github_repo.toLowerCase() !== requested.github_repo.toLowerCase() ||
368
+ actual.head_sha !== requested.head_sha)
369
+ throw refuseNamed('unresolved_repo', 'The named build revision is not the eligible local checkout');
370
+ context = named;
371
+ }
372
+ }
373
+ if (!build && !cwd && !context.inputs.length && !context.note) context = { ...context, note: TEXT_ONLY_NOTE };
374
+ const newFiles = [];
217
375
  // A build patch must apply to the requester's own commit: no packed local diff and no text-only fallback.
218
376
  if (build && !buildScope(request.brief).length) throw new Refusal(BUILD_NEEDS_SCOPE);
219
- if (build && (!context.inputs.length || context.packBase || context.note)) throw new Refusal(BUILD_NEEDS_PUSHED);
377
+ if (build && (!context.inputs.length || context.packBase || context.note))
378
+ throw new Refusal(env.DOT_ACP_TEXT_ONLY === '1' ? BUILD_NEEDS_PUSHED : await buildCheckoutRefusal(cwd, options));
220
379
  if (build) {
221
380
  const why = buildIneligible(context.inputs[0].github_repo, buildScope(request.brief));
222
381
  if (why) throw new Refusal(why);
223
382
  // Each listed path is a file at HEAD or a new file; a directory would widen the scope past the file bound and path terms.
224
- for (const p of buildScope(request.brief)) if ((await git(cwd, ['cat-file', '-t', `HEAD:${p}`])).out === 'tree') throw new Refusal(`[dot-build] lists a directory (${p}); list files`);
383
+ // A path absent at HEAD is a new file the worker creates, as a local subagent would: it goes to output_paths.
384
+ for (const p of buildScope(request.brief)) {
385
+ const kind = await git(cwd, ['cat-file', '-t', `HEAD:${p}`]);
386
+ if (kind.out === 'tree') throw new Refusal(`[dot-build] lists a directory (${p}); list files`);
387
+ // Only a path git reports as absent from HEAD is a new file; any other git failure (timeout, bad object store) refuses.
388
+ if (!kind.ok && !/does not exist in|exists on disk, but not in|Not a valid object name|invalid object name/i.test(kind.err)) throw new Refusal(`[dot-build] could not read ${p} at HEAD: ${kind.err.slice(0, 160)}`);
389
+ if (!kind.ok) newFiles.push(p);
390
+ }
225
391
  }
226
392
  // Identity is the requester's brief only; packed context and notes are presentation and never enter this hash.
227
- const assignment = { ...buildAssignment({ ...request, inputs: context.inputs, build }), acp_brief_hash: sha256(request.brief) };
228
- if (context.packBase) return packRepoDiff(cwd, assignment, context.packBase, NO_REPO_NOTE);
229
- if (context.untracked && !build) return { ...assignment, brief: `${UNTRACKED_NOTE}\n\n${assignment.brief}` };
230
- return context.note ? { ...assignment, brief: `${context.note}\n\n${assignment.brief}` } : assignment;
393
+ let assignment = { ...buildAssignment({ ...request, inputs: context.inputs, build, newFiles, repoScope: build && buildExecution(env) === 'host' }), acp_brief_hash: sha256(request.brief) };
394
+ if (context.packBase) assignment = await packRepoDiff(cwd, assignment, context.packBase, NO_REPO_NOTE);
395
+ else if (context.untracked && !build) assignment.brief = `${UNTRACKED_NOTE}\n\n${assignment.brief}`;
396
+ else if (context.note) assignment.brief = `${context.note}\n\n${assignment.brief}`;
397
+ const input = assignment.inputs[0];
398
+ if (!input) {
399
+ const base = context.packBase ? ` The candidate pushed commit was ${context.packBase}.` : '';
400
+ return { assignment, repositoryContext: `No repository input was submitted.${base} The worker sees only the local material included in the brief.` };
401
+ }
402
+ const revision = named?.inputs && !build ? 'pinned' : 'pushed';
403
+ const visibility = context.packBase
404
+ ? 'The brief includes a packed text diff. Local binary, sensitive, symlink, and ignored changes are unseen.'
405
+ : 'No local diff was included. Untracked and other checkout-only work is unseen.';
406
+ return { assignment, repositoryContext: `Repository input: ${input.github_repo} at ${revision} commit ${input.head_sha}. ${visibility}` };
231
407
  }
232
408
 
233
409
  // ---------------------------------------------------------------- build tasks
@@ -242,6 +418,23 @@ const buildLine = /^\[dot-build\]((?:[ \t]+\S+)*)[ \t]*$/;
242
418
  export const isBuild = brief => typeof brief === 'string' && buildLine.test(brief.split('\n', 1)[0].trim());
243
419
  export const buildScope = brief => (buildLine.exec(brief.split('\n', 1)[0].trim())?.[1] ?? '').trim().split(/[ \t]+/).filter(Boolean);
244
420
  export const BUILD_NEEDS_PUSHED = 'a [dot-build] task needs a clean checkout whose HEAD is pushed to a GitHub origin; push first, or use dalan submit with an explicit base_sha';
421
+ async function buildCheckoutRefusal(cwd, options) {
422
+ if (!cwd || !(await git(cwd, ['rev-parse', '--is-inside-work-tree'])).ok) return BUILD_NEEDS_PUSHED;
423
+ const status = await git(cwd, ['status', '--porcelain', '--untracked-files=no']);
424
+ if (!status.ok) return BUILD_NEEDS_PUSHED;
425
+ if (status.out) return 'a [dot-build] task needs a clean checkout; commit your changes first, then delegate again';
426
+ const origin = await git(cwd, ['remote', 'get-url', 'origin']);
427
+ if (!origin.ok || !(options?.repoOf ?? githubRepoOf)(origin.out)) return BUILD_NEEDS_PUSHED;
428
+ const head = await git(cwd, ['rev-parse', '--short=12', 'HEAD']);
429
+ if (!head.ok || !/^[a-f0-9]{12,64}$/.test(head.out)) return BUILD_NEEDS_PUSHED;
430
+ const branch = await git(cwd, ['symbolic-ref', '--quiet', 'HEAD']);
431
+ const detached = !(branch.ok && branch.out.startsWith('refs/heads/'));
432
+ const ref = detached ? `refs/heads/dalan/${head.out}` : branch.out;
433
+ const refspec = 'HEAD:' + ref;
434
+ const commandArg = /^[\w./:-]+$/.test(refspec) ? refspec : "'" + refspec.replaceAll("'", "'\\''") + "'";
435
+ const how = detached ? 'HEAD is detached, so if approved to publish, push it as a new branch first' : 'if approved to publish, push this branch first';
436
+ return `a [dot-build] task needs the committed revision on origin; ${how}: git push origin ${commandArg}, then delegate again`;
437
+ }
245
438
  export const BUILD_NEEDS_SCOPE = 'a [dot-build] line must name the files the worker may read and change, e.g. "[dot-build] src/a.py tests/test_a.py"';
246
439
  // Who may receive a build comes from the operator's owner allowlist because a parent can send a [dot-build] task without
247
440
  // the delegation gate's offer. The repo exclusion config and credential path terms add further restrictions.
@@ -272,10 +465,26 @@ export function buildIneligible(repo, files, env = process.env) {
272
465
  }
273
466
  const BUILD_OUTPUT = 'A patch: make the change with apply_patch, run the named check with run_check, then finish with a short summary, the check result and anything you could not do.';
274
467
 
275
- export function buildAssignment({ requestId, brief, inputs, validUntil, build = false }) {
468
+ // Where a build runs its checks. The bridge applies the patch and runs the repo's named checks only on host execution
469
+ // (run_check, and the default check it runs itself before finish); the profile default is often none, which leaves a
470
+ // delegated build unchecked. Host checks need the operator's opt-in on the bridge, so the adapter asks for host only
471
+ // when DALAN_ACP_BUILD_EXECUTION (legacy DOT_ACP_BUILD_EXECUTION) says so. Unset keeps the profile default.
472
+ export function buildExecution(env = process.env) {
473
+ const value = env.DALAN_ACP_BUILD_EXECUTION || env.DOT_ACP_BUILD_EXECUTION || '';
474
+ if (!value) return null;
475
+ if (!['none', 'worker', 'host'].includes(value)) throw new Refusal(`DALAN_ACP_BUILD_EXECUTION must be none, worker or host, not ${value.slice(0, 40)}`);
476
+ return value;
477
+ }
478
+
479
+ // repoScope: on host execution the bridge's checks run only on a whole-repository scope (src/host-execution-policy.mjs#hostCheckRefusal
480
+ // refuses a narrow one), so a host build reads and changes the repository with sensitive paths excluded at submit, as the
481
+ // fleet's own host builds do. The [dot-build] list still names the files the change is about and stays in the brief.
482
+ export function buildAssignment({ requestId, brief, inputs, validUntil, build = false, newFiles = [], repoScope = false }) {
483
+ const created = build ? newFiles : [];
276
484
  return {
277
485
  schema_version: 1, request_id: requestId, brief, inputs,
278
- ...(inputs.length ? { scope_paths: build ? buildScope(brief) : ['.'] } : {}),
486
+ ...(inputs.length ? { scope_paths: build && !repoScope ? buildScope(brief).filter(p => !created.includes(p)) : ['.'] } : {}),
487
+ ...(inputs.length && created.length ? { output_paths: created } : {}),
279
488
  expected_output: build ? BUILD_OUTPUT : 'A complete answer as plain text. Put the result in the finish call.',
280
489
  execution_scope: build ? 'implementation' : 'read-only', valid_until: validUntil,
281
490
  };
@@ -397,14 +606,33 @@ function diffstat(patch) {
397
606
  }
398
607
  // One line that asks the requester for the one word that records what the result was worth.
399
608
  export const decideHint = rid => `decide: dalan decide ${rid} accepted|applied|useful_no_change|useful_negative|not_useful`;
400
- // The text a build task returns to its T3 parent: the worker's own result, then what to apply and how to record the verdict.
609
+ // A build answer includes the worker's result, patch evidence and owner-decision instructions.
401
610
  // patch is the artifact's bytes (Buffer or string) or null when it could not be read.
402
- export function buildResultText(row, text, patch, proseCheck = null) {
611
+ // Publication is best effort: keep all build evidence and the patch on every failure.
612
+ export async function materializeBuildResult(row, text, patch, proseCheck, {cwd, getCurrent}) {
613
+ let publication;
614
+ try {
615
+ const result=await materialize({id:row.request_id, got:row, dir:cwd, recheck:getCurrent,
616
+ grantFile:path.join(os.homedir(),'.config/dot-bridge/materialize.json'),
617
+ download:async()=>patch, standingOnly:true, fetchBase:true});
618
+ publication=result.published ? `Branch: ${result.branch}\nDraft PR: ${result.pr_url}` : `Not published: ${result.reason}`;
619
+ } catch(error) { publication='Not published: '+String(error?.message ?? error).replace(/[\r\n]+/g,' '); }
620
+ return buildResultText(row,text,patch,proseCheck,publication);
621
+ }
622
+
623
+ export function buildResultText(row, text, patch, proseCheck = null, publication = null) {
403
624
  const rid = row.request_id, ev = row.report?.workspace_evidence ?? {}, input = row.assignment?.inputs?.[0] ?? {};
404
625
  const art = ev.patch_artifact, lines = [text, '', `--- worker build evidence (request ${rid}) ---`, `base: ${input.github_repo ?? '?'}@${ev.base_sha ?? input.base_sha ?? '?'}`];
405
626
  const checks = (ev.checks ?? []).map(c => `${c.check_id} ${c.status}${c.exit_code === null || c.exit_code === undefined ? '' : ` exit ${c.exit_code}`} on diff ${String(c.diff_sha256 ?? '').slice(0, 12)}${c.check_summary?`; ${c.check_summary}`:''}`);
406
- lines.push(`worker checks: ${checks.length ? checks.join('; ') : 'none run'}`);
627
+ const skippedReason=ev.checks_skipped?.at(-1)?.reason;
628
+ // A check from an older diff does not cover this one: then the skip reason still explains the current diff.
629
+ const currentChecked = (ev.checks ?? []).some(c => c.applies_to_current_diff === true);
630
+ lines.push(`worker checks: ${checks.length ? checks.join('; ') : 'none run'}${skippedReason && !currentChecked ? ` (check not run${checks.length ? ' on the current diff' : ''}: ${skippedReason})` : ''}`);
631
+ const runs = (row.worker_runs ?? []).map(run => `${run.command} exit ${run.exit_code}`);
632
+ if (runs.length) lines.push(`worker runs (worker_reported, not checked by the bridge): ${runs.join('; ')}`);
633
+ if (row.worker_run_limit) lines.push(`worker run limit (worker_reported): ${row.worker_run_limit}`);
407
634
  if (proseCheck) lines.push(proseCheckText(proseCheck));
635
+ if (publication) lines.push(publication);
408
636
  if (!art?.artifact_id || !art.size) lines.push('patch: none (empty diff). Nothing to apply.');
409
637
  else {
410
638
  const body = patch === null || patch === undefined ? null : Buffer.from(patch).toString('utf8');
@@ -1,9 +1,38 @@
1
- // The bridge's admin socket lives in the bridge home. A Unix socket path has a fixed size limit (108 bytes on Linux and
2
- // 104 on macOS, including the terminating NUL), so a long bridge home cannot hold it. The server and every client check
3
- // the path first and say so, in place of the system's bare EINVAL.
1
+ // The bridge's admin socket normally lives in the bridge home: <home>/.local/share/dalan/admin.sock. A Unix socket path
2
+ // has a fixed size limit (108 bytes on Linux and 104 on macOS, including the terminating NUL), so a long bridge home
3
+ // cannot hold it. The path is short by construction: when the standard path does not fit, the socket moves to a private
4
+ // per-user directory under /tmp, named by a hash of the data directory, so every home gets its own short path and the
5
+ // server and every client compute the same one. The server alone creates that directory.
6
+ import crypto from 'node:crypto';
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+
4
10
  export const socketPathLimit = platform => platform === 'darwin' ? 103 : 107; // usable bytes, excluding the terminating NUL
5
11
  export const SOCKET_PATH_LIMIT = socketPathLimit(process.platform);
6
12
 
13
+ const currentUid = () => process.getuid?.() ?? 0;
14
+ export const shortSocketDir = (uid = currentUid()) => `/tmp/dalan-${uid}`;
15
+
16
+ // The admin socket path for a data directory. The standard path when it fits, otherwise the short one.
17
+ export function adminSocketPath(dataDir, { platform = process.platform, uid = currentUid(), dir = shortSocketDir(uid) } = {}) {
18
+ const standard = path.join(dataDir, 'admin.sock');
19
+ if (Buffer.byteLength(standard) <= socketPathLimit(platform)) return standard;
20
+ const name = crypto.createHash('sha256').update(path.resolve(dataDir)).digest('hex').slice(0, 16);
21
+ return path.join(dir, `${name}.sock`);
22
+ }
23
+
24
+ // Server side: make the short socket directory if it is the one in use. It must be a real directory that only this user
25
+ // can use; a link or a directory that belongs to someone else is refused.
26
+ export function ensureAdminSocketDir(socket, { uid = currentUid(), dir = shortSocketDir(uid) } = {}) {
27
+ if (path.dirname(socket) !== dir) return;
28
+ try { fs.mkdirSync(dir, { mode: 0o700 }); } catch (error) { if (error.code !== 'EEXIST') throw error; }
29
+ const stat = fs.lstatSync(dir);
30
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== uid || (stat.mode & 0o077) !== 0) {
31
+ throw Object.assign(new Error(`the admin socket directory ${dir} is not a private directory owned by this user`),
32
+ { code: 'ADMIN_SOCKET_DIR_UNSAFE', fix: [`remove or fix ${dir}, or use a bridge home with a shorter path (DALAN_HOME)`] });
33
+ }
34
+ }
35
+
7
36
  // Null when the path fits; otherwise the error to report.
8
37
  export function adminSocketPathError(socket) {
9
38
  const bytes = Buffer.byteLength(socket);
package/src/alerts.mjs CHANGED
@@ -43,12 +43,17 @@ async function emit(rawTitle,rawMessage,log,settings,options={}) {
43
43
  if(options.idempotencyKey) headers['X-Idempotency-Key']=options.idempotencyKey;
44
44
  if(settings.NTFY_TOKEN) headers.Authorization=`Bearer ${settings.NTFY_TOKEN}`;
45
45
  const response=await fetch(settings.NTFY_URL,{method:'POST',headers,body:message,signal:AbortSignal.timeout(5000)});
46
- if(!response.ok) {
47
- const message=`ntfy HTTP ${response.status}`;
48
- if(response.status>=400&&response.status<500) throw notAccepted(message);
49
- throw new Error(message);
46
+ try {
47
+ if(!response.ok) {
48
+ const message=`ntfy HTTP ${response.status}`;
49
+ if(response.status>=400&&response.status<500) throw notAccepted(message);
50
+ throw new Error(message);
51
+ }
52
+ return true;
53
+ } finally {
54
+ // The HTTP status determines delivery even if closing the unused body fails.
55
+ try { await response.body?.cancel(); } catch { /* the response may already be closed */ }
50
56
  }
51
- return true;
52
57
  }
53
58
  export async function publishAlert(title,message,log,options={}) { return emit(title,message,log,config(),options); }
54
59
  const minutes=ms=>Math.round(ms/60000);
@@ -128,12 +133,16 @@ async function checkAlertsNow(store,log) {
128
133
  const started=old?.active&&old.started_at?old.started_at:now;
129
134
  if(!old?.active||!old.started_at)store.db.prepare('INSERT INTO alert_episodes(condition,active,started_at,last_change_at,attention_sent_at) VALUES(?,1,?,?,NULL) ON CONFLICT(condition) DO UPDATE SET active=1,started_at=excluded.started_at,last_change_at=excluded.last_change_at,attention_sent_at=NULL').run(name,started,now);
130
135
  if(store.nowMs()-Date.parse(started)>=ALERT_ATTENTION_DELAY_MS&&!old?.attention_sent_at) {
131
- const published=await emit('Dalan attention',message?message():`${name}: inspect dalan status --json`,log,settings);
132
- // Remote acceptance and the local marker are not atomic; lost replies may duplicate transport.
136
+ // The episode start is stored before publishing; use it to reproduce the same key after any retry or restart.
137
+ const idempotencyKey=`alert:attention:${name}:${started}`;
138
+ const published=await emit('Dalan attention',message?message():`${name}: inspect dalan status --json`,log,settings,{idempotencyKey});
133
139
  if(published)store.db.prepare('UPDATE alert_episodes SET attention_sent_at=? WHERE condition=? AND active=1 AND attention_sent_at IS NULL').run(store.stamp(),name);
134
140
  }
135
141
  } else if(old?.active) {
136
- if(old.attention_sent_at&&!await emit('Dalan recovered',`${name} resolved`,log,settings))continue;
142
+ if(old.attention_sent_at) {
143
+ const idempotencyKey=`alert:recovery:${name}:${old.started_at??old.attention_sent_at}`;
144
+ if(!await emit('Dalan recovered',`${name} resolved`,log,settings,{idempotencyKey}))continue;
145
+ }
137
146
  store.db.prepare('UPDATE alert_episodes SET active=0,started_at=NULL,last_change_at=?,attention_sent_at=NULL WHERE condition=?').run(now,name);
138
147
  }
139
148
  }
@@ -0,0 +1,82 @@
1
+ // Local retention companion. Call only while journal writers and filesystem renames
2
+ // are quiesced by the host; Node's path APIs do not provide portable unlinkat.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {journalPath} from './answer-journal.mjs';
6
+
7
+ const JOB = /^[-\w]{8,128}$/;
8
+ const QUESTION = /^[A-Za-z0-9_.:-]{1,128}$/;
9
+ const fail = code => { throw Object.assign(new Error(code), {code}); };
10
+ const same = (a,b) => a.dev === b.dev && a.ino === b.ino;
11
+ function directoryChain(value) {
12
+ const absolute = path.resolve(value), parsed = path.parse(absolute);
13
+ let current = parsed.root;
14
+ for (const part of absolute.slice(parsed.root.length).split(path.sep).filter(Boolean)) {
15
+ current = path.join(current, part);
16
+ const stat = fs.lstatSync(current);
17
+ if (stat.isSymbolicLink() || !stat.isDirectory()) fail('unsafe_directory');
18
+ }
19
+ return absolute;
20
+ }
21
+ function journalName(name, receiptsDir, job) {
22
+ if (!name.endsWith('.json')) return false;
23
+ let question;
24
+ try { question = decodeURIComponent(name.slice(0,-5)); } catch { return false; }
25
+ return QUESTION.test(question) && path.basename(journalPath(receiptsDir,job,question)) === name;
26
+ }
27
+ export function assertJournalAllowed(store, job) {
28
+ // Retained tombstones remain authoritative even if other native rows are gone.
29
+ if (store.db.prepare('SELECT 1 FROM job_retention_tombstones WHERE job=?').get(job)) fail('TOMBSTONE');
30
+ return store.assertProtocolAvailable(job);
31
+ }
32
+ export function pruneExpiredAnswerJournals({store, receiptsDir}) {
33
+ if (typeof receiptsDir !== 'string' || !receiptsDir) fail('invalid_receipts_directory');
34
+ const jobs = store.db.prepare('SELECT job FROM job_retention_tombstones ORDER BY job').all();
35
+ const result = {pruned:[], skipped:[]};
36
+ let root, rootStat;
37
+ try { root=directoryChain(receiptsDir); rootStat=fs.lstatSync(root); }
38
+ catch(error) {
39
+ for (const {job} of jobs) result.skipped.push({job,reason:error.code==='ENOENT'?'receipts_missing':'unsafe_receipts_directory'});
40
+ return result;
41
+ }
42
+ for (const {job} of jobs) {
43
+ if (typeof job !== 'string' || !JOB.test(job)) { result.skipped.push({job,reason:'invalid_job_id'}); continue; }
44
+ const dir=path.join(root,job+'.answers');
45
+ try {
46
+ const assertRoot=()=>{
47
+ if (directoryChain(root)!==root || !same(rootStat,fs.lstatSync(root))) fail('receipts_changed');
48
+ };
49
+ assertRoot();
50
+ const directoryStat=fs.lstatSync(dir);
51
+ if (directoryStat.isSymbolicLink() || !directoryStat.isDirectory()) fail('unsafe_answers_directory');
52
+ const assertDirectory=()=>{
53
+ assertRoot();
54
+ const current=fs.lstatSync(dir);
55
+ if (!current.isDirectory() || current.isSymbolicLink() || !same(directoryStat,current)) fail('answers_changed');
56
+ };
57
+ // Inspect the entire directory BEFORE deleting anything. Unexpected files,
58
+ // staged writes, nested directories and symlinks preserve the whole entry.
59
+ const names=fs.readdirSync(dir).sort();
60
+ const entries=names.map(name=>{
61
+ if (!journalName(name,root,job)) fail('unexpected_journal_name');
62
+ const stat=fs.lstatSync(path.join(dir,name));
63
+ if (!stat.isFile() || stat.isSymbolicLink()) fail('unsafe_journal_entry');
64
+ return {name,stat};
65
+ });
66
+ for (const {name,stat} of entries) {
67
+ assertDirectory();
68
+ const file=path.join(dir,name),current=fs.lstatSync(file);
69
+ if (!current.isFile() || current.isSymbolicLink() || !same(stat,current)) fail('journal_changed');
70
+ fs.unlinkSync(file);
71
+ }
72
+ assertDirectory();
73
+ fs.rmdirSync(dir); // Never recursive: new/unrecognized children are retained.
74
+ const fd=fs.openSync(root,'r');
75
+ try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
76
+ result.pruned.push(job);
77
+ } catch(error) {
78
+ result.skipped.push({job,reason:error.code==='ENOENT'?'journal_missing':error.code??'prune_failed'});
79
+ }
80
+ }
81
+ return result;
82
+ }
@@ -102,10 +102,12 @@ function createJournal(file, entry, io) {
102
102
  }
103
103
  function setState(file, entry, state) {
104
104
  if (entry.state === state) return;
105
- entry.state = state;
106
- const tmp = stage(file, entry);
107
- fs.renameSync(tmp, file);
108
- fsyncDir(path.dirname(file));
105
+ const tmp = stage(file, {...entry, state});
106
+ try {
107
+ fs.renameSync(tmp, file);
108
+ fsyncDir(path.dirname(file));
109
+ entry.state = state;
110
+ } finally { fs.rmSync(tmp, {force: true}); }
109
111
  }
110
112
 
111
113
  function classify(error) {