copilot-operator 0.1.93 → 0.1.96

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 (64) hide show
  1. package/README.md +640 -625
  2. package/dist/src/api/operator.controller.js +5 -1
  3. package/dist/src/api/operator.service.js +354 -66
  4. package/dist/src/config/live.js +12 -12
  5. package/dist/src/exec/readOnly.js +27 -2
  6. package/dist/src/orchestrator/kerriganRunner.js +20 -6
  7. package/dist/src/orchestrator/leadRunner.js +76 -23
  8. package/dist/src/orchestrator/review.js +6 -2
  9. package/dist/src/orchestrator/subtaskRetry.js +2 -1
  10. package/dist/src/orchestrator/taskRunner.js +89 -19
  11. package/dist/src/plan/kerrigan.js +263 -243
  12. package/dist/src/plan/systemGuide.js +130 -82
  13. package/dist/src/queue/queue.js +12 -0
  14. package/dist/src/queue/queueBranch.js +34 -9
  15. package/dist/src/session/compose.js +13 -0
  16. package/dist/src/session/locatorFailures.js +8 -5
  17. package/dist/src/session/store.js +9 -0
  18. package/dist/src/session/workspace.js +3 -2
  19. package/dist/src/transport/copilotTransport.js +103 -70
  20. package/dist/src/transport/keptWindow.js +17 -14
  21. package/dist/src/vcs/newBranch.js +69 -0
  22. package/dist/src/vcs/referenceGuard.js +16 -2
  23. package/dist/web/404.html +2 -2
  24. package/dist/web/_next/static/chunks/1024-214ded25b9048526.js +1 -0
  25. package/dist/web/_next/static/chunks/1077.161de82f740d47f0.js +1 -0
  26. package/dist/web/_next/static/chunks/1548.f2688468bf946e13.js +1 -0
  27. package/dist/web/_next/static/chunks/2163.b8ada3b7bde69f03.js +1 -0
  28. package/dist/web/_next/static/chunks/714.d1489788e598833b.js +1 -0
  29. package/dist/web/_next/static/chunks/7220.b85c8d105f394389.js +1 -0
  30. package/dist/web/_next/static/chunks/7921-00ebbcc6f65fbe35.js +1 -0
  31. package/dist/web/_next/static/chunks/8584.a678bfced1cea938.js +1 -0
  32. package/dist/web/_next/static/chunks/9067.6da03ae052877b19.js +1 -0
  33. package/dist/web/_next/static/chunks/9747.ba29e64e97e8a15b.js +1 -0
  34. package/dist/web/_next/static/chunks/app/{layout-1b7d13f7b2efd008.js → layout-2364903896c2c175.js} +1 -1
  35. package/dist/web/_next/static/chunks/app/{page-b71841852e6b9ff5.js → page-d031bf326e401246.js} +1 -1
  36. package/dist/web/_next/static/chunks/app/queue/page-9cfc8f78d536cfb6.js +1 -0
  37. package/dist/web/_next/static/chunks/app/settings/page-9c2b961beb8b3dce.js +1 -0
  38. package/dist/web/_next/static/chunks/{webpack-33252b1a0a7d93ba.js → webpack-3f144d13be3516c2.js} +1 -1
  39. package/dist/web/_next/static/css/{6b92f118889ca88b.css → 523d11041085f836.css} +1 -1
  40. package/dist/web/defaults.html +2 -2
  41. package/dist/web/defaults.txt +8 -8
  42. package/dist/web/index.html +3 -3
  43. package/dist/web/index.txt +9 -9
  44. package/dist/web/queue.html +2 -2
  45. package/dist/web/queue.txt +9 -9
  46. package/dist/web/settings.html +2 -2
  47. package/dist/web/settings.txt +9 -9
  48. package/dist/web/system.html +2 -2
  49. package/dist/web/system.txt +9 -9
  50. package/package.json +2 -1
  51. package/dist/web/_next/static/chunks/1024-dee283a1ddf295bf.js +0 -1
  52. package/dist/web/_next/static/chunks/1077.626a11362f53d35c.js +0 -1
  53. package/dist/web/_next/static/chunks/1548.79f05ff765581b0a.js +0 -1
  54. package/dist/web/_next/static/chunks/2163.09f1212655504f3a.js +0 -1
  55. package/dist/web/_next/static/chunks/714.acea3698b6af7a61.js +0 -1
  56. package/dist/web/_next/static/chunks/7220.1eba10bd9d449cea.js +0 -1
  57. package/dist/web/_next/static/chunks/7921-29256ac683ea4bc5.js +0 -1
  58. package/dist/web/_next/static/chunks/8584.b5aac5354f124d4b.js +0 -1
  59. package/dist/web/_next/static/chunks/9067.177163495f3bd8fa.js +0 -1
  60. package/dist/web/_next/static/chunks/9747.5b9d763e89abc7e4.js +0 -1
  61. package/dist/web/_next/static/chunks/app/queue/page-7909ba7c9e3d4c2d.js +0 -1
  62. package/dist/web/_next/static/chunks/app/settings/page-c92548f9c6318962.js +0 -1
  63. /package/dist/web/_next/static/{ZrEcjGdZEXe66UUxUqine → kNfJ9jSwlboc-1sFBBfuI}/_buildManifest.js +0 -0
  64. /package/dist/web/_next/static/{ZrEcjGdZEXe66UUxUqine → kNfJ9jSwlboc-1sFBBfuI}/_ssgManifest.js +0 -0
@@ -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'];
@@ -99,6 +99,9 @@ const AZ_SECRET = /(?:^|-)(?:keys?|credentials?|secrets?|passwords?|tokens?|sas|
99
99
  const AZ_READ = /^(?:list|show|query|exists|wait|version|what-if|(?:list|show|get)-[a-z0-9-]+|check-name(?:-availability)?)$/;
100
100
  /** The verbs that change something, in Azure or in az's own setup; and the ones named after them (`create-for-rbac`). */
101
101
  const AZ_WRITE = /^(?:create|delete|update|set|unset|add|remove|start|stop|restart|reboot|deploy|redeploy|reimage|deallocate|generalize|capture|resize|scale|swap|assign|unassign|purge|recover|restore|backup|renew|regenerate|rotate|reset|import|upload|sync|move|lock|unlock|enable|disable|approve|reject|attach|detach|connect|disconnect|apply|cancel|abort|run|invoke|execute|install|uninstall|register|unregister|grant|revoke|push|tag|untag|migrate|upgrade|failover|promote|convert|link|unlink|clear|flush|cordon|drain|retry|rerun|trigger|publish|release|merge|close|reopen|accept|archive|unarchive|schedule|power-off|rollback|repair|refresh|replace|rename|copy|patch|put|post|send|mount|unmount|activate|deactivate|pause|resume|suspend|terminate|kill)(?:-[a-z0-9-]+)?$/;
102
+ /** az's own options, which it takes anywhere, before its command too: alone, and with a value. */
103
+ const AZ_GLOBAL_FLAGS = new Set(['--debug', '--verbose', '--only-show-errors']);
104
+ const AZ_GLOBAL_WITH_VALUE = new Set(['--output', '-o', '--query', '--subscription']);
102
105
  /**
103
106
  * One `az` invocation. Its command is the group path and the verb at its end, the words before the first option:
104
107
  * `az storage account list --query ...` is `storage account list`, read by `list`. `--help` anywhere only prints help.
@@ -106,15 +109,37 @@ const AZ_WRITE = /^(?:create|delete|update|set|unset|add|remove|start|stop|resta
106
109
  function azReading(args) {
107
110
  if (args.some((a) => !a.dynamic && /^(?:--help|-h)$/i.test(a.literal)))
108
111
  return { kind: 'reads' };
112
+ /*
113
+ * az's own options may come before its command (2026-11-18: `az -o none group delete -n rg --yes` was read as `az`
114
+ * alone, "nothing but the version", and ran with no card where az is read only). Those are passed over, with the value
115
+ * of one that takes a value; any other option there is not read as anything, and is put to the operator.
116
+ */
117
+ let i = 0;
118
+ while (i < args.length) {
119
+ const a = args[i];
120
+ if (a.dynamic)
121
+ return { kind: 'unclear', why: 'a word of the az command is known only when it runs' };
122
+ if (!a.literal.startsWith('-'))
123
+ break;
124
+ const name = a.literal.split('=')[0].toLowerCase();
125
+ if (name === '--version' && args.length === 1)
126
+ return { kind: 'reads' };
127
+ if (AZ_GLOBAL_FLAGS.has(name))
128
+ i += 1;
129
+ else if (AZ_GLOBAL_WITH_VALUE.has(name))
130
+ i += a.literal.includes('=') ? 1 : 2;
131
+ else
132
+ return { kind: 'unclear', why: `az's option ${a.literal} comes before its command, and is not one of az's own options this check knows` };
133
+ }
109
134
  const path = [];
110
- for (const a of args) {
135
+ for (const a of args.slice(i)) {
111
136
  if (a.dynamic)
112
137
  return { kind: 'unclear', why: 'a word of the az command is known only when it runs' };
113
138
  if (a.literal.startsWith('-'))
114
139
  break;
115
140
  path.push(a.literal.toLowerCase());
116
141
  }
117
- // `az`, `az --version`: nothing but the version or the help.
142
+ // `az`, `az --version`, `az -o table`: nothing but the version or the help.
118
143
  if (path.length === 0)
119
144
  return { kind: 'reads' };
120
145
  const p = path.join(' ');
@@ -161,7 +161,15 @@ export async function runKerriganTask(transport, session, task, deps) {
161
161
  sink.event('acting', acting, `at work now: ${actor === 'kerrigan' ? 'Kerrigan' : actor}`);
162
162
  };
163
163
  const maxSends = () => Math.max(1, cfg.limits.maxKerriganSends ?? 6);
164
- const k = { rounds: [], sent: 0, maxSends: maxSends(), messages: 0, chats: [] };
164
+ /*
165
+ * Carried on (2026-11-18): the attempt before, of this same message — its chats, and how many messages she sent. Each
166
+ * attempt started from none, so "same" was refused ("no chat of yours is there yet"), the chat she was directing was
167
+ * lost with its conversation, and the most messages she may send began again.
168
+ */
169
+ const before = task.continuing ? task.attempts?.at(-1)?.kerrigan : undefined;
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());
165
173
  const save = async () => {
166
174
  const copy = JSON.parse(JSON.stringify(k));
167
175
  await setTask((t) => {
@@ -320,7 +328,8 @@ export async function runKerriganTask(transport, session, task, deps) {
320
328
  let lastChat = null;
321
329
  let lastTitle = '';
322
330
  {
323
- const earlier = [...session.tasks].reverse().find((x) => x.id !== task.id && (x.kerrigan?.chats.length ?? 0) > 0);
331
+ // This message's own attempt before, when it is carried on; else the last message of hers that sent to a chat.
332
+ const earlier = (before?.chats.length ?? 0) > 0 ? { kerrigan: before } : [...session.tasks].reverse().find((x) => x.id !== task.id && (x.kerrigan?.chats.length ?? 0) > 0);
324
333
  const id = earlier?.kerrigan?.chats.at(-1);
325
334
  const found = id ? await store.getSession(id) : null;
326
335
  if (found) {
@@ -755,7 +764,7 @@ export async function runKerriganTask(transport, session, task, deps) {
755
764
  ];
756
765
  if (attached)
757
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.`);
758
- 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.');
759
768
  return lines.join('\n');
760
769
  };
761
770
  const finish = async (status, reason, summary) => {
@@ -845,8 +854,8 @@ export async function runKerriganTask(transport, session, task, deps) {
845
854
  sink.event('kerrigan-reply', { round: k.rounds.length, status: r.status }, `Kerrigan: ${r.status}${r.title ? ` — ${r.title}` : ''}`);
846
855
  switch (r.status) {
847
856
  case 'send': {
848
- if (k.sent >= k.maxSends) {
849
- 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)));
850
859
  break;
851
860
  }
852
861
  const ran = await sendToChat(r, round);
@@ -872,7 +881,7 @@ export async function runKerriganTask(transport, session, task, deps) {
872
881
  sink.event('kerrigan-question-answered', {}, 'the operator answered Kerrigan');
873
882
  await actingNow('kerrigan');
874
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()}`;
875
- 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);
876
885
  break;
877
886
  }
878
887
  case 'done': {
@@ -908,6 +917,11 @@ export async function runKerriganTask(transport, session, task, deps) {
908
917
  // Why, as the kept window says it (2026-11-13): not opened again by Settings, past the times allowed, or not found.
909
918
  if (e instanceof WindowClosed || transport.closedOutside())
910
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
+ }
911
925
  sink.event('task-error', { error: message, stack: e.stack }, message, 'error');
912
926
  return await finish('failed', message);
913
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';