copilot-operator 0.1.69 → 0.1.75

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/operator.controller.js +6 -3
  2. package/dist/src/api/operator.service.js +58 -13
  3. package/dist/src/api/server.js +10 -0
  4. package/dist/src/cli.js +3 -0
  5. package/dist/src/config/lockedPolicy.js +14 -0
  6. package/dist/src/config/schema.js +29 -0
  7. package/dist/src/exec/authorizer.js +47 -8
  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 +124 -9
  12. package/dist/src/exec/policyManifest.js +15 -0
  13. package/dist/src/exec/processes.js +8 -3
  14. package/dist/src/exec/programs.js +6 -1
  15. package/dist/src/exec/redaction.js +17 -2
  16. package/dist/src/exec/scriptFiles.js +230 -34
  17. package/dist/src/exec/scriptKinds.js +86 -0
  18. package/dist/src/exec/stepEnv.js +9 -2
  19. package/dist/src/orchestrator/handoff.js +80 -29
  20. package/dist/src/orchestrator/hold.js +83 -4
  21. package/dist/src/orchestrator/leadRunner.js +5 -2
  22. package/dist/src/orchestrator/review.js +13 -3
  23. package/dist/src/orchestrator/taskRunner.js +106 -19
  24. package/dist/src/plan/kerrigan.js +36 -15
  25. package/dist/src/plan/systemGuide.js +117 -22
  26. package/dist/src/protocol/leadSchema.js +8 -1
  27. package/dist/src/protocol/replySchema.js +13 -3
  28. package/dist/src/protocol/reviewSchema.js +4 -1
  29. package/dist/src/queue/queue.js +8 -4
  30. package/dist/src/session/checkpoint.js +48 -0
  31. package/dist/src/session/compose.js +1 -1
  32. package/dist/src/session/story.js +14 -0
  33. package/dist/src/vcs/gitConfigGuard.js +126 -0
  34. package/dist/src/vcs/newBranch.js +76 -13
  35. package/dist/web/404.html +2 -2
  36. package/dist/web/_next/static/chunks/1024-67625a65f58057ae.js +1 -0
  37. package/dist/web/_next/static/chunks/1077.14d6c828d8f71111.js +1 -0
  38. package/dist/web/_next/static/chunks/1548.2f75926c6e664f79.js +1 -0
  39. package/dist/web/_next/static/chunks/2163.f9f1ad4af05520cc.js +1 -0
  40. package/dist/web/_next/static/chunks/714.4507656685cb9337.js +1 -0
  41. package/dist/web/_next/static/chunks/7220.9bc9dd9f211b11e4.js +1 -0
  42. package/dist/web/_next/static/chunks/7921-9aaec581982b2329.js +1 -0
  43. package/dist/web/_next/static/chunks/8124-a39d85dff0db6600.js +1 -0
  44. package/dist/web/_next/static/chunks/8584.f2cb3ca81223d626.js +1 -0
  45. package/dist/web/_next/static/chunks/9067.a6cb3b9157a80921.js +1 -0
  46. package/dist/web/_next/static/chunks/9747.15aa40a046d54a2a.js +1 -0
  47. package/dist/web/_next/static/chunks/9929-2e0b1d006ebd5345.js +1 -0
  48. package/dist/web/_next/static/chunks/app/{layout-e23bb58f3ea117d5.js → layout-52a2079ffa83c21f.js} +1 -1
  49. package/dist/web/_next/static/chunks/app/page-80730838a81da226.js +1 -0
  50. package/dist/web/_next/static/chunks/app/queue/{page-fb49cb2d3dc6d14c.js → page-82f724d0842f4870.js} +1 -1
  51. package/dist/web/_next/static/chunks/app/settings/page-4f3c739287d7f32e.js +1 -0
  52. package/dist/web/_next/static/chunks/{webpack-77c6c045264c9213.js → webpack-f9f820c51a8952c8.js} +1 -1
  53. package/dist/web/_next/static/css/63b30b8e1a4aa500.css +1 -0
  54. package/dist/web/defaults.html +2 -2
  55. package/dist/web/defaults.txt +8 -8
  56. package/dist/web/index.html +3 -3
  57. package/dist/web/index.txt +9 -9
  58. package/dist/web/queue.html +2 -2
  59. package/dist/web/queue.txt +9 -9
  60. package/dist/web/settings.html +2 -2
  61. package/dist/web/settings.txt +9 -9
  62. package/dist/web/system.html +2 -2
  63. package/dist/web/system.txt +9 -9
  64. package/package.json +3 -2
  65. package/prompts/level1.md +50 -27
  66. package/dist/web/_next/static/chunks/1024-e4e596b184e05e91.js +0 -1
  67. package/dist/web/_next/static/chunks/1077.b3943e5b41c4bef4.js +0 -1
  68. package/dist/web/_next/static/chunks/1548.0ff0c0ece685ffe7.js +0 -1
  69. package/dist/web/_next/static/chunks/2163.9cfb1b06beaf5001.js +0 -1
  70. package/dist/web/_next/static/chunks/6262-d074473db83ee798.js +0 -1
  71. package/dist/web/_next/static/chunks/714.bee98f5a3db75882.js +0 -1
  72. package/dist/web/_next/static/chunks/7220.610988766a1104b7.js +0 -1
  73. package/dist/web/_next/static/chunks/7921-ac5793d5663674b2.js +0 -1
  74. package/dist/web/_next/static/chunks/8124-665327221384ba6e.js +0 -1
  75. package/dist/web/_next/static/chunks/8584.9220e445a8ce2265.js +0 -1
  76. package/dist/web/_next/static/chunks/9067.f05516f2f2a2e8f5.js +0 -1
  77. package/dist/web/_next/static/chunks/9747.e249434ff7e05f4f.js +0 -1
  78. package/dist/web/_next/static/chunks/app/page-fd49cf4fb6681d30.js +0 -1
  79. package/dist/web/_next/static/chunks/app/settings/page-7d120feb5af0ace9.js +0 -1
  80. package/dist/web/_next/static/css/52131c6d864daf3f.css +0 -1
  81. /package/dist/web/_next/static/{8i6gf0zoo-KiUKdzxsCJR → 9DmRzBb0M5BZ3dvVpbFMM}/_buildManifest.js +0 -0
  82. /package/dist/web/_next/static/{8i6gf0zoo-KiUKdzxsCJR → 9DmRzBb0M5BZ3dvVpbFMM}/_ssgManifest.js +0 -0
@@ -7,6 +7,13 @@
7
7
  * operator continues. Nothing ends: it is the same task, in the same conversation and the same browser window,
8
8
  * after it, and the time it spent held does not count against `maxRunMinutes`.
9
9
  *
10
+ * Nor does the time the work waits for the operator (operator, 2026-10-29: "the time the browser session may be used
11
+ * went on while the user had not answered the chat's questions; while the bot waits for the user to type something or
12
+ * answer, it must not count"): a card — a command, a question, a plan, the model to choose, a subtask to try again,
13
+ * commands handed over —, Git's password window, a sign-in or a check that a person is there, each from the moment it
14
+ * waits to the moment it is answered (`waitFor`, `waited`). A pause and a wait, or two waits, at the same time are
15
+ * counted once.
16
+ *
10
17
  * Not `RunDeps.shouldPause`, which holds a queue between tasks, after the task running has ended properly.
11
18
  */
12
19
  export class Hold {
@@ -18,6 +25,10 @@ export class Hold {
18
25
  * paused is taken off a task's minutes — its limit, and the minutes the page shows.
19
26
  */
20
27
  spans = [];
28
+ /** What waits for the operator now, by a key of its own (`card:<id>`, `pw:<session>`…), since when. */
29
+ waits = new Map();
30
+ /** The waits that were answered, or went any other way. */
31
+ waitedSpans = [];
21
32
  /** Whether the operator has asked the task to hold. */
22
33
  get held() {
23
34
  return this.paused;
@@ -42,13 +53,30 @@ export class Hold {
42
53
  go();
43
54
  return true;
44
55
  }
45
- /** How long the work was paused since `since` (ms), the pause going on counted to now. */
56
+ /** Something waits for the operator from now; a second start of the same one changes nothing. */
57
+ waitFor(key, at = Date.now()) {
58
+ if (!this.waits.has(key))
59
+ this.waits.set(key, at);
60
+ }
61
+ /** It was answered, or went any other way; nothing when it was not waiting. */
62
+ waited(key, at = Date.now()) {
63
+ const from = this.waits.get(key);
64
+ if (from === undefined)
65
+ return;
66
+ this.waits.delete(key);
67
+ this.waitedSpans.push({ from, to: Math.max(from, at) });
68
+ }
69
+ /** The time not counted — paused, or waiting for the operator — joined where it overlaps, in order. */
70
+ notCounted() {
71
+ return joined([...this.spans, ...this.waitedSpans, ...[...this.waits.values()].map((from) => ({ from }))]);
72
+ }
73
+ /** How long the work was paused or waited for the operator since `since` (ms), what goes on counted to now. */
46
74
  pausedSince(since, now = Date.now()) {
47
- return pausedWithin(this.spans, since, now);
75
+ return pausedWithin(this.notCounted(), since, now);
48
76
  }
49
- /** The pauses, for the page to take them off the minutes it shows. */
77
+ /** The time not counted, for the page to take it off the minutes it shows: the pauses and the waits, joined. */
50
78
  get pauses() {
51
- return this.spans.map((s) => ({ from: new Date(s.from).toISOString(), ...(s.to !== undefined ? { to: new Date(s.to).toISOString() } : {}) }));
79
+ return this.notCounted().map((s) => ({ from: new Date(s.from).toISOString(), ...(s.to !== undefined ? { to: new Date(s.to).toISOString() } : {}) }));
52
80
  }
53
81
  /** Resolves at once when not held; otherwise when the operator continues, or the run is stopped. */
54
82
  until(signal) {
@@ -65,6 +93,57 @@ export class Hold {
65
93
  });
66
94
  }
67
95
  }
96
+ /** Spans joined where they overlap or touch, in order; one with no end takes in every span that starts after it. */
97
+ export function joined(spans) {
98
+ const out = [];
99
+ for (const s of [...spans].sort((a, b) => a.from - b.from)) {
100
+ const last = out.at(-1);
101
+ if (last && (last.to === undefined || s.from <= last.to)) {
102
+ if (last.to !== undefined) {
103
+ if (s.to === undefined)
104
+ delete last.to;
105
+ else
106
+ last.to = Math.max(last.to, s.to);
107
+ }
108
+ }
109
+ else
110
+ out.push(s.to === undefined ? { from: s.from } : { from: s.from, to: s.to });
111
+ }
112
+ return out;
113
+ }
114
+ /**
115
+ * The cards that wait for the operator, kept as a map, each starting a wait when it is put in and ending it when it
116
+ * goes — answered, set aside, stopped —, so no card can wait without its time being left out (2026-10-29).
117
+ */
118
+ export class WaitsFor extends Map {
119
+ onWait;
120
+ constructor(onWait) {
121
+ super();
122
+ this.onWait = onWait;
123
+ }
124
+ set(key, value) {
125
+ const fresh = !this.has(key);
126
+ super.set(key, value);
127
+ // `onWait` is not there yet while `super()` runs: Map's constructor puts nothing in, but be sure.
128
+ if (fresh)
129
+ this.onWait?.(key, value, true);
130
+ return this;
131
+ }
132
+ delete(key) {
133
+ const had = this.has(key);
134
+ const value = this.get(key);
135
+ const gone = super.delete(key);
136
+ if (had && gone)
137
+ this.onWait(key, value, false);
138
+ return gone;
139
+ }
140
+ clear() {
141
+ const all = [...this.entries()];
142
+ super.clear();
143
+ for (const [key, value] of all)
144
+ this.onWait(key, value, false);
145
+ }
146
+ }
68
147
  /** The time of `spans` that falls between `since` and `now`, a span with no end lasting to `now`. */
69
148
  export function pausedWithin(spans, since, now) {
70
149
  let ms = 0;
@@ -33,7 +33,7 @@ import { leadFormatErrorMessage, parseLeadReply, UNDERSTANDING_FIRST } from '../
33
33
  import { describePlan, planFrom } from './planMode.js';
34
34
  import { closeLedger, describeLedger, nextLedger } from './leadLedger.js';
35
35
  import { classifySubtaskEnd, describeAttempts, FAILURE_WORDS, retryMessage, retryPlan, sanitizedReason, sideEffectsOf, stepFacts, stepsOf } from './subtaskRetry.js';
36
- import { ACTOR_WORDS, applySessionModel, enterSessionConversation, holdsWhilePaused, limitsMessageLength, runTask, Sink, speakFor, StoppedSend } from './taskRunner.js';
36
+ import { ACTOR_WORDS, applySessionModel, enterSessionConversation, holdsWhilePaused, limitsMessageLength, redactsMessages, runTask, Sink, speakFor, StoppedSend } from './taskRunner.js';
37
37
  import { DEFAULT_VCS } from '../session/store.js';
38
38
  /** The assignment as the lead is given it: the operator's message, and what the runner tells it about the work. */
39
39
  export function assignmentMessage(task, n, facts, again) {
@@ -253,10 +253,13 @@ export async function runLeadTask(transport, session, task, deps) {
253
253
  return stopped;
254
254
  };
255
255
  // No message to the lead longer than Settings allow as text: the rest goes attached (2026-10-22).
256
- const leadChat = limitsMessageLength(holdsWhilePaused(transport, holdHere), {
256
+ const leadChat = redactsMessages(limitsMessageLength(holdsWhilePaused(transport, holdHere), {
257
257
  max: cfg.limits.maxMessageChars,
258
258
  dir: log.path('messages'),
259
259
  onLong: ({ chars, max, file }) => sink.event('message-long', { chars, max, file, lead: true }, `a message to the lead of ${chars} characters is over the ${max} sent as text: its beginning is sent, the whole of it attached as ${file}`, 'warn'),
260
+ }), {
261
+ patterns: cfg.report.redactPatterns,
262
+ onRedacted: (hits) => sink.event('message-redacted', { redactions: hits, lead: true }, `secrets taken out of a message to the lead before it was sent: ${hits.map((h) => `${h.name} ×${h.count}`).join(', ')}`, 'warn'),
260
263
  });
261
264
  let sent = 0;
262
265
  let replies = 0;
@@ -25,7 +25,7 @@ import { parseReview, formatErrorMessage, findLikelyDamage, damageGuidance } fro
25
25
  import { describeFindings, findingId, isGrounded } from '../protocol/reviewSchema.js';
26
26
  import { runStep } from '../exec/runner.js';
27
27
  import { effectiveShell, preferredShell, refusalForChat, resolveShell, shellNote } from '../exec/shells.js';
28
- import { describeStep, checkCommandRefusal } from '../exec/policy.js';
28
+ import { describeStep, modelCheckRefusal } from '../exec/policy.js';
29
29
  import { validateDerivedChecks } from './derivedChecks.js';
30
30
  import { writeReport } from '../exec/reportFile.js';
31
31
  import { mergeRedactions } from '../exec/redaction.js';
@@ -33,6 +33,7 @@ import { trackedRepoOf } from '../vcs/taskVcs.js';
33
33
  import { buildCoveringMessage, assertSendable } from '../protocol/reporter.js';
34
34
  import { planForReviewer } from './planMode.js';
35
35
  import { inScope } from '../vcs/scope.js';
36
+ import { gitConfigMessage, watchGitConfig } from '../vcs/gitConfigGuard.js';
36
37
  /** The sentence both sides get when a review left something listening. */
37
38
  function leftoverNote(leftovers) {
38
39
  const listening = leftovers.filter((l) => l.ports.length > 0);
@@ -406,7 +407,7 @@ ${machineNote}` : contract);
406
407
  * at a gate. The finding stands without it, as for any check the runner will not run.
407
408
  * See `network.ts`.
408
409
  */
409
- deny: (command, shell, cwd) => checkCommandRefusal(command, shell, cfg.execution, { roots: deps.roots, cwd }),
410
+ deny: (command, shell, cwd) => modelCheckRefusal(command, shell, cfg.execution, { roots: deps.roots, cwd, workStartedAt: deps.workStartedAt }),
410
411
  roots: deps.roots,
411
412
  signal,
412
413
  defaultShell,
@@ -454,9 +455,11 @@ ${machineNote}` : contract);
454
455
  }
455
456
  // --- run what the reviewer asked for ------------------------------------------------
456
457
  const results = [];
457
- for (const step of review.steps) {
458
+ for (const proposed of review.steps) {
458
459
  if (signal?.aborted)
459
460
  break;
461
+ // Screened in the shell it will run in (audit, 2026-10-27): see the implementer's step loop.
462
+ const step = proposed.shell ? proposed : { ...proposed, shell: defaultShell };
460
463
  if (step.type !== 'command') {
461
464
  results.push(refused(step.id, 'a review runs commands only; it does not download or execute files', '(not run)', step.shell));
462
465
  continue;
@@ -499,6 +502,7 @@ ${machineNote}` : contract);
499
502
  results.push(refused(step.id, refusalForChat(named.problem, defaultShell), step.cmd, step.shell));
500
503
  continue;
501
504
  }
505
+ const gitConfigAfter = watchGitConfig(deps.cwd);
502
506
  const result = await runStep({
503
507
  id: step.id,
504
508
  shell: step.shell ?? defaultShell,
@@ -511,6 +515,12 @@ ${machineNote}` : contract);
511
515
  }, { signal, tracker: deps.tracker });
512
516
  stepsRun += 1;
513
517
  results.push(result);
518
+ // Git's settings that would make the runner's own git run a program, put back (audit, 2026-10-27).
519
+ const configPutBack = gitConfigAfter();
520
+ if (configPutBack.length > 0) {
521
+ deps.event('git-config-put-back', { round, id: step.id, changes: configPutBack }, `review step ${step.id} changed git settings that name a program; put back`);
522
+ result.stderr = `${result.stderr}${result.stderr && !result.stderr.endsWith('\n') ? '\n' : ''}[runner] ${gitConfigMessage(configPutBack)}\n`;
523
+ }
514
524
  const touched = deps.afterStep ? await deps.afterStep().catch(() => null) : null;
515
525
  if (touched)
516
526
  result.stderr = `${result.stderr}${result.stderr && !result.stderr.endsWith('\n') ? '\n' : ''}[runner] ${touched}\n`;
@@ -28,16 +28,18 @@ import { availableShells, detectShells, effectiveShell, preferredShell, refusalF
28
28
  import { runChecks, failureMessage, failureRedactions, failureReport, environmentProblemIn, COMMIT_CLEAN_CHECK, CONTENT_CLEAN_CHECK, RUNNER_CHECK_KINDS } from '../exec/checks.js';
29
29
  import { activeChecks, suspendDisputed, settleAfterReview, onlyDerivedFailing, isDerivedCheck, withAttemptIds } from './derivedChecks.js';
30
30
  import { workingDirFor, isWorkingDirProblem, workingDirNote } from '../exec/workDir.js';
31
- import { redactSecrets } from '../exec/redaction.js';
31
+ import { findRedactions, redactSecrets } from '../exec/redaction.js';
32
32
  import { snapshotProcesses, reapLeftovers, describeLeftovers, ProcessTracker } from '../exec/processes.js';
33
33
  import { collectEnvironment, describeEnvironment } from '../exec/environment.js';
34
34
  import { describeCrash } from '../transport/edgeCrash.js';
35
35
  import { runReview, findingsMessage, deliverableFor } from './review.js';
36
36
  import { allAboutTheTask, isRepeat, findingId } from '../protocol/reviewSchema.js';
37
37
  import { repoState, workingTreePaths } from '../vcs/git.js';
38
- import { describeStep, checkAccessRefusal, checkCommandRefusal, commandRefusal, staticCheck } from '../exec/policy.js';
38
+ import { describeStep, checkAccessRefusal, checkCommandRefusal, commandRefusal } from '../exec/policy.js';
39
39
  import { networkFetchReason } from '../exec/network.js';
40
- import { handoffCard, handoffResultMessage, HANDOFF_NOBODY } from './handoff.js';
40
+ import { handoffCard, handoffOutcomeOf, handoffResultMessage, HANDOFF_NOBODY } from './handoff.js';
41
+ import { gitConfigMessage, watchGitConfig } from '../vcs/gitConfigGuard.js';
42
+ import { scriptsNote } from '../exec/scriptKinds.js';
41
43
  import { collectPolicyManifest, describePolicyManifest } from '../exec/policyManifest.js';
42
44
  import { assessIsolation, readIsolationSignals } from '../exec/isolation.js';
43
45
  import { confinementRefusal, isWithin, sessionRoots } from '../exec/confinement.js';
@@ -330,6 +332,29 @@ export function limitsMessageLength(transport, opts) {
330
332
  },
331
333
  });
332
334
  }
335
+ /**
336
+ * The same chat, whose every message has its secrets taken out before it goes (audit, 2026-10-27): the shapes of
337
+ * `redaction.ts` and the operator's own patterns, as each report already had. The reports were redacted where they were
338
+ * written; the texts made elsewhere were not — the output the operator pasted from a script they ran, an answer they
339
+ * typed, the message after a Stop that quotes the end of each step's log — and a token printed there went to Copilot.
340
+ * Put outside `limitsMessageLength`, so a message too long for text is redacted before its whole is written to a file.
341
+ */
342
+ export function redactsMessages(transport, opts) {
343
+ return new Proxy(transport, {
344
+ get(target, key) {
345
+ if (key === 'sendAndConfirm') {
346
+ return async (text, attachments = []) => {
347
+ const hits = findRedactions(text, opts.patterns);
348
+ if (hits.length > 0)
349
+ opts.onRedacted?.(hits);
350
+ return await target.sendAndConfirm(hits.length > 0 ? redactSecrets(text, opts.patterns) : text, attachments);
351
+ };
352
+ }
353
+ const value = Reflect.get(target, key, target);
354
+ return typeof value === 'function' ? value.bind(target) : value;
355
+ },
356
+ });
357
+ }
333
358
  /** One place that writes to the transcript, the console and the live stream at once. */
334
359
  export class Sink {
335
360
  log;
@@ -1029,6 +1054,11 @@ export async function runTask(transport, session, task, deps) {
1029
1054
  dir: log.path('messages'),
1030
1055
  onLong: ({ chars, max, file }) => sink.event('message-long', { chars, max, file }, `a message of ${chars} characters is over the ${max} sent as text: its beginning is sent, the whole of it attached as ${file}`, 'warn'),
1031
1056
  });
1057
+ // Nothing goes to the chat with a secret in it, whatever made the message (audit, 2026-10-27).
1058
+ transport = redactsMessages(transport, {
1059
+ patterns: cfg.report.redactPatterns,
1060
+ onRedacted: (hits) => sink.event('message-redacted', { redactions: hits }, `secrets taken out of a message before it was sent: ${hits.map((h) => `${h.name} ×${h.count}`).join(', ')}`, 'warn'),
1061
+ });
1032
1062
  let iterations = 0;
1033
1063
  /** What the model has declared it could not do as written, merged across every reply. */
1034
1064
  let deviations = [];
@@ -1037,10 +1067,25 @@ export async function runTask(transport, session, task, deps) {
1037
1067
  /** What the runner tells the model in its next message about the reply just processed. */
1038
1068
  let runnerNotes = [];
1039
1069
  /*
1040
- * Commands the operator chose an answer for (2026-10-23): the click is the permission for that one command, once.
1041
- * The rules that refuse a command still apply to it.
1070
+ * The command of the answer the operator chose (2026-10-23): the click is the permission for that one command, once,
1071
+ * in the reply made of it and no later one (audit, 2026-10-27: one refused before it ran stayed allowed for the next
1072
+ * step of the same text). An answer taken because nobody was there to ask is no click: its command is asked about as
1073
+ * any step is. The rules that refuse a command, and the holds, still apply to it.
1042
1074
  */
1043
- const consented = new Set();
1075
+ let chosenRun = null;
1076
+ /** The handoff's revision, and whether the last one was sent back for a correction (2026-10-27). */
1077
+ let handoffRevision = 0;
1078
+ let handoffSentBack = false;
1079
+ /**
1080
+ * Each handoff as it was shown and answered, kept in the run folder, so the conversation shows every revision, the
1081
+ * note it was sent back with and what the operator's own run printed (`session/story.ts`).
1082
+ */
1083
+ let handoffsKept = 0;
1084
+ const keepHandoff = async (entry) => {
1085
+ handoffsKept += 1;
1086
+ await mkdir(log.path('handoffs'), { recursive: true }).catch(() => undefined);
1087
+ await writeFile(log.path('handoffs', `${String(handoffsKept).padStart(3, '0')}.json`), JSON.stringify(entry, null, 2), 'utf8').catch(() => undefined);
1088
+ };
1044
1089
  /** The projects for reference only, watched for the length of the task (see `vcs/referenceGuard.ts`). */
1045
1090
  let reference = null;
1046
1091
  /** Steps the chat sent that were not run, for the handoff at the end. */
@@ -1554,6 +1599,9 @@ export async function runTask(transport, session, task, deps) {
1554
1599
  networkFetch: cfg.execution.networkFetch,
1555
1600
  allowedPrograms: cfg.execution.allowedPrograms,
1556
1601
  readOnlyPrograms: cfg.execution.readOnlyPrograms,
1602
+ runWithoutAsking: cfg.execution.runWithoutAsking,
1603
+ scripts: cfg.execution.scripts,
1604
+ writtenScripts: cfg.execution.writtenScripts,
1557
1605
  denyPatterns: cfg.execution.denyPatterns,
1558
1606
  cwd: work.cwd,
1559
1607
  lock: cfg.policyLock,
@@ -1779,6 +1827,7 @@ export async function runTask(transport, session, task, deps) {
1779
1827
  `each listed in "tried". With fewer, the runner asks you for another approach instead of accepting it.`
1780
1828
  : undefined,
1781
1829
  shellNote: shellNote(shells, defaultShell),
1830
+ scriptsNote: scriptsNote(cfg.execution.scripts, cfg.execution.writtenScripts),
1782
1831
  ...(planning && planMode !== 'off'
1783
1832
  ? { planNote: planModeNote(planMode, planEnforced, planMode === 'approve' && !!deps.approvePlan && (session.kind === 'chat' || (deps.currentMode?.() ?? cfg.execution.mode) === 'confirm')) }
1784
1833
  : {}),
@@ -2685,12 +2734,18 @@ export async function runTask(transport, session, task, deps) {
2685
2734
  * they printed, or that they did not run it, goes back, and the work goes on.
2686
2735
  */
2687
2736
  if (reply.status === 'handoff' && reply.handoff) {
2688
- const card = handoffCard(reply.handoff, work.cwd, confinement.roots, cfg.execution.denyPatterns);
2737
+ // The next revision of the one sent back for a correction; otherwise the first of a new one (2026-10-27).
2738
+ handoffRevision = handoffSentBack ? handoffRevision + 1 : 1;
2739
+ handoffSentBack = false;
2740
+ const card = handoffCard(reply.handoff, work.cwd, confinement.roots, cfg.execution.denyPatterns, handoffRevision);
2689
2741
  const why = reply.handoff.why?.trim() || 'Run these commands yourself, and send what they print.';
2690
2742
  let message = HANDOFF_NOBODY;
2691
- await record('HANDOFF', `${why}\n\nin ${card.cwd}:\n${card.commands.join('\n')}\n\nexpected: ${card.expect}${card.files.length ? `\n\nscripts: ${card.files.map((f) => `${f.path}${f.sha256 ? ` (sha256 ${f.sha256})` : f.problem ? ` (${f.problem})` : ''}`).join(', ')}` : ''}`);
2743
+ let outcome = null;
2744
+ let answer = '';
2745
+ const askedAt = new Date().toISOString();
2746
+ await record('HANDOFF', `revision ${card.revision}: ${why}\n\nin ${card.cwd}:\n${card.commands.join('\n')}\n\nexpected: ${card.expect}${card.files.length ? `\n\nscripts: ${card.files.map((f) => `${f.path}${f.problem ? ` (${f.problem})` : ''}`).join(', ')}` : ''}`);
2692
2747
  if (deps.askQuestion) {
2693
- sink.event('handoff-asked', { commands: card.commands, cwd: card.cwd, files: card.files.map((f) => ({ path: f.path, sha256: f.sha256 })) }, `the chat hands the operator commands to run themselves: ${card.commands.join(' ; ')}`, 'warn');
2748
+ sink.event('handoff-asked', { commands: card.commands, cwd: card.cwd, revision: card.revision, files: card.files.map((f) => f.path) }, `the chat hands the operator commands to run themselves (revision ${card.revision}): ${card.commands.join(' ; ')}`, 'warn');
2694
2749
  await setTask((t) => {
2695
2750
  t.status = 'waiting-approval';
2696
2751
  });
@@ -2698,15 +2753,22 @@ export async function runTask(transport, session, task, deps) {
2698
2753
  await setTask((t) => {
2699
2754
  t.status = 'running';
2700
2755
  });
2701
- if (got === 'stop' || signal?.aborted)
2756
+ if (got === 'stop' || signal?.aborted) {
2757
+ await keepHandoff({ askedAt, card, outcome: 'stopped' });
2702
2758
  return await finish('aborted', 'stopped by the operator at the commands handed over', undefined, lastMarkdown);
2703
- const ran = got.ran !== false;
2704
- sink.event('handoff-answered', { ran }, ran ? 'the operator ran the commands and sent what they printed' : 'the operator did not run the commands');
2705
- message = handoffResultMessage(card, ran, got.answer);
2759
+ }
2760
+ outcome = handoffOutcomeOf(got.outcome, got.ran);
2761
+ answer = got.answer;
2762
+ handoffSentBack = outcome === 'revise';
2763
+ sink.event('handoff-answered', { outcome, revision: card.revision }, outcome === 'ran' ? 'the operator ran the commands and sent what they printed'
2764
+ : outcome === 'revise' ? `the operator sent revision ${card.revision} back for a correction`
2765
+ : 'the operator will not run the commands');
2766
+ message = handoffResultMessage(card, outcome, got.answer);
2706
2767
  }
2707
2768
  else {
2708
2769
  sink.event('handoff-nobody', { commands: card.commands }, 'the chat handed over commands to run, and nobody is here to run them', 'warn');
2709
2770
  }
2771
+ await keepHandoff({ askedAt, card, outcome: outcome ?? 'nobody', answer, answeredAt: new Date().toISOString() });
2710
2772
  await record('HANDOFF RESULT', message);
2711
2773
  await pacer.throttleSend();
2712
2774
  const before = await transport.sendAndConfirm(message);
@@ -2757,7 +2819,7 @@ export async function runTask(transport, session, task, deps) {
2757
2819
  const chosen = options.find((o) => o.answer === answer);
2758
2820
  if (chosen?.run) {
2759
2821
  // Run as this reply's one step: through the step loop below, its output reported as any step's.
2760
- consented.add(chosen.run.trim());
2822
+ chosenRun = agree && deps.askQuestion === undefined ? null : chosen.run.trim();
2761
2823
  const mutable = reply;
2762
2824
  mutable.status = 'continue';
2763
2825
  mutable.steps = [{ id: 1, type: 'command', cmd: chosen.run, ...(chosen.shell ? { shell: chosen.shell } : {}) }];
@@ -2943,7 +3005,14 @@ export async function runTask(transport, session, task, deps) {
2943
3005
  * tests run on the old code (live run 2026-10-03).
2944
3006
  */
2945
3007
  let refusedAt = null;
2946
- for (const step of reply.steps) {
3008
+ const chosenNow = chosenRun;
3009
+ chosenRun = null;
3010
+ for (const proposed of reply.steps) {
3011
+ /*
3012
+ * Screened in the shell it will run in (audit, 2026-10-27): a step that names none runs in the default shell, and
3013
+ * the gate read it as PowerShell — a line one string to PowerShell is several commands to cmd.
3014
+ */
3015
+ const step = proposed.shell ? proposed : { ...proposed, shell: defaultShell };
2947
3016
  // Paused: no other command runs until Continue. Stopped while held, the Stop just below takes it.
2948
3017
  await holdHere('command');
2949
3018
  if (signal?.aborted) {
@@ -3011,10 +3080,19 @@ export async function runTask(transport, session, task, deps) {
3011
3080
  t.status = 'waiting-approval';
3012
3081
  });
3013
3082
  sink.event('step-proposed', { id: step.id, description: describeStep(step) }, `step ${step.id}: ${describeStep(step)}`);
3014
- // The command of an answer the operator chose (2026-10-23): their click allowed it; the refusing rules still hold.
3015
- const decided = consented.delete(step.cmd.trim())
3016
- ? (staticCheck(step, { mode: 'confirm', denyPatterns: cfg.execution.denyPatterns, allowedPrograms: cfg.execution.allowedPrograms }, undefined, confinement) ?? { action: 'run' })
3017
- : await authorizer.authorize(step, { sessionId: session.id, taskId: task.id, iteration: iterations, confinement, actor: planning ? 'plan' : 'worker' });
3083
+ /*
3084
+ * The command of an answer the operator chose (2026-10-23): their click allowed it, so the plain card is not put
3085
+ * again; every rule and hold still applies, through the run's own policy (audit, 2026-10-27: it was checked with
3086
+ * a policy of three fields, which left the read-only, network and platform holds and the unattended rules out).
3087
+ */
3088
+ const decided = await authorizer.authorize(step, {
3089
+ sessionId: session.id,
3090
+ taskId: task.id,
3091
+ iteration: iterations,
3092
+ confinement,
3093
+ actor: planning ? 'plan' : 'worker',
3094
+ ...(chosenNow !== null && chosenNow === step.cmd.trim() ? { chosen: true } : {}),
3095
+ });
3018
3096
  await setTask((t) => {
3019
3097
  t.status = 'running';
3020
3098
  });
@@ -3039,6 +3117,8 @@ export async function runTask(transport, session, task, deps) {
3039
3117
  const hard = Math.min(step.timeoutSec ?? (long ? cfg.execution.longCommandTimeoutSec : cfg.execution.commandTimeoutSec), cap);
3040
3118
  const idle = Math.min(step.idleTimeoutSec ?? (long ? cfg.execution.longIdleTimeoutSec : cfg.execution.idleTimeoutSec), cap);
3041
3119
  sink.event('step-started', { id: step.id, shell: step.shell ?? defaultShell }, `running step ${step.id}: ${describeStep(step)}`);
3120
+ // Git's settings that would make the runner's own git run a program: read now, put back after (audit, 2026-10-27).
3121
+ const gitConfigAfter = watchGitConfig(work.cwd);
3042
3122
  const result = await runStep({
3043
3123
  id: step.id,
3044
3124
  shell: step.shell ?? defaultShell,
@@ -3059,6 +3139,13 @@ export async function runTask(transport, session, task, deps) {
3059
3139
  : `step ${step.id}: Git's password window closed`, open ? 'warn' : 'info'),
3060
3140
  onHeartbeat: ({ elapsedMs, idleMs, lastLine }) => sink.event('step-heartbeat', { id: step.id, elapsedMs, idleMs, lastLine }, `step ${step.id} still running: ${Math.round(elapsedMs / 1000)}s elapsed, ${Math.round(idleMs / 1000)}s since output${lastLine ? ` — ${lastLine.slice(0, 60)}` : ''}`),
3061
3141
  });
3142
+ const configPutBack = gitConfigAfter();
3143
+ if (configPutBack.length > 0) {
3144
+ const told = gitConfigMessage(configPutBack);
3145
+ sink.event('git-config-put-back', { id: step.id, changes: configPutBack }, `step ${step.id} changed git settings that name a program; put back: ${configPutBack.map((c) => c.keys.join(', ')).join('; ')}`, 'warn');
3146
+ result.stderr = `${result.stderr}${result.stderr.endsWith('\n') || !result.stderr ? '' : '\n'}[runner] ${told}\n`;
3147
+ runnerNotes.push(told);
3148
+ }
3062
3149
  results.push(result);
3063
3150
  stepsRunThisAttempt += 1;
3064
3151
  // The run counts toward the limit only if it changed nothing about the answer.