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
@@ -6,7 +6,9 @@
6
6
  * Microsoft 365 sign-in — a file carrying that would sign anybody who has it in as the operator.
7
7
  */
8
8
  import { readdirSync, readFileSync, statSync } from 'node:fs';
9
+ import { readFile } from 'node:fs/promises';
9
10
  import { join, relative } from 'node:path';
11
+ import { ZipWriter } from '../util/zip.js';
10
12
  /** Files of the data folder never exported, by name: this machine's key and the API's own bookkeeping. */
11
13
  const NEVER = new Set(['api-token', 'dev-pids.json', '.cop-lock.json', 'api.lock.json']);
12
14
  function filesUnder(dir) {
@@ -44,17 +46,11 @@ export function exportSizes(layout) {
44
46
  const runs = filesUnder(layout.runsDir);
45
47
  return { data: data.reduce((n, f) => n + f.size, 0), dataFiles: data.length, runs: runs.reduce((n, f) => n + f.size, 0), runsFiles: runs.length };
46
48
  }
47
- /** The files of an export, named as they go in the archive (`data/…`, `runs/…`), and its manifest first. */
48
- export function exportEntries(layout, opts) {
49
+ export function exportPlan(layout, opts) {
49
50
  const now = opts.now ?? new Date();
50
- const entries = [];
51
- const add = (root, under) => (f) => {
52
- entries.push({ name: `${under}/${relative(root, f.path).replace(/\\/g, '/')}`, data: readFileSync(f.path), mtime: f.mtime });
53
- };
51
+ const named = (root, under) => (f) => ({ name: `${under}/${relative(root, f.path).replace(/\\/g, '/')}`, path: f.path, mtime: f.mtime });
54
52
  const data = dataFiles(layout);
55
- data.forEach(add(layout.dataDir, 'data'));
56
53
  const runs = opts.runs ? filesUnder(layout.runsDir) : [];
57
- runs.forEach(add(layout.runsDir, 'runs'));
58
54
  const manifest = {
59
55
  exportedBy: `copilot-operator ${opts.version}`,
60
56
  exportedAt: now.toISOString(),
@@ -69,7 +65,53 @@ export function exportEntries(layout, opts) {
69
65
  ...(opts.runs ? [] : [{ what: 'runs/', why: 'not asked for' }]),
70
66
  ],
71
67
  };
72
- return [{ name: 'manifest.json', data: Buffer.from(JSON.stringify(manifest, null, 2), 'utf8'), mtime: now }, ...entries];
68
+ return { files: [...data.map(named(layout.dataDir, 'data')), ...runs.map(named(layout.runsDir, 'runs'))], manifest, now };
69
+ }
70
+ /** The manifest as it goes in, with the files that could not be read named. */
71
+ function manifestEntry(plan, notRead) {
72
+ const manifest = notRead.length > 0 ? { ...plan.manifest, notRead } : plan.manifest;
73
+ return { name: 'manifest.json', data: Buffer.from(JSON.stringify(manifest, null, 2), 'utf8'), mtime: plan.now };
74
+ }
75
+ /** The files of an export, read now, and its manifest last: for a few small files. An export goes through `writeExport`. */
76
+ export function exportEntries(layout, opts) {
77
+ const plan = exportPlan(layout, opts);
78
+ const entries = [];
79
+ const notRead = [];
80
+ for (const f of plan.files) {
81
+ try {
82
+ entries.push({ name: f.name, data: readFileSync(f.path), mtime: f.mtime });
83
+ }
84
+ catch (e) {
85
+ notRead.push({ what: f.name, why: e.message });
86
+ }
87
+ }
88
+ return [...entries, manifestEntry(plan, notRead)];
89
+ }
90
+ /**
91
+ * An export written to the download as it goes (second bug hunt, 2026-11-19): one file read at a time, off the API's
92
+ * thread, the archive never whole in memory. A file that cannot be read — held by another program, gone since it was
93
+ * listed — is named in the manifest, which goes in last, and the rest go on: it failed the whole export, which the
94
+ * page's link then saved as a file of its own, the reason not shown.
95
+ */
96
+ export async function writeExport(plan, out) {
97
+ const zip = new ZipWriter(out);
98
+ const notRead = [];
99
+ let files = 0;
100
+ for (const f of plan.files) {
101
+ let data;
102
+ try {
103
+ data = await readFile(f.path);
104
+ }
105
+ catch (e) {
106
+ notRead.push({ what: f.name, why: e.message });
107
+ continue;
108
+ }
109
+ await zip.add({ name: f.name, data, mtime: f.mtime });
110
+ files += 1;
111
+ }
112
+ await zip.add(manifestEntry(plan, notRead));
113
+ await zip.finish();
114
+ return { files, notRead: notRead.length };
73
115
  }
74
116
  /** The export's file name: copilot-operator-export-20261023-1142.zip. */
75
117
  export function exportFileName(now = new Date()) {
@@ -8,7 +8,7 @@
8
8
  * were kept until then — `.copilot-operator` in the folder it was started from — and none yet in its folder copies
9
9
  * them over once, and says so; the old folder is left for the operator to delete.
10
10
  */
11
- import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
11
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
12
12
  import { isAbsolute, join, resolve, sep } from 'node:path';
13
13
  import { defaultHome, HOME_CHOICE_FILE } from './layout.js';
14
14
  /** The file in the bot's folder that says where its records were copied from, and when. */
@@ -77,23 +77,39 @@ export function homeRefusal(dir, layout) {
77
77
  }
78
78
  /**
79
79
  * The operator's choice of folder, written where the next start reads it; `null` back to the default. With `copy`,
80
- * what is in the folder now — settings, conversations, logs, the Edge profile — is copied into the new one first,
81
- * leaving out what the new one has already (`kept`): nothing in it is overwritten. Takes effect when the bot starts
80
+ * what is in the folder now — settings, conversations, logs, the Edge profile — is copied into the new one first.
81
+ * What the new one has already of those is put aside beside it (`asideDir`, `<folder>.before-<when>`), never overwritten
82
+ * and never used (second bug hunt, 2026-11-19): it was kept and used, so "Back to the default" with a copy came back to
83
+ * the records the default had before the move, and the work since stayed behind, with only "Saved" said. Beside the
84
+ * folder, not in it, so an export of the folder never takes an old Edge profile along. Takes effect when the bot starts
82
85
  * again.
83
86
  */
84
- export function chooseHome(layout, dir, copy, env = process.env) {
87
+ export function chooseHome(layout, dir, copy, env = process.env, now = new Date()) {
85
88
  const target = dir ? resolve(dir.trim()) : defaultHome(env);
86
89
  const copied = [];
87
- const kept = [];
90
+ const aside = [];
91
+ let asideDir;
88
92
  if (copy && !same(target, layout.homeDir) && existsSync(layout.homeDir)) {
89
93
  mkdirSync(target, { recursive: true });
90
- for (const part of readdirSync(layout.homeDir)) {
91
- if (part === HOME_CHOICE_FILE || part === MOVED_FILE)
92
- continue;
93
- if (existsSync(join(target, part))) {
94
- kept.push(part);
94
+ const parts = readdirSync(layout.homeDir).filter((part) => part !== HOME_CHOICE_FILE && part !== MOVED_FILE);
95
+ for (const part of parts) {
96
+ if (!existsSync(join(target, part)))
95
97
  continue;
98
+ if (!asideDir) {
99
+ const stamp = now.toISOString().slice(0, 19).replace(/[-:]/g, '').replace('T', '-');
100
+ asideDir = `${target.replace(/[\\/]+$/, '')}.before-${stamp}`;
101
+ mkdirSync(asideDir, { recursive: true });
102
+ }
103
+ try {
104
+ renameSync(join(target, part), join(asideDir, part));
96
105
  }
106
+ catch (e) {
107
+ throw new Error(`"${part}" in ${target} could not be put aside, to copy the bot's own in its place (${e.message}). ` +
108
+ `${aside.length > 0 ? `Put aside already, in ${asideDir}: ${aside.join(', ')}. ` : ''}Nothing was copied; the folder is not chosen.`);
109
+ }
110
+ aside.push(part);
111
+ }
112
+ for (const part of parts) {
97
113
  cpSync(join(layout.homeDir, part), join(target, part), { recursive: true, force: false, errorOnExist: false });
98
114
  copied.push(part);
99
115
  }
@@ -105,5 +121,5 @@ export function chooseHome(layout, dir, copy, env = process.env) {
105
121
  rmSync(pointer, { force: true });
106
122
  else
107
123
  writeFileSync(pointer, JSON.stringify({ home: target }, null, 2), 'utf8');
108
- return { home: target, copied, kept };
124
+ return { home: target, copied, aside, ...(asideDir ? { asideDir } : {}) };
109
125
  }
@@ -38,9 +38,14 @@ export function makeAuthorizer(cfg, askPerson, signal) {
38
38
  * Asked, and the run gone over to running without asking meanwhile ("run the rest without asking"): the rules of a
39
39
  * run nobody watches are put to the step before it runs (audit, 2026-10-27) — it was checked as a watched one.
40
40
  */
41
+ /*
42
+ * Not the step whose own card the operator answered (third hunt, 2026-11-20): "Run this and the rest" turns the run
43
+ * unattended before its step is answered, and that step, read and pressed by a person, was then refused as one nobody
44
+ * read (`node -e`, a nested shell) and the rest of the round skipped.
45
+ */
41
46
  const ask = async (s, c, held) => {
42
47
  const decided = await askPerson(s, c, held);
43
- return decided.action === 'run' && cfg.mode === 'unattended' ? (staticCheck(s, cfg, undefined, c.confinement, c.actor) ?? decided) : decided;
48
+ return decided.action === 'run' && decided.by !== 'operator' && cfg.mode === 'unattended' ? (staticCheck(s, cfg, undefined, c.confinement, c.actor) ?? decided) : decided;
44
49
  };
45
50
  const cwd = ctx.confinement?.cwd;
46
51
  // Scripts the bot wrote that the operator's boxes let run (2026-10-27): what is in them goes on the card.
@@ -73,17 +78,19 @@ export function makeAuthorizer(cfg, askPerson, signal) {
73
78
  ...(unclear ? { readOnly: unclear.why, readOnlyProgram: unclear.program } : {}),
74
79
  ...(scripts.length ? { scripts } : {}),
75
80
  };
81
+ // The bot's scripts go on a card with their text, unless Settings run them without asking (2026-10-27).
82
+ const scriptsAsked = scripts.length > 0 && !(cfg.mode === 'unattended' && cfg.writtenScripts === 'run');
76
83
  if (network) {
77
84
  if (cfg.mode === 'unattended' && cfg.networkFetch === 'refuse')
78
85
  return { action: 'skip', reason: networkFetchRefusal(network) };
79
- if (!platform && cfg.mode === 'unattended' && cfg.networkFetch === 'run')
86
+ // A download Settings run without asking still waits for the card of a script the bot wrote (third hunt, 2026-11-20).
87
+ if (!platform && !scriptsAsked && cfg.mode === 'unattended' && cfg.networkFetch === 'run')
80
88
  return { action: 'run' };
81
89
  return await ask(step, ctx, { network, ...held });
82
90
  }
83
91
  if (platform)
84
92
  return await ask(step, ctx, held);
85
- // The bot's scripts: on a card with their text, unless Settings run them without asking (2026-10-27).
86
- if (scripts.length && !(cfg.mode === 'unattended' && cfg.writtenScripts === 'run'))
93
+ if (scriptsAsked)
87
94
  return await ask(step, ctx, held);
88
95
  if (cfg.mode === 'unattended' || ctx.chosen)
89
96
  return { action: 'run' };
@@ -470,7 +470,20 @@ class PowerShellScan {
470
470
  /** A bare word, with the quoted parts and escapes inside it resolved. */
471
471
  readWord(i) {
472
472
  let literal = '';
473
+ /*
474
+ * `@name` where an argument starts is a splat (third hunt, 2026-11-20): PowerShell hands the program the words the
475
+ * variable holds, known only when it runs. Read as the word "@a", `$a=@('group','delete'); az @a list` was az's
476
+ * `list`, a read, and deleted the resource group; `git @a` got past every git rule. Only the name alone: `@types/node`
477
+ * is the text it reads as, which PowerShell hands over as written.
478
+ */
473
479
  let dynamic = false;
480
+ if (this.at(i) === '@' && isIdent(this.at(i + 1))) {
481
+ let k = i + 1;
482
+ while (isIdent(this.at(k)))
483
+ k += 1;
484
+ const after = this.at(k);
485
+ dynamic = after === '' || isSpace(after) || WORD_BREAK.has(after);
486
+ }
474
487
  let j = i;
475
488
  while (j < this.s.length) {
476
489
  const c = this.at(j);
@@ -812,6 +825,18 @@ function scanCmd(src) {
812
825
  k += 3; // a EQU b
813
826
  }
814
827
  else if (word() === 'for') {
828
+ /*
829
+ * `for /f %i in ('nmap -sV host') do …` runs the command in its brackets (third hunt, 2026-11-20): only the one
830
+ * after `do` was read, so a program not on the list ran there unseen. With `usebackq` the command is in back-quotes.
831
+ */
832
+ const inner = /\bin\s*\(\s*(['`])([\s\S]*?)\1\s*\)/i.exec(segment);
833
+ if (inner && tokens.some((t) => t.toLowerCase() === '/f')) {
834
+ const sub = scanCmd(inner[2]);
835
+ heads.push(...sub.heads);
836
+ calls.push(...sub.calls);
837
+ if (sub.uncertain)
838
+ fail(sub.uncertain);
839
+ }
815
840
  const doAt = tokens.findIndex((t) => t.toLowerCase() === 'do');
816
841
  k = doAt < 0 ? tokens.length : doAt + 1;
817
842
  }
@@ -37,6 +37,7 @@
37
37
  * that is the operating system's to give — a separate Windows account whose file permissions reach
38
38
  * the project folders and nothing of the operator's — and the README says how.
39
39
  */
40
+ import { existsSync } from 'node:fs';
40
41
  import { win32 } from 'node:path';
41
42
  function normalise(p) {
42
43
  return win32.resolve(p).replace(/[\\/]+$/, '').toLowerCase();
@@ -103,6 +104,9 @@ const HOME_VAR = /\$HOME\b/i;
103
104
  const TILDE = /(?:^|[\s"'=(,])~(?=[\\/]|$|[\s"'`;|&)])/;
104
105
  /** Changing to the root of the current drive, which needs no drive letter to leave the project. */
105
106
  const CD_TO_ROOT = /(?:^|[\s;|&({])(?:Set-Location|Push-Location|cd|chdir|sl|pushd)\s+["']?[\\/]["']?(?=$|[\s;|&)}])/i;
107
+ /** A drive alone where a word starts, and a change of location to one, quoted or not. */
108
+ const LONE_DRIVE = /(?:^|[\s;|&({])([A-Za-z]:)(?=$|[\s;|&)}])/g;
109
+ const CD_TO_DRIVE = /(?:^|[\s;|&({])(?:Set-Location|Push-Location|cd|chdir|sl|pushd)\s+(?:-\w+\s+)?["']?([A-Za-z]:)["']?(?=$|[\s;|&)}])/i;
106
110
  /** A path segment that climbs: `..` on its own, or between separators. */
107
111
  const CLIMBS = /(?:^|[\\/])\.\.(?:$|[\\/])/;
108
112
  /**
@@ -287,16 +291,58 @@ export function confinementRefusal(command, c) {
287
291
  return outside('a network share is not the project', c);
288
292
  if (CD_TO_ROOT.test(line))
289
293
  return outside('this changes to the root of the drive', c);
294
+ /*
295
+ * A drive alone — `cd D:`, `Set-Location "D:"`, `D:` as a statement, `Get-ChildItem D:` — is that drive's current folder
296
+ * (third hunt, 2026-11-20). Read outside quotes, or after a change of location: `{ c: 1, d: 2 }` in code is not one.
297
+ */
298
+ const lone = [...line.replace(QUOTED, ' ').matchAll(LONE_DRIVE)].map((m) => m[1]);
299
+ const cdDrive = CD_TO_DRIVE.exec(line);
300
+ if (cdDrive)
301
+ lone.push(cdDrive[1]);
302
+ for (const d of lone) {
303
+ const where = win32.resolve(c.cwd, d);
304
+ if (!isWithin(where, c.roots))
305
+ return outside(`\`${d}\` is ${where}, outside the project`, c);
306
+ }
290
307
  for (const p of drivePaths(line)) {
291
308
  if (!isWithin(p, c.roots))
292
309
  return outside(`\`${p}\` is outside the project`, c);
293
310
  }
294
311
  for (const t of tokens(line)) {
295
- if (!CLIMBS.test(t))
312
+ if (CLIMBS.test(t)) {
313
+ const resolved = win32.resolve(c.cwd, t);
314
+ if (!isWithin(resolved, c.roots))
315
+ return outside(`\`${t}\` climbs out of the project to ${resolved}`, c);
296
316
  continue;
297
- const resolved = win32.resolve(c.cwd, t);
298
- if (!isWithin(resolved, c.roots))
299
- return outside(`\`${t}\` climbs out of the project to ${resolved}`, c);
317
+ }
318
+ const fromRoot = rootRelative(t, c.cwd);
319
+ if (fromRoot && !isWithin(fromRoot, c.roots))
320
+ return outside(`\`${t}\` is ${fromRoot}, outside the project`, c);
300
321
  }
301
322
  return null;
302
323
  }
324
+ /**
325
+ * Where a path written without its drive's letter leads, or null when the word is not one (third hunt, 2026-11-20):
326
+ * `\Users\x\.ssh\id_rsa` and `/Users/x` from the root of the folder's drive, `D:x.txt` and `D:` on another drive's
327
+ * current folder. Only `X:\` paths, shares and `..` were read, so `Get-Content \Users\<name>\.ssh\id_rsa` sent the key
328
+ * to the chat. A word led by a separator is a path only when its first part is there at the drive's root — `\d+` in a
329
+ * pattern, `/p:Configuration=Release`, `/s` and `/api/users` are not — and a separator alone is not read here
330
+ * (`.Replace('\', '/')`; a change to the root is `CD_TO_ROOT`'s).
331
+ */
332
+ function rootRelative(t, cwd) {
333
+ /*
334
+ * `D:` alone, or with what reads as a path after it (`D:x.txt`, `D:dir\x`), or a name there on that drive: not the
335
+ * `{d:1}` of an object written inline. On the folder's own drive it resolves into the folder, as PowerShell does.
336
+ */
337
+ const drive = /^[A-Za-z]:(?![\\/])(.*)$/.exec(t);
338
+ if (drive) {
339
+ const where = win32.resolve(cwd, t);
340
+ return drive[1] && (/[.\\/]/.test(drive[1]) || existsSync(where)) ? where : null;
341
+ }
342
+ if (!/^[\\/](?![\\/])/.test(t))
343
+ return null;
344
+ const first = t.slice(1).split(/[\\/]/)[0] ?? '';
345
+ if (!first || /[*?<>|":]/.test(first))
346
+ return null;
347
+ return existsSync(win32.resolve(cwd, `\\${first}`)) ? win32.resolve(cwd, t) : null;
348
+ }
@@ -142,7 +142,17 @@ const FILE_EXTENSIONS = new Set([
142
142
  'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'css', 'map', 'ps1', 'psm1', 'cs', 'py', 'java', 'go', 'rs',
143
143
  'png', 'jpg', 'jpeg', 'gif', 'svg', 'ico', 'webp', 'pdf', 'out', 'tmp', 'bak', 'lock',
144
144
  'exe', 'cmd', 'bat', 'dll', 'tar', 'gz', 'tgz',
145
+ // A project's own files named in a local request (third hunt, 2026-11-20): `App.vue`, `page.aspx`, `site.scss`.
146
+ 'vue', 'svelte', 'astro', 'aspx', 'ascx', 'cshtml', 'razor', 'scss', 'sass', 'less', 'sql', 'graphql', 'gql',
147
+ 'woff', 'woff2', 'ttf', 'zip', 'env', 'sh', 'rb', 'php', 'kt', 'swift', 'mts', 'cts',
145
148
  ]);
149
+ /**
150
+ * The text a request sends, as PowerShell's `-Body`/`-Form` and curl's `-d`/`--data…`/`--json`/`-F` give it: data for
151
+ * the address the URL names, not a place the request goes (third hunt, 2026-11-20 — `-Body '{"email":"user@test.com"}'`
152
+ * read `test.com` as a second host, and a local API test was held as a download). Only a quoted value that runs nothing:
153
+ * a double-quoted one with `$` in it can hold `$(…)`, which runs, and is read as before.
154
+ */
155
+ const SENT_TEXT = /(\s(?:-Body|-Form|-d|--data(?:-raw|-binary|-urlencode|-ascii)?|--json|-F|--form)(?::|=|\s+))('(?:[^']|'')*'|"[^"$`]*")/gi;
146
156
  /**
147
157
  * The host a URL names, read from the text after its `://`, or null when it cannot be read for
148
158
  * certain.
@@ -229,7 +239,7 @@ export function onlyLoopbackTargets(command) {
229
239
  * quote, `;`, `|`, `&`, a bracket or a comma — so that a second command glued on after a path
230
240
  * (`…/x;iwr('evil.example')`) is still read.
231
241
  */
232
- const rest = command.replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s'"`;|&(){}<>,]*/gi, ' ');
242
+ const rest = command.replace(SENT_TEXT, '$1 ').replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s'"`;|&(){}<>,]*/gi, ' ');
233
243
  for (const token of rest.split(/[\s'"`=,;|&(){}<>]+/)) {
234
244
  // A bracketed IPv6 address anywhere in the token: a proxy (`-x [2001:db8::1]:8080`) or an address given to curl.
235
245
  for (const v6 of token.matchAll(/\[([0-9a-f:.]*:[0-9a-f:.]*)\]/gi))
@@ -14,6 +14,7 @@ import { existsSync, readFileSync, statSync } from 'node:fs';
14
14
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
15
15
  import { gitSync } from '../vcs/git.js';
16
16
  import { scanCommandHeads } from './commandHeads.js';
17
+ import { foldersAlong } from './locations.js';
17
18
  const RUNNERS = new Set(['npm', 'pnpm', 'yarn', 'bun']);
18
19
  /** The runners' own commands, which a bare word after them is before it is a script's name (pnpm, yarn and bun run a script by its name alone). */
19
20
  const OWN_COMMANDS = new Set([
@@ -133,6 +134,38 @@ export function packageScriptsRun(command, cwd, shell) {
133
134
  }
134
135
  return out;
135
136
  }
137
+ /**
138
+ * What a line's npm or pnpm left out of package.json (third hunt, 2026-11-20): a step is started with scripts off
139
+ * (`npm_config_ignore_scripts`, `stepEnv.ts`), which keeps a package's install scripts from running — and also each
140
+ * script's `pre…` and `post…`. `npm test` ran without its `pretest` (a build first, say) and came back as an ordinary pass
141
+ * or fail, nothing said. The words for the step's output, or null when nothing was left out.
142
+ */
143
+ export function npmHooksNote(command, cwd, shell) {
144
+ const left = [];
145
+ for (const seg of foldersAlong(command, cwd, shell)) {
146
+ for (const call of scanCommandHeads(seg.text, shell ?? 'pwsh').calls) {
147
+ const runner = call.head.replace(/^.*[\\/]/, '').replace(/\.(?:exe|cmd|ps1)$/i, '').toLowerCase();
148
+ if (runner !== 'npm' && runner !== 'pnpm')
149
+ continue;
150
+ for (const run of packageScriptsRun(seg.text, seg.cwd, shell)) {
151
+ if (run.dynamic || run.command === null)
152
+ continue;
153
+ const scripts = scriptsOnDisk(run.pkg);
154
+ for (const hook of [`pre${run.name}`, `post${run.name}`]) {
155
+ const cmd = scripts?.[hook];
156
+ if (cmd && !left.some((l) => l.startsWith(`"${hook}"`)))
157
+ left.push(`"${hook}" (${cmd.length > 120 ? `${cmd.slice(0, 120)}…` : cmd})`);
158
+ }
159
+ }
160
+ break;
161
+ }
162
+ }
163
+ if (left.length === 0)
164
+ return null;
165
+ return (`npm left out package.json's ${left.join(' and ')} here: the runner starts npm with scripts off, which keeps packages' ` +
166
+ 'install scripts from running and also skips a script\'s "pre" and "post" scripts. If the work needs one, run it as a step of its ' +
167
+ `own first (npm run ${left[0].slice(1, left[0].indexOf('"', 1))}).`);
168
+ }
136
169
  /** Whether a line writes package.json's scripts itself: `npm pkg set scripts.x=…`, `npm set-script`, or the file written. */
137
170
  export function writesPackageScripts(command) {
138
171
  return (/\b(?:npm|pnpm)(?:\.cmd)?\s+(?:pkg\s+set\b[^|;\n]*\bscripts\.|set-script\b)/i.test(command) ||
@@ -1,7 +1,7 @@
1
1
  import { effectiveShell } from './shells.js';
2
2
  import { dangerousRefusal } from './dangerous.js';
3
3
  import { findShellExecuteTrap } from './shellExecuteTrap.js';
4
- import { inlineCodeRefusal, programRefusal } from './programs.js';
4
+ import { inlineCodeRefusal, programRefusal, startProcessTargets } from './programs.js';
5
5
  import { unattendedIsolationRefusal } from './isolation.js';
6
6
  import { confinementRefusal } from './confinement.js';
7
7
  import { botSelfRefusal, networkFetchReason, networkFetchRefusal } from './network.js';
@@ -31,6 +31,70 @@ export function matchDenyPattern(text, patterns) {
31
31
  }
32
32
  return null;
33
33
  }
34
+ /** git's own options before its subcommand that take the next word as their value: `-C dir`, `-c k=v`, `--git-dir x`. */
35
+ const GIT_OPTION_VALUE = /^(?:-C|-c|--git-dir|--work-tree|--namespace|--config-env|--super-prefix|--attr-source)$/;
36
+ /** Subcommands that write or read by their arguments: one of those known only when it runs may be the writing one. */
37
+ const GIT_BY_ARGUMENTS = new Set(['remote', 'branch', 'tag', 'config', 'reflog', 'notes', 'stash', 'worktree', 'submodule', 'symbolic-ref', 'bisect', 'sparse-checkout']);
38
+ const programName = (head) => head.replace(/^["']|["']$/g, '').replace(/^.*[\\/]/, '').replace(/\.(?:exe|cmd|bat)$/i, '').toLowerCase();
39
+ /**
40
+ * Every git invocation on a line, as git reads it (third hunt, 2026-11-20): `git <subcommand> …`, whatever the head's
41
+ * spelling (`git.exe`, a path, `& 'C:\…\git.exe'`), with the quotes resolved and git's own options before the subcommand
42
+ * left out, whichever they are. `null` for one whose subcommand — or, for a subcommand that writes by its arguments, an
43
+ * argument — is known only when it runs (a variable, a splat), and for git started by Start-Process, whose words sit in
44
+ * `-ArgumentList`. The deny list's patterns read the line as written, and `git.exe push`, `git "push"`,
45
+ * `git --no-optional-locks push`, `git -P push` and `$a=@('push'); git @a` each ran past them.
46
+ */
47
+ export function gitAsRead(command, shell) {
48
+ const out = [];
49
+ for (const call of scanCommandHeads(command, shell === 'cmd' ? 'cmd' : 'pwsh').calls) {
50
+ if (programName(call.head) !== 'git')
51
+ continue;
52
+ const args = call.args;
53
+ let i = 0;
54
+ while (i < args.length && !args[i].dynamic && args[i].literal.startsWith('-'))
55
+ i += GIT_OPTION_VALUE.test(args[i].literal) ? 2 : 1;
56
+ const sub = args[i];
57
+ if (!sub)
58
+ continue;
59
+ if (sub.dynamic || (GIT_BY_ARGUMENTS.has(sub.literal.toLowerCase()) && args.slice(i + 1).some((a) => a.dynamic))) {
60
+ out.push(null);
61
+ continue;
62
+ }
63
+ out.push(['git', ...args.slice(i).map((a) => a.literal)].join(' '));
64
+ }
65
+ for (const target of startProcessTargets(command))
66
+ if (programName(target) === 'git')
67
+ out.push(null);
68
+ return out;
69
+ }
70
+ /**
71
+ * Why the operator's deny list refuses a line, or null: the line as written, the line with `git.exe` read as `git` and
72
+ * its quotes taken out (`cmd /c "git.exe push"`), and every git invocation as git reads it (`gitAsRead`). A git whose
73
+ * subcommand is known only when it runs is refused wherever the list refuses `git push`, the plainest git write.
74
+ */
75
+ export function denyPatternRefusal(command, shell, denyPatterns) {
76
+ const said = (hit) => `matches deny pattern /${hit}/`;
77
+ const raw = matchDenyPattern(command, denyPatterns);
78
+ if (raw)
79
+ return said(raw);
80
+ const plain = matchDenyPattern(command.replace(/\bgit\.exe\b/gi, 'git').replace(/["'`\u2018\u2019\u201c\u201d]/g, ''), denyPatterns);
81
+ if (plain)
82
+ return said(plain);
83
+ for (const read of gitAsRead(command, shell)) {
84
+ if (read === null) {
85
+ const writes = matchDenyPattern('git push', denyPatterns);
86
+ if (writes) {
87
+ return (`matches deny pattern /${writes}/: this runs git with its command — or the words that decide whether it changes something — known only ` +
88
+ 'when it runs (a variable, a splat, Start-Process), and git commands that change something are refused. Write the git command out in full.');
89
+ }
90
+ continue;
91
+ }
92
+ const hit = matchDenyPattern(read, denyPatterns);
93
+ if (hit)
94
+ return `${said(hit)} (as git reads it: ${read.slice(0, 120)})`;
95
+ }
96
+ return null;
97
+ }
34
98
  /** `git config`'s switches that read, and the ones that take the next word as their value. */
35
99
  const GIT_CONFIG_READS = /^(?:--get|--get-all|--get-regexp|--get-urlmatch|--get-color|--get-colorbool|--list|-l|get|list)$/;
36
100
  const GIT_CONFIG_VALUE = /^(?:--type|-t|--file|-f|--blob|--default|--comment|--value)$/;
@@ -142,9 +206,9 @@ readOnlyPrograms = []) {
142
206
  const internals = repositoryInternalsRefusal(command);
143
207
  if (internals)
144
208
  return internals;
145
- const hit = matchDenyPattern(command, denyPatterns);
209
+ const hit = denyPatternRefusal(command, shell, denyPatterns);
146
210
  if (hit)
147
- return `matches deny pattern /${hit}/`;
211
+ return hit;
148
212
  // Where it reaches, before which program it is: a binary named by a path outside the project is
149
213
  // better refused for being outside than for not being on a list, and a cmdlet — which the
150
214
  // allowlist never sees — is only caught here. See `confinement.ts`.
@@ -174,7 +238,7 @@ readOnlyPrograms = []) {
174
238
  return scriptFileRefusal(command, confinement.cwd, (text) => dangerousRefusal(text) ??
175
239
  botSelfRefusal(text) ??
176
240
  repositoryInternalsRefusal(text) ??
177
- (matchDenyPattern(text, denyPatterns) ? `matches deny pattern /${matchDenyPattern(text, denyPatterns)}/` : null) ??
241
+ denyPatternRefusal(text, 'pwsh', denyPatterns) ??
178
242
  confinementRefusal(text, confinement) ??
179
243
  programRefusal(text, allowedPrograms) ??
180
244
  // Inside a script nothing is put to the operator command by command: one that cannot be read as reading is refused.
@@ -242,8 +306,8 @@ export function writtenScriptScreen(cfg, confinement, env = process.env) {
242
306
  return commandRefusal(text, 'cmd', cfg.denyPatterns, allowed, env, confinement, cfg.readOnlyPrograms ?? []);
243
307
  }
244
308
  if (run.kind === 'sh') {
245
- const deny = matchDenyPattern(text, cfg.denyPatterns);
246
- return dangerousRefusal(text) ?? botSelfRefusal(text) ?? repositoryInternalsRefusal(text) ?? (deny ? `refused: matches deny pattern /${deny}/` : null) ?? confinementRefusal(text, confinement);
309
+ const deny = denyPatternRefusal(text, 'pwsh', cfg.denyPatterns);
310
+ return dangerousRefusal(text) ?? botSelfRefusal(text) ?? repositoryInternalsRefusal(text) ?? (deny ? `refused: ${deny}` : null) ?? confinementRefusal(text, confinement);
247
311
  }
248
312
  return null;
249
313
  };
@@ -131,9 +131,25 @@ const SLACK_MS = 2_000;
131
131
  * older than the bot's work are never read at all.
132
132
  */
133
133
  export async function processTable(since) {
134
+ return (await readProcessTable(since)) ?? [];
135
+ }
136
+ let tableQuery = powershell;
137
+ /** For the checks: a table that cannot be read, without a machine under load. Undefined puts PowerShell back. */
138
+ export function setProcessTableQueryForChecks(query) {
139
+ tableQuery = query ?? powershell;
140
+ }
141
+ /**
142
+ * The processes created since `since`, or null when the list could not be read — its query timed out or failed, twice
143
+ * (third hunt, 2026-11-20: read as an empty list, a server the task left running was never stopped nor named; a second
144
+ * try with more time is what a machine busy for a moment needs).
145
+ */
146
+ export async function readProcessTable(since) {
134
147
  const from = dmtfOf(since - SLACK_MS);
135
- const text = await powershell(`Get-CimInstance Win32_Process -Filter "CreationDate >= '${from}'" | Select-Object ProcessId, ParentProcessId, Name, CommandLine, ` +
136
- "@{n='Created';e={ if ($_.CreationDate) { $_.CreationDate.ToFileTimeUtc() } else { 0 } }} | ConvertTo-Json -Compress");
148
+ const script = `Get-CimInstance Win32_Process -Filter "CreationDate >= '${from}'" | Select-Object ProcessId, ParentProcessId, Name, CommandLine, ` +
149
+ "@{n='Created';e={ if ($_.CreationDate) { $_.CreationDate.ToFileTimeUtc() } else { 0 } }} | ConvertTo-Json -Compress";
150
+ const text = (await tableQuery(script, 20_000)) ?? (await tableQuery(script, 45_000));
151
+ if (text === null)
152
+ return null;
137
153
  return parseJsonList(text)
138
154
  .map((p) => ({
139
155
  pid: p.ProcessId,
@@ -289,7 +305,10 @@ export async function snapshotProcesses(_projectDir, from) {
289
305
  * tracker nothing is the bot's, and everything new in the folder is `notOurs`.
290
306
  */
291
307
  export async function findLeftovers(projectDir, before, tracker) {
292
- const now = await processTable(before.since);
308
+ const read = await readProcessTable(before.since);
309
+ if (read === null)
310
+ return { ours: [], notOurs: [], unread: 'the list of processes could not be read (Get-CimInstance Win32_Process timed out or failed, twice)' };
311
+ const now = read;
293
312
  // A process is "the same" only if its id *and* its creation time match: an id alone is reused.
294
313
  const known = new Set(before.processes.map((p) => `${p.pid}@${p.created}`));
295
314
  // The console host of a server's own window is its child in the table, and goes when the last
@@ -314,8 +333,8 @@ export async function findLeftovers(projectDir, before, tracker) {
314
333
  }
315
334
  /** Stops what the bot left running since the snapshot, and says what it stopped and what it did not. */
316
335
  export async function reapLeftovers(projectDir, before, tracker) {
317
- const { ours, notOurs } = await findLeftovers(projectDir, before, tracker);
318
- const result = { killed: [], failed: [], notOurs };
336
+ const { ours, notOurs, unread } = await findLeftovers(projectDir, before, tracker);
337
+ const result = { killed: [], failed: [], notOurs, ...(unread ? { unread } : {}) };
319
338
  if (ours.length === 0)
320
339
  return result;
321
340
  const how = await stopProcesses(ours.map((l) => l.pid));
@@ -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'