copilot-operator 0.1.94 → 0.1.97

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 (71) hide show
  1. package/dist/src/api/apiLock.js +82 -0
  2. package/dist/src/api/main.js +5 -0
  3. package/dist/src/api/operator.controller.js +23 -5
  4. package/dist/src/api/operator.service.js +518 -83
  5. package/dist/src/api/server.js +10 -0
  6. package/dist/src/config/exportHome.js +1 -1
  7. package/dist/src/config/live.js +12 -12
  8. package/dist/src/config/schema.js +13 -0
  9. package/dist/src/exec/policy.js +9 -18
  10. package/dist/src/orchestrator/kerriganRunner.js +11 -4
  11. package/dist/src/orchestrator/leadRunner.js +76 -23
  12. package/dist/src/orchestrator/review.js +6 -2
  13. package/dist/src/orchestrator/subtaskRetry.js +2 -1
  14. package/dist/src/orchestrator/taskRunner.js +75 -16
  15. package/dist/src/plan/kerrigan.js +4 -4
  16. package/dist/src/plan/systemGuide.js +36 -36
  17. package/dist/src/queue/queue.js +19 -0
  18. package/dist/src/queue/queueBranch.js +34 -9
  19. package/dist/src/session/locatorFailures.js +10 -11
  20. package/dist/src/session/model.js +4 -0
  21. package/dist/src/session/store.js +56 -0
  22. package/dist/src/session/workspace.js +3 -2
  23. package/dist/src/transport/copilotTransport.js +83 -68
  24. package/dist/src/transport/keptWindow.js +17 -14
  25. package/dist/src/vcs/newBranch.js +28 -0
  26. package/dist/src/vcs/operatorGit.js +9 -10
  27. package/dist/src/vcs/referenceGuard.js +16 -2
  28. package/dist/web/404.html +2 -2
  29. package/dist/web/_next/static/chunks/1024-c0eee3ec374816d1.js +1 -0
  30. package/dist/web/_next/static/chunks/1077.4da389906036b1bb.js +1 -0
  31. package/dist/web/_next/static/chunks/1548.4aa3e42afe4542ab.js +1 -0
  32. package/dist/web/_next/static/chunks/2163.4c6ce20cf967756c.js +1 -0
  33. package/dist/web/_next/static/chunks/714.ffb1325246519f64.js +1 -0
  34. package/dist/web/_next/static/chunks/7220.f483b83c11525063.js +1 -0
  35. package/dist/web/_next/static/chunks/7921-946e538fe3f9630f.js +1 -0
  36. package/dist/web/_next/static/chunks/8124-967df691ec1bfeeb.js +1 -0
  37. package/dist/web/_next/static/chunks/8584.3301b056c97be517.js +1 -0
  38. package/dist/web/_next/static/chunks/9067.03cdfb01ebf6a35d.js +1 -0
  39. package/dist/web/_next/static/chunks/9747.fe06238bc42bd23d.js +1 -0
  40. package/dist/web/_next/static/chunks/app/{layout-1b7d13f7b2efd008.js → layout-7943a4391ad2f88f.js} +1 -1
  41. package/dist/web/_next/static/chunks/app/page-6ec948e0cf4b24f0.js +1 -0
  42. package/dist/web/_next/static/chunks/app/queue/page-9cfc8f78d536cfb6.js +1 -0
  43. package/dist/web/_next/static/chunks/app/settings/page-9c2b961beb8b3dce.js +1 -0
  44. package/dist/web/_next/static/chunks/{webpack-91b2de9c3da6f8b9.js → webpack-710628d673fa4afb.js} +1 -1
  45. package/dist/web/defaults.html +2 -2
  46. package/dist/web/defaults.txt +7 -7
  47. package/dist/web/index.html +3 -3
  48. package/dist/web/index.txt +8 -8
  49. package/dist/web/queue.html +2 -2
  50. package/dist/web/queue.txt +8 -8
  51. package/dist/web/settings.html +2 -2
  52. package/dist/web/settings.txt +8 -8
  53. package/dist/web/system.html +2 -2
  54. package/dist/web/system.txt +8 -8
  55. package/package.json +1 -1
  56. package/dist/web/_next/static/chunks/1024-dee283a1ddf295bf.js +0 -1
  57. package/dist/web/_next/static/chunks/1077.b7df9cb8ca810075.js +0 -1
  58. package/dist/web/_next/static/chunks/1548.417c17b63c371f00.js +0 -1
  59. package/dist/web/_next/static/chunks/2163.469367b8fbcc862d.js +0 -1
  60. package/dist/web/_next/static/chunks/714.72112704f3cb8127.js +0 -1
  61. package/dist/web/_next/static/chunks/7220.8bd897c7ddfee701.js +0 -1
  62. package/dist/web/_next/static/chunks/7921-25d1755799107ea7.js +0 -1
  63. package/dist/web/_next/static/chunks/8124-1dba8babfcfbc6e2.js +0 -1
  64. package/dist/web/_next/static/chunks/8584.f87df7324303ab75.js +0 -1
  65. package/dist/web/_next/static/chunks/9067.67a7c7cf3b019b5c.js +0 -1
  66. package/dist/web/_next/static/chunks/9747.a87dbd4acd45e39d.js +0 -1
  67. package/dist/web/_next/static/chunks/app/page-7eae1e8848525e1d.js +0 -1
  68. package/dist/web/_next/static/chunks/app/queue/page-7909ba7c9e3d4c2d.js +0 -1
  69. package/dist/web/_next/static/chunks/app/settings/page-c92548f9c6318962.js +0 -1
  70. /package/dist/web/_next/static/{UNygvDtRnBVZrGJt53IE4 → D3ew46wEw5JXPsTVwZwFC}/_buildManifest.js +0 -0
  71. /package/dist/web/_next/static/{UNygvDtRnBVZrGJt53IE4 → D3ew46wEw5JXPsTVwZwFC}/_ssgManifest.js +0 -0
@@ -24,6 +24,7 @@ import { existsSync } from 'node:fs';
24
24
  import { installLayout } from '../config/layout.js';
25
25
  import { moveLegacyHome } from '../config/home.js';
26
26
  import { captureTerminal } from '../log/terminal.js';
27
+ import { acquireApiLock } from './apiLock.js';
27
28
  /**
28
29
  * A settings file, or a policy lock, that cannot be used, answered the same way on every route: 409,
29
30
  * with the message that names the file and says what to do (see `SettingsUnusableError` and
@@ -149,6 +150,15 @@ export async function startApi(opts = {}) {
149
150
  await app.close();
150
151
  throw e;
151
152
  });
153
+ /*
154
+ * The records are this process's, or another copilot-operator runs on them and this one does not start (second bug
155
+ * hunt, 2026-11-19): started anyway, it put the other's work to rest below — its task marked stopped, its queue
156
+ * stopped — and the two wrote the same files. Before the port and before anything is recovered.
157
+ */
158
+ await acquireApiLock(dataDir, PORT).catch(async (e) => {
159
+ await app.close().catch(() => undefined);
160
+ throw e;
161
+ });
152
162
  // A port that cannot be taken (in use, or reserved by Windows: EACCES) closes what was opened, so a caller can try another.
153
163
  await app.listen(PORT, '127.0.0.1').catch(async (e) => {
154
164
  await app.close().catch(() => undefined);
@@ -8,7 +8,7 @@
8
8
  import { readdirSync, readFileSync, statSync } from 'node:fs';
9
9
  import { join, relative } from 'node:path';
10
10
  /** Files of the data folder never exported, by name: this machine's key and the API's own bookkeeping. */
11
- const NEVER = new Set(['api-token', 'dev-pids.json', '.cop-lock.json']);
11
+ const NEVER = new Set(['api-token', 'dev-pids.json', '.cop-lock.json', 'api.lock.json']);
12
12
  function filesUnder(dir) {
13
13
  const out = [];
14
14
  const walk = (d) => {
@@ -10,11 +10,12 @@
10
10
  * agreement with the bot — the time a command may take, the limits, the pauses, the reports and their redaction.
11
11
  * Each is read where it is used, so the next step, the next reply or the next message goes by the new value;
12
12
  * - from the next message (`next`): what a message is built on when it starts — the models, plan mode, the shell and
13
- * folder a step runs in by default, the project and its folders, the skills, the contract's stop word, the mode a
14
- * start takes, and the lead's number of subtasks, which its assignment states;
15
- * - when the chat window opens again (`window`): the chat's address, its browser and the waits the window was opened
16
- * with; it is kept open between messages. Its locators and the steps on the way to the chat are taken at once
17
- * (2026-11-17): the window open is handed them (`takeSettings`).
13
+ * folder a step runs in by default, the project and its folders, the skills, the contract's stop word, and the mode a
14
+ * start takes. Every limit is at once: the lead's number of subtasks too since 2026-11-18 — it is told how many are
15
+ * left with each report — as are Kerrigan's messages, the times the window is opened again and the carrying on;
16
+ * - when the chat window opens again (`window`): the chat's address and its browser; it is kept open between
17
+ * messages. Its locators and the steps on the way to the chat are taken at once (2026-11-17), and its waits for a
18
+ * reply, a sign-in and a verification (2026-11-18): the window open is handed them (`takeSettings`).
18
19
  *
19
20
  * A step that is running, and a card already put to the operator, go on as they began. The locked policy, when there is
20
21
  * one, is in what was saved (`loadConfigObject`), so it is taken with the rest and still wins.
@@ -30,16 +31,15 @@ const NOW = {
30
31
  limits: '*',
31
32
  pacing: '*',
32
33
  report: '*',
33
- // The locators and the steps on the way to the chat (2026-11-17): handed to the window open, at once (`takeSettings`).
34
- copilot: ['pickerLocators', 'chatLocators', 'pickerSteps', 'builtInSteps', 'extraSteps'],
35
- };
36
- /** Of a section taken whole, what a message is told when it starts: the lead's number of subtasks is its assignment's. */
37
- const NOT_NOW = {
38
- limits: ['maxSubtasks'],
34
+ // The locators and the steps on the way to the chat (2026-11-17): handed to the window open, at once (`takeSettings`);
35
+ // its waits too (2026-11-18), which the window kept open between messages went on with for days.
36
+ copilot: ['pickerLocators', 'chatLocators', 'pickerSteps', 'builtInSteps', 'extraSteps', 'replyTimeoutSec', 'signInTimeoutSec', 'humanWaitSec'],
39
37
  };
38
+ /** Of a section taken whole, what a message is told only when it starts: none since 2026-11-18. */
39
+ const NOT_NOW = {};
40
40
  /** What the chat window was opened with. */
41
41
  const WINDOW = {
42
- copilot: ['url', 'profileDir', 'channel', 'headless', 'replyTimeoutSec', 'signInTimeoutSec', 'humanWaitSec', 'keepFailurePage'],
42
+ copilot: ['url', 'profileDir', 'channel', 'headless', 'keepFailurePage'],
43
43
  };
44
44
  /** The sections a run compares; the rest (where the bot keeps its records) is read when the bot starts. */
45
45
  const SECTIONS = ['copilot', 'task', 'execution', 'report', 'project', 'skills', 'pacing', 'limits'];
@@ -456,6 +456,19 @@ export const RunConfigSchema = z.object({
456
456
  readOnly: z.boolean().default(false),
457
457
  }))
458
458
  .default([]),
459
+ /**
460
+ * Folders that were the project before "Open a folder" put another in their place (2026-11-19), with their name,
461
+ * level 2 and "for reference only", given back when one is opened again. Only remembered: the chat works in none
462
+ * of them.
463
+ */
464
+ earlier: z
465
+ .array(z.object({
466
+ rootDir: z.string().trim().min(1),
467
+ name: z.string().trim().default(''),
468
+ level2: z.string().default(''),
469
+ readOnly: z.boolean().default(false),
470
+ }))
471
+ .default([]),
459
472
  })
460
473
  .prefault({}),
461
474
  /**
@@ -265,24 +265,15 @@ export function scriptNetworkReason(command, cwd) {
265
265
  });
266
266
  return found;
267
267
  }
268
- /**
269
- * Why an unattended run may not begin at all, or null.
270
- *
271
- * Both conditions are about the same thing: an unattended run has given up the person who made
272
- * every other rule survivable, so the two things that stand in for them have to be there. Nowhere
273
- * to run and nobody watching is refused outright; an empty allowlist and nobody watching means
274
- * nothing at all limits a step.
275
- *
276
- * Asked in two places on purpose. At the entrance — `start`, `startBatch`, the CLI, and the button
277
- * that turns a running session unattended — so the operator is told once, before anything begins,
278
- * what to set and where. And again in `staticCheck`, because the entrance is a courtesy and the
279
- * step gate is the rule: a path that reached execution another way still finds it there.
280
- *
281
- * It is deliberately *not* a warning. The first version of this refused each step as it arrived,
282
- * which technically held the line and in practice turned the ordinary "Run sessions" button into a
283
- * run where every step came back refused — a gate that breaks the working bot is a gate that gets
284
- * switched off, and the fix was to make the condition reachable rather than to soften it.
285
- */
268
+ export function unattendedBlock(cfg) {
269
+ if (cfg.lockedToConfirm)
270
+ return 'lock';
271
+ if (unattendedIsolationRefusal('unattended', cfg.isolation ?? 'none'))
272
+ return 'isolation';
273
+ if (!cfg.allowedPrograms || cfg.allowedPrograms.length === 0)
274
+ return 'allowlist';
275
+ return null;
276
+ }
286
277
  export function unattendedPrecondition(cfg) {
287
278
  if (cfg.mode !== 'unattended')
288
279
  return null;
@@ -168,6 +168,8 @@ export async function runKerriganTask(transport, session, task, deps) {
168
168
  */
169
169
  const before = task.continuing ? task.attempts?.at(-1)?.kerrigan : undefined;
170
170
  const k = { rounds: [], sent: before?.sent ?? 0, maxSends: maxSends(), messages: 0, chats: [...(before?.chats ?? [])] };
171
+ /** The most she may send, as Settings have it now: saved during the message, it counts at once (bug hunt 2026-11-18). */
172
+ const budget = () => (k.maxSends = maxSends());
171
173
  const save = async () => {
172
174
  const copy = JSON.parse(JSON.stringify(k));
173
175
  await setTask((t) => {
@@ -762,7 +764,7 @@ export async function runKerriganTask(transport, session, task, deps) {
762
764
  ];
763
765
  if (attached)
764
766
  lines.push('', `Attached, \`${attached}\`: the whole exchange of this message, as JSON — every message the chat was sent, every reply of its, every command with all it printed. Read it where the summary above is not enough.`);
765
- lines.push('', `Messages to chats left: ${Math.max(0, k.maxSends - k.sent)} of ${k.maxSends}.`, 'Reply in your format: the next message (send), your report (done), a question for the person (ask), or blocked.');
767
+ lines.push('', `Messages to chats left: ${Math.max(0, budget() - k.sent)} of ${budget()}.`, 'Reply in your format: the next message (send), your report (done), a question for the person (ask), or blocked.');
766
768
  return lines.join('\n');
767
769
  };
768
770
  const finish = async (status, reason, summary) => {
@@ -852,8 +854,8 @@ export async function runKerriganTask(transport, session, task, deps) {
852
854
  sink.event('kerrigan-reply', { round: k.rounds.length, status: r.status }, `Kerrigan: ${r.status}${r.title ? ` — ${r.title}` : ''}`);
853
855
  switch (r.status) {
854
856
  case 'send': {
855
- if (k.sent >= k.maxSends) {
856
- r = await askHer(`You have sent the ${k.maxSends} message(s) to chats you may for this task. Deliver what you have now — status "done" with your report, what is missing said plainly — or "blocked".`, async (x) => (x.status === 'send' ? 'No message to a chat is left: reply "done" or "blocked".' : await decides(x)));
857
+ if (k.sent >= budget()) {
858
+ r = await askHer(`You have sent the ${budget()} message(s) to chats you may for this task. Deliver what you have now — status "done" with your report, what is missing said plainly — or "blocked".`, async (x) => (x.status === 'send' ? 'No message to a chat is left: reply "done" or "blocked".' : await decides(x)));
857
859
  break;
858
860
  }
859
861
  const ran = await sendToChat(r, round);
@@ -879,7 +881,7 @@ export async function runKerriganTask(transport, session, task, deps) {
879
881
  sink.event('kerrigan-question-answered', {}, 'the operator answered Kerrigan');
880
882
  await actingNow('kerrigan');
881
883
  const said = got.chosen ? `The person answered your question, ${chosenSaid({ chosen: got.chosen, ...(got.written ? { written: got.written } : {}) })}` : `The person answers your question:\n\n${got.answer.trim()}`;
882
- r = await askHer(`${said}\n\nGo on in your format. Messages to chats left: ${Math.max(0, k.maxSends - k.sent)} of ${k.maxSends}.`, decides);
884
+ r = await askHer(`${said}\n\nGo on in your format. Messages to chats left: ${Math.max(0, budget() - k.sent)} of ${budget()}.`, decides);
883
885
  break;
884
886
  }
885
887
  case 'done': {
@@ -915,6 +917,11 @@ export async function runKerriganTask(transport, session, task, deps) {
915
917
  // Why, as the kept window says it (2026-11-13): not opened again by Settings, past the times allowed, or not found.
916
918
  if (e instanceof WindowClosed || transport.closedOutside())
917
919
  return await finish('aborted', e instanceof WindowClosed ? e.message : CLOSED_NOT_REOPENED);
920
+ // A conversation the window could not be put back on, nothing sent: stopped, and Continue tries it again (2026-11-18).
921
+ if (e instanceof ChatLost) {
922
+ sink.event('chat-lost', { chatId: e.chatId, found: e.found }, message, 'warn');
923
+ return await finish('aborted', message);
924
+ }
918
925
  sink.event('task-error', { error: message, stack: e.stack }, message, 'error');
919
926
  return await finish('failed', message);
920
927
  }
@@ -20,7 +20,7 @@
20
20
  * are shown and "go back" works for the whole of it.
21
21
  */
22
22
  import { appendFile, mkdir, writeFile } from 'node:fs/promises';
23
- import { isReplyTimeout, WindowClosed } from '../transport/chatTransport.js';
23
+ import { ChatLost, isReplyTimeout, WindowClosed } from '../transport/chatTransport.js';
24
24
  import { CLOSED_NOT_REOPENED } from '../transport/keptWindow.js';
25
25
  import { buildChatName, chatCode, savePointer } from '../transport/chatSession.js';
26
26
  import { RunLog } from '../log/runLog.js';
@@ -82,12 +82,15 @@ export function assignmentMessage(task, n, facts, again) {
82
82
  * conversation, told why it stopped, to carry on from where the work got to — the subtasks and their reports are above
83
83
  * it — rather than to start the assignment again.
84
84
  */
85
- export function continuationMessage(task, n, facts) {
85
+ export function continuationMessage(task, n, facts, unreported) {
86
86
  const instruction = task.continuing?.instruction?.trim();
87
87
  return [
88
88
  `Continue assignment ${n}: ${task.title.trim() || 'untitled'}, in this same conversation. ${task.continuing ? whyItStopped(task.continuing) : ''}`.trim(),
89
89
  '',
90
90
  'Do not start over: the subtasks so far and the worker\'s reports are above in this conversation. Say in "notes" where the work got to, and carry on from there in the lead\'s format.',
91
+ ...(unreported
92
+ ? ['', `Subtask ${unreported.n} (${unreported.title}) was cut off when the work stopped, and has no report: what it did is not known. Give it again, or a subtask that checks what it left, if the work still needs it. The next subtask you give is number ${unreported.n + 1}.`]
93
+ : []),
91
94
  ...(instruction ? ['', 'The operator adds this, which wins where it and the assignment disagree:', '', instruction] : []),
92
95
  '',
93
96
  `You may give the worker up to ${facts.maxSubtasks} more subtask(s) for it.`,
@@ -141,6 +144,11 @@ export function noSubtasksLeft(max) {
141
144
  'Deliver what the work has found (status "done", with what is missing said plainly in "answer"), or stop (status "blocked", with what would let it go on in "needed").',
142
145
  ].join('\n');
143
146
  }
147
+ /** What the lead is told when it gives a subtask that changes the folder before the operator approved its plan. */
148
+ export const PLAN_BEFORE_CHANGES = [
149
+ 'That subtask was not given to the worker: it changes the folder ("readOnly": false), and the operator approves plans in this conversation, so nothing changes before your plan is approved.',
150
+ 'Send your plan first ("status": "plan"). A survey that changes nothing ("readOnly": true) may still be given before it.',
151
+ ].join('\n');
144
152
  /** The plan, as the lead is told it was approved. */
145
153
  export function leadPlanApproved(approval, left) {
146
154
  return [
@@ -196,13 +204,15 @@ export async function runLeadTask(transport, session, task, deps) {
196
204
  });
197
205
  sink.event('acting', acting, `at work now: ${ACTOR_WORDS[actor]}${more.subtask ? ` (subtask ${more.subtask})` : ''}`);
198
206
  };
199
- const max = Math.max(1, cfg.limits.maxSubtasks ?? 20);
207
+ /** "Most subtasks the lead may give", as Settings have it now: saved during the message, it counts at once (bug hunt 2026-11-18). */
208
+ const max = () => Math.max(1, cfg.limits.maxSubtasks ?? 20);
200
209
  /*
201
210
  * The most subtasks this attempt may have given in all: `max`, and as many again as the attempt before had given when a
202
- * subtask is tried again after a Stop, its record carried on (2026-10-25).
211
+ * subtask is tried again after a Stop, its record carried on (2026-10-25), or when the message is carried on (2026-11-18).
203
212
  */
204
- let limit = max;
205
- const lead = { rounds: [], subtasks: 0, maxSubtasks: max };
213
+ let givenBefore = 0;
214
+ const lead = { rounds: [], subtasks: 0, maxSubtasks: max() };
215
+ const limit = () => (lead.maxSubtasks = givenBefore + max());
206
216
  const saveLead = async () => {
207
217
  const copy = JSON.parse(JSON.stringify(lead));
208
218
  await setTask((t) => {
@@ -217,7 +227,7 @@ export async function runLeadTask(transport, session, task, deps) {
217
227
  t.runId = runId;
218
228
  t.runGroup = deps.runGroup;
219
229
  t.startedAt = new Date().toISOString();
220
- t.lead = { rounds: [], subtasks: 0, maxSubtasks: max };
230
+ t.lead = { rounds: [], subtasks: 0, maxSubtasks: max() };
221
231
  });
222
232
  await writeFile(taskLogPath, `TASK: ${task.title}\nSESSION: ${session.name} (${session.id})\nRUN: ${runId}\nSTARTED: ${new Date().toISOString()}\nMODE: lead and worker\n`, 'utf8');
223
233
  sink.event('task-started', { runId, title: task.title, lead: true }, `task "${task.title}" starting with a lead and a worker (run ${runId})`);
@@ -432,9 +442,9 @@ export async function runLeadTask(transport, session, task, deps) {
432
442
  files.length > 0 ? `Files it changed: ${files.join(', ')}.` : 'It changed no file.',
433
443
  ...((t?.deviations?.length ?? 0) > 0 ? ['', describeDeviations(t.deviations)] : []),
434
444
  '',
435
- `Subtasks left: ${limit - lead.subtasks} of ${limit}.`,
445
+ `Subtasks left: ${limit() - lead.subtasks} of ${limit()}.`,
436
446
  // Its own list, as it sent it last, to send again with the next subtask (2026-10-21).
437
- ...(lead.ledger ? ['', describeLedger(lead.ledger, lead.subtasks, limit)] : []),
447
+ ...(lead.ledger ? ['', describeLedger(lead.ledger, lead.subtasks, limit())] : []),
438
448
  'Reply in the lead\'s format: the next subtask, the plan, a question for the operator, or the result.',
439
449
  ].join('\n');
440
450
  };
@@ -571,7 +581,8 @@ export async function runLeadTask(transport, session, task, deps) {
571
581
  const sub = round.subtask;
572
582
  await saveLead();
573
583
  let attempt = (sub.attempts?.length ?? 0) + 1;
574
- let how = resume ? { fresh: resume.fresh, continued: true, restored: false, by: 'after-stop' } : { fresh: given.fresh, continued: false, restored: false };
584
+ // Put back to its start before (a card the queue kept, 2026-11-18): told it starts over, not to carry on.
585
+ let how = resume ? { fresh: resume.fresh, continued: !resume.restored, restored: !!resume.restored, by: 'after-stop' } : { fresh: given.fresh, continued: false, restored: false };
575
586
  // What the attempt before left, for the next one's message: what finished, what was cut off, what changed so far.
576
587
  let previous;
577
588
  let changedSoFar = [];
@@ -581,7 +592,8 @@ export async function runLeadTask(transport, session, task, deps) {
581
592
  const lastTask = w?.tasks.find((x) => x.id === last.taskId);
582
593
  const facts = stepFacts(await stepsOfTask(lastTask));
583
594
  previous = { why: last.reason ? `${FAILURE_WORDS[last.category ?? 'USER_STOPPED']}: ${last.reason}` : FAILURE_WORDS[last.category ?? 'USER_STOPPED'], done: facts.done, cutOff: facts.cutOff };
584
- changedSoFar = [...new Set(resume.from.attempts.flatMap((a) => (w?.tasks.find((x) => x.id === a.taskId)?.vcs?.files ?? []).map((f) => f.path)))];
595
+ // Put back to the subtask's start: nothing the attempts before changed is there any more.
596
+ changedSoFar = resume.restored ? [] : [...new Set(resume.from.attempts.flatMap((a) => (w?.tasks.find((x) => x.id === a.taskId)?.vcs?.files ?? []).map((f) => f.path)))];
585
597
  }
586
598
  let ended;
587
599
  for (;;) {
@@ -699,7 +711,7 @@ export async function runLeadTask(transport, session, task, deps) {
699
711
  try {
700
712
  const facts = {
701
713
  workDir: chatDir,
702
- maxSubtasks: max,
714
+ maxSubtasks: max(),
703
715
  maxIterations: cfg.limits.maxIterations,
704
716
  maxRunMinutes: cfg.limits.maxRunMinutes,
705
717
  planApproval: session.planMode === 'approve' && !!deps.approvePlan,
@@ -712,7 +724,14 @@ export async function runLeadTask(transport, session, task, deps) {
712
724
  const contract = (await store.getLead1()).content.trim();
713
725
  // Carried on in its own conversation: told why it stopped, and to go on from there (see `continuationMessage`).
714
726
  const carryingOn = !!task.continuing && !!session.contractSent;
715
- const assignment = carryingOn ? continuationMessage(task, n || 1, facts) : assignmentMessage(task, n || 1, facts, !!session.contractSent);
727
+ /*
728
+ * The attempt carried on (bug hunt 2026-11-18): its subtasks are counted on, not numbered from 1 again under the
729
+ * reports of 1 to k above in the conversation, and one it was cut off in, with no report, is named to the lead.
730
+ */
731
+ const prior = carryingOn ? task.attempts?.at(-1)?.lead : undefined;
732
+ const lastGiven = prior ? [...prior.rounds].reverse().find((r) => r.subtask)?.subtask : undefined;
733
+ const unreported = lastGiven && !lastGiven.report && !task.continuing?.retrySubtask ? { n: lastGiven.n, title: lastGiven.title } : undefined;
734
+ const assignment = carryingOn ? continuationMessage(task, n || 1, facts, unreported) : assignmentMessage(task, n || 1, facts, !!session.contractSent);
716
735
  await setTask((t) => {
717
736
  t.firstMessage = session.contractSent ? assignment : `${contract}\n\n---\n\n${assignment}`;
718
737
  });
@@ -733,17 +752,24 @@ export async function runLeadTask(transport, session, task, deps) {
733
752
  * folder as it is; then the lead is told to carry on, with that subtask's report.
734
753
  */
735
754
  const retryFirst = carryingOn ? task.continuing?.retrySubtask : undefined;
755
+ /*
756
+ * The rounds of the attempt before, copied with its record when a subtask is tried again after a Stop: not this
757
+ * attempt's to count against its limit (bug hunt 2026-11-18: a Stop near the last round ended the next attempt at
758
+ * the limit as soon as the retried subtask's report went out).
759
+ */
760
+ let roundsBefore = 0;
736
761
  const before = retryFirst ? task.attempts?.at(-1)?.lead : undefined;
737
762
  const from = before && retryFirst ? [...before.rounds].reverse().find((r) => r.subtask?.n === retryFirst.n)?.subtask : undefined;
738
763
  if (retryFirst && before && from) {
764
+ roundsBefore = before.rounds.length;
739
765
  lead.rounds = JSON.parse(JSON.stringify(before.rounds));
740
766
  lead.subtasks = before.subtasks;
741
767
  if (before.ledger)
742
768
  lead.ledger = before.ledger;
743
769
  if (before.workerSessionId)
744
770
  lead.workerSessionId = before.workerSessionId;
745
- limit = before.subtasks + max;
746
- lead.maxSubtasks = limit;
771
+ givenBefore = before.subtasks;
772
+ limit();
747
773
  const w = before.workerSessionId ? await store.getSession(before.workerSessionId) : null;
748
774
  const firstId = from.attempts?.[0]?.taskId ?? from.taskId;
749
775
  const firstTask = w?.tasks.find((x) => x.id === firstId);
@@ -755,12 +781,18 @@ export async function runLeadTask(transport, session, task, deps) {
755
781
  lead.rounds.push(round);
756
782
  await saveLead();
757
783
  sink.event('subtask-retry-after-stop', { n: retryFirst.n, fresh: !!retryFirst.fresh }, `subtask ${retryFirst.n} is tried again after the Stop, at the operator's word${retryFirst.fresh ? ', by a fresh worker' : ''}`);
758
- const ran = await runSubtask({ title: from.title, readOnly: !!from.readOnly, fresh: !!retryFirst.fresh, prompt: () => firstTask?.prompt ?? '' }, round, { n: retryFirst.n, fresh: !!retryFirst.fresh, from: { ...from, attempts }, firstPrompt: firstTask?.prompt ?? '' });
784
+ const ran = await runSubtask({ title: from.title, readOnly: !!from.readOnly, fresh: !!retryFirst.fresh, prompt: () => firstTask?.prompt ?? '' }, round, { n: retryFirst.n, fresh: !!retryFirst.fresh, ...(retryFirst.restored ? { restored: true } : {}), from: { ...from, attempts }, firstPrompt: firstTask?.prompt ?? '' });
759
785
  if (ran === 'stopped')
760
786
  return await finish('aborted', 'stopped by the operator');
761
787
  markdown = await tell(afterStopRetryMessage(assignment, retryFirst.n, ran.report));
762
788
  }
763
789
  else {
790
+ if (prior) {
791
+ lead.subtasks = prior.subtasks;
792
+ givenBefore = prior.subtasks;
793
+ limit();
794
+ await saveLead();
795
+ }
764
796
  markdown = await tell(assignment);
765
797
  }
766
798
  const maxFormat = () => Math.max(0, cfg.limits.maxFormatRetries ?? 2);
@@ -769,11 +801,16 @@ export async function runLeadTask(transport, session, task, deps) {
769
801
  let understood = carryingOn;
770
802
  let planVersion = 0;
771
803
  let revisions = [];
804
+ /*
805
+ * Whether a plan of this message was approved: in this attempt, or, carried on, in one before it (a plan approved on
806
+ * a card the queue kept, or before a Stop) — what lets a subtask that changes the folder go to the worker.
807
+ */
808
+ let planApproved = !!task.plan?.approved || (!!task.continuing && (task.attempts ?? []).some((a) => !!a.plan?.approved));
772
809
  const maxRounds = () => Math.max(1, cfg.limits.maxIterations);
773
810
  for (;;) {
774
811
  if (signal?.aborted)
775
812
  return await finish('aborted', 'stopped by the operator');
776
- if (lead.rounds.length >= maxRounds()) {
813
+ if (lead.rounds.length - roundsBefore >= maxRounds()) {
777
814
  limitHit = { setting: 'maxIterations', value: maxRounds() };
778
815
  return await finish('limit-reached', `maxIterations (${maxRounds()}) reached: the lead's replies`);
779
816
  }
@@ -809,7 +846,7 @@ export async function runLeadTask(transport, session, task, deps) {
809
846
  };
810
847
  lead.rounds.push(round);
811
848
  // Its list of subtasks, as this reply sends it (2026-10-21); the subtask given now is the running one.
812
- const giving = r.status === 'delegate' && r.subtask && lead.subtasks < limit ? { title: r.subtask.title, n: lead.subtasks + 1 } : undefined;
849
+ const giving = r.status === 'delegate' && r.subtask && lead.subtasks < limit() ? { title: r.subtask.title, n: lead.subtasks + 1 } : undefined;
813
850
  const listed = nextLedger(lead.ledger, r.todo, round.at, giving);
814
851
  lead.ledger = listed.ledger;
815
852
  if (listed.change) {
@@ -823,8 +860,18 @@ export async function runLeadTask(transport, session, task, deps) {
823
860
  sink.event('lead-reply', { round: round.n, status: r.status }, `the lead: ${r.status}${r.subtask ? ` — ${r.subtask.title}` : ''}`);
824
861
  switch (r.status) {
825
862
  case 'delegate': {
826
- if (lead.subtasks >= limit) {
827
- markdown = await tell(noSubtasksLeft(limit));
863
+ if (lead.subtasks >= limit()) {
864
+ markdown = await tell(noSubtasksLeft(limit()));
865
+ break;
866
+ }
867
+ /*
868
+ * Plans approved by the operator, and none approved yet (bug hunt 2026-11-18): only the contract asked the lead to
869
+ * wait, and a subtask that changes the folder went to the worker all the same. A survey that changes nothing may
870
+ * go before the plan, as the contract says; anything else waits for the plan's approval.
871
+ */
872
+ if (facts.planApproval && !planApproved && !r.subtask.readOnly) {
873
+ sink.event('lead-plan-first', { round: round.n, title: r.subtask.title }, `the lead gave a subtask that changes the folder before its plan was approved; told to send the plan first: ${r.subtask.title}`, 'warn');
874
+ markdown = await tell(PLAN_BEFORE_CHANGES);
828
875
  break;
829
876
  }
830
877
  const ran = await runSubtask(givenOf(r.subtask), round);
@@ -863,7 +910,8 @@ export async function runLeadTask(transport, session, task, deps) {
863
910
  if (t.plan)
864
911
  t.plan.approved = approved;
865
912
  });
866
- markdown = await tell(leadPlanApproved(approved, limit - lead.subtasks));
913
+ planApproved = true;
914
+ markdown = await tell(leadPlanApproved(approved, limit() - lead.subtasks));
867
915
  break;
868
916
  }
869
917
  case 'ask': {
@@ -880,7 +928,7 @@ export async function runLeadTask(transport, session, task, deps) {
880
928
  round.question.at = new Date().toISOString();
881
929
  await saveLead();
882
930
  sink.event('question-agreed', { round: round.n, question: r.question, answer: agreed }, `the lead asked: ${r.question} — answered as it recommends (Settings agree with what the bot proposes): ${agreed}`);
883
- markdown = await tell(operatorAnswerMessage(agreed, limit - lead.subtasks));
931
+ markdown = await tell(operatorAnswerMessage(agreed, limit() - lead.subtasks));
884
932
  break;
885
933
  }
886
934
  if (!deps.askQuestion) {
@@ -899,7 +947,7 @@ export async function runLeadTask(transport, session, task, deps) {
899
947
  round.question.at = new Date().toISOString();
900
948
  await saveLead();
901
949
  sink.event('lead-question-answered', { round: round.n, ...(got.by ? { by: got.by } : {}) }, got.by === 'kerrigan' ? 'Kerrigan answered the lead' : 'the operator answered the lead');
902
- markdown = await tell(operatorAnswerMessage(got.answer, limit - lead.subtasks, got.chosen ? { chosen: got.chosen, ...(got.written ? { written: got.written } : {}) } : undefined, got.by === 'kerrigan'));
950
+ markdown = await tell(operatorAnswerMessage(got.answer, limit() - lead.subtasks, got.chosen ? { chosen: got.chosen, ...(got.written ? { written: got.written } : {}) } : undefined, got.by === 'kerrigan'));
903
951
  break;
904
952
  }
905
953
  case 'done': {
@@ -926,6 +974,11 @@ export async function runLeadTask(transport, session, task, deps) {
926
974
  // Why, as the kept window says it (2026-11-13): not opened again by Settings, past the times allowed, or not found.
927
975
  if (e instanceof WindowClosed || transport.closedOutside())
928
976
  return await finish('aborted', e instanceof WindowClosed ? e.message : CLOSED_NOT_REOPENED);
977
+ // A conversation the window could not be put back on, nothing sent: stopped, and Continue tries it again (2026-11-18).
978
+ if (e instanceof ChatLost) {
979
+ sink.event('chat-lost', { chatId: e.chatId, found: e.found }, message, 'warn');
980
+ return await finish('aborted', message);
981
+ }
929
982
  sink.event('task-error', { error: message, stack: e.stack }, message, 'error');
930
983
  return await finish('failed', message);
931
984
  }
@@ -21,6 +21,7 @@
21
21
  import { readFile, writeFile, mkdir } from 'node:fs/promises';
22
22
  import { join } from 'node:path';
23
23
  import { installLayout } from '../config/layout.js';
24
+ import { ChatLost, WindowClosed } from '../transport/chatTransport.js';
24
25
  import { parseReview, formatErrorMessage, findLikelyDamage, damageGuidance } from '../protocol/parser.js';
25
26
  import { describeFindings, findingId, isGrounded } from '../protocol/reviewSchema.js';
26
27
  import { runStep } from '../exec/runner.js';
@@ -262,8 +263,8 @@ export async function runReview(transport, session, task, deps) {
262
263
  // The machine's shells, when they are not what the contract's example assumes — the same note
263
264
  // the implementer's conversation opens with, for a conversation working to the same example.
264
265
  const machineNote = shellNote(undefined, defaultShell);
265
- let before = await transport.sendAndConfirm(machineNote ? `${contract}
266
-
266
+ let before = await transport.sendAndConfirm(machineNote ? `${contract}
267
+
267
268
  ${machineNote}` : contract);
268
269
  await transport.waitForReply(before);
269
270
  await pacer.throttleSend();
@@ -572,6 +573,9 @@ ${machineNote}` : contract);
572
573
  }
573
574
  }
574
575
  catch (e) {
576
+ // The window closed, or its conversation lost: not the review failing, the work's to stop on (`gateOnReview`).
577
+ if (e instanceof ChatLost || e instanceof WindowClosed)
578
+ throw e;
575
579
  return { verdict: 'error', findings: [], stepsRun, iterations, problem: e.message };
576
580
  }
577
581
  }
@@ -25,7 +25,8 @@ export function stepFacts(steps) {
25
25
  export function classifySubtaskEnd(task, opts = {}) {
26
26
  if (task.status === 'done')
27
27
  return null;
28
- if (opts.stopped || task.status === 'aborted')
28
+ // Aborted by a fault of the chat (its conversation lost, 2026-11-18), not by the operator: a fault of the means.
29
+ if (opts.stopped || (task.status === 'aborted' && task.failure?.kind !== 'transport'))
29
30
  return 'USER_STOPPED';
30
31
  if (task.stopCode === 'environment' || task.failure?.kind === 'shell')
31
32
  return 'COMMAND_INFRASTRUCTURE_FAILURE';