copilot-operator 0.1.52 → 0.1.53

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 (57) hide show
  1. package/README.md +17 -1
  2. package/dist/src/api/operator.controller.js +35 -2
  3. package/dist/src/api/operator.service.js +83 -6
  4. package/dist/src/config/schema.js +32 -0
  5. package/dist/src/exec/policy.js +11 -1
  6. package/dist/src/exec/scriptFiles.js +108 -2
  7. package/dist/src/orchestrator/leadRunner.js +50 -4
  8. package/dist/src/orchestrator/review.js +9 -3
  9. package/dist/src/orchestrator/taskRunner.js +55 -3
  10. package/dist/src/plan/kerrigan.js +35 -4
  11. package/dist/src/plan/systemGuide.js +123 -4
  12. package/dist/src/session/compose.js +16 -4
  13. package/dist/src/session/store.js +3 -0
  14. package/dist/src/util/pacing.js +33 -2
  15. package/dist/src/vcs/git.js +11 -1
  16. package/dist/src/vcs/referenceGuard.js +299 -0
  17. package/dist/web/404.html +3 -2
  18. package/dist/web/_next/static/chunks/163.980c5145848efbdf.js +1 -0
  19. package/dist/web/_next/static/chunks/220.447d1d8624d4644c.js +1 -0
  20. package/dist/web/_next/static/chunks/500-34d01f8d8d73eb2c.js +1 -0
  21. package/dist/web/_next/static/chunks/548.c6dfd1cb270f3c93.js +1 -0
  22. package/dist/web/_next/static/chunks/584.fc9e061dd4069406.js +1 -0
  23. package/dist/web/_next/static/chunks/67.1a3ca07919abce27.js +1 -0
  24. package/dist/web/_next/static/chunks/714.5b2e291a430adc9c.js +1 -0
  25. package/dist/web/_next/static/chunks/747.157732b5b3f3c435.js +1 -0
  26. package/dist/web/_next/static/chunks/77.d478a6f2eafe31e3.js +1 -0
  27. package/dist/web/_next/static/chunks/921-b2219533c5a6e38f.js +1 -0
  28. package/dist/web/_next/static/chunks/app/defaults/page-b7e4e94a55e65806.js +1 -0
  29. package/dist/web/_next/static/chunks/app/layout-2b3718748721c1ac.js +1 -0
  30. package/dist/web/_next/static/chunks/app/page-59b9867b52914a6c.js +1 -0
  31. package/dist/web/_next/static/chunks/{webpack-77147e31d2125631.js → webpack-0c3cad1f3181d857.js} +1 -1
  32. package/dist/web/_next/static/css/06f314fa5fccd68d.css +1 -0
  33. package/dist/web/defaults.html +3 -2
  34. package/dist/web/defaults.txt +9 -9
  35. package/dist/web/index.html +3 -2
  36. package/dist/web/index.txt +9 -9
  37. package/dist/web/system.html +3 -2
  38. package/dist/web/system.txt +9 -9
  39. package/package.json +6 -2
  40. package/prompts/level1.md +32 -12
  41. package/prompts/review1.md +287 -286
  42. package/dist/web/_next/static/chunks/163.dbd7d36584d0bb37.js +0 -1
  43. package/dist/web/_next/static/chunks/220.35531b39410e1a9f.js +0 -1
  44. package/dist/web/_next/static/chunks/548.71ac96c94136659b.js +0 -1
  45. package/dist/web/_next/static/chunks/584.6df695c5b86a75aa.js +0 -1
  46. package/dist/web/_next/static/chunks/67.9ed79e2fbfb56f26.js +0 -1
  47. package/dist/web/_next/static/chunks/714.1e2338736a70b9c7.js +0 -1
  48. package/dist/web/_next/static/chunks/747.d2c1249d736dc03b.js +0 -1
  49. package/dist/web/_next/static/chunks/77.a200abef0f5b4a7f.js +0 -1
  50. package/dist/web/_next/static/chunks/808-bc7d7eac6d823291.js +0 -1
  51. package/dist/web/_next/static/chunks/921-dc5538cd779c6432.js +0 -1
  52. package/dist/web/_next/static/chunks/app/defaults/page-edd7534ca9ecf366.js +0 -1
  53. package/dist/web/_next/static/chunks/app/layout-8f99a164d76897a0.js +0 -1
  54. package/dist/web/_next/static/chunks/app/page-4bed816eda370d0c.js +0 -1
  55. package/dist/web/_next/static/css/3bea264adc472bc8.css +0 -1
  56. /package/dist/web/_next/static/{_1zhoDsMOPAH2xW702E5A → FGzV3mVZpXRCVjiw1diNu}/_buildManifest.js +0 -0
  57. /package/dist/web/_next/static/{_1zhoDsMOPAH2xW702E5A → FGzV3mVZpXRCVjiw1diNu}/_ssgManifest.js +0 -0
@@ -12,7 +12,7 @@
12
12
  */
13
13
  import { createHash } from 'node:crypto';
14
14
  import { readFile, mkdir, writeFile, appendFile } from 'node:fs/promises';
15
- import { join, resolve } from 'node:path';
15
+ import { basename, join, resolve } from 'node:path';
16
16
  import { buttonShows, normModel } from '../transport/modelMatch.js';
17
17
  import { createTransport, isReplyTimeout, WindowClosed } from '../transport/chatTransport.js';
18
18
  import { buildChatName, chatCode, loadPointer, savePointer } from '../transport/chatSession.js';
@@ -35,11 +35,12 @@ import { describeStep, checkCommandRefusal, commandRefusal } from '../exec/polic
35
35
  import { networkFetchReason } from '../exec/network.js';
36
36
  import { collectPolicyManifest, describePolicyManifest } from '../exec/policyManifest.js';
37
37
  import { assessIsolation, readIsolationSignals } from '../exec/isolation.js';
38
- import { confinementRefusal, sessionRoots } from '../exec/confinement.js';
38
+ import { confinementRefusal, isWithin, sessionRoots } from '../exec/confinement.js';
39
39
  import { writeReport } from '../exec/reportFile.js';
40
- import { Pacer } from '../util/pacing.js';
40
+ import { gapFrom, Pacer } from '../util/pacing.js';
41
41
  import { RunLog } from '../log/runLog.js';
42
42
  import { composeOpening, operatorNotesSection, readOnlyNote } from '../session/compose.js';
43
+ import { describeChange, ReferenceGuard, referenceMessage, referenceNote } from '../vcs/referenceGuard.js';
43
44
  import { changedSince, takeAfter, takeCheckpoint } from '../session/checkpoint.js';
44
45
  import { MIN_TRIED_APPROACHES } from '../protocol/replySchema.js';
45
46
  import { enforceScope, scopeMessage, scopeNote } from '../vcs/scope.js';
@@ -872,6 +873,10 @@ export async function runTask(transport, session, task, deps) {
872
873
  enabled: cfg.pacing.enabled,
873
874
  settleMs: cfg.pacing.settleMs,
874
875
  maxMessagesPerHour: cfg.pacing.maxMessagesPerHour,
876
+ // The operator's pause between messages (2026-10-21), said in the log when a message waits for it.
877
+ gapMs: gapFrom(cfg.pacing),
878
+ signal,
879
+ onGap: (ms) => sink.event('pacing-gap', { ms }, `the next message waits ${Math.ceil(ms / 1000)} s: Settings ask for a pause between messages`),
875
880
  });
876
881
  const artifactsDir = log.path('artifacts');
877
882
  const reportsDir = log.path('reports');
@@ -934,6 +939,8 @@ export async function runTask(transport, session, task, deps) {
934
939
  let disputes = [];
935
940
  /** What the runner tells the model in its next message about the reply just processed. */
936
941
  let runnerNotes = [];
942
+ /** The projects for reference only, watched for the length of the task (see `vcs/referenceGuard.ts`). */
943
+ let reference = null;
937
944
  /** Steps the chat sent that were not run, for the handoff at the end. */
938
945
  const notRun = [];
939
946
  /**
@@ -1053,6 +1060,8 @@ export async function runTask(transport, session, task, deps) {
1053
1060
  await record(`ENDING: ${status.toUpperCase()}`, [summary ?? '', reason ? `Reason: ${reason}` : ''].filter(Boolean).join('\n\n') || '(no details)');
1054
1061
  // The net under the plan's own checks: whatever the task left running is stopped and named.
1055
1062
  await reap(processesBefore, 'the task');
1063
+ await reference?.close().catch(() => undefined);
1064
+ reference = null;
1056
1065
  /*
1057
1066
  * A chat message: the folder photographed again after it, on top of its checkpoint, so what it changed is
1058
1067
  * one commit's worth of files, shown under the message and in the changes view. Nothing is committed on the
@@ -1403,8 +1412,26 @@ export async function runTask(transport, session, task, deps) {
1403
1412
  const confinement = {
1404
1413
  roots: sessionRoots(work.cwd, [cfg.project.rootDir, ...cfg.project.others.map((o) => o.rootDir)]),
1405
1414
  cwd: work.cwd,
1415
+ // A script committed after this is the work's, not the project's (see `ownScriptRefusal`).
1416
+ workStartedAt: session.createdAt,
1406
1417
  };
1407
1418
  sink.event('confinement', { roots: confinement.roots }, `commands are confined to ${confinement.roots.join(', ')}`);
1419
+ /*
1420
+ * The projects for reference only (operator, 2026-10-21) that this task can reach: photographed now, and after every
1421
+ * step compared with that, whatever changed put back (see `vcs/referenceGuard.ts`).
1422
+ */
1423
+ const forReference = [
1424
+ ...(cfg.project.readOnly && cfg.project.rootDir ? [{ name: cfg.project.name || basename(cfg.project.rootDir), dir: cfg.project.rootDir }] : []),
1425
+ ...cfg.project.others.filter((o) => o.readOnly).map((o) => ({ name: o.name, dir: o.rootDir })),
1426
+ ].filter((p) => isWithin(p.dir, confinement.roots));
1427
+ if (forReference.length > 0) {
1428
+ reference = await ReferenceGuard.start(forReference, runId);
1429
+ for (const p of reference.projects)
1430
+ sink.event('reference', { name: p.name, dir: p.dir }, `for reference only, nothing may change there: ${p.name} (${p.dir})`);
1431
+ for (const p of reference.unwatched) {
1432
+ sink.event('reference-unwatched', { name: p.name, dir: p.dir, problem: p.problem }, `for reference only, but it cannot be watched (${p.problem}): ${p.name} (${p.dir}); the chat is told to leave it alone`, 'warn');
1433
+ }
1434
+ }
1408
1435
  const isolation = assessIsolation(cfg.execution.isolation, readIsolationSignals());
1409
1436
  for (const concern of isolation.warnings) {
1410
1437
  sink.event('isolation', { claim: isolation.claim, elevated: isolation.signals.elevated }, concern, 'warn');
@@ -1606,6 +1633,7 @@ export async function runTask(transport, session, task, deps) {
1606
1633
  // Said of the session's conversation, so with none on record nothing has had it: this run
1607
1634
  // entered a fresh one (see `enterSessionConversation`), whatever an older record says.
1608
1635
  contractAlreadySent: session.contractSent && !!session.chat,
1636
+ skill: task.skill,
1609
1637
  continuing,
1610
1638
  buildsOn,
1611
1639
  // The operator's new prompt goes out whether or not the attempt it follows reached a conversation.
@@ -1613,6 +1641,7 @@ export async function runTask(transport, session, task, deps) {
1613
1641
  workDirNote: workingDirNote(work),
1614
1642
  vcsNote: session.kind === 'chat' ? CHAT_NOTE : prepared.note,
1615
1643
  // What is said about a commit is true only where one happens (live run 2026-10-03: promised with commits off).
1644
+ referenceNote: forReference.length > 0 ? referenceNote(forReference, work.cwd) : undefined,
1616
1645
  readOnlyNote: task.readOnly ? readOnlyNote(!!(session.vcs?.enabled && session.vcs.commitOnFinish !== false && trackedRepoOf(session)), artifactPatterns(session.vcs)) : undefined,
1617
1646
  scopeNote: [
1618
1647
  scopeNote(scope, scopeEnforced, {
@@ -2103,6 +2132,16 @@ export async function runTask(transport, session, task, deps) {
2103
2132
  round: reviewRounds,
2104
2133
  cwd: work.cwd,
2105
2134
  roots: confinement.roots,
2135
+ workStartedAt: confinement.workStartedAt,
2136
+ afterStep: reference?.active
2137
+ ? async () => {
2138
+ const touched = await reference.check();
2139
+ if (touched.length === 0)
2140
+ return null;
2141
+ sink.event('reference-put-back', { review: true, changes: touched }, `a review step changed a project for reference only: ${touched.map((c) => `${c.name}: ${describeChange(c)}`).join('; ')}`, 'warn');
2142
+ return referenceMessage(touched);
2143
+ }
2144
+ : undefined,
2106
2145
  tracker,
2107
2146
  changedFiles,
2108
2147
  deliverable,
@@ -2822,6 +2861,19 @@ export async function runTask(transport, session, task, deps) {
2822
2861
  sink.event('step-environment', { id: step.id, requested: result.requestedShell ?? null, available: result.shellProblem.available }, result.shellProblem.message, 'error');
2823
2862
  break;
2824
2863
  }
2864
+ /*
2865
+ * A project for reference only changed: put back as it was, the chat told with the step's own output, and
2866
+ * the rest of the round not run — a step after it could build on what was just undone.
2867
+ */
2868
+ const touched = reference?.active ? await reference.check() : [];
2869
+ if (touched.length > 0) {
2870
+ const told = referenceMessage(touched);
2871
+ const all = touched.every((c) => c.putBack);
2872
+ sink.event('reference-put-back', { id: step.id, changes: touched }, `step ${step.id} changed a project for reference only, ${all ? 'put back' : 'NOT all put back'}: ${touched.map((c) => `${c.name}: ${describeChange(c)}`).join('; ')}`, all ? 'warn' : 'error');
2873
+ result.stderr = `${result.stderr}${result.stderr.endsWith('\n') || !result.stderr ? '' : '\n'}[runner] ${told}\n`;
2874
+ runnerNotes.push(told);
2875
+ break;
2876
+ }
2825
2877
  if (cfg.execution.stopOnFailure && result.exitCode !== 0) {
2826
2878
  sink.event('stop-on-failure', { id: step.id }, 'stopping the iteration: stopOnFailure is set', 'warn');
2827
2879
  break;
@@ -85,6 +85,11 @@ function projectsPart(lang, projects) {
85
85
  out.push('');
86
86
  out.push(`### ${name}${p.chat ? (bg ? ' (папката на чата)' : ' (the chat\'s folder)') : ''}`);
87
87
  out.push(`- ${bg ? 'Папка' : 'Folder'}: \`${p.rootDir}\``);
88
+ if (p.readOnly) {
89
+ out.push(bg
90
+ ? '- **Само за справка**: ботът го чете, но не променя нищо в него; всяка промяна там се връща. Не предлагай задачи, които го променят.'
91
+ : '- **For reference only**: the bot reads it and changes nothing in it; any change there is put back. Do not suggest tasks that change it.');
92
+ }
88
93
  if (p.branch) {
89
94
  out.push(p.branch === 'HEAD'
90
95
  ? `- ${bg ? 'Клон: няма (откачен HEAD)' : 'Branch: none (a detached HEAD)'}`
@@ -96,6 +101,22 @@ function projectsPart(lang, projects) {
96
101
  }
97
102
  return out.join('\n');
98
103
  }
104
+ /** The skills of Settings, one line each: what a message starts with to call it, its project, what it is for. */
105
+ function skillsPart(lang, skills) {
106
+ const bg = WRITTEN(lang) === 'bg';
107
+ if (skills.length === 0) {
108
+ return bg
109
+ ? 'Още няма skill-ове. Skill е инструкцията на човека за вид задача, която се повтаря — нов тест, ново entity, миграция; пише се в Настройки, в „Skill-ове“.'
110
+ : 'There are no skills yet. A skill is the person\'s instructions for a kind of task that comes back — a new test, a new entity, a migration; it is written in Settings, under "Skills".';
111
+ }
112
+ return [
113
+ bg
114
+ ? 'Тези са в Настройки. Съобщение, което започва с `/името`, отива с инструкциите на skill-а; ползвай ги, когато задачата е от този вид, и пиши в съобщението само това, което е особено за нея.'
115
+ : 'These are in Settings. A message that starts with `/its-name` goes with the skill\'s instructions; use one when the task is of its kind, and write in the message only what is particular to it.',
116
+ '',
117
+ ...skills.map((k) => `- \`/${k.name}\`${k.project ? ` (${k.project})` : bg ? ' (всички проекти)' : ' (every project)'}${k.description ? ` — ${k.description}` : ''}`),
118
+ ].join('\n');
119
+ }
99
120
  export function kerriganPersona(lang, facts) {
100
121
  return WRITTEN(lang) === 'bg' ? bgText(facts) : enText(lang, facts);
101
122
  }
@@ -112,7 +133,7 @@ You are **Kerrigan**. You help the person talking to you get their work done wit
112
133
 
113
134
  ## What copilot-operator is
114
135
 
115
- - A local program that opens in the browser, at the address it prints when it starts. Its home screen is a **chat beside the project's folder**, laid out like an IDE: the folder's files on the left, each with an icon of its kind (a file opens in an editor, coloured by its language, where it can be changed and saved with Ctrl+S), the folder's git (its changes and its commits), the chat on the right, and a panel below with the ${Q('wb.terminal')} (the commands of the latest message and what they printed), ${Q('wb.problems')} and ${Q('wb.output')}.
136
+ - A local program that opens in the browser, at the address it prints when it starts. Its home screen is a **chat beside the project's folder**, laid out like an IDE: the folder's files on the left, each with an icon of its kind (a file opens in an editor, coloured by its language, where it can be changed and saved with Ctrl+S), the folder's git (its changes and its commits), the chat on the right, and a panel below with the ${Q('wb.terminal')} (the commands of the latest message and what they printed), ${Q('wb.problems')} and ${Q('wb.output')}. That is where they start: the three — the files, the editor with its panel, the chat — can be moved as in VS Code, by dragging the grip ⠿ in a panel's head onto another (the two swap places) or with ${Q('wb.move')}; Ctrl+K puts them back. ${Q('nav.appearance')}, in the bar on top, sets the theme, the text size and the reading aids.
116
137
  - The person writes a task in the chat, about the **project folder** open there. The program sends it to **Microsoft 365 Copilot** (a work account) in an Edge window it opens and keeps open between messages; when the work on a message has ended, a card in that window says so, with an OK. Copilot cannot touch the machine itself: it answers with **PowerShell commands**, in a fixed JSON form.
117
138
  - copilot-operator **runs those commands on the machine, in the project folder**, and sends back what they printed. Round after round, until Copilot says the task is **done** (with a summary of what it did), or **blocked** (with what it tried and what it needs), or a limit is reached.
118
139
  - Copilot learns the project only through those commands: it lists files, reads them, runs the build and the tests. It is not sent the files themselves, and it knows nothing about the project that the task does not say and the commands cannot find.
@@ -124,7 +145,7 @@ You are **Kerrigan**. You help the person talking to you get their work done wit
124
145
  - Each message is one task. The next message goes into the **same Copilot conversation**, so it can build on what was done ("now add tests for that"). ${Q('chat.newChat')} starts a conversation with nothing of the earlier one. Before each message the folder is photographed, and with ${Q('chat.rewind')} the folder is put back exactly as it was then.
125
146
  - ${Q('chat.lead')} (under the chat's box, for a new conversation; not ticked at first): not ticked, the chat works as it always has — one conversation that does the work; ticked, the message goes to a **lead** that directs a **worker** — see "Two chats" below. The person chooses for each conversation; to change it, they start a ${Q('chat.newChat')}.
126
147
  - Limits from the settings: at most ${n(f.maxIterations)} messages to Copilot and ${n(f.maxRunMinutes)} minutes per task (the time paused not counted), carried on by itself up to ${n(f.autoContinue)} time(s) when a limit is reached. One message in the chat can be at most ${n(MAX_INSTRUCTION_CHARS)} characters.
127
- - ${Q('nav.defaults')} (the link at the top): the projects — each with its folder, its branch and its level 2, which is where the notes below come from —, ${Q('login.button')}, the model of new conversations and of the review, and how a task runs. Every field there has an ⓘ that says what it is for. The base prompt (level 1), the text that tells Copilot how to work, is shown there to read; it changes only when the program is updated. ${Q('nav.system')} is the report on the machine.
148
+ - ${Q('nav.defaults')} (the link at the top): the projects — each with its folder, its branch and its level 2, which is where the notes below come from —, ${Q('login.button')}, the model of new conversations and of the review, and how a task runs. Every field there has an ⓘ that says what it is for. A project can be marked ${Q('proj.readOnly')}: the bot then reads it and runs what only reads it, but changes nothing in it — whatever a command changes there is put back and the chat is told; on the chat's own folder every message can then only read and report. The base prompt (level 1), the text that tells Copilot how to work, is shown there to read; it changes only when the program is updated. ${Q('nav.system')} is the report on the machine.
128
149
 
129
150
  ## Two chats: a lead and a worker
130
151
 
@@ -142,6 +163,10 @@ It is a choice, not the new way: without it the chat works as it always has, one
142
163
 
143
164
  ${projectsPart(lang, f.projects ?? [])}
144
165
 
166
+ ## The skills
167
+
168
+ ${skillsPart(lang, f.skills ?? [])}
169
+
145
170
  ## How you help
146
171
 
147
172
  1. Ask what they want to achieve, in their words. If something essential is missing — which project, folder or files, what "done" means, how to check it — ask for it before you write the task. Do not invent paths, names or commands you were not told.
@@ -158,6 +183,7 @@ ${projectsPart(lang, f.projects ?? [])}
158
183
  6. Suggest ${Q('chat.planMode')} for a change that touches several files or that the person wants to see planned first, and ${Q('chat.modeAsk')} when they want to watch every step. Leave ${Q('chat.review')} on for work that matters; when they choose the models by hand, suggest a different, stronger model for the review than for the work. For a complex task that needs a plan and judgement along the way — a test suite to go through, a defect to investigate and report — suggest ${Q('chat.lead')}, and write the assignment in the shape under "Two chats": with two chats, suggest the strongest reasoning model for the lead and a model good at code for the worker.
159
184
  7. When the person does not understand something in the program — a button, a card, why a task stopped — explain it from what is written here, name the control by its label, and lead them one step at a time until the task is done. If they are stuck, ask what they see on the screen.
160
185
  8. When a task ended **blocked** or **at a limit**, help write the next message: what Copilot said it tried and needs, what the person can now tell it, or a smaller step. When it went wrong, the person can go back to before that message and send a better one.
186
+ 9. When the same kind of task keeps coming back — a new automated test, a new entity, a database migration — suggest a skill for it in Settings, under "Skills", and help write it: a short name with hyphens (\`new-test\`), one line on what it is for, its project or every project, and instructions that say where the files go, the conventions, the steps, how to check the result and what to leave alone. A task of that kind then starts with \`/its-name\` (or the skill is chosen in ${Q('chat.skill')} under the chat's box), and the message only needs what is particular to it.
161
187
 
162
188
  ## The chat's screen, and what everything on it is called
163
189
  ${screenGuide(lang, '/')}
@@ -176,7 +202,7 @@ function bgText(f) {
176
202
 
177
203
  ## Какво е copilot-operator
178
204
 
179
- - Локална програма, която се отваря в браузъра, на адреса, който изписва при пускане. Началният ѝ екран е **чат до папката на проекта**, подреден като IDE: файловете на папката вляво, всеки с икона според вида си (файл се отваря в редактор, оцветен според езика си, където може да се променя и запазва с Ctrl+S), git на папката (промените и комитите), чатът вдясно и панел отдолу с ${Q('wb.terminal')} (командите на последното съобщение и какво са изписали), ${Q('wb.problems')} и ${Q('wb.output')}.
205
+ - Локална програма, която се отваря в браузъра, на адреса, който изписва при пускане. Началният ѝ екран е **чат до папката на проекта**, подреден като IDE: файловете на папката вляво, всеки с икона според вида си (файл се отваря в редактор, оцветен според езика си, където може да се променя и запазва с Ctrl+S), git на папката (промените и комитите), чатът вдясно и панел отдолу с ${Q('wb.terminal')} (командите на последното съобщение и какво са изписали), ${Q('wb.problems')} и ${Q('wb.output')}. Така започват: трите — файловете, редакторът с панела си, чатът — могат да се местят както във VS Code, като дръжката ⠿ в заглавието на панел се пусне върху друг (двата си разменят местата) или с ${Q('wb.move')}; Ctrl+K ги връща. ${Q('nav.appearance')} в лентата горе задава темата, размера на текста и помощните опции.
180
206
  - Човекът пише задание в чата, за **папката на проекта**, отворена там. Програмата го изпраща на **Microsoft 365 Copilot** (служебен акаунт) в прозорец на Edge, който отваря и държи отворен между съобщенията; когато работата по съобщение свърши, карта в този прозорец го казва, с бутон „ОК“. Copilot не може сам да пипа машината: отговаря с **команди на PowerShell**, в определен вид JSON.
181
207
  - copilot-operator **изпълнява тези команди на машината, в папката на проекта**, и връща какво са изписали. Кръг след кръг, докато Copilot каже, че заданието е **готово** (с обобщение на направеното), или **блокирано** (с какво е опитал и какво му трябва), или се стигне ограничение.
182
208
  - Copilot опознава проекта само чрез тези команди: изброява файлове, чете ги, пуска компилацията и тестовете. Самите файлове не му се изпращат и той не знае за проекта нищо, което заданието не казва и командите не могат да намерят.
@@ -188,7 +214,7 @@ function bgText(f) {
188
214
  - Всяко съобщение е едно задание. Следващото съобщение отива в **същия разговор в Copilot**, така че може да надгражда („сега добави тестове за това“). ${Q('chat.newChat')} започва разговор без нищо от предишния. Преди всяко съобщение папката се „снима“ и с ${Q('chat.rewind')} папката се връща точно каквато е била тогава.
189
215
  - ${Q('chat.lead')} (под полето на чата, за нов разговор; в началото не е отметнато): неотметнато, чатът работи както винаги — един разговор, който върши работата; отметнато, съобщението отива при **ръководител**, който ръководи **изпълнител** — виж „Два чата“ по-долу. Човекът избира за всеки разговор; за да го смени, започва ${Q('chat.newChat')}.
190
216
  - Ограничения от настройките: най-много ${n(f.maxIterations)} съобщения към Copilot и ${n(f.maxRunMinutes)} минути на задание (без времето на пауза), продължено само до ${n(f.autoContinue)} път(и), когато се стигне ограничение. Едно съобщение в чата може да е най-много ${n(MAX_INSTRUCTION_CHARS)} знака.
191
- - ${Q('nav.defaults')} (връзката горе): проектите — всеки с папката, клона и шаблона си ниво 2, откъдето са бележките по-долу, —, ${Q('login.button')}, моделът на новите разговори и на рецензията и как върви едно задание. Всяко поле там има ⓘ, което казва за какво е. Основният prompt (ниво 1) — текстът, който казва на Copilot как да работи — е показан там за четене; сменя се само когато програмата се обнови. ${Q('nav.system')} е отчетът за машината.
217
+ - ${Q('nav.defaults')} (връзката горе): проектите — всеки с папката, клона и шаблона си ниво 2, откъдето са бележките по-долу, —, ${Q('login.button')}, моделът на новите разговори и на рецензията и как върви едно задание. Всяко поле там има ⓘ, което казва за какво е. Проект може да се отбележи ${Q('proj.readOnly')}: тогава ботът го чете и пуска това, което само го чете, но не променя нищо в него — каквото команда промени там, се връща, и чатът научава; ако е папката на чата, всяко съобщение може само да чете и да докладва. Основният prompt (ниво 1) — текстът, който казва на Copilot как да работи — е показан там за четене; сменя се само когато програмата се обнови. ${Q('nav.system')} е отчетът за машината.
192
218
 
193
219
  ## Два чата: ръководител и изпълнител
194
220
 
@@ -206,6 +232,10 @@ function bgText(f) {
206
232
 
207
233
  ${projectsPart('bg', f.projects ?? [])}
208
234
 
235
+ ## Skill-овете
236
+
237
+ ${skillsPart('bg', f.skills ?? [])}
238
+
209
239
  ## Как помагаш
210
240
 
211
241
  1. Питай какво иска да постигне, с неговите думи. Ако липсва нещо съществено — кой проект, коя папка или кои файлове, какво значи „готово“, как да се провери, — попитай, преди да напишеш заданието. Не измисляй пътища, имена или команди, които не са ти казани.
@@ -222,6 +252,7 @@ ${projectsPart('bg', f.projects ?? [])}
222
252
  6. Предлагай ${Q('chat.planMode')} за промяна, която пипа няколко файла или която човекът иска първо да види планирана, и ${Q('chat.modeAsk')}, когато иска да следи всяка стъпка. Оставяй ${Q('chat.review')} включена за важна работа; когато моделите се избират ръчно, предлагай за рецензията различен и по-силен модел от този за работата. За сложна задача, която иска план и преценка по пътя — тестове за преглед, дефект за изследване и докладване, — предлагай ${Q('chat.lead')} и пиши заданието във вида от „Два чата“; с два чата предлагай най-силния модел за разсъждение за ръководителя и модел, добър с код, за изпълнителя.
223
253
  7. Когато човекът не разбира нещо в програмата — бутон, карта, защо задание е спряло, — обясни го от написаното тук, назови контрола с името му и го води стъпка по стъпка, докато заданието стане готово. Ако е заседнал, питай какво вижда на екрана.
224
254
  8. Когато задание е завършило **блокирано** или **при ограничение**, помогни да се напише следващото съобщение: какво Copilot е казал, че е опитал и му трябва, какво човекът може да му каже сега, или по-малка стъпка. Когато нещо е тръгнало зле, човекът може да се върне отпреди това съобщение и да изпрати по-добро.
255
+ 9. Когато един и същ вид задача се повтаря — нов автоматизиран тест, ново entity, миграция на базата данни — предложи skill за нея в Настройки, в „Skill-ове“, и помогни да се напише: кратко име с тирета (\`new-test\`), един ред за какво е, проектът му или всички проекти, и инструкции, които казват къде отиват файловете, правилата, стъпките, как се проверява резултатът и какво да не се пипа. Задача от този вид после започва с \`/името\` (или skill-ът се избира в ${Q('chat.skill')} под полето на чата), и в съобщението трябва само особеното за нея.
225
256
 
226
257
  ## Екранът на чата и как се казва всичко по него
227
258
  ${screenGuide('bg', '/')}
@@ -325,8 +325,8 @@ export const SYSTEM_GUIDE = [
325
325
  route: '/',
326
326
  nameEn: 'Chat',
327
327
  nameBg: 'Чат',
328
- purposeEn: 'The home screen, laid out as an IDE: the open folder\'s files or its git on the left, the open files and diffs in the middle with Kerrigan when nothing is open, the terminal, the problems and the output of the chat\'s conversation below, and the chat on the right, which works in the open folder. The status bar says what runs; Ctrl+K finds anything.',
329
- purposeBg: 'Началният екран, подреден като IDE: файловете или git на отворената папка отляво, отворените файлове и разлики в средата, с Кериган, когато нищо не е отворено, терминалът, проблемите и изходът на разговора в чата отдолу и чатът отдясно, който работи в отворената папка. Лентата най-долу казва какво върви; Ctrl+K намира всичко.',
328
+ purposeEn: 'The home screen, laid out as an IDE: the open folder\'s files or its git on the left, the open files and diffs in the middle with Kerrigan when nothing is open, the terminal, the problems and the output of the chat\'s conversation below, and the chat on the right, which works in the open folder — where they start: the three panels can be moved (the grip ⠿ in the head of each). The status bar says what runs; Ctrl+K finds anything.',
329
+ purposeBg: 'Началният екран, подреден като IDE: файловете или git на отворената папка отляво, отворените файлове и разлики в средата, с Кериган, когато нищо не е отворено, терминалът, проблемите и изходът на разговора в чата отдолу и чатът отдясно, който работи в отворената папка — така започват: трите панела могат да се местят (дръжката ⠿ в заглавието на всеки). Лентата най-долу казва какво върви; Ctrl+K намира всичко.',
330
330
  sections: [
331
331
  {
332
332
  headingKey: null,
@@ -663,8 +663,8 @@ export const SYSTEM_GUIDE = [
663
663
  kind: 'button',
664
664
  en: 'Copy',
665
665
  bg: 'Копирай',
666
- doesEn: 'Under your message, under what the chat said, beside how it ended and beside a command: copies that text (a command with what it printed); it says "Copied" for a moment.',
667
- doesBg: 'Под твое съобщение, под казаното от чата, до края и до команда: копира този текст (команда — заедно с изписаното от нея); за момент пише „Копирано“.',
666
+ doesEn: 'Under your message, under what the chat said, beside how it ended, beside a command and at the top and foot of a plan: copies that text (a command with what it printed, a plan whole with its headings); it says "Copied" for a moment.',
667
+ doesBg: 'Под твое съобщение, под казаното от чата, до края, до команда и в началото и края на план: копира този текст (команда — заедно с изписаното от нея, план — целия, със заглавията му); за момент пише „Копирано“.',
668
668
  },
669
669
  {
670
670
  key: 'chat.foldOpen',
@@ -762,6 +762,14 @@ export const SYSTEM_GUIDE = [
762
762
  doesEn: 'While it works: stops it; the message in flight ends stopped and can be carried on. The Copilot window stays open for the next message.',
763
763
  doesBg: 'Докато работи: спира го; текущото съобщение завършва спряно и може да продължи. Прозорецът на Copilot остава отворен за следващото съобщение.',
764
764
  },
765
+ {
766
+ key: 'chat.skill',
767
+ kind: 'select',
768
+ en: 'Skill',
769
+ bg: 'Skill',
770
+ doesEn: 'Under the chat\'s box when Settings have skills for this folder: chooses one for the next message, and its instructions for that kind of task go with it. Starting the message with /its-name does the same.',
771
+ doesBg: 'Под полето на чата, когато в Настройки има skill-ове за тази папка: избира един за следващото съобщение и инструкциите му за този вид задача отиват с него. Същото става, ако съобщението започне с /името му.',
772
+ },
765
773
  {
766
774
  key: 'chat.planMode',
767
775
  kind: 'checkbox',
@@ -890,6 +898,22 @@ export const SYSTEM_GUIDE = [
890
898
  doesEn: 'Does not run it; the chat is told and goes on.',
891
899
  doesBg: 'Не я изпълнява; чатът научава и продължава.',
892
900
  },
901
+ {
902
+ key: 'nav.appearance',
903
+ kind: 'button',
904
+ en: 'Appearance',
905
+ bg: 'Изглед',
906
+ doesEn: 'In the bar on top, between Settings and System: the theme (System, Light, Dark), the text size with A− and A+, and the reading aids — night light, underlined links, less motion, more contrast, a thick focus outline, the system\'s cursor.',
907
+ doesBg: 'В лентата горе, между Настройки и Система: темата (Системна, Светла, Тъмна), размерът на текста с A− и A+, и помощните опции — нощна светлина, подчертани връзки, по-малко движение, повече контраст, дебел фокусен контур, курсорът на системата.',
908
+ },
909
+ {
910
+ key: 'wb.move',
911
+ kind: 'button',
912
+ en: 'Move {name}',
913
+ bg: 'Премести {name}',
914
+ doesEn: 'The grip ⠿ at the head of the explorer, of the editor and of the chat: drag it onto another panel and the two swap places — the chat where the editor was, for one — or click it and choose to the left, to the middle or to the right. The order is kept in this browser; "Put the panels back where they were" (Ctrl+K) undoes it.',
915
+ doesBg: 'Дръжката ⠿ в заглавието на изследователя, на редактора и на чата: хванете я и я пуснете върху друг панел — двата си разменят местата, например чатът отива там, където е бил редакторът; или щракнете и изберете наляво, в средата или надясно. Подредбата се помни в този браузър; „Върни панелите по местата им“ (Ctrl+K) я връща.',
916
+ },
893
917
  {
894
918
  key: 'wb.toggleChat',
895
919
  kind: 'button',
@@ -1285,6 +1309,14 @@ export const SYSTEM_GUIDE = [
1285
1309
  doesEn: 'On another project: takes it out of the list (the folder stays where it is).',
1286
1310
  doesBg: 'На друг проект: маха го от списъка (папката си остава на мястото).',
1287
1311
  },
1312
+ {
1313
+ key: 'proj.readOnly',
1314
+ kind: 'checkbox',
1315
+ en: 'For reference only (no changes)',
1316
+ bg: 'Само за справка (без промени)',
1317
+ doesEn: 'Ticked, the bot reads the project and runs what only reads it, and changes nothing there: after every command whatever changed in it — files, branches, what is staged — is put back, and the chat is told. On the chat\'s own folder, every message can then only read and report.',
1318
+ doesBg: 'Отметнато, ботът чете проекта и пуска това, което само го чете, без да променя нищо там: след всяка команда всичко променено в него — файлове, клонове, подготвеното за commit — се връща, и чатът научава. Ако е папката на чата, всяко съобщение може само да чете и да докладва.',
1319
+ },
1288
1320
  {
1289
1321
  key: 'proj.level2',
1290
1322
  kind: 'field',
@@ -1334,6 +1366,61 @@ export const SYSTEM_GUIDE = [
1334
1366
  },
1335
1367
  ],
1336
1368
  },
1369
+ {
1370
+ headingKey: 'skills.title',
1371
+ en: 'Skills',
1372
+ bg: 'Skill-ове',
1373
+ controls: [
1374
+ {
1375
+ key: 'skills.name',
1376
+ kind: 'field',
1377
+ en: 'Name',
1378
+ bg: 'Име',
1379
+ doesEn: 'What the skill is called by: lowercase with hyphens (new-test), typed after / at the start of a message.',
1380
+ doesBg: 'Как се извиква skill-ът: с малки букви и тирета (new-test), написано след / в началото на съобщение.',
1381
+ },
1382
+ {
1383
+ key: 'skills.description',
1384
+ kind: 'field',
1385
+ en: 'What it is for',
1386
+ bg: 'За какво е',
1387
+ doesEn: 'One line on which tasks it is for, shown in the chat\'s list.',
1388
+ doesBg: 'Един ред за кои задачи е, показан в списъка на чата.',
1389
+ },
1390
+ {
1391
+ key: 'skills.project',
1392
+ kind: 'select',
1393
+ en: 'Project',
1394
+ bg: 'Проект',
1395
+ doesEn: 'The project the skill is for, or every project.',
1396
+ doesBg: 'Проектът, за който е skill-ът, или всички проекти.',
1397
+ },
1398
+ {
1399
+ key: 'skills.text',
1400
+ kind: 'field',
1401
+ en: 'Instructions',
1402
+ bg: 'Инструкции',
1403
+ doesEn: 'What the chat should know and do for this kind of task — where files go, conventions, steps, how to check it — sent with the message.',
1404
+ doesBg: 'Какво трябва да знае и да прави чатът за този вид задача — къде отиват файловете, правилата, стъпките, как се проверява — изпраща се със съобщението.',
1405
+ },
1406
+ {
1407
+ key: 'skills.remove',
1408
+ kind: 'button',
1409
+ en: 'Remove',
1410
+ bg: 'Махни',
1411
+ doesEn: 'Takes the skill out of the list; messages already sent with it keep it.',
1412
+ doesBg: 'Маха skill-а от списъка; вече изпратените с него съобщения го запазват.',
1413
+ },
1414
+ {
1415
+ key: 'skills.add',
1416
+ kind: 'button',
1417
+ en: 'Add the skill',
1418
+ bg: 'Добави skill-а',
1419
+ doesEn: 'Adds the skill written in the fields above it.',
1420
+ doesBg: 'Добавя skill-а, написан в полетата над него.',
1421
+ },
1422
+ ],
1423
+ },
1337
1424
  {
1338
1425
  headingKey: 'login.title',
1339
1426
  en: 'Sign in to Copilot',
@@ -1504,6 +1591,38 @@ export const SYSTEM_GUIDE = [
1504
1591
  doesEn: 'The most subtasks the lead of a conversation with two chats may give for one message.',
1505
1592
  doesBg: 'Най-много подзадачи, които ръководителят в разговор с два чата може да даде за едно съобщение.',
1506
1593
  },
1594
+ {
1595
+ key: 'exec.gap',
1596
+ kind: 'checkbox',
1597
+ en: 'Pause between messages',
1598
+ bg: 'Пауза между съобщенията',
1599
+ doesEn: 'Ticked, a message to Copilot waits until "At least" seconds have passed since the one before — to the lead or the worker, in any conversation; the log says how long it waits.',
1600
+ doesBg: 'Отметнато, съобщение към Copilot чака, докато от предишното минат „Най-малко“ секунди — към ръководителя или изпълнителя, във всеки разговор; дневникът казва колко чака.',
1601
+ },
1602
+ {
1603
+ key: 'exec.gapSec',
1604
+ kind: 'field',
1605
+ en: 'At least',
1606
+ bg: 'Най-малко',
1607
+ doesEn: 'Shown with the pause: its shortest time, in seconds (60: one a minute at most).',
1608
+ doesBg: 'Показва се с паузата: най-краткото ѝ време, в секунди (60: най-много по едно на минута).',
1609
+ },
1610
+ {
1611
+ key: 'exec.gapRandom',
1612
+ kind: 'checkbox',
1613
+ en: 'Random time',
1614
+ bg: 'Случайно време',
1615
+ doesEn: 'Shown with the pause: each pause drawn anew between "At least" and "At most" (60 to 90 seconds, say).',
1616
+ doesBg: 'Показва се с паузата: всяка пауза се избира наново между „Най-малко“ и „Най-много“ (например 60 до 90 секунди).',
1617
+ },
1618
+ {
1619
+ key: 'exec.gapMax',
1620
+ kind: 'field',
1621
+ en: 'At most',
1622
+ bg: 'Най-много',
1623
+ doesEn: 'Shown with a random time: the longest pause, in seconds.',
1624
+ doesBg: 'Показва се със случайното време: най-дългата пауза, в секунди.',
1625
+ },
1507
1626
  {
1508
1627
  key: 'exec.replyTimeout',
1509
1628
  kind: 'field',
@@ -25,7 +25,7 @@ const TASK_HEADER = '## Task';
25
25
  * and a note that is empty simply leaves nothing behind.
26
26
  */
27
27
  function runnerBlock(input) {
28
- const notes = [input.workDirNote, input.readOnlyNote, input.scopeNote, input.approachesNote, input.vcsNote, input.shellNote, input.planNote, input.operatorNotes].map((n) => (n ?? '').trim()).filter((n) => n.length > 0);
28
+ const notes = [input.workDirNote, input.readOnlyNote, input.referenceNote, input.scopeNote, input.approachesNote, input.vcsNote, input.shellNote, input.planNote, input.operatorNotes].map((n) => (n ?? '').trim()).filter((n) => n.length > 0);
29
29
  return notes.length > 0 ? `${notes.join('\n\n')}\n\n` : '';
30
30
  }
31
31
  /**
@@ -39,7 +39,7 @@ export function readOnlyNote(commits, artifacts = []) {
39
39
  'This task must not change any file: it reads, runs and reports. The runner fails it if it',
40
40
  'changed the working tree, whatever the summary says' +
41
41
  (commits ? ", and commits the change on the task's branch so it is not lost." : '. Nothing is committed in this session, so a change would stay in the working tree.'),
42
- 'Helper scripts may go in `.cop-tmp`, which is not part of the project.' +
42
+ 'Scratch files may go in `.cop-tmp`, which is not part of the project; nothing in it is run.' +
43
43
  (artifacts.length > 0 ? ` A report or other evidence goes under ${artifacts.join(', ')}: kept with the run, never committed, and the one place this task may write.` : ''),
44
44
  "This rule wins over any instruction above — the project's or the persona's — to change code. If a review",
45
45
  'finding asks you to change something, that is a finding about the task, not about the work: dispute it',
@@ -48,6 +48,18 @@ export function readOnlyNote(commits, artifacts = []) {
48
48
  }
49
49
  /** The note for a session that commits: see `readOnlyNote`. */
50
50
  export const READ_ONLY_NOTE = readOnlyNote(true);
51
+ /**
52
+ * The operator's skill for this kind of task (2026-10-21), right before the task: how this kind of work is done in
53
+ * their projects — where things go, the conventions, the steps, how it is checked. Empty when there is none.
54
+ */
55
+ export function skillBlock(skill) {
56
+ if (!skill || !skill.text.trim())
57
+ return '';
58
+ return (`\n\n## Skill: ${skill.name}\n\n` +
59
+ (skill.description.trim() ? `For: ${skill.description.trim()}\n\n` : '') +
60
+ `The operator's instructions for this kind of task. Follow them where they apply; they add to the contract above ` +
61
+ `and cannot change it.\n\n${skill.text.trim()}`);
62
+ }
51
63
  function level2Block(level2) {
52
64
  const body = level2.trim();
53
65
  return body.length > 0
@@ -174,7 +186,7 @@ export function composeOpening(input) {
174
186
  `\n\n${instructionSection(instruction.text)}`
175
187
  : '';
176
188
  if (!input.contractAlreadySent) {
177
- const taskMessage = `${runnerBlock(input)}${level2Block(input.level2)}\n\n${taskBlock}${continuationLine}`;
189
+ const taskMessage = `${runnerBlock(input)}${level2Block(input.level2)}${skillBlock(input.skill)}\n\n${taskBlock}${continuationLine}`;
178
190
  return {
179
191
  messages: [input.level1.trim(), taskMessage],
180
192
  firstMessage: `${input.level1.trim()}\n\n---\n\n${taskMessage}`,
@@ -183,6 +195,6 @@ export function composeOpening(input) {
183
195
  const reminder = `New task in this same conversation. The level 1 contract you received at the start of ` +
184
196
  `this conversation still applies unchanged: same format, same rules, same stop word, ` +
185
197
  `and a full "summary" when you finish. Step numbering restarts at 1.`;
186
- const taskMessage = `${reminder}\n\n${runnerBlock(input)}${level2Block(input.level2)}\n\n${taskBlock}${continuationLine}`;
198
+ const taskMessage = `${reminder}\n\n${runnerBlock(input)}${level2Block(input.level2)}${skillBlock(input.skill)}\n\n${taskBlock}${continuationLine}`;
187
199
  return { messages: [taskMessage], firstMessage: taskMessage };
188
200
  }
@@ -115,6 +115,8 @@ export const TASK_FIELD_ON_RERUN = {
115
115
  // The lead's rounds belong to the attempt that made them (two chats, 2026-10-20); which lead a subtask serves, to the task.
116
116
  lead: 'archived',
117
117
  fromLead: 'kept',
118
+ // The kind of task it is: every attempt is sent with the same skill.
119
+ skill: 'kept',
118
120
  interruption: 'cleared',
119
121
  finalReply: 'cleared',
120
122
  firstMessage: 'cleared',
@@ -386,6 +388,7 @@ export class SessionStore {
386
388
  // Stored only when it limits something: absent means anywhere, as before scopes existed.
387
389
  ...((input.scope ?? []).filter((p) => p.trim()).length > 0 ? { scope: (input.scope ?? []).map((p) => p.trim()).filter(Boolean) } : {}),
388
390
  ...((input.outputs ?? []).filter((p) => p.trim()).length > 0 ? { outputs: (input.outputs ?? []).map((p) => p.trim()).filter(Boolean) } : {}),
391
+ ...(input.skill ? { skill: { name: input.skill.name, description: input.skill.description, text: input.skill.text } } : {}),
389
392
  };
390
393
  await this.updateSession(sessionId, (s) => {
391
394
  s.tasks.push(task);
@@ -17,7 +17,24 @@
17
17
  * against service-side throttling on long runs.
18
18
  * - `backoffFor()` exponential backoff with jitter, so a failing step cannot turn into a
19
19
  * tight retry loop.
20
+ * - the gap (operator, 2026-10-21) a pause the operator sets between two messages to Copilot, fixed or drawn
21
+ * anew each time between two bounds: kept by `throttleSend` across every pacer of the program, so the
22
+ * lead's message after the worker's waits as one after the lead's does.
20
23
  */
24
+ /** The settings' pause between messages, as `gapMs`; undefined when it is off. */
25
+ export function gapFrom(p) {
26
+ if (!p.gapEnabled)
27
+ return undefined;
28
+ const lo = Math.max(1, p.gapSec ?? 60) * 1000;
29
+ const hi = p.gapRandom ? Math.max(lo, Math.max(1, p.gapMaxSec ?? 90) * 1000) : lo;
30
+ return [lo, hi];
31
+ }
32
+ /** When the program last sent a message to Copilot: one window, one account, so one clock for every pacer. */
33
+ let lastSentAt = 0;
34
+ /** For the checks: as if nothing had been sent yet. */
35
+ export function forgetLastSend() {
36
+ lastSentAt = 0;
37
+ }
21
38
  export const DEFAULT_PACING = {
22
39
  enabled: true,
23
40
  settleMs: 1_000,
@@ -57,6 +74,19 @@ export class Pacer {
57
74
  * waited, so the caller can log a visible "throttled for N s".
58
75
  */
59
76
  async throttleSend(signal) {
77
+ const stop = signal ?? this.profile.signal;
78
+ let gapWaited = 0;
79
+ // The operator's pause between two messages: from the last one the program sent, whichever pacer sent it.
80
+ if (this.profile.gapMs && lastSentAt > 0) {
81
+ const [lo, hi] = this.profile.gapMs;
82
+ const gap = lo + Math.round(this.rnd() * Math.max(0, hi - lo));
83
+ const wait = lastSentAt + gap - Date.now();
84
+ if (wait > 0) {
85
+ this.profile.onGap?.(wait);
86
+ await sleep(wait, stop);
87
+ gapWaited = wait;
88
+ }
89
+ }
60
90
  const hour = 3_600_000;
61
91
  const now = Date.now();
62
92
  while (this.sentAt.length && now - this.sentAt[0] > hour)
@@ -65,10 +95,11 @@ export class Pacer {
65
95
  if (this.sentAt.length >= this.profile.maxMessagesPerHour) {
66
96
  waited = this.sentAt[0] + hour - now;
67
97
  if (waited > 0)
68
- await sleep(waited, signal);
98
+ await sleep(waited, stop);
69
99
  }
70
100
  this.sentAt.push(Date.now());
71
- return Math.max(waited, 0);
101
+ lastSentAt = Date.now();
102
+ return Math.max(waited, 0) + gapWaited;
72
103
  }
73
104
  /** Exponential backoff with jitter, for retries after a failure. */
74
105
  backoffFor(attempt, baseMs = 2_000, capMs = 60_000) {
@@ -15,7 +15,7 @@
15
15
  * - Nothing runs through a shell. `execFile` takes an argument list, so a branch name or a
16
16
  * commit message cannot turn into another command.
17
17
  */
18
- import { execFile } from 'node:child_process';
18
+ import { execFile, spawnSync } from 'node:child_process';
19
19
  import { existsSync, statSync } from 'node:fs';
20
20
  import { readFile, stat } from 'node:fs/promises';
21
21
  import { createHash } from 'node:crypto';
@@ -78,6 +78,16 @@ opts = {}) {
78
78
  }
79
79
  });
80
80
  }
81
+ /**
82
+ * One git command, synchronously, for the gate: it decides before a step starts, in a function with no await to give
83
+ * (see `exec/scriptFiles.ts`). Only reading commands go through it. Never throws: a git that is missing, fails or
84
+ * runs out of time is `ok: false`.
85
+ */
86
+ export function gitSync(cwd, args, timeoutMs = 15_000) {
87
+ const r = spawnSync('git', [...SAFE_GIT, ...args], { cwd, timeout: timeoutMs, windowsHide: true, encoding: 'utf8', maxBuffer: 8 * 1024 * 1024 });
88
+ const code = typeof r.status === 'number' ? r.status : 1;
89
+ return { ok: !r.error && code === 0, stdout: (r.stdout ?? '').trim(), stderr: (r.stderr ?? '').trim() || (r.error ? r.error.message : ''), code };
90
+ }
81
91
  /**
82
92
  * When this repository last fetched successfully, or undefined when that cannot be told.
83
93
  *