@tnunamak/dalan 0.8.4 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,27 @@ This file lists user-visible changes, newest first. Check the section for your t
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.9.0
8
+
9
+ - **Before upgrading, keep a verified backup and the previous installation.** The bridge still uses schema 75 and adds records for native withdrawal, lane reservations and worker-scoped breaks. Before rolling back, verify the old package can use the retained state. Keep newer reports, receipts, artifacts and delivery acknowledgments.
10
+ - **Native cancellation survives the requester exiting.** Unclaimed work is withdrawn. The caller sees whether the requester stopped and what the bridge knows about the worker. An explicit correction creates a linked revision and keeps the original repository restrictions.
11
+ - **Admission shows eligible work ahead of you.** It says work can start immediately only when a current worker subscription has a lane reserved for that request. Admission and dispatch respect a confirmed break for the affected worker, and a worker's own refusal text remains visible.
12
+ - **Reconnect to paused or interrupted work.** The native adapter restores the existing work handle and approved file list. The recovery inbox uses passive reads. When it can read some pages, it returns their results and flags any unread pages. When every attempted page fails, it reports the bridge error or unavailability.
13
+ - **Review an exact revision and file set.** Native repository reviews can name a pushed revision and approved files. Wide read-only scopes can be paged without passing excluded files or granting host execution. Download manifests confirm completeness for an exact file list when every requested file was included.
14
+ - **Use verified publication and check results.** Successful publication names the draft, its branch and verified commit. If a remote write may have occurred but verification is incomplete, the reply gives the known remote state and retains the patch. Worker-reported checks are labeled separately from bridge checks.
15
+
16
+ ## 0.8.5 (2026-12-03)
17
+
18
+ - Look up delegated work with `dalan get` and the ID from its first reply, even without an original local receipt. This read uses the installed bridge owner's existing permission.
19
+ - Admission shows a run-length estimate when worker session reports are absent. It names its source and sample count: observed first claim to final report per worker run. Provider start and end times remain unknown.
20
+
21
+ ## 0.8.4 (2026-12-03)
22
+
23
+ - Identical requests to different workers stay separate. Retries still find matching work submitted before the upgrade.
24
+ - Cancelling withdraws queued or claimed work after a short grace window. An immediate follow-up keeps the original job attached; a late follow-up is not silently run as a new task.
25
+ - Published build results name the branch, draft PR and verified commit. They no longer ask callers to apply and push an already published patch. Changed publication details or verification timeouts keep the patch fallback.
26
+ - Worker-reported runtime safety blocks use the refusal outcome and preserve their text. Ordinary checkout and tool failures remain blocked.
27
+
7
28
  ## 0.8.3 (2026-12-03)
8
29
 
9
30
  ## 0.8.2 (2026-12-03)
@@ -14,7 +14,7 @@ import { createRefuse, cancelBudgetMs, CANCEL_CLEANUP_MS } from '../integrations
14
14
  import { detectPresentPatches } from '../src/patch-apply.mjs';
15
15
  import {
16
16
  buildExecution, paths, adminRequest, adminRequestThroughRestart, transient, sha256, parsePrompt, attemptId, ownerToken, readOrCreateSecret, bridgeRefusal,
17
- prepareAssignmentWithContext, sizeRefusal, withoutNote, Refusal, verdictRefusal, CONTINUE_PROMPT, promptText, isBuild, materializeBuildResult, decideHint, runBuildProseCheck, adminArtifact, withExpectedWait,
17
+ prepareAssignmentWithContext, explicitReadIntent, sizeRefusal, withoutNote, Refusal, verdictRefusal, CONTINUE_PROMPT, promptText, isBuild, materializeBuildResult, decideHint, runBuildProseCheck, adminArtifact, withExpectedWait, workerRunEvidenceLines,
18
18
  } from '../src/acp-bridge.mjs';
19
19
 
20
20
  const num = (name, fallback) => { const v = Number(process.env[name]); return Number.isFinite(v) && v > 0 ? v : fallback; };
@@ -77,7 +77,7 @@ const sessionFile = id => {
77
77
  // Keep active work and terminal receipts; probes and idle sessions leave nothing behind.
78
78
  function saveSession(s) {
79
79
  if (!s.pending && !s.completed?.length && !s.builds?.length && !s.cancelledRid) { fs.rmSync(sessionFile(s.id), { force: true }); return; }
80
- writeJsonPrivate(sessionFile(s.id), { id: s.id, cwd: s.cwd, model: s.model, pending: s.pending, cancelledRid: s.cancelledRid ?? null, cancelledAt:s.cancelledAt ?? null, cancelledByGrace:s.cancelledByGrace === true, builds: s.builds ?? [], completed: s.completed ?? [] });
80
+ writeJsonPrivate(sessionFile(s.id), { id: s.id, cwd: s.cwd, model: s.model, pending: s.pending, cancelledRid: s.cancelledRid ?? null, cancelledAt:s.cancelledAt ?? null, cancelledByGrace:s.cancelledByGrace === true, finishedAfterCancel:s.finishedAfterCancel===true, builds: s.builds ?? [], completed: s.completed ?? [] });
81
81
  }
82
82
  const readSession = id => readJsonPrivate(sessionFile(id));
83
83
  // Independent of the session lock: never overwrite another process's live session record.
@@ -126,6 +126,26 @@ async function readRow(rid, signal, admission = false, matchingWorkerOnly = fals
126
126
  }
127
127
  const attachedAdmission = row => ({ status: row.status, execution: row.execution, ...(row.status === 'queued' ? row.admission : {}) });
128
128
 
129
+ function assertReadIntent(intent,assignment) {
130
+ if(!intent) return;
131
+ const input=assignment.inputs?.[0], paths=assignment.scope_paths;
132
+ const original=explicitReadIntent(withoutNote(assignment.brief));
133
+ if(!original||original.repo.toLowerCase()!==intent.repo.toLowerCase()||original.sha!==intent.sha||
134
+ original.scope.length!==intent.scope.length||!original.scope.every(file=>intent.scope.includes(file))||
135
+ input?.github_repo?.toLowerCase()!==intent.repo.toLowerCase()||input.base_sha!==intent.sha||input.head_sha!==intent.sha||
136
+ !Array.isArray(paths)||!paths.length||!Array.isArray(assignment.read_paths)||
137
+ assignment.read_paths.length!==paths.length||!paths.every(file=>assignment.read_paths.includes(file)&&
138
+ intent.scope.some(entry=>file===entry||file.startsWith(entry+'/')))) {
139
+ throw new Refusal('The existing work does not match the requested repository revision and read scope. Submit new work with the full task.');
140
+ }
141
+ }
142
+
143
+ function withReadScope(context,scope,count) {
144
+ const accepted=Number.isSafeInteger(count)&&count>0?`${count} files. Use list_files to page through them`
145
+ :Array.isArray(scope)&&scope.length?JSON.stringify(scope):null;
146
+ return accepted===null?context:`${context.split('\nAccepted read scope: ',1)[0]}\nAccepted read scope: ${accepted}.`;
147
+ }
148
+
129
149
  // Find the assignment for this brief, or submit one. A retried or restarted task attaches to the row it already
130
150
  // submitted, so the worker never gets the same brief twice:
131
151
  // no row -> check eligibility, submit
@@ -133,6 +153,7 @@ const attachedAdmission = row => ({ status: row.status, execution: row.execution
133
153
  // row cancelled or expired -> next attempt id `<root>_r<n>`
134
154
  // row queued/claimed/finished-> attach; the wait returns the result or keeps waiting
135
155
  async function acquire(s, parsed, ctl) {
156
+ const readIntent=explicitReadIntent(parsed.brief);
136
157
  // Reuse work admitted before worker-scoped anonymous identities were introduced.
137
158
  // A legacy row belongs to this retry only when its authenticated worker matches.
138
159
  if (!parsed.root && !ctl.correction && parsed.legacyRequestRoot !== parsed.requestRoot) {
@@ -153,22 +174,41 @@ async function acquire(s, parsed, ctl) {
153
174
  if (row) {
154
175
  const storedHash = row.assignment.acp_brief_hash ?? sha256(withoutNote(row.assignment.brief ?? ''));
155
176
  if (storedHash !== briefHash) throw new Refusal(`token ${parsed.requestRoot} was already used with a different brief`);
177
+ assertReadIntent(readIntent,row.assignment);
178
+ if (ctl.correction && row.revises?.request_id !== ctl.correction.prior.rid) throw new Refusal('the stored work does not match the requested correction');
179
+ if (ctl.correction && row.status === 'cancelled') throw new Refusal(`correction ${rid} was withdrawn; no new work was submitted`);
156
180
  if (row.status === 'cancelled' && !conflictExhausted) continue;
157
181
  if (row.status === 'cancelled') throw new Refusal('request conflict persisted after the submit retry budget', 'adapter_error');
158
182
  return { root: parsed.requestRoot, rid, attempt, briefHash, admission: attachedAdmission(row),
159
- repositoryContext: preparedByAttempt.get(rid)?.repositoryContext ?? storedRepositoryContext(row.assignment),
183
+ ...(row.revises?.request_id ? { revises: row.revises.request_id } : {}),
184
+ repositoryContext: storedRepositoryContext(row.assignment, preparedByAttempt.get(rid)?.repositoryContext),
160
185
  validUntil: row.assignment.valid_until ?? null, notes: [], startedAt: Date.now() };
161
186
  }
162
187
  // On the last conflict still reread once: the same brief may already exist.
163
188
  if (conflictExhausted) throw new Refusal('request conflict persisted after the submit retry budget', 'adapter_error');
164
189
  const status = await call('/status', null);
165
- const refusal = bridgeRefusal(status, IN_FLIGHT_CAP, WORKER, parsed.priority, true);
190
+ const target = WORKER ?? status.default_worker ?? 'dot';
191
+ const workerBreak = status.by_worker?.[target]?.worker_break ?? (target==='dot'?status.worker_break:null);
192
+ const refusal = bridgeRefusal({...status,worker_break:workerBreak}, IN_FLIGHT_CAP+(ctl.correction?.row.status==='queued'?1:0), WORKER, parsed.priority, true);
166
193
  if (refusal) throw new Refusal(refusal,'deferred',{failure_type_source:'bridge_status_refusal',verdict:'defer'});
167
194
  let prepared=preparedByAttempt.get(rid);
168
195
  if(!prepared) {
169
196
  const validUntil = new Date(Date.now() + VALID_MS).toISOString();
170
- const {assignment, repositoryContext} = await prepareAssignmentWithContext({ cwd: s.cwd, requestId: rid, brief: parsed.brief, validUntil });
197
+ const correction=ctl.correction;
198
+ const {assignment, repositoryContext} = correction
199
+ ? {assignment:{...correction.row.assignment,request_id:rid,brief:parsed.brief,valid_until:validUntil,acp_brief_hash:briefHash},repositoryContext:correction.prior.repositoryContext}
200
+ : await prepareAssignmentWithContext({ cwd: s.cwd, requestId: rid, brief: parsed.brief, validUntil });
171
201
  const body = { ...(parsed.priority === 'background' ? {background:true} : {}), required_capabilities: parsed.requirements ?? [], max_queued: IN_FLIGHT_CAP, caller_waiting: true, delivery: 'none', ...(WORKER ? { worker: WORKER } : {}), assignment, owner_token: tokenFor(rid), meta: { source: 'agent', ...(assignment.execution_scope === 'implementation' ? { task_kind: 'build' } : {}) }, ...(assignment.execution_scope === 'implementation' && buildExecution() ? { execution: buildExecution() } : {}), ...(assignment.inputs.length && assignment.execution_scope !== 'implementation' ? { exclude_sensitive: true } : {}) };
202
+ if(correction) {
203
+ // The bridge derives inherited exclusions after checking the prior owner capability.
204
+ delete assignment.scope_excluded;
205
+ delete assignment.paged_read_scope;
206
+ if(assignment.inputs.length) assignment.read_paths=assignment.scope_paths;
207
+ body.revises={prior_id:correction.prior.rid,prior_token:tokenFor(correction.prior.rid),withdraw_prior:true,require_active_prior:true};
208
+ body.command_key=`acp-correct:${rid}`;
209
+ if(correction.row.execution) body.execution=correction.row.execution;
210
+ if(correction.row.review) body.review=true;
211
+ }
172
212
  // max_queued makes admission atomic; the bridge counts only this worker's waiting callers of the same priority.
173
213
  prepared={body,validUntil,repositoryContext}; preparedByAttempt.set(rid,prepared);
174
214
  }
@@ -191,14 +231,22 @@ async function acquire(s, parsed, ctl) {
191
231
  // A late response may arrive after bounded cancel has released the session lock.
192
232
  ctl.abort.signal.throwIfAborted();
193
233
  if (!currentTurn(s, ctl)) throw new Error('Cannot submit outside the active ACP turn.');
234
+ // All retries use the same deadline, within the bridge's pre-admission withdrawal retention.
235
+ body.facade_submit_until ??= Math.min(Date.parse(validUntil),Date.now()+600_000);
194
236
  const intent = { root: parsed.requestRoot, rid, attempt, briefHash, validUntil, repositoryContext: prepared.repositoryContext,
195
237
  priority: parsed.priority, requirements: parsed.requirements, notes: ctl.pending?.notes ?? [],
238
+ ...(ctl.correction ? { revises:ctl.correction.prior.rid, correctionPrior:ctl.correction.prior,
239
+ admitUntil:body.facade_submit_until } : {}),
196
240
  work_id: rid, original_host_task_id: ctl.hostTaskId ?? null, original_prompt_request_id: ctl.promptRequestId,
197
241
  later_prompt_request_ids: [], later_host_task_ids: [], startedAt: Date.now(), submission_pending: true };
198
242
  ctl.pending = intent;
199
243
  publishPending(s, ctl);
200
244
  // Admission belongs to the bridge; the richer forecast can replace this reply without changing ACP.
201
- try { const admitted = await call('/submit', null, { method: 'POST', payload: body, timeoutMs: SUBMIT_DEADLINE_MS }); prepared.admission = admitted.admission ?? {status:admitted.status ?? 'queued', execution:admitted.execution, submission_warnings:admitted.submission_warnings}; }
245
+ try {
246
+ const admitted=await call('/submit',null,{method:'POST',payload:body,timeoutMs:SUBMIT_DEADLINE_MS});
247
+ prepared.admission=admitted.admission??{status:admitted.status??'queued',execution:admitted.execution,submission_warnings:admitted.submission_warnings};
248
+ prepared.repositoryContext=withReadScope(prepared.repositoryContext,admitted.repository_scope?.scope_paths,admitted.repository_scope?.file_count);
249
+ }
202
250
  catch (e) {
203
251
  if (e.message === 'request_id conflict') {
204
252
  if (submitRetries >= SUBMIT_RETRIES) conflictExhausted = true;
@@ -222,6 +270,7 @@ async function acquire(s, parsed, ctl) {
222
270
  throw e;
223
271
  }
224
272
  return { root: parsed.requestRoot, rid, attempt, briefHash, admission: prepared.admission, validUntil, repositoryContext: prepared.repositoryContext,
273
+ ...(ctl.correction ? { revises:ctl.correction.prior.rid } : {}),
225
274
  expectedWaitLine: withExpectedWait('', status, WORKER).trimStart(), notes: [], startedAt: Date.now() };
226
275
  }
227
276
  throw new Refusal(`no usable assignment after ${MAX_ATTEMPTS} attempts for ${parsed.requestRoot}`);
@@ -232,12 +281,15 @@ async function resultText(row, s) {
232
281
  if (r?.outcome === 'refused_by_provider') return `[worker outcome: refused_by_provider]\n${r.result ?? r.summary ?? ''}`;
233
282
  let text = (r?.result || r?.summary || '').trim() || '(the worker finished without a result)';
234
283
  if (r && r.outcome !== 'completed') text = `[worker outcome: ${r.outcome}]\n${text}`;
235
- if (!isBuild(withoutNote(row.assignment?.brief ?? ''))) return `${text}\n\n${decideHint(row.request_id)}`;
284
+ if (!isBuild(withoutNote(row.assignment?.brief ?? ''))) {
285
+ const evidence = workerRunEvidenceLines(row);
286
+ return [text, ...(evidence.length ? [evidence.join('\n')] : []), decideHint(row.request_id)].join('\n\n');
287
+ }
236
288
  const art = r?.workspace_evidence?.patch_artifact;
237
289
  const patch = art?.artifact_id && art.size ? await adminArtifact(P.socket, art.artifact_id, tokenFor(row.request_id)) : null;
238
290
  const proseCheck = await runBuildProseCheck(row.assignment?.inputs?.[0]?.github_repo, patch);
239
291
  return materializeBuildResult(row, text, patch, proseCheck, {cwd:s.cwd,
240
- getCurrent:()=>call('/get?id='+encodeURIComponent(row.request_id)+'&peek=1',row.request_id)});
292
+ getCurrent:({signal})=>call('/get?id='+encodeURIComponent(row.request_id)+'&peek=1',row.request_id,{signal})});
241
293
  }
242
294
 
243
295
  // ---------------------------------------------------------------- patch observations
@@ -269,19 +321,21 @@ function publishPending(s, ctl) {
269
321
  saveSession(s);
270
322
  }
271
323
 
272
- function storedRepositoryContext(assignment) {
324
+ function storedRepositoryContext(assignment, preparedContext) {
273
325
  const input = assignment?.inputs?.[0];
274
- if (!input) return 'No repository input was submitted. The worker sees only the local material included in the brief.';
275
- return `Repository input: ${input.github_repo} at pinned commit ${input.head_sha ?? input.base_sha}. The worker can see local changes included in the brief. Other local work is unseen.`;
326
+ if (!input) return preparedContext ?? 'No repository input was submitted. The worker sees only the local material included in the brief.';
327
+ const context = preparedContext ?? `Repository input: ${input.github_repo} at pinned commit ${input.head_sha ?? input.base_sha}. The worker can see local changes included in the brief. Other local work is unseen.`;
328
+ const fileCount = assignment.paged_read_scope === true ? assignment.scope_paths.length : undefined;
329
+ return withReadScope(context, assignment.read_paths, fileCount);
276
330
  }
277
331
 
278
332
  function admissionText(admission, attached) {
279
- const {start, status, execution, ahead, latency, worker_state, until, until_source, duration_ms, track_record, submission_warnings} = admission ?? {};
333
+ const {start, status, execution, ahead, latency, worker_state, until, until_source, duration_ms, track_record, submission_warnings, reserved_until} = admission ?? {};
280
334
  const count = value => Number.isSafeInteger(value) && value >= 0;
281
335
  const duration = ms => ms < 1000 ? `${ms} ms` : ms < 60000 ? `${Math.round(ms / 1000)} s` : `${Math.round(ms / 60000)} min`;
282
336
  const counts = (record, keys) => keys.filter(key => count(record?.[key])).map(key => `${key.replaceAll('_', ' ')} ${record[key]}`);
283
337
  const window = days => count(days) ? `, ${days} days` : '';
284
- const line = [start === 'now' ? 'starts now' : start === 'queued' ? 'queued' :
338
+ const line = [start === 'now' && Date.parse(reserved_until)>Date.now() ? 'starts now' : ['queued','now'].includes(start) ? 'queued' :
285
339
  ['queued', 'claimed', 'finished', 'cancelled'].includes(status) ? status : attached ? 'attached' : 'queued'];
286
340
  if (['host', 'worker', 'none'].includes(execution)) line.push(`execution ${execution}`);
287
341
  if (count(ahead?.count)) {
@@ -321,7 +375,9 @@ function admissionText(admission, attached) {
321
375
  if (session?.source === 'worker_reported_sessions') {
322
376
  if (count(session.p50_ms)) line.push(`typical session ~${duration(session.p50_ms)} (worker reported, n ${session.n}${window(session.window_days)})`);
323
377
  else line.push(`typical session: not enough history (worker reported, n ${count(session.n) ? session.n : 0})`);
324
-
378
+ } else if (session?.source === 'bridge_observed_acquisition_runs') {
379
+ if (count(session.p50_ms)) line.push(`typical session estimate ~${duration(session.p50_ms)} (bridge-observed claim-to-final-report per run, n ${session.n}${window(session.window_days)})`);
380
+ else line.push(`typical session estimate: not enough history (bridge-observed run spans, n ${count(session.n) ? session.n : 0})`);
325
381
  }
326
382
  const warnings = Array.isArray(submission_warnings) ? submission_warnings.filter(value => typeof value === 'string') : [];
327
383
  return [`${line.join('; ')}.`, ...warnings.map(warning => `Submission warning: ${warning}`)].join('\n');
@@ -331,39 +387,72 @@ async function runTurn(s, ctl, text, say, client) {
331
387
  const incoming = { ...parsePrompt(text, { worker: WORKER }), legacyRequestRoot: parsePrompt(text).requestRoot };
332
388
  let parsed = incoming;
333
389
  const notes = ctl.pending?.notes ?? [];
390
+ const correction=/^Correct ([-\w]{8,128})\r?\n([\s\S]+)$/i.exec(incoming.brief);
391
+ const incomingRead=explicitReadIntent(correction?correction[2].trim():incoming.brief);
392
+ const correctionRoot=correction ? `acp-${sha256(JSON.stringify([WORKER,correction[1],correction[2].trim()])).slice(0,24)}` : null;
393
+ let correctionRetry=correction&&ctl.pending?.revises===correction[1]&&ctl.pending.root===correctionRoot;
394
+ if(correction&&!correctionRetry&&ctl.pending?.rid!==correction[1]) throw new Refusal('the named work is not held by this child; no correction was sent');
334
395
  if (ctl.pending) {
335
- const row = ctl.pending.submission_pending ? await readRow(ctl.pending.rid, undefined, true) : await readRowOrThrow(ctl.pending.rid, undefined, true);
396
+ const pending = ctl.pending;
397
+ // Take the deadline sample before the authoritative read. A read that
398
+ // started before the deadline can still miss a concurrent first admission.
399
+ const admissionExpired = (pending.admitUntil ?? Date.parse(pending.validUntil ?? '')) <= Date.now();
400
+ let row = pending.submission_pending ? await readRow(pending.rid, undefined, true) : await readRowOrThrow(pending.rid, undefined, true);
336
401
  if (!row) {
337
- const { rid, validUntil } = ctl.pending;
338
- if (Date.parse(validUntil ?? '') <= Date.now()) {
339
- // The authoritative lookup still found no row after its admission window.
340
- // Clear the stale intent, but never reinterpret a continuation as new work.
402
+ if (!admissionExpired) throw new Refusal(`submission ${pending.rid} is not yet confirmed; retained its identity and did not submit again`);
403
+ const prior = pending.correctionPrior;
404
+ if (prior) row = await readRow(prior.rid, undefined, true);
405
+ if (!row || !['queued','claimed'].includes(row.status) || row.cancellation_requested) {
341
406
  ctl.pending = null;
342
407
  publishPending(s, ctl);
343
- throw new Refusal(`submission ${rid} did not appear before its admission window ended; no new work was submitted`);
408
+ const priorLocation = prior ? ` Find the earlier work with dalan get ${prior.rid}.` : '';
409
+ throw new Refusal(`submission ${pending.rid} did not appear before its admission window ended; no new work was submitted.${priorLocation}`);
344
410
  }
345
- throw new Refusal(`submission ${rid} is not yet confirmed; retained its identity and did not submit again`);
411
+ ctl.pending = prior;
412
+ correctionRetry = false;
413
+ publishPending(s, ctl);
414
+ if (!correction) await say('agent_message_chunk', `The correction was not admitted. Continuing earlier work ${prior.rid}.\n`);
346
415
  }
416
+ assertReadIntent(incomingRead,row.assignment);
347
417
  if (ctl.pending.submission_pending) {
348
418
  const storedHash = row.assignment.acp_brief_hash ?? sha256(withoutNote(row.assignment.brief ?? ''));
349
419
  if (storedHash !== ctl.pending.briefHash) throw new Refusal(`request ${ctl.pending.rid} resolved to a different brief`);
420
+ if (ctl.pending.revises && row.revises?.request_id !== ctl.pending.revises) throw new Refusal('the stored work does not match the requested correction');
350
421
  delete ctl.pending.submission_pending;
422
+ delete ctl.pending.correctionPrior;
423
+ delete ctl.pending.admitUntil;
351
424
  }
352
425
  ctl.pending.admission = attachedAdmission(row);
353
- ctl.pending.repositoryContext ??= storedRepositoryContext(row.assignment);
426
+ ctl.pending.revises ??= row.revises?.request_id;
427
+ ctl.pending.repositoryContext = storedRepositoryContext(row.assignment, ctl.pending.repositoryContext);
354
428
  parsed = { brief: withoutNote(row.assignment.brief), priority: ctl.pending.priority ?? 'normal', requirements: ctl.pending.requirements ?? [], requestRoot: ctl.pending.root };
429
+ if(correction&&!correctionRetry) {
430
+ const rawDelta=correction[2].trim();
431
+ const delta=incomingRead?rawDelta.split(/\r?\n/).slice(1).join('\n').trim():rawDelta;
432
+ const prior=ctl.pending;
433
+ if(!delta)throw new Refusal('write the correction on the next line');
434
+ ctl.correction={prior,row};
435
+ parsed.brief=`${parsed.brief}\n\nRequester correction:\n${delta}`;
436
+ parsed.requestRoot=correctionRoot;
437
+ // Save the successor only when acquire has a durable submit identity to reconcile.
438
+ ctl.pending=null;
439
+ }
355
440
  }
356
441
  for (let expiries = 0; ; expiries++) {
357
442
  const attached = !!ctl.pending;
358
443
  if (ctl.pending) {
359
444
  // Attached already (a steer, or T3's continuation prompt after a restart): do not submit; report what was not sent.
360
445
  const steerText = text.trim();
361
- if (steerText && steerText !== CONTINUE_PROMPT && sha256(incoming.brief) !== ctl.pending.briefHash && !ctl.pending.notes.includes(steerText.slice(0, 200))) ctl.pending.notes.push(steerText.slice(0, 200));
446
+ if (!correctionRetry && steerText && steerText !== CONTINUE_PROMPT && sha256(incoming.brief) !== ctl.pending.briefHash && !ctl.pending.notes.includes(steerText.slice(0, 200))) ctl.pending.notes.push(steerText.slice(0, 200));
362
447
  } else {
363
448
  // An explicit withdrawal may still have landed despite a failed submit reply; clean up only that scoped request.
364
449
  try { ctl.pending = await acquire(s, parsed, ctl); }
365
- catch (e) { if (ctl.cancelled && ctl.withdrawWork && ctl.pending) await cancelPending(s, ctl); throw e; }
366
- ctl.pending.notes = notes;
450
+ catch (e) {
451
+ if(!ctl.pending&&ctl.correction) { ctl.pending=ctl.correction.prior; publishPending(s,ctl); }
452
+ if (ctl.cancelled && ctl.withdrawWork && ctl.pending) await cancelPending(s, ctl);
453
+ throw e;
454
+ }
455
+ ctl.pending.notes = ctl.correction ? [] : notes;
367
456
  if (ctl.cancelled) {
368
457
  if (ctl.withdrawWork) {
369
458
  ctl.cancelDone = Promise.resolve(ctl.cancelDone).then(() => cancelPending(s, ctl));
@@ -386,7 +475,7 @@ async function runTurn(s, ctl, text, say, client) {
386
475
  const contextLine = ctl.pending.repositoryContext ? `\n${ctl.pending.repositoryContext}` : '';
387
476
  const waitLine = !attached && ctl.pending.expectedWaitLine && !['break', 'no_live_subscription'].includes(admission?.worker_state)
388
477
  ? `\n${ctl.pending.expectedWaitLine}` : '';
389
- await say('agent_message_chunk', `Work ${ctl.pending.rid}${attached ? ': re-attached' : ''}. Admission: ${line}${contextLine}${waitLine}\n\n`);
478
+ await say('agent_message_chunk', `Work ${ctl.pending.rid}${attached ? ': re-attached' : ''}${ctl.correction ? ` corrects ${ctl.correction.prior.rid}` : ''}. Admission: ${line}${contextLine}${waitLine}\n\n`);
390
479
  for (const [type, message] of ctl.observations.splice(0)) await say(type, message);
391
480
  // A local interruption leaves the submitted work running. Only a scoped withdrawal changes its authority.
392
481
  if (ctl.cancelled) {
@@ -396,6 +485,7 @@ async function runTurn(s, ctl, text, say, client) {
396
485
  if (ctl.pending.terminal) return {text:ctl.pending.terminal.text};
397
486
  const outcome = await waitLoop(s, ctl, say, client);
398
487
  if (outcome.expired) {
488
+ if(ctl.pending.revises) throw refuse(`correction ${ctl.pending.rid} expired before it was claimed`,{failure_type:'expired',failure_type_source:'bridge_observed_transition'});
399
489
  if (expiries + 1 >= MAX_EXPIRIES) throw refuse(`assignment ${ctl.pending.rid} expired ${MAX_EXPIRIES} times before the worker claimed it`,{failure_type:'expired',failure_type_source:'bridge_observed_transition'});
400
490
  await say('agent_thought_chunk', `${ctl.pending.rid} expired unclaimed; resubmitting\n`);
401
491
  ctl.pending = null;
@@ -477,9 +567,10 @@ async function waitLoop(s, ctl, say, client) {
477
567
  const timeoutAt = Date.now();
478
568
  const status = await heartbeat(s, ctl, say, '', signal);
479
569
  if (ctl.cancelled) return { cancelled: true };
480
- // Refill reports the default worker's break. A missing reply cannot clear a known break.
481
- const confirmedBreak = status?.refill?.worker_break;
482
- if ((row.target_worker === 'dot' || (breakActive && !row.target_worker)) && typeof confirmedBreak === 'boolean') {
570
+ const ownedBreak = status?.states?.find(state=>state.request_id===ctl.pending.rid)?.worker_break;
571
+ const legacyBreak = (row.target_worker==='dot'||(breakActive&&!row.target_worker)) ? status?.refill?.worker_break : undefined;
572
+ const confirmedBreak = typeof ownedBreak==='boolean' ? ownedBreak : legacyBreak;
573
+ if (typeof confirmedBreak === 'boolean') {
483
574
  if (confirmedBreak && !breakActive) {
484
575
  await say('agent_message_chunk', `Work ${ctl.pending.rid}: worker usage break; expected end: unknown. The child turn remains held.\n\n`);
485
576
  }
@@ -660,9 +751,9 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
660
751
  if (s.ctl) {
661
752
  const rid = s.ctl.pending?.rid;
662
753
  const correction = rid
663
- ? `Submit corrected work with dalan correct ${rid} or dalan_correct with revises=${rid}.`
754
+ ? `Steer with "Correct ${rid}" on the first line and your correction on the next. You can also submit corrected work with dalan correct ${rid}.`
664
755
  : 'Once the work ID is available, submit corrected work with dalan correct WORK_ID or dalan_correct with revises=WORK_ID.';
665
- throw acp.RequestError.invalidRequest(null, `prompt already active. Steering a held ACP child is unprobed. ${correction}`);
756
+ throw acp.RequestError.invalidRequest(null, `prompt already active. ${correction}`);
666
757
  }
667
758
  const ctl = s.ctl = { abort: new AbortController(), cancelled: false, cancelDone: null, pending: null, hostTaskId: params._meta?.delegatedTaskId ?? null, promptRequestId: requestId, generation: s.generation = (s.generation ?? 0) + 1 };
668
759
  const say = (type, text) => !currentTurn(s, ctl) ? Promise.resolve() : client.notify(acp.methods.client.session.update, { sessionId: s.id, update: { sessionUpdate: type, content: { type: 'text', text } } }).catch(() => {});
@@ -684,11 +775,18 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
684
775
  s.cancelledRid = saved?.cancelledRid ?? null;
685
776
  s.cancelledAt = saved?.cancelledAt ?? null;
686
777
  s.cancelledByGrace = saved?.cancelledByGrace === true;
778
+ s.finishedAfterCancel = saved?.finishedAfterCancel === true;
687
779
  let intent = readJsonPrivate(cancellationFile(s.id));
688
780
  if (intent?.not_before && intent.rid === ctl.pending?.rid) {
689
- if (text.trim() !== CONTINUE_PROMPT && Date.now() < intent.not_before) {
690
- // A prompt in the native steer window keeps the original work attached.
691
- fs.rmSync(cancellationFile(s.id), {force:true}); intent=null;
781
+ const followUp = text.trim() !== CONTINUE_PROMPT;
782
+ const insideGrace = Date.now() < intent.not_before;
783
+ const kept = intent.bridge
784
+ ? (await askGraceBridge(intent, followUp && insideGrace ? 'keep' : 'state', ctl.abort.signal)).kept
785
+ : followUp && insideGrace;
786
+ if (kept) {
787
+ delete ctl.pending.cancel_requested; publishPending(s, ctl);
788
+ fs.rmSync(cancellationFile(s.id), {force:true});
789
+ intent=null;
692
790
  } else if (Date.now() < intent.not_before) {
693
791
  await sleep(intent.not_before-Date.now(), ctl.abort.signal);
694
792
  }
@@ -708,7 +806,10 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
708
806
  }
709
807
  if (!ctl.pending && s.cancelledRid && s.cancelledByGrace && Date.now()-Date.parse(s.cancelledAt)<60000) {
710
808
  s.cancelledByGrace=false;saveSession(s);
711
- await say('agent_message_chunk', `Your earlier work ${s.cancelledRid} was cancelled at ${s.cancelledAt} (no follow-up within 2 s). This message was not submitted. Resend the full task if you want new work.\n`);
809
+ const state = s.finishedAfterCancel
810
+ ? 'finished after cancellation was requested. Its result was not delivered to this turn.'
811
+ : `was cancelled at ${s.cancelledAt} (no follow-up within 2 s).`;
812
+ await say('agent_message_chunk', `Your earlier work ${s.cancelledRid} ${state} This message was not submitted. Resend the full task if you want new work.\n`);
712
813
  return {stopReason:'end_turn'};
713
814
  }
714
815
  if (!ctl.pending && s.cancelledRid && text.trim() === CONTINUE_PROMPT) {
@@ -759,7 +860,7 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
759
860
  if (outcome.cancelled) {
760
861
  await Promise.race([ctl.cancelDone, sleep(CANCEL_CLEANUP_MS)]);
761
862
  await say('agent_message_chunk', `requester_interrupted: true; worker_state: ${ctl.workerState ?? 'still_running'}; work_id: ${ctl.pending?.rid ?? ctl.cancelledWorkId ?? 'not yet assigned'}; compute_stopped: ${ctl.computeStopped === true ? 'true' : ctl.computeStopped === false ? 'false' : 'unknown'}\n`);
762
- if (ctl.withdrawWork && ctl.pending?.cancel_requested) throw refuse('Cancellation requested; bridge withdrawal not yet confirmed. Retrying in the background.', {failure_type:'transport_error',failure_type_source:'dot_acp_cancel_pending'});
863
+ if (ctl.graceUnconfirmed || ctl.withdrawWork && ctl.pending?.cancel_requested) throw refuse('Cancellation requested; bridge withdrawal not yet confirmed. Retrying in the background.', {failure_type:'transport_error',failure_type_source:'dot_acp_cancel_pending'});
763
864
  return { stopReason: 'cancelled' };
764
865
  }
765
866
  if (outcome.resumable) {
@@ -790,22 +891,59 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
790
891
  const s = sessions.get(params.sessionId);
791
892
  const ctl = s?.ctl;
792
893
  if (!s) return;
894
+ if (ctl?.cancelled) return;
793
895
  const explicitControl = params._meta?.dalanControl !== undefined;
794
896
  const withdrawalRid = explicitControl ? explicitWithdrawalRid(params._meta)
795
897
  : ctl?.pending?.rid ?? s.pending?.rid ?? readSession(s.id)?.pending?.rid;
796
- if (!explicitControl && withdrawalRid) {
797
- writeJsonPrivate(cancellationFile(s.id), {rid:withdrawalRid,not_before:Date.now()+CANCEL_GRACE_MS});
798
- retryWithdrawal(s,withdrawalRid);
799
- }
898
+ const grace = !explicitControl && withdrawalRid ? armWithdrawalGrace(s, withdrawalRid, ctl) : null;
800
899
  if (!ctl) { if (explicitControl && withdrawalRid) void cancelYieldedSession(s, withdrawalRid); return; }
801
- if (ctl.cancelled) return;
802
900
  ctl.cancelled = true;
803
901
  ctl.withdrawWork = explicitControl && !!withdrawalRid && withdrawalRid === ctl.pending?.rid;
804
902
  if(!explicitControl) ctl.workerState='withdrawal_pending_grace';
805
- ctl.cancelDone = ctl.withdrawWork ? cancelPending(s, ctl) : Promise.resolve();
903
+ ctl.cancelDone = ctl.withdrawWork ? cancelPending(s, ctl) : grace ?? Promise.resolve();
806
904
  ctl.abort.abort();
807
905
  });
808
906
 
907
+ function askGraceBridge(intent, action, signal) {
908
+ return adminRequest(P.socket,'/cancel-grace',{method:'POST',token:tokenFor(intent.rid),timeoutMs:1500,signal,
909
+ payload:{id:intent.rid,intent:intent.bridge,action,...(intent.before_admission?{before_admission:true}:{})}});
910
+ }
911
+
912
+ async function armWithdrawalGrace(s, rid, ctl) {
913
+ if (ctl) ctl.graceUnconfirmed=true;
914
+ const file = cancellationFile(s.id);
915
+ const saved = readJsonPrivate(file);
916
+ const newIntent=()=>({rid,requested_at:Date.now(),not_before:Date.now()+CANCEL_GRACE_MS,bridge:randomUUID(),
917
+ before_admission:(ctl?.pending??s.pending)?.submission_pending===true});
918
+ let intent = saved?.rid===rid && saved.not_before ? saved :newIntent();
919
+ writeJsonPrivate(file,intent);
920
+ try {
921
+ if (intent.bridge) {
922
+ let reply = await askGraceBridge(intent,'arm');
923
+ if(reply.kept) {
924
+ // A new cancellation of this session must not inherit an earlier keep decision.
925
+ intent=newIntent(); writeJsonPrivate(file,intent);
926
+ reply=await askGraceBridge(intent,'arm');
927
+ }
928
+ intent.not_before=reply.not_before;
929
+ writeJsonPrivate(file,intent);
930
+ }
931
+ if (ctl) {
932
+ ctl.graceUnconfirmed=false;
933
+ ctl.workerState=intent.bridge ? 'withdrawal_scheduled' : 'withdrawal_pending_grace';
934
+ }
935
+ } catch (error) {
936
+ if (error.http_status===404 || error.message==='unknown route') {
937
+ // Compatibility with a serving bridge from before durable withdrawal.
938
+ delete intent.bridge; writeJsonPrivate(file,intent);
939
+ if (ctl) ctl.graceUnconfirmed=false;
940
+ } else {
941
+ log(`grace withdrawal was not confirmed for ${rid}: ${error.message}`);
942
+ }
943
+ }
944
+ retryWithdrawal(s,rid);
945
+ }
946
+
809
947
  function explicitWithdrawalRid(meta) {
810
948
  const control = meta?.dalanControl;
811
949
  if (control?.intent !== 'withdraw_work' || typeof control.scope !== 'string') return null;
@@ -888,14 +1026,32 @@ async function cancelPending(s, ctl) {
888
1026
  const intent=readJsonPrivate(cancellationFile(s.id));
889
1027
  if (currentTurn(s, ctl) && intent?.rid === pending.rid) {
890
1028
  if(intent.not_before && s.cancelledRid===pending.rid) {
891
- s.cancelledAt=new Date().toISOString();s.cancelledByGrace=true;saveSession(s);
1029
+ s.cancelledAt=new Date().toISOString();s.cancelledByGrace=true;
1030
+ s.finishedAfterCancel=ctl.workerState==='finished_after_withdrawal_request';saveSession(s);
892
1031
  }
893
1032
  fs.rmSync(cancellationFile(s.id), { force: true });
894
1033
  }
895
1034
  };
896
1035
  ctl.cancelledWorkId = pending.rid;
897
1036
  let row = await readRowOrThrow(pending.rid);
898
- if (row.status === 'finished' && pending.withdrawal_started) {
1037
+ const grace = readJsonPrivate(cancellationFile(s.id));
1038
+ if (grace?.bridge && !ctl.withdrawWork) {
1039
+ const decision=await askGraceBridge(grace,'settle');
1040
+ if(decision.kept) {
1041
+ delete pending.cancel_requested;
1042
+ publishPending(s,ctl);
1043
+ clearIntent();
1044
+ return;
1045
+ }
1046
+ if(decision.status==='queued'||decision.status==='claimed') {
1047
+ if(!decision.pending) await askGraceBridge(grace,'arm');
1048
+ return;
1049
+ }
1050
+ if(decision.status!==row.status) row=await readRowOrThrow(pending.rid);
1051
+ }
1052
+ const requestedAt = grace?.requested_at ?? (grace?.not_before-CANCEL_GRACE_MS);
1053
+ const finishedDuringGrace = Date.parse(row.report?.created_at)>=requestedAt;
1054
+ if (row.status === 'finished' && (pending.withdrawal_started || finishedDuringGrace)) {
899
1055
  ctl.workerState = 'finished_after_withdrawal_request';
900
1056
  s.cancelledRid = pending.rid; ctl.pending = null; publishPending(s, ctl); clearIntent(); return;
901
1057
  }