copilot-operator 0.1.69 → 0.1.70

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 (78) hide show
  1. package/dist/src/api/operator.controller.js +4 -2
  2. package/dist/src/api/operator.service.js +23 -9
  3. package/dist/src/api/server.js +10 -0
  4. package/dist/src/cli.js +2 -0
  5. package/dist/src/config/lockedPolicy.js +14 -0
  6. package/dist/src/config/schema.js +22 -0
  7. package/dist/src/exec/authorizer.js +45 -6
  8. package/dist/src/exec/dangerous.js +1 -1
  9. package/dist/src/exec/npmScripts.js +180 -0
  10. package/dist/src/exec/platforms.js +45 -1
  11. package/dist/src/exec/policy.js +110 -7
  12. package/dist/src/exec/policyManifest.js +13 -0
  13. package/dist/src/exec/programs.js +6 -1
  14. package/dist/src/exec/redaction.js +17 -2
  15. package/dist/src/exec/scriptFiles.js +210 -32
  16. package/dist/src/exec/scriptKinds.js +86 -0
  17. package/dist/src/exec/stepEnv.js +9 -2
  18. package/dist/src/orchestrator/handoff.js +80 -29
  19. package/dist/src/orchestrator/leadRunner.js +5 -2
  20. package/dist/src/orchestrator/review.js +13 -3
  21. package/dist/src/orchestrator/taskRunner.js +105 -19
  22. package/dist/src/plan/kerrigan.js +4 -4
  23. package/dist/src/plan/systemGuide.js +83 -12
  24. package/dist/src/protocol/leadSchema.js +8 -1
  25. package/dist/src/protocol/replySchema.js +13 -3
  26. package/dist/src/protocol/reviewSchema.js +4 -1
  27. package/dist/src/queue/queue.js +8 -4
  28. package/dist/src/session/checkpoint.js +48 -0
  29. package/dist/src/session/compose.js +1 -1
  30. package/dist/src/session/story.js +14 -0
  31. package/dist/src/vcs/gitConfigGuard.js +126 -0
  32. package/dist/src/vcs/newBranch.js +7 -3
  33. package/dist/web/404.html +2 -2
  34. package/dist/web/_next/static/chunks/1024-67625a65f58057ae.js +1 -0
  35. package/dist/web/_next/static/chunks/1077.9fe1c0425bf51375.js +1 -0
  36. package/dist/web/_next/static/chunks/1548.cae3ba2196c8d52f.js +1 -0
  37. package/dist/web/_next/static/chunks/2163.5c9f8477d98b75a4.js +1 -0
  38. package/dist/web/_next/static/chunks/714.a0b32193f71e0e91.js +1 -0
  39. package/dist/web/_next/static/chunks/7220.5d6da026e0b34169.js +1 -0
  40. package/dist/web/_next/static/chunks/7921-0f7954cb5a9f697b.js +1 -0
  41. package/dist/web/_next/static/chunks/8124-a39d85dff0db6600.js +1 -0
  42. package/dist/web/_next/static/chunks/8584.6aa7ce56f7552f17.js +1 -0
  43. package/dist/web/_next/static/chunks/9067.2e4ba2e0e572f21e.js +1 -0
  44. package/dist/web/_next/static/chunks/9747.763da2026719a863.js +1 -0
  45. package/dist/web/_next/static/chunks/9929-2e0b1d006ebd5345.js +1 -0
  46. package/dist/web/_next/static/chunks/app/{layout-e23bb58f3ea117d5.js → layout-52a2079ffa83c21f.js} +1 -1
  47. package/dist/web/_next/static/chunks/app/{page-fd49cf4fb6681d30.js → page-44eac9d137f26dc5.js} +1 -1
  48. package/dist/web/_next/static/chunks/app/queue/{page-fb49cb2d3dc6d14c.js → page-82f724d0842f4870.js} +1 -1
  49. package/dist/web/_next/static/chunks/app/settings/page-2df196e25cb7bfe1.js +1 -0
  50. package/dist/web/_next/static/chunks/{webpack-77c6c045264c9213.js → webpack-950df0f512eef7ec.js} +1 -1
  51. package/dist/web/_next/static/css/{52131c6d864daf3f.css → cfe8ccb4adf3a311.css} +1 -1
  52. package/dist/web/defaults.html +2 -2
  53. package/dist/web/defaults.txt +8 -8
  54. package/dist/web/index.html +3 -3
  55. package/dist/web/index.txt +9 -9
  56. package/dist/web/queue.html +2 -2
  57. package/dist/web/queue.txt +9 -9
  58. package/dist/web/settings.html +2 -2
  59. package/dist/web/settings.txt +9 -9
  60. package/dist/web/system.html +2 -2
  61. package/dist/web/system.txt +9 -9
  62. package/package.json +3 -2
  63. package/prompts/level1.md +25 -8
  64. package/dist/web/_next/static/chunks/1024-e4e596b184e05e91.js +0 -1
  65. package/dist/web/_next/static/chunks/1077.b3943e5b41c4bef4.js +0 -1
  66. package/dist/web/_next/static/chunks/1548.0ff0c0ece685ffe7.js +0 -1
  67. package/dist/web/_next/static/chunks/2163.9cfb1b06beaf5001.js +0 -1
  68. package/dist/web/_next/static/chunks/6262-d074473db83ee798.js +0 -1
  69. package/dist/web/_next/static/chunks/714.bee98f5a3db75882.js +0 -1
  70. package/dist/web/_next/static/chunks/7220.610988766a1104b7.js +0 -1
  71. package/dist/web/_next/static/chunks/7921-ac5793d5663674b2.js +0 -1
  72. package/dist/web/_next/static/chunks/8124-665327221384ba6e.js +0 -1
  73. package/dist/web/_next/static/chunks/8584.9220e445a8ce2265.js +0 -1
  74. package/dist/web/_next/static/chunks/9067.f05516f2f2a2e8f5.js +0 -1
  75. package/dist/web/_next/static/chunks/9747.e249434ff7e05f4f.js +0 -1
  76. package/dist/web/_next/static/chunks/app/settings/page-7d120feb5af0ace9.js +0 -1
  77. /package/dist/web/_next/static/{8i6gf0zoo-KiUKdzxsCJR → DzoLjnxX5FvdxuPasWlnb}/_buildManifest.js +0 -0
  78. /package/dist/web/_next/static/{8i6gf0zoo-KiUKdzxsCJR → DzoLjnxX5FvdxuPasWlnb}/_ssgManifest.js +0 -0
@@ -6,8 +6,11 @@ import { unattendedIsolationRefusal } from './isolation.js';
6
6
  import { confinementRefusal } from './confinement.js';
7
7
  import { botSelfRefusal, networkFetchReason, networkFetchRefusal } from './network.js';
8
8
  import { ownScriptRefusal, scriptFileRefusal } from './scriptFiles.js';
9
+ import { existsSync, readdirSync } from 'node:fs';
10
+ import { dirname, join } from 'node:path';
9
11
  import { readOnlyRefusal, readOnlyUnaskedRefusal, readOnlyUnclearRefusal, readOnlyVerdict } from './readOnly.js';
10
12
  import { platformReason } from './platforms.js';
13
+ import { scanCommandHeads } from './commandHeads.js';
11
14
  export function describeStep(step) {
12
15
  // The shell it will really be read by, not the one this file used to assume: a line in the
13
16
  // log that names an interpreter the machine has not got explains the wrong failure.
@@ -28,6 +31,51 @@ export function matchDenyPattern(text, patterns) {
28
31
  }
29
32
  return null;
30
33
  }
34
+ /** `git config`'s switches that read, and the ones that take the next word as their value. */
35
+ const GIT_CONFIG_READS = /^(?:--get|--get-all|--get-regexp|--get-urlmatch|--get-color|--get-colorbool|--list|-l|get|list)$/;
36
+ const GIT_CONFIG_VALUE = /^(?:--type|-t|--file|-f|--blob|--default|--comment|--value)$/;
37
+ const GIT_CONFIG_WRITES = /^(?:set|unset|edit|rename-section|remove-section|-e|--edit|--add|--unset|--unset-all|--replace-all|--rename-section|--remove-section)$/;
38
+ /** Whether a line runs `git config` in any form that is not plainly a read: one key looked up, or a listing. */
39
+ function gitConfigWrites(command) {
40
+ for (const call of scanCommandHeads(command, 'pwsh').calls) {
41
+ if (call.head.replace(/^.*[\\/]/, '').replace(/\.exe$/i, '').toLowerCase() !== 'git')
42
+ continue;
43
+ const args = call.args;
44
+ let i = 0;
45
+ // git's own options before the subcommand: `-C dir`, `-c k=v`, `--git-dir x`, `--no-pager`.
46
+ while (i < args.length && args[i].literal.startsWith('-'))
47
+ i += /^(?:-C|-c|--git-dir|--work-tree|--namespace|--exec-path|--config-env)$/.test(args[i].literal) ? 2 : 1;
48
+ if (args[i]?.literal.toLowerCase() !== 'config')
49
+ continue;
50
+ const rest = args.slice(i + 1);
51
+ if (rest.some((a) => a.dynamic))
52
+ return true;
53
+ let reads = false;
54
+ const words = [];
55
+ for (let k = 0; k < rest.length; k++) {
56
+ const w = rest[k].literal;
57
+ const flag = w.includes('=') && w.startsWith('-') ? w.slice(0, w.indexOf('=')) : w;
58
+ if (GIT_CONFIG_WRITES.test(flag))
59
+ return true;
60
+ if (GIT_CONFIG_READS.test(flag)) {
61
+ reads = true;
62
+ continue;
63
+ }
64
+ if (flag.startsWith('-')) {
65
+ if (!w.includes('=') && GIT_CONFIG_VALUE.test(flag))
66
+ k++;
67
+ continue;
68
+ }
69
+ words.push(w);
70
+ }
71
+ // `git config user.name` looks one key up; with a value after it, it sets one.
72
+ if (!reads && words.length !== 1)
73
+ return true;
74
+ if (reads && words.length > 2)
75
+ return true;
76
+ }
77
+ return false;
78
+ }
31
79
  /**
32
80
  * A step that reaches into the repository's own machinery: a path inside `.git`, or a git setting
33
81
  * written to stay. Built in, like `dangerous.ts`, because the operator's deny list is editable and
@@ -42,8 +90,20 @@ export function matchDenyPattern(text, patterns) {
42
90
  * contract already tells the chat to use git commands, never the folder.
43
91
  */
44
92
  export function repositoryInternalsRefusal(command) {
45
- const intoGitDir = /(^|[\s'"=(\\/,;])\.git[\\/]/i.test(command);
46
- const setting = /\bgit\s+(?:-C\s+\S+\s+)?config\s+(?:(?:--(?:local|global|system|worktree)|--file\s+\S+)\s+)?(?:(?:set|unset)\s+)?[A-Za-z][\w.-]*\s+[^\s|;-]/i.test(command);
93
+ /*
94
+ * A path inside `.git`, and since the audit of 2026-10-27 the folder itself in a line that goes into it or writes:
95
+ * `Set-Location .git; Add-Content config …` and `Add-Content (Join-Path .git config) …` reached the config with no
96
+ * `.git\` in the line. A line that only names it (`Where-Object Name -ne '.git'`) is left alone.
97
+ */
98
+ const intoGitDir = /(^|[\s'"=(\\/,;])\.git[\\/]/i.test(command) ||
99
+ (/(^|[\s'"=(\\/,;])\.git(?=$|[\s'"),;|])/i.test(command) &&
100
+ /\b(Set-Location|sl|cd|chdir|pushd|Push-Location|Join-Path|Set-Content|Add-Content|Out-File|New-Item|Copy-Item|Move-Item|Remove-Item|Rename-Item|Tee-Object|sc|ac|ni|cp|copy|mv|move|rm|del|ren)\b|>/i.test(command));
101
+ /*
102
+ * A git setting written: every `git config` that is not plainly a read (audit, 2026-10-27). The form that wanted a
103
+ * bare key and a value let `git config "filter.x.clean" "node fmt.js"`, `--type=bool`, `-z`, `git.exe config` and
104
+ * the scopes past, and the runner's own git then ran the filter. `--config-env` sets a key for one command, as -c does.
105
+ */
106
+ const setting = gitConfigWrites(command) || /\bgit(?:\.exe)?\b[^|;\n]*\s--config-env\b/i.test(command);
47
107
  // `git -c key=value <command>` sets the key for that one command — and some keys name a program
48
108
  // git then starts (hooks, fsmonitor, the pager, the editor, credential helpers, filters, diff and
49
109
  // merge drivers, aliases), which the allowlist never sees. Those keys are refused inline as well.
@@ -138,6 +198,17 @@ export function checkCommandRefusal(command, shell, cfg, confinement, env = proc
138
198
  const network = networkFetchReason(command, confinement.cwd) ?? scriptNetworkReason(command, confinement.cwd);
139
199
  return network ? networkFetchRefusal(network) : null;
140
200
  }
201
+ /**
202
+ * The gate for a check the reviewer wrote (audit, 2026-10-27): a check's gate, and the rules for the chat's own steps
203
+ * in a run nobody watches, since such a check is kept and run at every later gate with no one asked — no allowed
204
+ * interpreter evaluating a string, no shell inside a shell, and only the scripts the operator's boxes let run. Refused,
205
+ * the finding stands without its check, as for any check the runner will not run.
206
+ */
207
+ export function modelCheckRefusal(command, shell, cfg, confinement, env = process.env) {
208
+ return (checkCommandRefusal(command, shell, cfg, confinement, env) ??
209
+ inlineCodeRefusal(command) ??
210
+ ownScriptRefusal(command, confinement.cwd, confinement.workStartedAt, shell, { rules: cfg.scripts, reviewer: true, screen: writtenScriptScreen(cfg, confinement, env) }));
211
+ }
141
212
  /**
142
213
  * A check reaching a platform with the operator's access, which a step puts to the operator every time (2026-10-26):
143
214
  * a check has nobody to put it to, so it is refused unless Settings agree with what the bot proposes. A program set to
@@ -152,6 +223,31 @@ export function checkAccessRefusal(command, shell, cfg) {
152
223
  return null;
153
224
  return `refused: this check reaches ${platform} with the operator's access, which only the operator may allow, and a check runs with nobody asked. Check it another way, or do it in a step, where it is put to the operator.`;
154
225
  }
226
+ /**
227
+ * The gate a script the bot wrote is read through when the operator's box lets it run (2026-10-27): its text, as a
228
+ * line of its own. A `.ps1` is read by `scriptFileRefusal` in every case; a `.cmd` or `.bat` and a script of package.json
229
+ * (which npm hands to cmd) by the whole gate for cmd; a bash script by the rules that read text — refused techniques,
230
+ * the bot's own things, the repository's machinery, the deny list, the project's folders — since what it starts are
231
+ * bash's tools, not Windows programs. A script of package.json may start what the project installed
232
+ * (`node_modules/.bin`). A file of code (`.ts`, `.js`, `.py`) is code, and is not read.
233
+ */
234
+ export function writtenScriptScreen(cfg, confinement, env = process.env) {
235
+ return (run, text) => {
236
+ if (run.kind === 'cmd')
237
+ return commandRefusal(text, 'cmd', cfg.denyPatterns, cfg.allowedPrograms, env, confinement, cfg.readOnlyPrograms ?? []);
238
+ if (run.kind === 'npm') {
239
+ const bin = join(dirname(run.file), 'node_modules', '.bin');
240
+ const installed = existsSync(bin) ? readdirSync(bin).map((n) => n.replace(/\.(?:cmd|ps1|exe)$/i, '')) : [];
241
+ const allowed = cfg.allowedPrograms.length ? [...cfg.allowedPrograms, ...installed] : [];
242
+ return commandRefusal(text, 'cmd', cfg.denyPatterns, allowed, env, confinement, cfg.readOnlyPrograms ?? []);
243
+ }
244
+ 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);
247
+ }
248
+ return null;
249
+ };
250
+ }
155
251
  /** A fetch inside a script the line runs — held or refused exactly as one on the line would be. */
156
252
  export function scriptNetworkReason(command, cwd) {
157
253
  let found = null;
@@ -199,14 +295,21 @@ export function unattendedPrecondition(cfg) {
199
295
  * Applies the automatic rules. Returns null when the step is acceptable so far, or a
200
296
  * decision when it is refused without asking anyone.
201
297
  */
202
- export function staticCheck(step, cfg, env = process.env, confinement) {
298
+ export function staticCheck(step, cfg, env = process.env, confinement,
299
+ /** Whose step: the reviewer is told to check another way, since a review hands nothing over. */
300
+ actor) {
203
301
  /*
204
- * Only the project's own scripts, and nothing from .cop-tmp (operator, 2026-10-21): a script the chat wrote is not
205
- * run, however it is called. First, so the chat is told that, and not the older advice of the shared gate to write
206
- * a script in one step and run it in the next. See `scriptFiles.ts`.
302
+ * The project's own scripts, and the bot's only where the operator's box lets them (2026-10-21, boxes 2026-10-27): a
303
+ * script the chat wrote is otherwise not run, however it is called, and one it is let run is read first. First, so
304
+ * the chat is told that, and not the older advice of the shared gate to write a script in one step and run it in the
305
+ * next. See `scriptFiles.ts`.
207
306
  */
208
307
  if (confinement) {
209
- const own = ownScriptRefusal(step.cmd, confinement.cwd, confinement.workStartedAt, effectiveShell(step.shell));
308
+ const own = ownScriptRefusal(step.cmd, confinement.cwd, confinement.workStartedAt, effectiveShell(step.shell), {
309
+ rules: cfg.scripts,
310
+ reviewer: actor === 'review',
311
+ screen: writtenScriptScreen(cfg, confinement, env),
312
+ });
210
313
  if (own)
211
314
  return { action: 'skip', reason: own };
212
315
  }
@@ -20,6 +20,7 @@
20
20
  * says plainly that isolation is not determined here. A manifest that overstated its own evidence
21
21
  * would be worse than none, because somebody would rely on it.
22
22
  */
23
+ import { DEFAULT_SCRIPT_RULES, SCRIPT_KINDS } from './scriptKinds.js';
23
24
  import { createHash } from 'node:crypto';
24
25
  import { DANGEROUS_TECHNIQUES } from './dangerous.js';
25
26
  import { describeIsolation } from './isolation.js';
@@ -53,6 +54,16 @@ function readOnlyInForce(readOnly, allowed) {
53
54
  const listed = new Set(allowed.map((p) => p.trim().toLowerCase()));
54
55
  return [...new Set(readOnly.map((p) => p.trim().toLowerCase()))].filter((p) => capable.has(p) && (listed.size === 0 || listed.has(p)));
55
56
  }
57
+ /** What the scripts' boxes allowed in this run, in one line: the record says it, rather than implying it. */
58
+ function scriptsStatement(rules, written, mode) {
59
+ const mine = SCRIPT_KINDS.filter((k) => rules[k].written);
60
+ const notOwn = SCRIPT_KINDS.filter((k) => !rules[k].own);
61
+ const own = notOwn.length ? `the project's ran except ${notOwn.join(', ')}` : "the project's ran";
62
+ if (mine.length === 0)
63
+ return `${own}; none the bot wrote (each handed to the operator)`;
64
+ const how = mode === 'unattended' && written === 'run' ? 'without asking' : 'after the operator saw each';
65
+ return `${own}; the bot's own of ${mine.join(', ')} ran ${how}; the others it wrote were handed to the operator`;
66
+ }
56
67
  export function collectPolicyManifest(input, env = process.env) {
57
68
  const names = DANGEROUS_TECHNIQUES.map((t) => t.name);
58
69
  return {
@@ -67,6 +78,7 @@ export function collectPolicyManifest(input, env = process.env) {
67
78
  programs: [...input.allowedPrograms],
68
79
  },
69
80
  readOnly: readOnlyInForce(input.readOnlyPrograms ?? [], input.allowedPrograms),
81
+ scripts: scriptsStatement(input.scripts ?? DEFAULT_SCRIPT_RULES, input.writtenScripts ?? 'ask', input.mode),
70
82
  chatFiles: 'the chat cannot supply a file: this runner has no file step and executes nothing it did not receive as a command',
71
83
  networkFetch: networkFetchStatement(input.mode, input.networkFetch),
72
84
  denyPatterns: { count: input.denyPatterns.length, digest: digestOf(input.denyPatterns) },
@@ -88,6 +100,7 @@ export function describePolicyManifest(m) {
88
100
  `mode : ${m.mode}${m.mode === 'unattended' ? ' (no person saw the steps as they ran)' : ' (a person approved each step)'}`,
89
101
  `allowlist : ${m.allowlist.enforced ? `${m.allowlist.count} programs, digest ${m.allowlist.digest}` : 'NOT ENFORCED — any program could be started'}`,
90
102
  `read only : ${m.readOnly.length ? `${m.readOnly.join(', ')} — a command that changes something, signs in or out or shows a secret is refused` : 'none'}`,
103
+ `scripts : ${m.scripts}`,
91
104
  `chat files : ${m.chatFiles}`,
92
105
  `downloads : ${m.networkFetch}`,
93
106
  `deny list : ${m.denyPatterns.count} patterns, digest ${m.denyPatterns.digest}`,
@@ -140,7 +140,12 @@ const INLINE_CODE = [
140
140
  { what: 'ruby -e', pattern: /\bruby(\.exe)?\s+(-\S+\s+)*?-e\b/i },
141
141
  { what: 'php -r', pattern: /\bphp(\.exe)?\s+(-\S+\s+)*?-r\b/i },
142
142
  { what: 'a nested PowerShell', pattern: /\b(pwsh|powershell)(\.exe)?\s+(-\S+\s+)*?-c(ommand)?\b/i },
143
- { what: 'a nested cmd', pattern: /\bcmd(\.exe)?\s+(\/\S+\s+)*?\/c\b/i },
143
+ /*
144
+ * A nested cmd — but not one given a script file and nothing else (2026-10-27): `cmd /c tools\build.cmd` is how a
145
+ * `.cmd` or `.bat` is run, as `pwsh -File` runs a `.ps1`, and the file is read by the script rules
146
+ * (`scriptFiles.ts`) where no line is; `cmd /c "a & b"` and `cmd /c x.bat & calc` are still code the list cannot see.
147
+ */
148
+ { what: 'a nested cmd', pattern: /\bcmd(\.exe)?\s+(\/\S+\s+)*?\/c\b(?!\s+["']?[^\s"'&|<>^]+\.(?:cmd|bat)["']?(?:[ \t]+[^&|<>^\n;'"]*)?\s*(?:$|[;\n]))/i },
144
149
  ];
145
150
  /** Shells whose start through `Start-Process` is a nested shell however the arguments are spelled. */
146
151
  const SHELLS = new Set(['pwsh', 'powershell', 'cmd', 'wsl', 'bash', 'sh']);
@@ -24,6 +24,14 @@ const SHAPES = [
24
24
  },
25
25
  { name: 'JWT', pattern: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g, replace: '[REDACTED JWT]' },
26
26
  { name: 'bearer token', pattern: /\b(bearer)\s+[A-Za-z0-9\-._~+/]{16,}=*/gi, replace: '$1 [REDACTED]' },
27
+ // An HTTP header with credentials in it, as git's and curl's traces print them (audit, 2026-10-27).
28
+ {
29
+ name: 'authorization header',
30
+ pattern: /\b((?:proxy-)?authorization:\s*)(basic|digest|ntlm|negotiate|token|sharedkey)\s+[A-Za-z0-9+/=._~:,"-]{8,}/gi,
31
+ replace: '$1$2 [REDACTED]',
32
+ },
33
+ { name: 'cookie header', pattern: /^([ \t>]*(?:set-)?cookie:[ \t]*)\S.*$/gim, replace: '$1[REDACTED]' },
34
+ { name: 'Stripe key', pattern: /\b(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9]{16,}\b/g, replace: '[REDACTED STRIPE KEY]' },
27
35
  { name: 'AWS access key', pattern: /\b(AKIA|ASIA)[0-9A-Z]{16}\b/g, replace: '[REDACTED AWS KEY]' },
28
36
  { name: 'GitHub token', pattern: /\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g, replace: '[REDACTED GITHUB TOKEN]' },
29
37
  { name: 'Slack token', pattern: /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g, replace: '[REDACTED SLACK TOKEN]' },
@@ -38,9 +46,16 @@ const SHAPES = [
38
46
  name: 'secret in an environment listing',
39
47
  // `Get-ChildItem env:` and `set` print NAME and value in columns, with no `=` or `:` between —
40
48
  // the one shape the assignment rule below cannot see.
41
- pattern: /^([ \t]*[A-Za-z0-9_]*(?:PASSWORD|PASSWD|SECRET|TOKEN|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|CONN\w*STRING)[A-Za-z0-9_]*)([ \t]{2,})(\S.*)$/gim,
49
+ pattern: /^([ \t]*[A-Za-z0-9_]*(?:PASSWORD|PASSWD|_PASS|SECRET|TOKEN|CREDENTIAL|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|[A-Z0-9]_KEY|CONN\w*STRING)[A-Za-z0-9_]*)([ \t]{2,})(\S.*)$/gim,
42
50
  replace: '$1$2[REDACTED]',
43
51
  },
52
+ {
53
+ name: 'secret assignment (quoted)',
54
+ // A quoted value is the secret up to its closing quote, spaces and all (audit, 2026-10-27:
55
+ // `"password": "correct horse battery staple"` kept everything after its first word).
56
+ pattern: /\b([A-Za-z0-9_]*?(?:password|passwd|pwd|pass(?=["']?\s*[=:])|secret|credential|api[_-]?key|access[_-]?key|client[_-]?secret|auth[_-]?token|access[_-]?token|refresh[_-]?token|private[_-]?key|token|[A-Za-z0-9]_key)[A-Za-z0-9_]*)(["']?\s*[=:]\s*)(["'])([^"'\r\n]{6,})\3/gi,
57
+ replace: (_m, name, sep, quote, value) => NOT_A_VALUE.has(value.trim().toLowerCase()) || value.startsWith('[REDACTED') ? _m : `${name}${sep}${quote}[REDACTED]${quote}`,
58
+ },
44
59
  {
45
60
  name: 'secret assignment',
46
61
  // `password=...`, `api_key: ...`, `"client_secret": "..."` — the name is kept, the value goes.
@@ -51,7 +66,7 @@ const SHAPES = [
51
66
  // `AWS_SECRET_ACCESS_KEY` — which is how environments and config files spell them; matching the
52
67
  // bare word only let every one of those through. Six characters is short enough for a real
53
68
  // password and long enough to leave `token: null` and `pwd: ok` alone.
54
- pattern: /\b([A-Za-z0-9_]*?(?:password|passwd|pwd|secret|api[_-]?key|access[_-]?key|client[_-]?secret|auth[_-]?token|access[_-]?token|refresh[_-]?token|private[_-]?key|token)[A-Za-z0-9_]*)(["']?\s*[=:]\s*)(["']?)([^\s"';,]{6,})\3/gi,
69
+ pattern: /\b([A-Za-z0-9_]*?(?:password|passwd|pwd|pass(?=["']?\s*[=:])|secret|credential|api[_-]?key|access[_-]?key|client[_-]?secret|auth[_-]?token|access[_-]?token|refresh[_-]?token|private[_-]?key|token|[A-Za-z0-9]_key)[A-Za-z0-9_]*)(["']?\s*[=:]\s*)(["']?)([^\s"';,]{6,})\3/gi,
55
70
  replace: (_m, name, sep, quote, value) => NOT_A_VALUE.has(value.toLowerCase()) || value.startsWith('[REDACTED') ? _m : `${name}${sep}${quote}[REDACTED]${quote}`,
56
71
  },
57
72
  ];
@@ -29,9 +29,11 @@
29
29
  * nothing is run from `.cop-tmp`. What a step does it says in the step itself, which may be several lines.
30
30
  */
31
31
  import { existsSync, readFileSync, statSync } from 'node:fs';
32
- import { dirname, isAbsolute, relative, resolve } from 'node:path';
32
+ import { basename, dirname, isAbsolute, relative, resolve } from 'node:path';
33
33
  import { gitSync, RUNNER_EMAIL } from '../vcs/git.js';
34
34
  import { scanCommandHeads } from './commandHeads.js';
35
+ import { packageScriptsRun, packageScriptWritten, writesPackageScripts } from './npmScripts.js';
36
+ import { DEFAULT_SCRIPT_RULES, kindForChat, kindOfFile } from './scriptKinds.js';
35
37
  /** Larger than this is not a step's script; it is not read, and running it is refused. */
36
38
  const MAX_SCRIPT_BYTES = 256 * 1024;
37
39
  /** Paths of PowerShell scripts this command line runs, as written. */
@@ -139,7 +141,7 @@ const inScratch = (path) => path.split(/[\\/]+/).some((part) => part.toLowerCase
139
141
  */
140
142
  export function notTheProjects(file, since) {
141
143
  if (inScratch(file))
142
- return `it is in ${SCRATCH}, the folder for scratch files, and nothing there is run`;
144
+ return `it is in ${SCRATCH}, the folder for scratch files`;
143
145
  if (!existsSync(file))
144
146
  return 'it does not exist';
145
147
  const top = gitSync(dirname(file), ['rev-parse', '--show-toplevel']);
@@ -167,24 +169,85 @@ export function notTheProjects(file, since) {
167
169
  const CODE_RUNTIMES = new Set(['node', 'nodejs', 'tsx', 'ts-node', 'ts-node-esm', 'python', 'python3', 'pythonw', 'py', 'deno', 'bun', 'ruby', 'perl', 'php']);
168
170
  /** What a package runner starts that runs a file of code: `npx ts-node x.ts`, `npx tsx x.ts`. */
169
171
  const RUN_THROUGH = new Set(['npx', 'pnpx', 'bunx']);
172
+ /** A package manager's word that makes it a package runner: `npm exec`, `pnpm exec`, `pnpm dlx`, `yarn dlx`, `yarn exec`. */
173
+ const RUNNER_WORDS = { npm: new Set(['exec', 'x']), pnpm: new Set(['exec', 'dlx']), yarn: new Set(['exec', 'dlx']) };
174
+ /** A package runner's switches that take the next word: `--package tsx`, `-p tsx`. */
175
+ const RUNNER_VALUE = /^(?:-p|--package|-w|--workspace|--prefix|-C|--dir|--cwd|--filter|-F)$/;
176
+ /** A runtime's switches whose value is a file of code it loads before the one it runs: `node -r ./hook.js x.js`. */
177
+ const LOADS_CODE = /^(?:-r|--require|--import|--loader|--experimental-loader|--preload)$/;
178
+ /** A runtime's other switches that take the next word, which is not the file it runs. */
179
+ const RUNTIME_VALUE = /^(?:-m|--title|--env-file|--inspect-port|--max-old-space-size|--conditions|-C|--input-type|--tsconfig|--project|-P)$/;
170
180
  const CODE_FILE = /\.(?:js|mjs|cjs|jsx|ts|mts|cts|tsx|py|pyw|rb|pl|php)$/i;
181
+ const programOf = (head) => head.replace(/^.*[\\/]/, '').replace(/\.(?:exe|cmd)$/i, '').toLowerCase();
182
+ /** `Start-Process node -ArgumentList 'tools/x.js'`: the program it starts and the words it is given, as a call of its own. */
183
+ function startedProcesses(command) {
184
+ const calls = [];
185
+ for (const m of command.matchAll(/\b(?:Start-Process|saps)\b([^|;\n]*)/gi)) {
186
+ const words = [...m[1].matchAll(/"([^"]*)"|'([^']*)'|([^\s,]+)/g)].map((w) => w[1] ?? w[2] ?? w[3] ?? '');
187
+ let program;
188
+ const args = [];
189
+ for (let i = 0; i < words.length; i++) {
190
+ const w = words[i];
191
+ if (/^-(?:FilePath|f)$/i.test(w))
192
+ program = words[++i];
193
+ else if (/^-(?:ArgumentList|Args|a)$/i.test(w)) {
194
+ while (i + 1 < words.length && !/^-[A-Za-z]+$/.test(words[i + 1]))
195
+ args.push({ literal: words[++i], dynamic: /^\$/.test(words[i]) });
196
+ // A value that is itself a list of words: `-ArgumentList 'tools/x.js --flag'`.
197
+ if (args.length === 1 && /\s/.test(args[0].literal))
198
+ args.splice(0, 1, ...args[0].literal.split(/\s+/).map((l) => ({ literal: l, dynamic: false })));
199
+ }
200
+ else if (/^-[A-Za-z]+$/.test(w)) {
201
+ // A switch of Start-Process's own (`-Wait`, `-NoNewWindow`, `-WorkingDirectory dir`): its value is skipped where it has one.
202
+ if (/^-(?:WorkingDirectory|RedirectStandard\w+|Verb|WindowStyle|Credential)$/i.test(w))
203
+ i++;
204
+ }
205
+ else if (program === undefined)
206
+ program = w;
207
+ }
208
+ if (program)
209
+ calls.push({ head: program, args });
210
+ }
211
+ return calls;
212
+ }
171
213
  /**
172
214
  * The files of code a line gives straight to a runtime (2026-10-26): `node tools/x.js`, `npx ts-node tools/x.ts`,
173
- * `tsx x.ts`, `python x.py`, `deno run x.ts`, as full paths. The first argument that is not a switch is the file; a
174
- * line whose first one is not a file of code (`node --version`, `python -m pytest`) gives none. The project's test
175
- * runners are not this (operator, 2026-10-26: "tests as before"): `node --test` is left alone, as are `npm test`,
215
+ * `tsx x.ts`, `python x.py`, `deno run x.ts`, as full paths — and since the audit of 2026-10-27 every way of saying it
216
+ * found then: a package runner named as a word of npm, pnpm or yarn (`npm exec -- tsx x.ts`), a runner's switch with a
217
+ * value (`npx --package tsx tsx x.ts`), a file loaded before the one run (`node -r ./hook.js x.js`) and a runtime
218
+ * started with Start-Process (`Start-Process node -ArgumentList x.js`). The first argument that is not a switch is the
219
+ * file; a line whose first one is not a file of code (`node --version`, `python -m pytest`) gives none. The project's
220
+ * test runners are not this (operator, 2026-10-26: "tests as before"): `node --test` is left alone, as are `npm test`,
176
221
  * `npx playwright test` and the rest, which are not runtimes given a file.
177
222
  */
178
223
  export function codeFilesRun(command, cwd, shell) {
179
224
  const files = new Set();
180
- for (const call of scanCommandHeads(command, shell ?? 'pwsh').calls) {
181
- let program = call.head.replace(/^.*[\\/]/, '').replace(/\.(?:exe|cmd)$/i, '').toLowerCase();
225
+ const add = (literal) => void files.add(isAbsolute(literal) ? literal : resolve(cwd, literal));
226
+ for (const call of [...scanCommandHeads(command, shell ?? 'pwsh').calls, ...startedProcesses(command)]) {
227
+ let program = programOf(call.head);
182
228
  let args = call.args;
229
+ // `npm exec -- tsx x.ts`, `pnpm dlx tsx x.ts`: from here on, a package runner.
230
+ if (RUNNER_WORDS[program]?.has(args[0]?.literal.toLowerCase() ?? '')) {
231
+ program = 'npx';
232
+ args = args.slice(1);
233
+ }
183
234
  if (RUN_THROUGH.has(program)) {
184
- const first = args.findIndex((a) => !a.literal.startsWith('-'));
235
+ let first = -1;
236
+ for (let i = 0; i < args.length; i++) {
237
+ const a = args[i].literal;
238
+ if (a === '--')
239
+ continue;
240
+ if (a.startsWith('-')) {
241
+ if (RUNNER_VALUE.test(a))
242
+ i++;
243
+ continue;
244
+ }
245
+ first = i;
246
+ break;
247
+ }
185
248
  if (first < 0)
186
249
  continue;
187
- program = args[first].literal.toLowerCase();
250
+ program = programOf(args[first].literal);
188
251
  args = args.slice(first + 1);
189
252
  }
190
253
  if (!CODE_RUNTIMES.has(program))
@@ -192,10 +255,32 @@ export function codeFilesRun(command, cwd, shell) {
192
255
  if (args.some((a) => /^--test\b/.test(a.literal)))
193
256
  continue;
194
257
  const rest = (program === 'deno' || program === 'bun') && args[0]?.literal === 'run' ? args.slice(1) : args;
195
- const file = rest.find((a) => !a.literal.startsWith('-'));
258
+ let file;
259
+ for (let i = 0; i < rest.length; i++) {
260
+ const a = rest[i];
261
+ const [flag, inline] = a.literal.startsWith('-') && a.literal.includes('=') ? [a.literal.slice(0, a.literal.indexOf('=')), a.literal.slice(a.literal.indexOf('=') + 1)] : [a.literal, undefined];
262
+ if (flag === '--')
263
+ continue;
264
+ if (flag.startsWith('-')) {
265
+ if (LOADS_CODE.test(flag)) {
266
+ const value = inline ?? rest[++i]?.literal;
267
+ if (value && CODE_FILE.test(value) && /^(?:\.|[A-Za-z]:|[\\/])|[\\/]/.test(value))
268
+ add(value);
269
+ }
270
+ else if (inline === undefined && RUNTIME_VALUE.test(flag)) {
271
+ // `python -m pytest`: a module, not a file — the line runs no file of its own.
272
+ if (flag === '-m')
273
+ break;
274
+ i++;
275
+ }
276
+ continue;
277
+ }
278
+ file = a;
279
+ break;
280
+ }
196
281
  if (!file || file.dynamic || !CODE_FILE.test(file.literal))
197
282
  continue;
198
- files.add(isAbsolute(file.literal) ? file.literal : resolve(cwd, file.literal));
283
+ add(file.literal);
199
284
  }
200
285
  return [...files];
201
286
  }
@@ -234,36 +319,129 @@ export function writtenDuringTheWork(file, since) {
234
319
  }
235
320
  return Number.isFinite(born) && born >= began - 1000 ? 'it was made after this work began and is not committed' : null;
236
321
  }
322
+ /** A file in .cop-tmp given to a program that runs files — not output written there (`node x.js > .cop-tmp\out.txt`). */
323
+ const SCRATCH_RUN = new RegExp(String.raw `\b${RUNS_A_FILE}(?:\.exe|\.cmd)?\b[^|;\n]*?(?:^|[\s'"=(,:])((?:\.[\\/])?(?:[^\s'"|;]*[\\/])?\.cop-tmp[\\/][^\s'"|;]*\.(?:ps1|psm1|cmd|bat|js|mjs|cjs|jsx|ts|mts|cts|tsx|py|rb|pl|php|vbs|vbe|wsf|sh|jar|dll|exe|csx))\b`, 'gi');
324
+ /** Whether the line itself writes a file by that name: a cmdlet, an alias or a redirection naming it. */
325
+ function writesFileNamed(command, file) {
326
+ const name = basename(file).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
327
+ return new RegExp(String.raw `\b(Set-Content|Add-Content|Out-File|New-Item|Copy-Item|Move-Item|Rename-Item|Tee-Object|sc|ac|cp|copy|mv|move|ren|ni|tee)\b[^|;\n]*${name}\b|>\s*["']?[^\s"']*${name}\b`, 'i').test(command);
328
+ }
329
+ /** A script the line writes and runs at once: never run, whatever the boxes say, since nothing could be read before it ran. */
330
+ const SAME_LINE = 'this same line writes it';
237
331
  /**
238
- * Why a chat's step must not run a script, or null: a shell script that is not one of the project's own (see
239
- * `notTheProjects`), a file of code written during the work given to a runtime (see `writtenDuringTheWork`), or any
240
- * file in `.cop-tmp` given to a program that runs it. Every one of them is the operator's to run (2026-10-26), and the
241
- * chat is told to hand it over. Only for the chat's steps, the implementer's and the reviewer's: the operator's own
242
- * checks are theirs to point at whatever they choose.
332
+ * Every script the line runs, each judged: a shell script (`shellScriptsRun`) by `notTheProjects`, a file of code given
333
+ * to a runtime (`codeFilesRun`) by `writtenDuringTheWork`, anything else in .cop-tmp a program is given, and the scripts
334
+ * of package.json it runs (`npmScripts.ts`).
243
335
  */
244
- export function ownScriptRefusal(command, cwd, since, shell) {
245
- // A file of code in it, given to a program that runs files — not its output written there (`node x.js > .cop-tmp\out.txt`).
246
- const scratch = new RegExp(String.raw `\b${RUNS_A_FILE}(?:\.exe|\.cmd)?\b[^|;\n]*?(?:^|[\s'"=(,:])(?:\.[\\/])?(?:[^\s'"|;]*[\\/])?\.cop-tmp[\\/][^\s'"|;]*\.(?:ps1|psm1|cmd|bat|js|mjs|cjs|jsx|ts|mts|cts|tsx|py|rb|pl|php|vbs|vbe|wsf|sh|jar|dll|exe|csx)\b`, 'i');
247
- const why = (file, reason) => `refused: ${relative(cwd, file) || file} is not one of the project's own scripts — ${reason}. A script written or ` +
248
- 'changed during the work is run by the operator, not by the runner, nor is anything in .cop-tmp (the operator\'s rule). ' +
249
- HAND_IT_OVER;
250
- if (scratch.test(command)) {
251
- return 'refused: this runs a file in .cop-tmp, the folder for scratch files — the runner runs nothing there (the operator\'s rule). ' + HAND_IT_OVER;
252
- }
336
+ export function scriptsRun(command, cwd, since, shell) {
337
+ const out = [];
338
+ const seen = new Set();
339
+ const first = (file) => {
340
+ const key = file.toLowerCase();
341
+ if (seen.has(key))
342
+ return false;
343
+ seen.add(key);
344
+ return true;
345
+ };
253
346
  for (const file of shellScriptsRun(command, cwd)) {
254
- const reason = notTheProjects(file, since);
255
- if (reason)
256
- return why(file, reason);
347
+ if (first(file))
348
+ out.push({ file, kind: kindOfFile(file, /\.jse?$/i.test(file)), written: notTheProjects(file, since), shell: true });
257
349
  }
258
350
  for (const file of codeFilesRun(command, cwd, shell)) {
259
- const reason = writtenDuringTheWork(file, since);
260
- if (reason) {
261
- return (`refused: ${relative(cwd, file) || file} is a script written during this work — ${reason} — and such a script is run by ` +
262
- 'the operator, not by the runner (the operator\'s rule). ' + HAND_IT_OVER + ' The project\'s tests run as steps, as before.');
351
+ if (!first(file))
352
+ continue;
353
+ const written = inScratch(file) ? `it is in ${SCRATCH}, the folder for scratch files` : writesFileNamed(command, file) ? SAME_LINE : writtenDuringTheWork(file, since);
354
+ out.push({ file, kind: kindOfFile(file), written });
355
+ }
356
+ for (const m of command.matchAll(SCRATCH_RUN)) {
357
+ const file = resolve(cwd, m[1]);
358
+ if (first(file))
359
+ out.push({ file, kind: kindOfFile(file), written: `it is in ${SCRATCH}, the folder for scratch files` });
360
+ }
361
+ const sameLine = writesPackageScripts(command);
362
+ for (const run of packageScriptsRun(command, cwd, shell)) {
363
+ const written = packageScriptWritten(run, since, sameLine);
364
+ // No such script and nothing writes it: npm says so, and nothing runs.
365
+ if (run.command === null && written === null)
366
+ continue;
367
+ out.push({ file: run.pkg, kind: 'npm', written: written === 'this same line writes it into package.json' ? SAME_LINE : written, script: { name: run.name, command: run.command } });
368
+ }
369
+ return out;
370
+ }
371
+ /** No box decides it: the project's own may run, the work's may not. */
372
+ const FIXED = { own: true, written: false };
373
+ /** How a script is named in a refusal. */
374
+ function named(run, cwd) {
375
+ const path = relative(cwd, run.file) || run.file;
376
+ return run.script ? `the script "${run.script.name}" of ${path}` : path;
377
+ }
378
+ /** The most of one script read for the card. */
379
+ const MAX_SHOWN_BYTES = 64 * 1024;
380
+ /** A script's text as the gate and the card read it, or why it cannot be. */
381
+ export function scriptText(run) {
382
+ if (run.script)
383
+ return run.script.command === null ? { problem: 'package.json has no script by that name' } : { text: run.script.command };
384
+ try {
385
+ const size = statSync(run.file).size;
386
+ if (size > MAX_SCRIPT_BYTES)
387
+ return { problem: `it is ${Math.round(size / 1024)} KB, larger than a step's script` };
388
+ const text = readFileSync(run.file, 'utf8');
389
+ return text.length > MAX_SHOWN_BYTES ? { text: text.slice(0, MAX_SHOWN_BYTES), cut: true } : { text };
390
+ }
391
+ catch {
392
+ return { problem: 'it does not exist yet' };
393
+ }
394
+ }
395
+ /**
396
+ * Why a chat's step must not run a script, or null (2026-10-21, boxes since 2026-10-27). Each script the line runs is
397
+ * the project's own or the work's (`scriptsRun`); the operator's box for its kind says whether either may run. A box
398
+ * left empty is a refusal, and the chat is told to hand the script over; a script of the work let run is read through
399
+ * `screen` first. A script written and run in one line is refused whatever the boxes say. Only for the chat's steps,
400
+ * the implementer's and the reviewer's: the operator's own checks are theirs to point at whatever they choose.
401
+ */
402
+ export function ownScriptRefusal(command, cwd, since, shell, opts = {}) {
403
+ const rules = opts.rules ?? DEFAULT_SCRIPT_RULES;
404
+ const instead = opts.reviewer ? REVIEW_INSTEAD : HAND_IT_OVER;
405
+ for (const run of scriptsRun(command, cwd, since, shell)) {
406
+ const rule = run.kind ? rules[run.kind] : FIXED;
407
+ const name = named(run, cwd);
408
+ if (run.written === null) {
409
+ if (!rule.own && run.kind) {
410
+ return `refused: ${name} is one of the project's own scripts, and the operator does not let the runner run the project's own scripts of this kind (${kindForChat(run.kind)}; the operator's rule). ${instead}`;
411
+ }
412
+ continue;
413
+ }
414
+ if (run.written === SAME_LINE) {
415
+ 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}`;
416
+ }
417
+ if (!rule.written) {
418
+ if (run.shell) {
419
+ return (`refused: ${name} is not one of the project's own scripts — ${run.written}. A script written or changed during the work is run by ` +
420
+ `the operator, not by the runner, nor is anything in ${SCRATCH} (the operator's rule). ${instead}`);
421
+ }
422
+ if (run.written.includes(SCRATCH)) {
423
+ return `refused: this runs a file in ${SCRATCH}, the folder for scratch files — the runner does not run the scripts written there (the operator's rule). ${instead}`;
424
+ }
425
+ return `refused: ${name} is a script written during this work — ${run.written} — and such a script is run by the operator, not by the runner (the operator's rule). ${instead} The project's tests run as steps, as before.`;
426
+ }
427
+ // The work's, and the operator lets this kind run: what is in it passes the gate the line passed.
428
+ if (opts.screen) {
429
+ const read = scriptText(run);
430
+ if ('problem' in read)
431
+ return `refused: ${name} cannot be read before it runs — ${read.problem}. Write it in an earlier step, then run it.`;
432
+ const reason = opts.screen(run, read.text);
433
+ if (reason)
434
+ return `${reason} (in ${name}, written during this work)`;
263
435
  }
264
436
  }
265
437
  return null;
266
438
  }
439
+ /** The scripts of the work a line runs that the operator's boxes let run: shown on the card that asks about them. */
440
+ export function writtenScriptsLetRun(command, cwd, since, shell, rules) {
441
+ return scriptsRun(command, cwd, since, shell).filter((r) => r.written !== null && r.written !== SAME_LINE && r.kind !== null && rules[r.kind].written);
442
+ }
267
443
  /** What the chat is told to do instead (2026-10-26). */
268
444
  const HAND_IT_OVER = 'Put what it does in the step itself — a command may be several lines — or hand it to the operator with status "handoff": ' +
269
445
  'the commands, the folder, what they should see and the script; the operator runs it and you get what it printed.';
446
+ /** What the reviewer is told instead: a review hands nothing over. */
447
+ const REVIEW_INSTEAD = 'A review runs commands only: check what it would show with commands of your own, written out in the step itself, or say in a finding that the operator has to run it.';