copilot-operator 0.1.97 → 0.1.99

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 (82) hide show
  1. package/dist/src/api/folderPicker.js +22 -22
  2. package/dist/src/api/operator.controller.js +21 -9
  3. package/dist/src/api/operator.service.js +233 -39
  4. package/dist/src/config/exportHome.js +51 -9
  5. package/dist/src/config/home.js +27 -11
  6. package/dist/src/exec/authorizer.js +11 -4
  7. package/dist/src/exec/commandHeads.js +25 -0
  8. package/dist/src/exec/confinement.js +50 -4
  9. package/dist/src/exec/network.js +11 -1
  10. package/dist/src/exec/npmScripts.js +33 -0
  11. package/dist/src/exec/policy.js +70 -6
  12. package/dist/src/exec/processes.js +24 -5
  13. package/dist/src/exec/programs.js +21 -0
  14. package/dist/src/exec/reportFile.js +2 -1
  15. package/dist/src/exec/runner.js +31 -9
  16. package/dist/src/exec/scriptFiles.js +133 -6
  17. package/dist/src/orchestrator/handoff.js +3 -3
  18. package/dist/src/orchestrator/kerriganRunner.js +14 -6
  19. package/dist/src/orchestrator/leadRunner.js +43 -23
  20. package/dist/src/orchestrator/review.js +66 -10
  21. package/dist/src/orchestrator/taskRunner.js +73 -14
  22. package/dist/src/plan/kerrigan.js +253 -253
  23. package/dist/src/plan/schema.js +3 -13
  24. package/dist/src/plan/systemGuide.js +2 -2
  25. package/dist/src/protocol/kerriganSchema.js +5 -1
  26. package/dist/src/protocol/replySchema.js +2 -2
  27. package/dist/src/queue/queue.js +86 -0
  28. package/dist/src/session/compose.js +14 -10
  29. package/dist/src/session/locatorFailures.js +27 -6
  30. package/dist/src/session/model.js +19 -0
  31. package/dist/src/session/workspace.js +20 -5
  32. package/dist/src/transport/copilotTransport.js +82 -62
  33. package/dist/src/util/zip.js +147 -44
  34. package/dist/src/vcs/newBranch.js +20 -3
  35. package/dist/src/vcs/referenceGuard.js +9 -4
  36. package/dist/web/404.html +2 -2
  37. package/dist/web/_next/static/chunks/1077.a4fe6ae48f3d3ff9.js +1 -0
  38. package/dist/web/_next/static/chunks/1548.765d6eed5325bd01.js +1 -0
  39. package/dist/web/_next/static/chunks/2163.e8d6c85412d5d411.js +1 -0
  40. package/dist/web/_next/static/chunks/{8124-967df691ec1bfeeb.js → 6240-8ba644c53ffab87d.js} +1 -1
  41. package/dist/web/_next/static/chunks/714.f2dcd6b41b58d1a7.js +1 -0
  42. package/dist/web/_next/static/chunks/7220.652a8a339c1e7401.js +1 -0
  43. package/dist/web/_next/static/chunks/7921-9cf1ece94fc89bb3.js +1 -0
  44. package/dist/web/_next/static/chunks/{8584.3301b056c97be517.js → 8584.7c438425140f1d8d.js} +1 -1
  45. package/dist/web/_next/static/chunks/9067.8c4e6a64620a45d9.js +1 -0
  46. package/dist/web/_next/static/chunks/9747.43d25bdff8737d09.js +1 -0
  47. package/dist/web/_next/static/chunks/app/{layout-7943a4391ad2f88f.js → layout-97259931ed97e20d.js} +1 -1
  48. package/dist/web/_next/static/chunks/app/page-26e4ea30eb076e6b.js +1 -0
  49. package/dist/web/_next/static/chunks/app/queue/page-7228e045f8ea10c4.js +1 -0
  50. package/dist/web/_next/static/chunks/app/settings/page-c915d61553e1025b.js +1 -0
  51. package/dist/web/_next/static/chunks/app/system/page-4d24f44eb9077fb7.js +1 -0
  52. package/dist/web/_next/static/chunks/{webpack-710628d673fa4afb.js → webpack-31db88c3d5781520.js} +1 -1
  53. package/dist/web/_next/static/css/{523d11041085f836.css → 87999096d96266fd.css} +1 -1
  54. package/dist/web/defaults.html +2 -2
  55. package/dist/web/defaults.txt +26 -25
  56. package/dist/web/index.html +3 -3
  57. package/dist/web/index.txt +26 -25
  58. package/dist/web/queue.html +2 -2
  59. package/dist/web/queue.txt +26 -25
  60. package/dist/web/settings.html +2 -2
  61. package/dist/web/settings.txt +26 -25
  62. package/dist/web/system.html +2 -2
  63. package/dist/web/system.txt +26 -25
  64. package/package.json +3 -2
  65. package/prompts/kerrigan1.md +2 -1
  66. package/prompts/lead1.md +2 -1
  67. package/prompts/level1.md +6 -1
  68. package/prompts/review1.md +7 -4
  69. package/dist/web/_next/static/chunks/1077.4da389906036b1bb.js +0 -1
  70. package/dist/web/_next/static/chunks/1548.4aa3e42afe4542ab.js +0 -1
  71. package/dist/web/_next/static/chunks/2163.4c6ce20cf967756c.js +0 -1
  72. package/dist/web/_next/static/chunks/714.ffb1325246519f64.js +0 -1
  73. package/dist/web/_next/static/chunks/7220.f483b83c11525063.js +0 -1
  74. package/dist/web/_next/static/chunks/7921-946e538fe3f9630f.js +0 -1
  75. package/dist/web/_next/static/chunks/9067.03cdfb01ebf6a35d.js +0 -1
  76. package/dist/web/_next/static/chunks/9747.fe06238bc42bd23d.js +0 -1
  77. package/dist/web/_next/static/chunks/app/page-6ec948e0cf4b24f0.js +0 -1
  78. package/dist/web/_next/static/chunks/app/queue/page-9cfc8f78d536cfb6.js +0 -1
  79. package/dist/web/_next/static/chunks/app/settings/page-9c2b961beb8b3dce.js +0 -1
  80. package/dist/web/_next/static/chunks/app/system/page-3466496814a70b62.js +0 -1
  81. /package/dist/web/_next/static/{D3ew46wEw5JXPsTVwZwFC → n8n-2FmbL8PhXulu4hTV5}/_buildManifest.js +0 -0
  82. /package/dist/web/_next/static/{D3ew46wEw5JXPsTVwZwFC → n8n-2FmbL8PhXulu4hTV5}/_ssgManifest.js +0 -0
@@ -42,11 +42,25 @@ const HEARTBEAT_EVERY_MS = 30_000;
42
42
  * past it the text is not the whole output, and an answer read from it may not be the true one.
43
43
  */
44
44
  export const MAX_CAPTURE_CHARS = 200_000;
45
+ /**
46
+ * Of those, how much is the end of the stream (third hunt, 2026-11-20): past the cap the start was kept and the rest
47
+ * dropped, and a test run's summary and its failures, which test runners print last, never reached the chat — pointed
48
+ * at a log in the bot's own folder, which a step may not read. Past the cap now, the start and the end are kept.
49
+ */
50
+ export const KEPT_END_CHARS = 60_000;
45
51
  /**
46
52
  * How much of a line that has not ended yet is carried over to the next chunk, so the last line a
47
53
  * heartbeat shows is a whole line. Bounded, because a program can print a megabyte with no newline.
48
54
  */
49
55
  const LINE_CARRIED_CHARS = 2_000;
56
+ /** A stream as kept: its start, and past the cap its end, with what was left out between them said. */
57
+ function withEnd(start, end, omitted) {
58
+ if (!end)
59
+ return start;
60
+ if (omitted === 0)
61
+ return start + end;
62
+ return `${start}\n[runner] … ${omitted} characters of this output left out here; its end follows …\n${end}`;
63
+ }
50
64
  /** The longest delay a Node timer can hold: 2^31-1 ms, about 24.8 days. */
51
65
  const LONGEST_TIMER_MS = 2_147_483_647;
52
66
  /**
@@ -186,6 +200,9 @@ opts = {}) {
186
200
  return await new Promise((resolve) => {
187
201
  let stdout = '';
188
202
  let stderr = '';
203
+ /** Past the cap: the end of each stream, kept as it goes, and how much was left out between the start and it. */
204
+ const ends = { out: '', err: '' };
205
+ const omitted = { out: 0, err: 0 };
189
206
  let bytesOut = 0;
190
207
  let truncated = false;
191
208
  let lastLine = '';
@@ -241,8 +258,8 @@ opts = {}) {
241
258
  exitCode,
242
259
  outcome,
243
260
  durationMs: Date.now() - startedAt,
244
- stdout,
245
- stderr,
261
+ stdout: withEnd(stdout, ends.out, omitted.out),
262
+ stderr: withEnd(stderr, ends.err, omitted.err),
246
263
  truncated,
247
264
  logPath: req.logPath,
248
265
  lastOutputAgoMs: Date.now() - lastOutputAt,
@@ -289,18 +306,23 @@ opts = {}) {
289
306
  if (trimmed)
290
307
  lastLine = nl >= 0 ? trimmed.slice(nl + 1) : trimmed;
291
308
  const target = stream === 'out' ? stdout : stderr;
292
- if (target.length >= MAX_CAPTURE_CHARS) {
293
- truncated = true;
294
- return;
295
- }
296
- const room = MAX_CAPTURE_CHARS - target.length;
309
+ const startCap = MAX_CAPTURE_CHARS - KEPT_END_CHARS;
310
+ const room = Math.max(0, startCap - target.length);
297
311
  const slice = text.length > room ? text.slice(0, room) : text;
298
- if (slice.length < text.length)
299
- truncated = true;
300
312
  if (stream === 'out')
301
313
  stdout += slice;
302
314
  else
303
315
  stderr += slice;
316
+ // Past the start that is kept: the end of the stream, as it goes.
317
+ const rest = text.slice(slice.length);
318
+ if (rest) {
319
+ const end = ends[stream] + rest;
320
+ if (end.length > KEPT_END_CHARS) {
321
+ omitted[stream] += end.length - KEPT_END_CHARS;
322
+ truncated = true;
323
+ }
324
+ ends[stream] = end.slice(-KEPT_END_CHARS);
325
+ }
304
326
  };
305
327
  child.stdout.on('data', (c) => capture(c, 'out'));
306
328
  child.stderr.on('data', (c) => capture(c, 'err'));
@@ -51,8 +51,47 @@ export function scriptPathsRun(command) {
51
51
  paths.add(p);
52
52
  }
53
53
  }
54
+ /*
55
+ * `pwsh .\tools\fix.ps1`, `powershell -NoProfile .\tools\fix.ps1` (third hunt, 2026-11-20): PowerShell takes its first
56
+ * word that is not a switch as the script to run — pwsh as -File, Windows PowerShell as a command that runs it. Only
57
+ * `-File` and a script at the start of a statement were read, so a script the bot wrote ran without being read.
58
+ */
59
+ for (const call of scanCommandHeads(command, 'pwsh').calls) {
60
+ const program = call.head.replace(/^["']|["']$/g, '').replace(/^.*[\\/]/, '').replace(/\.exe$/i, '').toLowerCase();
61
+ if (program !== 'pwsh' && program !== 'powershell')
62
+ continue;
63
+ const file = shellFileArgument(call.args);
64
+ if (file && /\.ps1$/i.test(file))
65
+ paths.add(file);
66
+ }
54
67
  return [...paths];
55
68
  }
69
+ /** PowerShell's switches that take the next word as their value. */
70
+ const PWSH_VALUE = /^-(?:ExecutionPolicy|ex|ep|WorkingDirectory|wd|ConfigurationName|config|CustomPipeName|SettingsFile|settings|OutputFormat|o|of|InputFormat|inp|if|WindowStyle|w|Version|v|PSConsoleFile|ConfigurationFile)$/i;
71
+ /** PowerShell's switches after which what follows is a command, not a file. */
72
+ const PWSH_COMMAND = /^-(?:Command|c|CommandWithArgs|cwa|EncodedCommand|e|ec|enc)$/i;
73
+ /** The script a PowerShell command line is given: after `-File`, or its first word that is not a switch. */
74
+ function shellFileArgument(args) {
75
+ for (let i = 0; i < args.length; i++) {
76
+ const a = args[i];
77
+ if (a.dynamic)
78
+ return null;
79
+ const word = a.literal;
80
+ if (/^-(?:File|f)$/i.test(word))
81
+ return args[i + 1] && !args[i + 1].dynamic ? args[i + 1].literal : null;
82
+ if (/^-(?:File|f):/i.test(word))
83
+ return word.slice(word.indexOf(':') + 1);
84
+ if (PWSH_COMMAND.test(word.split(':')[0]))
85
+ return null;
86
+ if (word.startsWith('-')) {
87
+ if (!word.includes(':') && PWSH_VALUE.test(word))
88
+ i++;
89
+ continue;
90
+ }
91
+ return word;
92
+ }
93
+ return null;
94
+ }
56
95
  /** Whether the command also writes a PowerShell script — with a cmdlet or a redirection. */
57
96
  export function writesScript(command) {
58
97
  return /\b(Set-Content|Add-Content|Out-File|New-Item|Copy-Item|Move-Item|Rename-Item|sc|ac|cp|copy|mv|move|ren|ni)\b[^|;\n]*\.ps1\b|>\s*["']?[^\s"']*\.ps1\b/i.test(command);
@@ -85,8 +124,8 @@ export function scriptFileRefusal(command, cwd, screen) {
85
124
  if (paths.length === 0)
86
125
  return null;
87
126
  if (writesScript(command)) {
88
- return ('refused: this step writes a script and runs it in the same line. Write the file in one step and run it in the ' +
89
- 'next, so that what is in the file can be read before it runs.');
127
+ return ('refused: this step writes a script and runs it in the same line, so what is in it could not be read before it ran. ' +
128
+ 'Put what it does in the step itself — a command may be several lines.');
90
129
  }
91
130
  for (const file of scriptFilesRun(command, cwd)) {
92
131
  if (file.text === null)
@@ -300,12 +339,82 @@ function codeFilesRunIn(command, cwd, shell) {
300
339
  file = a;
301
340
  break;
302
341
  }
303
- if (!file || file.dynamic || !CODE_FILE.test(file.literal))
342
+ if (!file || file.dynamic)
343
+ continue;
344
+ if (CODE_FILE.test(file.literal)) {
345
+ add(file.literal);
304
346
  continue;
305
- add(file.literal);
347
+ }
348
+ /*
349
+ * `node tools\fix`, `node .`, `python tools\fix` (third hunt, 2026-11-20): a runtime finds the file it runs the way it
350
+ * finds a module — the name as given, with its extensions, the folder's package.json "main" or its index — and a file
351
+ * the bot wrote ran unread when only a name with its extension was taken as one.
352
+ */
353
+ const entry = entryRun(program, file.literal, cwd);
354
+ if (entry)
355
+ files.add(entry);
306
356
  }
307
357
  return [...files];
308
358
  }
359
+ const isFile = (p) => {
360
+ try {
361
+ return statSync(p).isFile();
362
+ }
363
+ catch {
364
+ return false;
365
+ }
366
+ };
367
+ const isFolder = (p) => {
368
+ try {
369
+ return statSync(p).isDirectory();
370
+ }
371
+ catch {
372
+ return false;
373
+ }
374
+ };
375
+ const NODE_RUNTIMES = new Set(['node', 'nodejs', 'tsx', 'ts-node', 'ts-node-esm']);
376
+ const NODE_EXTENSIONS = ['.js', '.cjs', '.mjs', '.ts', '.tsx', '.mts', '.cts', '.jsx'];
377
+ /** The file a runtime runs when given `name` without a code extension, as it would find it; null when there is none. */
378
+ function entryRun(program, name, cwd) {
379
+ // deno and bun take words of their own (`bun test`, `deno task`) where a file would be: only a file named in full is one.
380
+ if (program === 'deno' || program === 'bun')
381
+ return null;
382
+ const full = isAbsolute(name) ? name : resolve(cwd, name);
383
+ if (isFile(full))
384
+ return full;
385
+ if (NODE_RUNTIMES.has(program)) {
386
+ for (const ext of NODE_EXTENSIONS)
387
+ if (isFile(full + ext))
388
+ return full + ext;
389
+ if (isFolder(full)) {
390
+ try {
391
+ const main = JSON.parse(readFileSync(resolve(full, 'package.json'), 'utf8')).main;
392
+ if (typeof main === 'string' && main.trim()) {
393
+ const m = resolve(full, main);
394
+ if (isFile(m))
395
+ return m;
396
+ for (const ext of NODE_EXTENSIONS)
397
+ if (isFile(m + ext))
398
+ return m + ext;
399
+ for (const ext of NODE_EXTENSIONS)
400
+ if (isFile(resolve(m, `index${ext}`)))
401
+ return resolve(m, `index${ext}`);
402
+ }
403
+ }
404
+ catch {
405
+ /* no package.json, or not one that names a main: the folder's index */
406
+ }
407
+ for (const ext of NODE_EXTENSIONS)
408
+ if (isFile(resolve(full, `index${ext}`)))
409
+ return resolve(full, `index${ext}`);
410
+ }
411
+ return null;
412
+ }
413
+ if ((program === 'python' || program === 'python3' || program === 'py' || program === 'pythonw') && isFolder(full) && isFile(resolve(full, '__main__.py'))) {
414
+ return resolve(full, '__main__.py');
415
+ }
416
+ return null;
417
+ }
309
418
  /**
310
419
  * Why a file of code was written during this work, or null when it was the project's before the work began: added
311
420
  * to the repository by someone else before then, or, not committed, made on disk before then. A file of the project
@@ -373,7 +482,8 @@ export function scriptsRun(command, cwd, since, shell) {
373
482
  if (!first(file))
374
483
  continue;
375
484
  const written = inScratch(file) ? `it is in ${SCRATCH}, the folder for scratch files` : writesFileNamed(command, file) ? SAME_LINE : writtenDuringTheWork(file, since);
376
- out.push({ file, kind: kindOfFile(file), written });
485
+ // A file without an extension is of its runtime's kind: `node tools\fix` runs JavaScript.
486
+ out.push({ file, kind: kindOfFile(file) ?? kindOfRuntime(command), written });
377
487
  }
378
488
  const segments = foldersAlong(command, cwd, shell);
379
489
  for (const seg of segments) {
@@ -393,6 +503,19 @@ export function scriptsRun(command, cwd, since, shell) {
393
503
  }
394
504
  return out;
395
505
  }
506
+ /** The kind of the code a line's runtime runs, for a file named without its extension. */
507
+ function kindOfRuntime(command) {
508
+ for (const call of scanCommandHeads(command, 'pwsh').calls) {
509
+ const program = programOf(call.head);
510
+ if (NODE_RUNTIMES.has(program))
511
+ return program === 'node' || program === 'nodejs' ? 'js' : 'ts';
512
+ if (/^(?:python3?|pythonw|py)$/.test(program))
513
+ return 'py';
514
+ if (/^(?:ruby|perl|php)$/.test(program))
515
+ return 'other';
516
+ }
517
+ return null;
518
+ }
396
519
  /** No box decides it: the project's own may run, the work's may not. */
397
520
  const FIXED = { own: true, written: false };
398
521
  /** How a script is named in a refusal. */
@@ -437,7 +560,11 @@ export function ownScriptRefusal(command, cwd, since, shell, opts = {}) {
437
560
  continue;
438
561
  }
439
562
  if (run.written === SAME_LINE) {
440
- return `refused: ${name} is written and run in this same line, so nothing could read it before it ran. Write it in one step and run it in the next. ${instead}`;
563
+ /*
564
+ * "Write it in one step and run it in the next" only where the operator's box lets a script of the work run (third
565
+ * hunt, 2026-11-20): said under the default boxes, the next step was refused for the very thing it advised.
566
+ */
567
+ return `refused: ${name} is written and run in this same line, so nothing could read it before it ran.${run.kind && rule.written && !opts.reviewer ? ' Write it in one step and run it in the next.' : ''} ${instead}`;
441
568
  }
442
569
  if (!rule.written) {
443
570
  if (run.shell) {
@@ -19,7 +19,7 @@ import { existsSync, readFileSync, statSync } from 'node:fs';
19
19
  import { isAbsolute, relative, resolve } from 'node:path';
20
20
  import { dangerousRefusal } from '../exec/dangerous.js';
21
21
  import { botSelfRefusal, networkFetchReason } from '../exec/network.js';
22
- import { matchDenyPattern } from '../exec/policy.js';
22
+ import { denyPatternRefusal } from '../exec/policy.js';
23
23
  import { platformReason } from '../exec/platforms.js';
24
24
  import { codeFilesRun, shellScriptsRun } from '../exec/scriptFiles.js';
25
25
  import { endsTheShell } from '../exec/stops.js';
@@ -33,8 +33,8 @@ const inside = (roots, path) => roots.some((root) => {
33
33
  });
34
34
  /** Why the runner would refuse this text outright, or null. */
35
35
  function refusedText(text, denyPatterns) {
36
- const deny = matchDenyPattern(text, denyPatterns);
37
- const why = dangerousRefusal(text) ?? botSelfRefusal(text) ?? (deny ? `refused: matches deny pattern /${deny}/` : null);
36
+ const deny = denyPatternRefusal(text, 'pwsh', denyPatterns);
37
+ const why = dangerousRefusal(text) ?? botSelfRefusal(text) ?? (deny ? `refused: ${deny}` : null);
38
38
  return why ? why.replace(/^refused:\s*/, '') : null;
39
39
  }
40
40
  /**
@@ -105,7 +105,12 @@ function fenced(text) {
105
105
  return `${f}text\n${text.trim()}\n${f}`;
106
106
  }
107
107
  /** The opening: the person's task, with what the runner tells her about it. */
108
+ /**
109
+ * `sent`: the messages to chats a task carried on has sent already (second bug hunt, 2026-11-19), counted against the
110
+ * same allowance; told only the allowance, she sent one more after using them all and was refused.
111
+ */
108
112
  export function kerriganTaskMessage(task, n, facts, again) {
113
+ const sent = facts.sent ?? 0;
109
114
  return [
110
115
  again
111
116
  ? 'A new task from the person, in this same conversation. Your contract and the facts you were given at the start still apply unchanged: the same format, the same rules. Restate this task in "understanding" in your first reply to it.'
@@ -128,7 +133,9 @@ export function kerriganTaskMessage(task, n, facts, again) {
128
133
  '',
129
134
  ]
130
135
  : []),
131
- `You may send at most ${facts.maxSends} message(s) to chats for it.`,
136
+ sent > 0
137
+ ? `You may send at most ${facts.maxSends} message(s) to chats for it; ${sent} went out before it stopped, so ${Math.max(0, facts.maxSends - sent)} are left.`
138
+ : `You may send at most ${facts.maxSends} message(s) to chats for it.`,
132
139
  facts.chat
133
140
  ? `A chat of yours is there to carry on: "${facts.chat.name}"${facts.chat.title ? `, which worked last on "${facts.chat.title}"` : ''} — "same" sends to it.`
134
141
  : 'No chat of yours is there yet: your first message goes to a "new" one.',
@@ -241,10 +248,11 @@ export async function runKerriganTask(transport, session, task, deps) {
241
248
  * (2026-11-12: "I copy the whole JSON, or the one message, and send it to Kerrigan"); one that cannot be attached, the
242
249
  * message goes without it, saying so.
243
250
  */
244
- const tell = async (text, files = []) => {
251
+ const tell = async (text, files = [], withNotes = true) => {
245
252
  await pacer.throttleSend();
246
- // The person's notes written while the work goes on ("Add to it") go to her with her next message.
247
- const notes = await store.takeUnsentNotes(session.id, task.id).catch(() => []);
253
+ // The person's notes written while the work goes on ("Add to it") go to her with her next message — not with her
254
+ // contract, whose reply is not read (third hunt, 2026-11-20); her task, after it, carries them.
255
+ const notes = withNotes ? await store.takeUnsentNotes(session.id, task.id).catch(() => []) : [];
248
256
  const message = notes.length > 0 ? `${text}\n\n${operatorNotesSection(notes, true)}` : text;
249
257
  if (notes.length > 0)
250
258
  sink.event('operator-note-sent', { notes: notes.length, with: 'kerrigan' }, `${notes.length} note(s) from the operator go to Kerrigan`);
@@ -809,13 +817,13 @@ export async function runKerriganTask(transport, session, task, deps) {
809
817
  if (signal?.aborted)
810
818
  return await finish('aborted', 'stopped before anything was sent to Kerrigan');
811
819
  // Her acknowledgement is not read: what she does begins with the task.
812
- await tell(opening);
820
+ await tell(opening, [], false);
813
821
  session.contractSent = true;
814
822
  await store.updateSession(session.id, (s) => {
815
823
  s.contractSent = true;
816
824
  });
817
825
  }
818
- const opening = kerriganTaskMessage(task, n || 1, { maxSends: maxSends(), ...(lastChat ? { chat: { name: lastChat.name.replace(/^chat: /, ''), ...(lastTitle ? { title: lastTitle } : {}) } } : {}) }, k.messages === 0 && !!session.chat);
826
+ const opening = kerriganTaskMessage(task, n || 1, { maxSends: maxSends(), ...(task.continuing && k.sent > 0 ? { sent: k.sent } : {}), ...(lastChat ? { chat: { name: lastChat.name.replace(/^chat: /, ''), ...(lastTitle ? { title: lastTitle } : {}) } } : {}) }, k.messages === 0 && !!session.chat);
819
827
  await record('THE TASK', opening);
820
828
  if (signal?.aborted)
821
829
  return await finish('aborted', 'stopped before the task was sent to Kerrigan');
@@ -36,6 +36,7 @@ import { chosenSaid } from './chosenAnswers.js';
36
36
  import { closeLedger, describeLedger, nextLedger } from './leadLedger.js';
37
37
  import { classifySubtaskEnd, describeAttempts, FAILURE_WORDS, retryMessage, retryPlan, sanitizedReason, sideEffectsOf, stepFacts, stepsOf } from './subtaskRetry.js';
38
38
  import { ACTOR_WORDS, applySessionModel, enterSessionConversation, holdsWhilePaused, limitsMessageLength, redactsMessages, runTask, Sink, speakFor, staysOnItsChat, StoppedSend } from './taskRunner.js';
39
+ import { approvedPlanOf } from '../session/model.js';
39
40
  import { DEFAULT_VCS } from '../session/store.js';
40
41
  /** The assignment as the lead is given it: the operator's message, and what the runner tells it about the work. */
41
42
  export function assignmentMessage(task, n, facts, again) {
@@ -82,10 +83,10 @@ export function assignmentMessage(task, n, facts, again) {
82
83
  * conversation, told why it stopped, to carry on from where the work got to — the subtasks and their reports are above
83
84
  * it — rather than to start the assignment again.
84
85
  */
85
- export function continuationMessage(task, n, facts, unreported) {
86
+ export function continuationMessage(task, n, facts, unreported, committed = true) {
86
87
  const instruction = task.continuing?.instruction?.trim();
87
88
  return [
88
- `Continue assignment ${n}: ${task.title.trim() || 'untitled'}, in this same conversation. ${task.continuing ? whyItStopped(task.continuing) : ''}`.trim(),
89
+ `Continue assignment ${n}: ${task.title.trim() || 'untitled'}, in this same conversation. ${task.continuing ? whyItStopped(task.continuing, committed) : ''}`.trim(),
89
90
  '',
90
91
  '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
92
  ...(unreported
@@ -137,10 +138,19 @@ function endedAs(status) {
137
138
  return 'failed';
138
139
  }
139
140
  }
141
+ /**
142
+ * How many subtasks the lead has left, as it is told: never below none (second bug hunt, 2026-11-19). Settings lowered
143
+ * under what was given already told it "Subtasks left: -3 of 5".
144
+ */
145
+ export function subtasksLeft(given, max) {
146
+ return given > max ? `0 (${given} given; Settings now allow ${max})` : `${max - given} of ${max}`;
147
+ }
140
148
  /** What the lead is told when it has no subtask left. */
141
- export function noSubtasksLeft(max) {
149
+ export function noSubtasksLeft(max, given = max) {
142
150
  return [
143
- `No subtask is left: all ${max} of this assignment have been used. Do not send "delegate" again.`,
151
+ given > max
152
+ ? `No subtask is left: ${given} have been given, and Settings now allow ${max}. Do not send "delegate" again.`
153
+ : `No subtask is left: all ${max} of this assignment have been used. Do not send "delegate" again.`,
144
154
  '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").',
145
155
  ].join('\n');
146
156
  }
@@ -288,10 +298,14 @@ export async function runLeadTask(transport, session, task, deps) {
288
298
  let sent = 0;
289
299
  let replies = 0;
290
300
  /** One message to the lead, and its reply. */
291
- const tell = async (text) => {
301
+ /*
302
+ * `withNotes` false for the contract (third hunt, 2026-11-20): its reply is not read, and a note sent with it went with
303
+ * the rules of the conversation instead of with the work — the assignment, after it, carries them.
304
+ */
305
+ const tell = async (text, withNotes = true) => {
292
306
  await pacer.throttleSend();
293
307
  // The operator's notes written while the work goes on ("Add to it") go to the lead with its next message.
294
- const notes = await store.takeUnsentNotes(session.id, task.id).catch(() => []);
308
+ const notes = withNotes ? await store.takeUnsentNotes(session.id, task.id).catch(() => []) : [];
295
309
  const message = notes.length > 0 ? `${text}\n\n${operatorNotesSection(notes, true)}` : text;
296
310
  if (notes.length > 0)
297
311
  sink.event('operator-note-sent', { notes: notes.length, with: 'lead' }, `${notes.length} note(s) from the operator go to the lead`);
@@ -442,7 +456,7 @@ export async function runLeadTask(transport, session, task, deps) {
442
456
  files.length > 0 ? `Files it changed: ${files.join(', ')}.` : 'It changed no file.',
443
457
  ...((t?.deviations?.length ?? 0) > 0 ? ['', describeDeviations(t.deviations)] : []),
444
458
  '',
445
- `Subtasks left: ${limit() - lead.subtasks} of ${limit()}.`,
459
+ `Subtasks left: ${subtasksLeft(lead.subtasks, limit())}.`,
446
460
  // Its own list, as it sent it last, to send again with the next subtask (2026-10-21).
447
461
  ...(lead.ledger ? ['', describeLedger(lead.ledger, lead.subtasks, limit())] : []),
448
462
  'Reply in the lead\'s format: the next subtask, the plan, a question for the operator, or the result.',
@@ -730,8 +744,9 @@ export async function runLeadTask(transport, session, task, deps) {
730
744
  */
731
745
  const prior = carryingOn ? task.attempts?.at(-1)?.lead : undefined;
732
746
  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);
747
+ // Not one tried again first, nor one the operator took as failed on its card (2026-11-19): the lead is told that.
748
+ const unreported = lastGiven && !lastGiven.report && !task.continuing?.retrySubtask && task.continuing?.takenAsFailed?.n !== lastGiven.n ? { n: lastGiven.n, title: lastGiven.title } : undefined;
749
+ const assignment = carryingOn ? continuationMessage(task, n || 1, facts, unreported, !!session.vcs?.enabled) : assignmentMessage(task, n || 1, facts, !!session.contractSent);
735
750
  await setTask((t) => {
736
751
  t.firstMessage = session.contractSent ? assignment : `${contract}\n\n---\n\n${assignment}`;
737
752
  });
@@ -740,7 +755,7 @@ export async function runLeadTask(transport, session, task, deps) {
740
755
  return await finish('aborted', 'stopped before the assignment was sent');
741
756
  let markdown;
742
757
  if (!session.contractSent) {
743
- await tell(contract);
758
+ await tell(contract, false);
744
759
  session.contractSent = true;
745
760
  await store.updateSession(session.id, (s) => {
746
761
  s.contractSent = true;
@@ -805,7 +820,7 @@ export async function runLeadTask(transport, session, task, deps) {
805
820
  * Whether a plan of this message was approved: in this attempt, or, carried on, in one before it (a plan approved on
806
821
  * a card the queue kept, or before a Stop) — what lets a subtask that changes the folder go to the worker.
807
822
  */
808
- let planApproved = !!task.plan?.approved || (!!task.continuing && (task.attempts ?? []).some((a) => !!a.plan?.approved));
823
+ let planApproved = !!approvedPlanOf(task);
809
824
  const maxRounds = () => Math.max(1, cfg.limits.maxIterations);
810
825
  for (;;) {
811
826
  if (signal?.aborted)
@@ -845,8 +860,18 @@ export async function runLeadTask(transport, session, task, deps) {
845
860
  ...(r.notes ? { notes: r.notes } : {}),
846
861
  };
847
862
  lead.rounds.push(round);
848
- // Its list of subtasks, as this reply sends it (2026-10-21); the subtask given now is the running one.
849
- const giving = r.status === 'delegate' && r.subtask && lead.subtasks < limit() ? { title: r.subtask.title, n: lead.subtasks + 1 } : undefined;
863
+ /*
864
+ * Plans approved by the operator, and none approved yet (bug hunt 2026-11-18): only the contract asked the lead to
865
+ * wait, and a subtask that changes the folder went to the worker all the same. A survey that changes nothing may
866
+ * go before the plan, as the contract says; anything else waits for the plan's approval.
867
+ */
868
+ const beforePlan = r.status === 'delegate' && !!r.subtask && facts.planApproval && !planApproved && !r.subtask.readOnly;
869
+ /*
870
+ * Its list of subtasks, as this reply sends it (2026-10-21); the subtask given now is the running one. Only one that
871
+ * is given (second bug hunt, 2026-11-19): one held back for the plan was numbered as given, and the next one given
872
+ * took the same number.
873
+ */
874
+ const giving = r.status === 'delegate' && r.subtask && lead.subtasks < limit() && !beforePlan ? { title: r.subtask.title, n: lead.subtasks + 1 } : undefined;
850
875
  const listed = nextLedger(lead.ledger, r.todo, round.at, giving);
851
876
  lead.ledger = listed.ledger;
852
877
  if (listed.change) {
@@ -861,15 +886,10 @@ export async function runLeadTask(transport, session, task, deps) {
861
886
  switch (r.status) {
862
887
  case 'delegate': {
863
888
  if (lead.subtasks >= limit()) {
864
- markdown = await tell(noSubtasksLeft(limit()));
889
+ markdown = await tell(noSubtasksLeft(limit(), lead.subtasks));
865
890
  break;
866
891
  }
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) {
892
+ if (beforePlan) {
873
893
  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
894
  markdown = await tell(PLAN_BEFORE_CHANGES);
875
895
  break;
@@ -911,7 +931,7 @@ export async function runLeadTask(transport, session, task, deps) {
911
931
  t.plan.approved = approved;
912
932
  });
913
933
  planApproved = true;
914
- markdown = await tell(leadPlanApproved(approved, limit() - lead.subtasks));
934
+ markdown = await tell(leadPlanApproved(approved, Math.max(0, limit() - lead.subtasks)));
915
935
  break;
916
936
  }
917
937
  case 'ask': {
@@ -928,7 +948,7 @@ export async function runLeadTask(transport, session, task, deps) {
928
948
  round.question.at = new Date().toISOString();
929
949
  await saveLead();
930
950
  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}`);
931
- markdown = await tell(operatorAnswerMessage(agreed, limit() - lead.subtasks));
951
+ markdown = await tell(operatorAnswerMessage(agreed, Math.max(0, limit() - lead.subtasks)));
932
952
  break;
933
953
  }
934
954
  if (!deps.askQuestion) {
@@ -947,7 +967,7 @@ export async function runLeadTask(transport, session, task, deps) {
947
967
  round.question.at = new Date().toISOString();
948
968
  await saveLead();
949
969
  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');
950
- markdown = await tell(operatorAnswerMessage(got.answer, limit() - lead.subtasks, got.chosen ? { chosen: got.chosen, ...(got.written ? { written: got.written } : {}) } : undefined, got.by === 'kerrigan'));
970
+ markdown = await tell(operatorAnswerMessage(got.answer, Math.max(0, limit() - lead.subtasks), got.chosen ? { chosen: got.chosen, ...(got.written ? { written: got.written } : {}) } : undefined, got.by === 'kerrigan'));
951
971
  break;
952
972
  }
953
973
  case 'done': {
@@ -22,7 +22,8 @@ import { readFile, writeFile, mkdir } from 'node:fs/promises';
22
22
  import { join } from 'node:path';
23
23
  import { installLayout } from '../config/layout.js';
24
24
  import { ChatLost, WindowClosed } from '../transport/chatTransport.js';
25
- import { parseReview, formatErrorMessage, findLikelyDamage, damageGuidance } from '../protocol/parser.js';
25
+ import { parseReview, findLikelyDamage, damageGuidance } from '../protocol/parser.js';
26
+ import { CHECK_EXPECTS } from '../plan/schema.js';
26
27
  import { describeFindings, findingId, isGrounded } from '../protocol/reviewSchema.js';
27
28
  import { runStep } from '../exec/runner.js';
28
29
  import { effectiveShell, preferredShell, refusalForChat, resolveShell, shellNote } from '../exec/shells.js';
@@ -32,9 +33,41 @@ import { writeReport } from '../exec/reportFile.js';
32
33
  import { mergeRedactions } from '../exec/redaction.js';
33
34
  import { trackedRepoOf } from '../vcs/taskVcs.js';
34
35
  import { buildCoveringMessage, assertSendable } from '../protocol/reporter.js';
35
- import { planForReviewer } from './planMode.js';
36
+ import { describePlan, planForReviewer } from './planMode.js';
36
37
  import { inScope } from '../vcs/scope.js';
37
38
  import { gitConfigMessage, watchGitConfig } from '../vcs/gitConfigGuard.js';
39
+ /**
40
+ * What a reviewer is told when its reply did not match its contract (third hunt, 2026-11-20): its own statuses and its own
41
+ * example. It was given the implementer's message, whose example ends with "done", "blocked" or "ask" — none of them a
42
+ * review's — and a check with a guessed `expect` made the whole verdict invalid; when the retries ran out the work was
43
+ * accepted unreviewed.
44
+ */
45
+ export function reviewFormatErrorMessage(fail, attempt, maxAttempts) {
46
+ return [
47
+ `Your last reply did not match the review's format (format retry ${attempt} of ${maxAttempts}).`,
48
+ fail.reason === 'no-json-block' ? 'There was no fenced json code block in it.' : `The json block did not validate: ${fail.detail}`,
49
+ 'A review\'s "status" is "continue" (with the steps to run), "pass" or "fail" (each with its "summary"; "fail" with its "findings") — ' +
50
+ 'never "done", "blocked" or "ask", which are the implementer\'s. A finding\'s "check", when it has one, has "expect" set to one of: ' +
51
+ `${CHECK_EXPECTS.join(', ')}.`,
52
+ 'Only the format is wrong. Nothing from that reply was run. Send the same answer again, reformatted, as exactly one fenced code block ' +
53
+ 'tagged json — do not start over and do not change what it says. For example:',
54
+ '```json',
55
+ '{"status": "continue", "notes": "what this round looks at", "steps": [{"id": 1, "type": "command", "cmd": "npm test"}], "summary": "", "findings": []}',
56
+ '```',
57
+ 'or {"status": "pass", "steps": [], "summary": "several sentences: what you ran and what came back", "findings": []}',
58
+ 'or {"status": "fail", "steps": [], "summary": "…", "findings": [{"what": "…", "evidence": "…", "basis": "the sentence of the task it rests on", "where": "file and place", "about": "work", "check": {"name": "…", "expect": "exit-zero", "run": "npm test"}}]}',
59
+ ].join('\n');
60
+ }
61
+ /**
62
+ * A refusal as the reviewer is told it (third hunt, 2026-11-20): the gate's words are the implementer's, and told to "end
63
+ * blocked" — a status a review has not got — a reviewer that did so spent a format retry on it. Its own words instead.
64
+ */
65
+ export function forTheReviewer(reason) {
66
+ return reason
67
+ .replace(/\bend `?blocked`? and say in (?:`|")?(?:needed|notes)(?:`|")?/gi, 'say in a finding')
68
+ .replace(/\s+and end `?blocked`?/gi, '')
69
+ .replace(/\bin `notes`/g, 'in a finding');
70
+ }
38
71
  /** The sentence both sides get when a review left something listening. */
39
72
  function leftoverNote(leftovers) {
40
73
  const listening = leftovers.filter((l) => l.ports.length > 0);
@@ -57,7 +90,9 @@ export function deliverableFor(task, summary, tracked, changedFiles) {
57
90
  }
58
91
  export function reviewBrief(session, task, changedFiles, cwd, deviations = [], previous, disputes = [], derivedFailing = [], earlier = [], deliverable,
59
92
  /** The approved plan, in plan mode: see `planForReviewer`. */
60
- plan) {
93
+ plan,
94
+ /** The operator's notes the implementer was given (`ReviewDeps.notes`). */
95
+ notes = []) {
61
96
  // The same repository the runner branched and read the changed files from, however it is named.
62
97
  const repo = trackedRepoOf(session);
63
98
  // Each file marked against the task's scope, and the scope said: the reviewer was shown side effects as
@@ -80,6 +115,16 @@ plan) {
80
115
  '## The project instructions that applied',
81
116
  '',
82
117
  task.level2.trim() || '(none)',
118
+ /*
119
+ * The skill the task was sent with, and the operator's notes about it (third hunt, 2026-11-20): the implementer
120
+ * worked to them, and a reviewer without them judged the work against the prompt alone.
121
+ */
122
+ ...(task.skill?.text.trim()
123
+ ? ['', `## The skill the task was sent with: ${task.skill.name}`, '', ...(task.skill.description.trim() ? [`For: ${task.skill.description.trim()}`, ''] : []), task.skill.text.trim()]
124
+ : []),
125
+ ...(notes.length > 0
126
+ ? ['', "## The operator's notes about this task", '', 'Sent to the implementer while it worked; where a note and the task disagree, the note wins.', '', ...notes.map((n) => `- ${n.trim().replace(/\n/g, '\n ')}`)]
127
+ : []),
83
128
  ...(plan ? ['', planForReviewer(plan)] : []),
84
129
  ...(earlier.length > 0
85
130
  ? [
@@ -251,8 +296,19 @@ export async function runReview(transport, session, task, deps) {
251
296
  let derivedRetried = false;
252
297
  /** A finding whose basis is not in the task is sent back once; after that it is dropped. */
253
298
  let groundingRetried = false;
254
- /** What a finding may quote: this task, its instructions, and the earlier tasks it was shown. */
255
- const groundingSources = [task.prompt, task.level2, ...(deps.earlier ?? []).map((e) => e.prompt)];
299
+ /**
300
+ * What a finding may quote: this task, its instructions, the earlier tasks it was shown — and, since the third hunt
301
+ * (2026-11-20), the skill, the operator's notes, and the approved plan with what the operator added to it. The reviewer
302
+ * is told a stage left out of the plan is a finding, and such a finding was dropped as "invented".
303
+ */
304
+ const groundingSources = [
305
+ task.prompt,
306
+ task.level2,
307
+ ...(deps.earlier ?? []).map((e) => e.prompt),
308
+ task.skill?.text ?? '',
309
+ ...(deps.notes ?? []),
310
+ ...(deps.plan ? [describePlan(deps.plan), deps.plan.approved?.note ?? ''] : []),
311
+ ].filter((x) => x.trim());
256
312
  const saveReply = async (label, markdown) => {
257
313
  await writeFile(join(dir, `${label}.md`), markdown, 'utf8').catch(() => undefined);
258
314
  };
@@ -263,14 +319,14 @@ export async function runReview(transport, session, task, deps) {
263
319
  // The machine's shells, when they are not what the contract's example assumes — the same note
264
320
  // the implementer's conversation opens with, for a conversation working to the same example.
265
321
  const machineNote = shellNote(undefined, defaultShell);
266
- let before = await transport.sendAndConfirm(machineNote ? `${contract}
267
-
322
+ let before = await transport.sendAndConfirm(machineNote ? `${contract}
323
+
268
324
  ${machineNote}` : contract);
269
325
  await transport.waitForReply(before);
270
326
  await pacer.throttleSend();
271
327
  // The brief is saved as sent. Until it was, whether a later round had been told what the
272
328
  // earlier one found could not be checked from the run folder at all.
273
- const brief = reviewBrief(session, task, deps.changedFiles, deps.cwd, deps.deviations, deps.previous, deps.disputes, deps.derivedFailing, deps.earlier, deps.deliverable, deps.plan);
329
+ const brief = reviewBrief(session, task, deps.changedFiles, deps.cwd, deps.deviations, deps.previous, deps.disputes, deps.derivedFailing, deps.earlier, deps.deliverable, deps.plan, deps.notes ?? []);
274
330
  await saveReply('00-brief', brief);
275
331
  await deps.record(`REVIEW ${round} BRIEF`, brief);
276
332
  before = await transport.sendAndConfirm(brief);
@@ -296,7 +352,7 @@ ${machineNote}` : contract);
296
352
  return { verdict: 'error', findings: [], stepsRun, iterations, problem: `the reviewer would not keep its output contract: ${parsed.detail}` };
297
353
  }
298
354
  await pacer.throttleSend();
299
- const b = await transport.sendAndConfirm(formatErrorMessage(parsed, formatRetries, cfg.limits.maxFormatRetries));
355
+ const b = await transport.sendAndConfirm(reviewFormatErrorMessage(parsed, formatRetries, cfg.limits.maxFormatRetries));
300
356
  markdown = (await transport.waitForReply(b)).markdown;
301
357
  continue;
302
358
  }
@@ -479,7 +535,7 @@ ${machineNote}` : contract);
479
535
  confinement: { roots: deps.roots, cwd: deps.cwd, workStartedAt: deps.workStartedAt },
480
536
  });
481
537
  if (decision.action !== 'run') {
482
- results.push(refused(step.id, decision.reason, step.cmd, step.shell, decision.by === 'operator' ? 'operator' : 'runner'));
538
+ results.push(refused(step.id, forTheReviewer(decision.reason), step.cmd, step.shell, decision.by === 'operator' ? 'operator' : 'runner'));
483
539
  if (decision.action === 'abort')
484
540
  break;
485
541
  continue;