@tnunamak/dalan 0.8.5 → 0.9.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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,26 @@ This file lists user-visible changes, newest first. Check the section for your t
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.9.2
8
+
9
+ - An operator can limit private scoped-file reads to one held read-only assignment and set them to expire within its claim lease. The worker needs a separate grant for other assignments.
10
+
11
+ - Muse can accept a delegated review of specific files at a pushed commit and return its work ID.
12
+ - The requester reports an oversized bridge reply and stops retrying it, including when the bridge reports a server error.
13
+ - Work that fails, is blocked, or is refused shows its outcome without suggesting acceptance. Linked corrections remain available.
14
+ - If a worker cannot verify a required capability, Dalan points to a supported adapter.
15
+ - A caller can require identified questions on a worker configured for them. The worker must have both question tools enabled and granted.
16
+ - Use `dalan tell --work ID` to attach a lightweight message to your open work. While work is open, a worker-inbox acknowledgment appears in that child's transcript without waking the parent.
17
+
18
+ ## 0.9.0
19
+
20
+ - **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.
21
+ - **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.
22
+ - **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.
23
+ - **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.
24
+ - **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.
25
+ - **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.
26
+
7
27
  ## 0.8.5 (2026-12-03)
8
28
 
9
29
  - 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.
@@ -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)) {
@@ -333,39 +387,72 @@ async function runTurn(s, ctl, text, say, client) {
333
387
  const incoming = { ...parsePrompt(text, { worker: WORKER }), legacyRequestRoot: parsePrompt(text).requestRoot };
334
388
  let parsed = incoming;
335
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');
336
395
  if (ctl.pending) {
337
- 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);
338
401
  if (!row) {
339
- const { rid, validUntil } = ctl.pending;
340
- if (Date.parse(validUntil ?? '') <= Date.now()) {
341
- // The authoritative lookup still found no row after its admission window.
342
- // 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) {
343
406
  ctl.pending = null;
344
407
  publishPending(s, ctl);
345
- 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}`);
346
410
  }
347
- 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`);
348
415
  }
416
+ assertReadIntent(incomingRead,row.assignment);
349
417
  if (ctl.pending.submission_pending) {
350
418
  const storedHash = row.assignment.acp_brief_hash ?? sha256(withoutNote(row.assignment.brief ?? ''));
351
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');
352
421
  delete ctl.pending.submission_pending;
422
+ delete ctl.pending.correctionPrior;
423
+ delete ctl.pending.admitUntil;
353
424
  }
354
425
  ctl.pending.admission = attachedAdmission(row);
355
- ctl.pending.repositoryContext ??= storedRepositoryContext(row.assignment);
426
+ ctl.pending.revises ??= row.revises?.request_id;
427
+ ctl.pending.repositoryContext = storedRepositoryContext(row.assignment, ctl.pending.repositoryContext);
356
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
+ }
357
440
  }
358
441
  for (let expiries = 0; ; expiries++) {
359
442
  const attached = !!ctl.pending;
360
443
  if (ctl.pending) {
361
444
  // Attached already (a steer, or T3's continuation prompt after a restart): do not submit; report what was not sent.
362
445
  const steerText = text.trim();
363
- 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));
364
447
  } else {
365
448
  // An explicit withdrawal may still have landed despite a failed submit reply; clean up only that scoped request.
366
449
  try { ctl.pending = await acquire(s, parsed, ctl); }
367
- catch (e) { if (ctl.cancelled && ctl.withdrawWork && ctl.pending) await cancelPending(s, ctl); throw e; }
368
- 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;
369
456
  if (ctl.cancelled) {
370
457
  if (ctl.withdrawWork) {
371
458
  ctl.cancelDone = Promise.resolve(ctl.cancelDone).then(() => cancelPending(s, ctl));
@@ -388,7 +475,7 @@ async function runTurn(s, ctl, text, say, client) {
388
475
  const contextLine = ctl.pending.repositoryContext ? `\n${ctl.pending.repositoryContext}` : '';
389
476
  const waitLine = !attached && ctl.pending.expectedWaitLine && !['break', 'no_live_subscription'].includes(admission?.worker_state)
390
477
  ? `\n${ctl.pending.expectedWaitLine}` : '';
391
- 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`);
392
479
  for (const [type, message] of ctl.observations.splice(0)) await say(type, message);
393
480
  // A local interruption leaves the submitted work running. Only a scoped withdrawal changes its authority.
394
481
  if (ctl.cancelled) {
@@ -398,6 +485,7 @@ async function runTurn(s, ctl, text, say, client) {
398
485
  if (ctl.pending.terminal) return {text:ctl.pending.terminal.text};
399
486
  const outcome = await waitLoop(s, ctl, say, client);
400
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'});
401
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'});
402
490
  await say('agent_thought_chunk', `${ctl.pending.rid} expired unclaimed; resubmitting\n`);
403
491
  ctl.pending = null;
@@ -479,9 +567,10 @@ async function waitLoop(s, ctl, say, client) {
479
567
  const timeoutAt = Date.now();
480
568
  const status = await heartbeat(s, ctl, say, '', signal);
481
569
  if (ctl.cancelled) return { cancelled: true };
482
- // Refill reports the default worker's break. A missing reply cannot clear a known break.
483
- const confirmedBreak = status?.refill?.worker_break;
484
- 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') {
485
574
  if (confirmedBreak && !breakActive) {
486
575
  await say('agent_message_chunk', `Work ${ctl.pending.rid}: worker usage break; expected end: unknown. The child turn remains held.\n\n`);
487
576
  }
@@ -662,9 +751,9 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
662
751
  if (s.ctl) {
663
752
  const rid = s.ctl.pending?.rid;
664
753
  const correction = rid
665
- ? `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}.`
666
755
  : 'Once the work ID is available, submit corrected work with dalan correct WORK_ID or dalan_correct with revises=WORK_ID.';
667
- 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}`);
668
757
  }
669
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 };
670
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(() => {});
@@ -686,11 +775,18 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
686
775
  s.cancelledRid = saved?.cancelledRid ?? null;
687
776
  s.cancelledAt = saved?.cancelledAt ?? null;
688
777
  s.cancelledByGrace = saved?.cancelledByGrace === true;
778
+ s.finishedAfterCancel = saved?.finishedAfterCancel === true;
689
779
  let intent = readJsonPrivate(cancellationFile(s.id));
690
780
  if (intent?.not_before && intent.rid === ctl.pending?.rid) {
691
- if (text.trim() !== CONTINUE_PROMPT && Date.now() < intent.not_before) {
692
- // A prompt in the native steer window keeps the original work attached.
693
- 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;
694
790
  } else if (Date.now() < intent.not_before) {
695
791
  await sleep(intent.not_before-Date.now(), ctl.abort.signal);
696
792
  }
@@ -710,7 +806,10 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
710
806
  }
711
807
  if (!ctl.pending && s.cancelledRid && s.cancelledByGrace && Date.now()-Date.parse(s.cancelledAt)<60000) {
712
808
  s.cancelledByGrace=false;saveSession(s);
713
- 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`);
714
813
  return {stopReason:'end_turn'};
715
814
  }
716
815
  if (!ctl.pending && s.cancelledRid && text.trim() === CONTINUE_PROMPT) {
@@ -761,7 +860,7 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
761
860
  if (outcome.cancelled) {
762
861
  await Promise.race([ctl.cancelDone, sleep(CANCEL_CLEANUP_MS)]);
763
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`);
764
- 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'});
765
864
  return { stopReason: 'cancelled' };
766
865
  }
767
866
  if (outcome.resumable) {
@@ -792,22 +891,59 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
792
891
  const s = sessions.get(params.sessionId);
793
892
  const ctl = s?.ctl;
794
893
  if (!s) return;
894
+ if (ctl?.cancelled) return;
795
895
  const explicitControl = params._meta?.dalanControl !== undefined;
796
896
  const withdrawalRid = explicitControl ? explicitWithdrawalRid(params._meta)
797
897
  : ctl?.pending?.rid ?? s.pending?.rid ?? readSession(s.id)?.pending?.rid;
798
- if (!explicitControl && withdrawalRid) {
799
- writeJsonPrivate(cancellationFile(s.id), {rid:withdrawalRid,not_before:Date.now()+CANCEL_GRACE_MS});
800
- retryWithdrawal(s,withdrawalRid);
801
- }
898
+ const grace = !explicitControl && withdrawalRid ? armWithdrawalGrace(s, withdrawalRid, ctl) : null;
802
899
  if (!ctl) { if (explicitControl && withdrawalRid) void cancelYieldedSession(s, withdrawalRid); return; }
803
- if (ctl.cancelled) return;
804
900
  ctl.cancelled = true;
805
901
  ctl.withdrawWork = explicitControl && !!withdrawalRid && withdrawalRid === ctl.pending?.rid;
806
902
  if(!explicitControl) ctl.workerState='withdrawal_pending_grace';
807
- ctl.cancelDone = ctl.withdrawWork ? cancelPending(s, ctl) : Promise.resolve();
903
+ ctl.cancelDone = ctl.withdrawWork ? cancelPending(s, ctl) : grace ?? Promise.resolve();
808
904
  ctl.abort.abort();
809
905
  });
810
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
+
811
947
  function explicitWithdrawalRid(meta) {
812
948
  const control = meta?.dalanControl;
813
949
  if (control?.intent !== 'withdraw_work' || typeof control.scope !== 'string') return null;
@@ -890,14 +1026,32 @@ async function cancelPending(s, ctl) {
890
1026
  const intent=readJsonPrivate(cancellationFile(s.id));
891
1027
  if (currentTurn(s, ctl) && intent?.rid === pending.rid) {
892
1028
  if(intent.not_before && s.cancelledRid===pending.rid) {
893
- 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);
894
1031
  }
895
1032
  fs.rmSync(cancellationFile(s.id), { force: true });
896
1033
  }
897
1034
  };
898
1035
  ctl.cancelledWorkId = pending.rid;
899
1036
  let row = await readRowOrThrow(pending.rid);
900
- 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)) {
901
1055
  ctl.workerState = 'finished_after_withdrawal_request';
902
1056
  s.cancelledRid = pending.rid; ctl.pending = null; publishPending(s, ctl); clearIntent(); return;
903
1057
  }