copilot-operator 0.1.96 → 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 (92) hide show
  1. package/dist/src/api/apiLock.js +82 -0
  2. package/dist/src/api/folderPicker.js +22 -22
  3. package/dist/src/api/main.js +5 -0
  4. package/dist/src/api/operator.controller.js +37 -11
  5. package/dist/src/api/operator.service.js +493 -86
  6. package/dist/src/api/server.js +10 -0
  7. package/dist/src/config/exportHome.js +52 -10
  8. package/dist/src/config/home.js +27 -11
  9. package/dist/src/config/schema.js +13 -0
  10. package/dist/src/exec/authorizer.js +11 -4
  11. package/dist/src/exec/commandHeads.js +25 -0
  12. package/dist/src/exec/confinement.js +50 -4
  13. package/dist/src/exec/network.js +11 -1
  14. package/dist/src/exec/npmScripts.js +33 -0
  15. package/dist/src/exec/policy.js +79 -24
  16. package/dist/src/exec/processes.js +24 -5
  17. package/dist/src/exec/programs.js +21 -0
  18. package/dist/src/exec/reportFile.js +2 -1
  19. package/dist/src/exec/runner.js +31 -9
  20. package/dist/src/exec/scriptFiles.js +133 -6
  21. package/dist/src/orchestrator/handoff.js +3 -3
  22. package/dist/src/orchestrator/kerriganRunner.js +14 -6
  23. package/dist/src/orchestrator/leadRunner.js +43 -23
  24. package/dist/src/orchestrator/review.js +66 -10
  25. package/dist/src/orchestrator/taskRunner.js +73 -14
  26. package/dist/src/plan/kerrigan.js +253 -253
  27. package/dist/src/plan/schema.js +3 -13
  28. package/dist/src/plan/systemGuide.js +28 -28
  29. package/dist/src/protocol/kerriganSchema.js +5 -1
  30. package/dist/src/protocol/replySchema.js +2 -2
  31. package/dist/src/queue/queue.js +93 -0
  32. package/dist/src/session/compose.js +14 -10
  33. package/dist/src/session/locatorFailures.js +32 -12
  34. package/dist/src/session/model.js +23 -0
  35. package/dist/src/session/store.js +47 -0
  36. package/dist/src/session/workspace.js +20 -5
  37. package/dist/src/transport/copilotTransport.js +82 -62
  38. package/dist/src/util/zip.js +147 -44
  39. package/dist/src/vcs/newBranch.js +24 -2
  40. package/dist/src/vcs/operatorGit.js +9 -10
  41. package/dist/src/vcs/referenceGuard.js +9 -4
  42. package/dist/web/404.html +2 -2
  43. package/dist/web/_next/static/chunks/1024-c0eee3ec374816d1.js +1 -0
  44. package/dist/web/_next/static/chunks/1077.a4fe6ae48f3d3ff9.js +1 -0
  45. package/dist/web/_next/static/chunks/1548.765d6eed5325bd01.js +1 -0
  46. package/dist/web/_next/static/chunks/2163.e8d6c85412d5d411.js +1 -0
  47. package/dist/web/_next/static/chunks/6240-8ba644c53ffab87d.js +1 -0
  48. package/dist/web/_next/static/chunks/714.f2dcd6b41b58d1a7.js +1 -0
  49. package/dist/web/_next/static/chunks/7220.652a8a339c1e7401.js +1 -0
  50. package/dist/web/_next/static/chunks/7921-9cf1ece94fc89bb3.js +1 -0
  51. package/dist/web/_next/static/chunks/8584.7c438425140f1d8d.js +1 -0
  52. package/dist/web/_next/static/chunks/9067.8c4e6a64620a45d9.js +1 -0
  53. package/dist/web/_next/static/chunks/9747.43d25bdff8737d09.js +1 -0
  54. package/dist/web/_next/static/chunks/app/{layout-2364903896c2c175.js → layout-97259931ed97e20d.js} +1 -1
  55. package/dist/web/_next/static/chunks/app/page-26e4ea30eb076e6b.js +1 -0
  56. package/dist/web/_next/static/chunks/app/queue/page-7228e045f8ea10c4.js +1 -0
  57. package/dist/web/_next/static/chunks/app/settings/page-c915d61553e1025b.js +1 -0
  58. package/dist/web/_next/static/chunks/app/system/page-4d24f44eb9077fb7.js +1 -0
  59. package/dist/web/_next/static/chunks/{webpack-3f144d13be3516c2.js → webpack-31db88c3d5781520.js} +1 -1
  60. package/dist/web/_next/static/css/{523d11041085f836.css → 87999096d96266fd.css} +1 -1
  61. package/dist/web/defaults.html +2 -2
  62. package/dist/web/defaults.txt +26 -25
  63. package/dist/web/index.html +3 -3
  64. package/dist/web/index.txt +26 -25
  65. package/dist/web/queue.html +2 -2
  66. package/dist/web/queue.txt +26 -25
  67. package/dist/web/settings.html +2 -2
  68. package/dist/web/settings.txt +26 -25
  69. package/dist/web/system.html +2 -2
  70. package/dist/web/system.txt +26 -25
  71. package/package.json +3 -2
  72. package/prompts/kerrigan1.md +2 -1
  73. package/prompts/lead1.md +2 -1
  74. package/prompts/level1.md +6 -1
  75. package/prompts/review1.md +7 -4
  76. package/dist/web/_next/static/chunks/1024-214ded25b9048526.js +0 -1
  77. package/dist/web/_next/static/chunks/1077.161de82f740d47f0.js +0 -1
  78. package/dist/web/_next/static/chunks/1548.f2688468bf946e13.js +0 -1
  79. package/dist/web/_next/static/chunks/2163.b8ada3b7bde69f03.js +0 -1
  80. package/dist/web/_next/static/chunks/714.d1489788e598833b.js +0 -1
  81. package/dist/web/_next/static/chunks/7220.b85c8d105f394389.js +0 -1
  82. package/dist/web/_next/static/chunks/7921-00ebbcc6f65fbe35.js +0 -1
  83. package/dist/web/_next/static/chunks/8124-1dba8babfcfbc6e2.js +0 -1
  84. package/dist/web/_next/static/chunks/8584.a678bfced1cea938.js +0 -1
  85. package/dist/web/_next/static/chunks/9067.6da03ae052877b19.js +0 -1
  86. package/dist/web/_next/static/chunks/9747.ba29e64e97e8a15b.js +0 -1
  87. package/dist/web/_next/static/chunks/app/page-d031bf326e401246.js +0 -1
  88. package/dist/web/_next/static/chunks/app/queue/page-9cfc8f78d536cfb6.js +0 -1
  89. package/dist/web/_next/static/chunks/app/settings/page-9c2b961beb8b3dce.js +0 -1
  90. package/dist/web/_next/static/chunks/app/system/page-3466496814a70b62.js +0 -1
  91. /package/dist/web/_next/static/{kNfJ9jSwlboc-1sFBBfuI → n8n-2FmbL8PhXulu4hTV5}/_buildManifest.js +0 -0
  92. /package/dist/web/_next/static/{kNfJ9jSwlboc-1sFBBfuI → n8n-2FmbL8PhXulu4hTV5}/_ssgManifest.js +0 -0
@@ -203,6 +203,12 @@ export function inlineCodeRefusal(command) {
203
203
  }
204
204
  return null;
205
205
  }
206
+ /** Ways of starting a program that no command head shows, so the allowlist cannot judge which program it is. */
207
+ const PROGRAM_STARTED_UNSEEN = [
208
+ { what: 'through .NET (System.Diagnostics.Process)', pattern: /\[\s*(?:System\.)?Diagnostics\.Process(?:StartInfo)?\s*\]|\bNew-Object\b[^|;\n]*?\b(?:System\.)?Diagnostics\.Process(?:StartInfo)?\b/i },
209
+ { what: 'through WMI (Win32_Process Create)', pattern: /\bInvoke-(?:Cim|Wmi)Method\b[^|;\n]*\bCreate\b|\bWin32_Process\b[^|;\n]*\.Create\s*\(/i },
210
+ { what: 'through a COM object', pattern: /\bNew-Object\b[^|;\n]*\s-ComObject\b|\[\s*(?:System\.)?Activator\s*\]\s*::\s*CreateInstance/i },
211
+ ];
206
212
  /**
207
213
  * Why a command may not run under the allowlist, or null.
208
214
  *
@@ -231,6 +237,21 @@ export function programRefusal(command, allowedPrograms, shell = 'pwsh') {
231
237
  : 'Write it so every program is named literally — close each quote and bracket, and call a program by its ' +
232
238
  'name or a literal path rather than through a variable or an expression.'));
233
239
  }
240
+ /*
241
+ * A program started where no head is (third hunt, 2026-11-20): through .NET, WMI or a COM object, or by Start-Process
242
+ * given a name known only when it runs. `[Diagnostics.Process]::Start('nmap', …)` and `$p='nmap'; Start-Process $p`
243
+ * ran a program the list does not name.
244
+ */
245
+ const unseen = PROGRAM_STARTED_UNSEEN.find((u) => u.pattern.test(command));
246
+ if (unseen) {
247
+ return (`refused: this starts a program ${unseen.what}, where the runner cannot tell which program it is, and only the programs in ` +
248
+ 'execution.allowedPrograms may start. Call the program by its name, as a command of its own.');
249
+ }
250
+ const chosenLater = startProcessTargets(command).find((t) => /^[$@(]/.test(t) || t.includes('$'));
251
+ if (chosenLater) {
252
+ return (`refused: Start-Process is given "${chosenLater}", a program known only when it runs, and only the programs in ` +
253
+ 'execution.allowedPrograms may start. Name the program literally.');
254
+ }
234
255
  // What `Start-Process` is asked to start is a program this line starts, as much as a head is.
235
256
  for (const head of [...scan.heads, ...startProcessTargets(command)]) {
236
257
  const program = externalProgram(head);
@@ -51,7 +51,8 @@ function sectionFor(r, maxOutputChars) {
51
51
  : `--- step ${r.id} (${r.shell}, ${r.outcome}, exit ${r.exitCode}, ` + `${(r.durationMs / 1000).toFixed(1)}s)\n$ ${r.command}\n`;
52
52
  const out = clip(r.stdout, maxOutputChars);
53
53
  const err = r.stderr.trim().length > 0 ? `[stderr]\n${clip(r.stderr, maxOutputChars)}\n` : '';
54
- const note = r.truncated ? `[note] output was truncated; the full stream is in ${r.logPath}\n` : '';
54
+ // Not a path to the log: it is in the bot's own folder, which a step may not read (third hunt, 2026-11-20).
55
+ const note = r.truncated ? '[note] the output was longer than the runner keeps: its start and its end are shown, the middle left out where it says so.\n' : '';
55
56
  // Said in the file as well as in the covering message, because the file is what gets read.
56
57
  const silent = silentFailure(r)
57
58
  ? '[note] exited non-zero and printed nothing. In PowerShell that is usually a cmdlet that found nothing (a free port, no matching process), not a failed command.\n'
@@ -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': {