copilot-operator 0.1.68 → 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 (82) hide show
  1. package/dist/src/api/operator.controller.js +15 -2
  2. package/dist/src/api/operator.service.js +31 -10
  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 +93 -14
  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/session/workspaceGit.js +64 -24
  32. package/dist/src/vcs/gitConfigGuard.js +126 -0
  33. package/dist/src/vcs/newBranch.js +7 -3
  34. package/dist/web/404.html +2 -2
  35. package/dist/web/_next/static/chunks/1024-67625a65f58057ae.js +1 -0
  36. package/dist/web/_next/static/chunks/1077.9fe1c0425bf51375.js +1 -0
  37. package/dist/web/_next/static/chunks/1548.cae3ba2196c8d52f.js +1 -0
  38. package/dist/web/_next/static/chunks/2163.5c9f8477d98b75a4.js +1 -0
  39. package/dist/web/_next/static/chunks/714.a0b32193f71e0e91.js +1 -0
  40. package/dist/web/_next/static/chunks/7220.5d6da026e0b34169.js +1 -0
  41. package/dist/web/_next/static/chunks/7921-0f7954cb5a9f697b.js +1 -0
  42. package/dist/web/_next/static/chunks/8124-a39d85dff0db6600.js +1 -0
  43. package/dist/web/_next/static/chunks/8584.6aa7ce56f7552f17.js +1 -0
  44. package/dist/web/_next/static/chunks/9067.2e4ba2e0e572f21e.js +1 -0
  45. package/dist/web/_next/static/chunks/9747.763da2026719a863.js +1 -0
  46. package/dist/web/_next/static/chunks/9929-2e0b1d006ebd5345.js +1 -0
  47. package/dist/web/_next/static/chunks/app/layout-52a2079ffa83c21f.js +1 -0
  48. package/dist/web/_next/static/chunks/app/page-44eac9d137f26dc5.js +1 -0
  49. package/dist/web/_next/static/chunks/app/queue/{page-fb49cb2d3dc6d14c.js → page-82f724d0842f4870.js} +1 -1
  50. package/dist/web/_next/static/chunks/app/settings/page-2df196e25cb7bfe1.js +1 -0
  51. package/dist/web/_next/static/chunks/{webpack-a3dd4e873378e9ae.js → webpack-950df0f512eef7ec.js} +1 -1
  52. package/dist/web/_next/static/css/cfe8ccb4adf3a311.css +1 -0
  53. package/dist/web/defaults.html +2 -2
  54. package/dist/web/defaults.txt +8 -8
  55. package/dist/web/index.html +3 -3
  56. package/dist/web/index.txt +9 -9
  57. package/dist/web/queue.html +2 -2
  58. package/dist/web/queue.txt +9 -9
  59. package/dist/web/settings.html +2 -2
  60. package/dist/web/settings.txt +9 -9
  61. package/dist/web/system.html +2 -2
  62. package/dist/web/system.txt +9 -9
  63. package/package.json +3 -2
  64. package/prompts/level1.md +25 -8
  65. package/dist/web/_next/static/chunks/1024-e4e596b184e05e91.js +0 -1
  66. package/dist/web/_next/static/chunks/1077.61be1f7b74828a4c.js +0 -1
  67. package/dist/web/_next/static/chunks/1548.a112748131a396ed.js +0 -1
  68. package/dist/web/_next/static/chunks/2163.581b2e067fe95eb3.js +0 -1
  69. package/dist/web/_next/static/chunks/6262-d074473db83ee798.js +0 -1
  70. package/dist/web/_next/static/chunks/714.5cc35e9440591fd9.js +0 -1
  71. package/dist/web/_next/static/chunks/7220.9313ff4ad7480f12.js +0 -1
  72. package/dist/web/_next/static/chunks/7921-19f36659bdea8d09.js +0 -1
  73. package/dist/web/_next/static/chunks/8124-1952612d3a681879.js +0 -1
  74. package/dist/web/_next/static/chunks/8584.5ff9e8c49bf9b259.js +0 -1
  75. package/dist/web/_next/static/chunks/9067.f0db4983b81a2df6.js +0 -1
  76. package/dist/web/_next/static/chunks/9747.0e0c54e5f8fab6c4.js +0 -1
  77. package/dist/web/_next/static/chunks/app/layout-5e0e7601702723bb.js +0 -1
  78. package/dist/web/_next/static/chunks/app/page-18954867735bf8c0.js +0 -1
  79. package/dist/web/_next/static/chunks/app/settings/page-7d120feb5af0ace9.js +0 -1
  80. package/dist/web/_next/static/css/45da8a97dbf20586.css +0 -1
  81. /package/dist/web/_next/static/{52rfiQXdaggycbuMIIw4K → DzoLjnxX5FvdxuPasWlnb}/_buildManifest.js +0 -0
  82. /package/dist/web/_next/static/{52rfiQXdaggycbuMIIw4K → DzoLjnxX5FvdxuPasWlnb}/_ssgManifest.js +0 -0
@@ -164,9 +164,9 @@ You are **Kerrigan**. You help the person talking to you get their work done wit
164
164
  - 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.
165
165
  - 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.
166
166
  - 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.
167
- - The person chooses how commands run in Settings, under ${Q('exec.startMode')} (not in the chat): ${Q('exec.startModeAsk')} (they press ${Q('chat.askRun')}, ${Q('chat.askRunAll')} or ${Q('chat.askSkip')} on a card that says who asks) or ${Q('exec.startModeAuto')}. A list of forbidden commands applies either way; pushing to a remote is refused; nothing needs administrator rights. A command that reaches a platform with the person's own access — Azure, AWS, GitHub, Jira, publishing a package and the like — waits on a card even in a run without asking, unless ${Q('exec.questions')} in Settings is set to agree with what the bot proposes; so do the questions the chat or the lead asks, with their answers to click. Once one answer on a card is pressed, the card's other answers and its text box turn off and the one pressed stays marked until the card goes; only when the answer did not reach the program do they come back on, with the reason on the card.
167
+ - The person chooses how commands run in Settings, under ${Q('exec.startMode')} (not in the chat): ${Q('exec.startModeAsk')} (they press ${Q('chat.askRun')}, ${Q('chat.askRunAll')} or ${Q('chat.askSkip')} on a card that says who asks), ${Q('exec.startModeAutoAsk')} (a script the bot wrote still waits on a card with its text) or ${Q('exec.startModeAuto')}. A list of forbidden commands applies either way; pushing to a remote is refused; nothing needs administrator rights. A command that reaches a platform with the person's own access — Azure, AWS, GitHub, Jira, publishing a package and the like — waits on a card even in a run without asking, unless ${Q('exec.questions')} in Settings is set to agree with what the bot proposes; so do the questions the chat or the lead asks, with their answers to click. Once one answer on a card is pressed, the card's other answers and its text box turn off and the one pressed stays marked until the card goes; only when the answer did not reach the program do they come back on, with the reason on the card.
168
168
  - The programs a command may start are listed in Settings, under "Programs the bot may start": the person adds one by its name (${Q('prog.add')}, ${Q('prog.addButton')}) and takes one off with its ✕; a command that starts a program not on the list is refused, and the chat is told why. A program that reaches a platform with their access is set to ${Q('prog.modeAsk')}, or, for az, to ${Q('prog.modeReadOnly')}: az's commands that only look (list, show, query) then run without a card, the ones that create, change, delete, sign in or out, or show a secret are refused, and one the program cannot read waits on a card. The person signs in themselves, with az login in their own terminal; the program uses that sign-in and never sees the password. The program reads the command line and a script could go round it, so for a guarantee they sign in with an account that has only the Reader role in Azure, and Azure itself refuses every change.
169
- - A script Copilot writes during the work — a diagnostic, a reproduction, a small tool — is never run by the program (the person's rule): Copilot hands it over on a card, "Run this yourself", with the commands in order (and Copy), the folder, what should be seen, and each script with its SHA-256 to read first. The person runs them in their own terminal, pastes what they printed and presses ${Q('ho.send')}, or presses ${Q('ho.notRun')}; the card waits for them even when Settings agree with what the bot proposes. The project's tests, the build and the application run as steps, as before.
169
+ - Which scripts the program runs is the person's choice, in Settings, under "Scripts the bot may run": for each kind (TypeScript, JavaScript, Python, PowerShell, cmd, bash, Ruby/Perl/PHP, package.json scripts) a box ${Q('scr.own')}, on by default, and a box ${Q('scr.written')}, off by default. A script Copilot wrote during the work of a kind left unticked — a diagnostic, a reproduction, a small tool — is not run by the program: Copilot hands it over on a card, "Run this yourself", with its revision, the commands in order (and Copy), the folder, what should be seen and how it should end, what it reaches and changes, and each script in full to read first. The person runs them in their own terminal, pastes what they printed and presses ${Q('ho.send')}; or presses ${Q('ho.revise')}, writes what to correct and sends it — nothing runs, the task goes on, and the next revision comes on a new card; or presses ${Q('ho.notRun')}, which is final for that script. The card waits for them even when Settings agree with what the bot proposes. The project's tests, the build and the application run as steps, as before.
170
170
  - The model: ${Q('chat.model')} under the chat's box. When it is to be chosen by hand (the default), a card asks the person to choose the model in the Copilot window and press ${Q('approval.manualReady')}.
171
171
  - ${Q('chat.planMode')} (a choice under the chat's box): Copilot first looks at the project with read-only commands and proposes a plan — what is there, how it means to do it, the stages, the files, how it will show it works — and nothing is changed until the person approves the plan (${Q('pm.approve')}), asks for another (${Q('pm.revise')}), or stops.
172
172
  - ${Q('chat.review')} (under the chat's box, on unless unticked): when Copilot says the work is done, a conversation of its own reviews it — reads the changes, runs the checks — and sends back what it finds, up to ${n(rounds)} round(s) of fixing. When the model is chosen by hand, the card for the review's model says it is the review's: a different, stronger model than the one that did the work catches more mistakes.
@@ -248,9 +248,9 @@ function bgText(f) {
248
248
  - Човекът пише задание в чата, за **папката на проекта**, отворена там. Програмата го изпраща на **Microsoft 365 Copilot** (служебен акаунт) в прозорец на Edge, който отваря и държи отворен между съобщенията; когато работата по съобщение свърши, карта в този прозорец го казва, с бутон „ОК“. Copilot не може сам да пипа машината: отговаря с **команди на PowerShell**, в определен вид JSON.
249
249
  - copilot-operator **изпълнява тези команди на машината, в папката на проекта**, и връща какво са изписали. Кръг след кръг, докато Copilot каже, че заданието е **готово** (с обобщение на направеното), или **блокирано** (с какво е опитал и какво му трябва), или се стигне ограничение.
250
250
  - Copilot опознава проекта само чрез тези команди: изброява файлове, чете ги, пуска компилацията и тестовете. Самите файлове не му се изпращат и той не знае за проекта нищо, което заданието не казва и командите не могат да намерят.
251
- - Човекът избира как се изпълняват командите в Настройки, при ${Q('exec.startMode')} (не в чата): ${Q('exec.startModeAsk')} (натиска ${Q('chat.askRun')}, ${Q('chat.askRunAll')} или ${Q('chat.askSkip')} на карта, на която пише кой иска) или ${Q('exec.startModeAuto')}. И в двата случая важи списък със забранени команди; изпращането към отдалечено хранилище (push) се отказва; нищо не изисква администраторски права. Команда, която достъпва платформа със собствения достъп на човека — Azure, AWS, GitHub, Jira, публикуване на пакет и подобни, — чака на карта дори при пускане без питане, освен ако ${Q('exec.questions')} в Настройки не е настроено да се съгласява с това, което предлага ботът; същото важи за въпросите на чата или на ръководителя, с отговори за избор. Щом се натисне един отговор на карта, другите отговори и полето за текст на картата се изключват, а натиснатият остава отбелязан, докато картата изчезне; включват се отново само ако отговорът не е стигнал до програмата, с причината на картата.
251
+ - Човекът избира как се изпълняват командите в Настройки, при ${Q('exec.startMode')} (не в чата): ${Q('exec.startModeAsk')} (натиска ${Q('chat.askRun')}, ${Q('chat.askRunAll')} или ${Q('chat.askSkip')} на карта, на която пише кой иска), ${Q('exec.startModeAutoAsk')} (скрипт, написан от бота, пак чака на карта с текста си) или ${Q('exec.startModeAuto')}. Във всички случаи важи списък със забранени команди; изпращането към отдалечено хранилище (push) се отказва; нищо не изисква администраторски права. Команда, която достъпва платформа със собствения достъп на човека — Azure, AWS, GitHub, Jira, публикуване на пакет и подобни, — чака на карта дори при пускане без питане, освен ако ${Q('exec.questions')} в Настройки не е настроено да се съгласява с това, което предлага ботът; същото важи за въпросите на чата или на ръководителя, с отговори за избор. Щом се натисне един отговор на карта, другите отговори и полето за текст на картата се изключват, а натиснатият остава отбелязан, докато картата изчезне; включват се отново само ако отговорът не е стигнал до програмата, с причината на картата.
252
252
  - Програмите, които командата може да пуска, са изброени в Настройки, при „Програми, които ботът може да пуска“: човекът добавя програма по името ѝ (${Q('prog.add')}, ${Q('prog.addButton')}) и маха програма с нейното ✕; команда, която пуска програма извън списъка, се отказва и на чата се казва защо. Програма, която достъпва платформа с неговия достъп, е на ${Q('prog.modeAsk')} или, за az, на ${Q('prog.modeReadOnly')}: тогава командите на az, които само гледат (list, show, query), се изпълняват без карта, тези, които създават, променят, трият, влизат или излизат, или показват тайна, се отказват, а такава, която програмата не може да разчете, чака на карта. Човекът влиза сам, с az login в собствения си терминал; програмата ползва този вход и никога не вижда паролата. Програмата чете командния ред и скрипт би могъл да го заобиколи, затова за гаранция той влиза с акаунт, който има само ролята Reader в Azure, и тогава самият Azure отказва всяка промяна.
253
- - Скрипт, който Copilot пише по време на работата — диагностика, възпроизвеждане, малък инструмент, — програмата никога не го пуска (правилото на човека): Copilot го предава на карта „Пуснете го сами“ с командите по ред (и „Копирай“), папката, какво трябва да се види и всеки скрипт с неговия SHA-256, за да се прочете първо. Човекът ги пуска в собствения си терминал, поставя какво са изписали и натиска ${Q('ho.send')} или натиска ${Q('ho.notRun')}; картата чака него, дори когато Настройки се съгласяват с това, което предлага ботът. Тестовете на проекта, компилацията и приложението се пускат като стъпки, както досега.
253
+ - Кои скриптове пуска програмата, решава човекът в Настройки, при „Скриптове, които ботът може да пуска“: за всеки вид (TypeScript, JavaScript, Python, PowerShell, cmd, bash, Ruby/Perl/PHP, скриптове в package.json) отметка ${Q('scr.own')}, включена по подразбиране, и отметка ${Q('scr.written')}, изключена по подразбиране. Скрипт, който Copilot е написал по време на работата, от вид без отметка — диагностика, възпроизвеждане, малък инструмент, — програмата не го пуска: Copilot го предава на карта „Пуснете го сами“ с ревизията, командите по ред (и „Копирай“), папката, какво трябва да се види и как да завърши, какво достъпва и променя, и всеки скрипт изцяло, за да се прочете първо. Човекът ги пуска в собствения си терминал, поставя какво са изписали и натиска ${Q('ho.send')}; или натиска ${Q('ho.revise')}, пише какво да се коригира и го изпраща — нищо не се пуска, задачата продължава, а следващата ревизия идва на нова карта; или натиска ${Q('ho.notRun')}, което е окончателно за този скрипт. Картата чака него, дори когато Настройки се съгласяват с това, което предлага ботът. Тестовете на проекта, компилацията и приложението се пускат като стъпки, както досега.
254
254
  - Моделът: ${Q('chat.model')} под полето на чата. Когато се избира ръчно (по подразбиране), карта моли човека да избере модела в прозореца на Copilot и да натисне ${Q('approval.manualReady')}.
255
255
  - ${Q('chat.planMode')} (избор под полето на чата): Copilot първо разглежда проекта само с команди, които четат, и предлага план — какво има, как смята да го направи, етапите, файловете, как ще покаже, че работи, — и нищо не се променя, докато човекът не одобри плана (${Q('pm.approve')}), не поиска друг (${Q('pm.revise')}) или не спре.
256
256
  - ${Q('chat.review')} (под полето на чата, включена, освен ако не я изключат): когато Copilot каже, че работата е готова, отделен разговор я преглежда — чете промените, пуска проверките — и връща каквото открие, до ${n(rounds)} кръга поправка. Когато моделът се избира ръчно, картата за модела на рецензията казва, че е за нея: модел, различен и по-силен от този, с който е работено, хваща повече грешки.
@@ -205,6 +205,14 @@ export const SYSTEM_GUIDE = [
205
205
  doesEn: 'At the top of every page: one card per waiting step, with its session (a link) and the exact command. The browser tab shows "(n) waiting for you".',
206
206
  doesBg: 'Горе на всяка страница: по една карта за всяка чакаща стъпка, със сесията ѝ (връзка) и точната команда. Разделът на браузъра показва „(n) чака вас“.',
207
207
  },
208
+ {
209
+ key: 'awaiting.title',
210
+ kind: 'note',
211
+ en: "Waiting for the user's action",
212
+ bg: 'Изчаква се действие от потребителя',
213
+ doesEn: "While anything waits for you — a command to run or skip, a question, a plan, commands handed over to run yourself, a subtask's choices, the model to choose by hand, Git's password window — the rest of the window is darkened, the card is left lit inside a ring, and this label is shown large over the darkened part. It needs no button: it goes when you answer. Nothing is blocked; you can still click and read everything. The chat opens on the conversation that asks and moves to the card, even when it was closed or scrolled up; the keyboard goes to the card unless you are typing somewhere.",
214
+ doesBg: 'Докато нещо чака вас — команда за изпълнение или пропускане, въпрос, план, команди, предадени ви да ги пуснете сами, избор за подзадача, модел за избиране на ръка, прозорецът на Git за парола — останалата част от прозореца се затъмнява, картата остава осветена в рамка и този надпис се показва голям над затъмненото. Не иска бутон: изчезва, когато отговорите. Нищо не е блокирано; пак можете да натискате и четете всичко. Чатът се отваря на разговора, който пита, и отива на картата, дори да е бил затворен или скролнат нагоре; клавиатурата отива на картата, освен ако пишете някъде.',
215
+ },
208
216
  {
209
217
  key: 'approval.run',
210
218
  kind: 'button',
@@ -472,8 +480,8 @@ export const SYSTEM_GUIDE = [
472
480
  kind: 'button',
473
481
  en: 'Git',
474
482
  bg: 'Git',
475
- doesEn: 'Shows the open folder\'s git: the branch, the staged changes and the changes, each file with its letter (M modified, A added, D deleted, R renamed, U untracked, ! in conflict) and its lines, and the branch\'s commits; a file opens its two versions side by side, a commit opens to its files. Read-only.',
476
- doesBg: 'Показва git на отворената папка: клона, подготвените промени и промените — всеки файл с буквата си (M променен, A добавен, D изтрит, R преименуван, U непроследен, ! в конфликт) и редовете си — и комитите на клона; файл отваря двете си версии една до друга, комит се разгъва до файловете си. Само чете.',
483
+ doesEn: 'Shows the open folder\'s git: the branch, the staged changes and the changes, each file with its letter (M modified, A added, D deleted, R renamed, U untracked, ! in conflict) and its lines, and the branch\'s commits; a file opens its two versions side by side, a commit opens to its files. Read-only. Two numbers on the button: above, the files not committed yet; below, every file changed on this branch, committed or not, against the branch "Compared with" names (a number that is 0 is not shown; the button\'s tooltip says both).',
484
+ doesBg: 'Показва git на отворената папка: клона, подготвените промени и промените — всеки файл с буквата си (M променен, A добавен, D изтрит, R преименуван, U непроследен, ! в конфликт) и редовете си — и комитите на клона; файл отваря двете си версии една до друга, комит се разгъва до файловете си. Само чете. Две числа върху бутона: горе — файловете, които още не са комитнати; долу — всички файлове, променени на този клон, комитнати или не, спрямо клона в „Сравнен с“ (число 0 не се показва; подсказката на бутона казва и двете).',
477
485
  },
478
486
  {
479
487
  key: 'wb.refresh',
@@ -1061,18 +1069,42 @@ export const SYSTEM_GUIDE = [
1061
1069
  {
1062
1070
  key: 'ho.send',
1063
1071
  kind: 'button',
1064
- en: 'Send what it printed',
1065
- bg: 'Изпрати какво изписа',
1066
- doesEn: 'Sends what you pasted to the chat, beside what it expected, and the work goes on.',
1067
- doesBg: 'Изпраща поставеното на чата, до това, което е очаквал, и работата продължава.',
1072
+ en: 'I ran it — send the output',
1073
+ bg: 'Пуснах го — изпращам output',
1074
+ doesEn: 'Sends what you pasted to the chat, beside what it expected, as evidence and never as instructions, and the work goes on.',
1075
+ doesBg: 'Изпраща поставеното на чата, до това, което е очаквал, като доказателство, а не като указания, и работата продължава.',
1076
+ },
1077
+ {
1078
+ key: 'ho.revise',
1079
+ kind: 'button',
1080
+ en: 'Send the script back for a correction',
1081
+ bg: 'Върни скрипта за корекция',
1082
+ doesEn: 'Opens the field "What needs correcting?", which may not be empty; sent, nothing is run, the task goes on, and the chat changes only the script and hands it over again as the next revision, read again in full.',
1083
+ doesBg: 'Отваря полето „Какво трябва да се коригира?“, което не може да е празно; при изпращане нищо не се пуска, задачата продължава, а чатът променя само скрипта и го дава отново като следваща ревизия, прочетена отново изцяло.',
1084
+ },
1085
+ {
1086
+ key: 'ho.reviseNote',
1087
+ kind: 'field',
1088
+ en: 'What needs correcting?',
1089
+ bg: 'Какво трябва да се коригира?',
1090
+ doesEn: 'Shown under the card\'s buttons after "Send the script back for a correction": what the chat is to change in the script, in your words.',
1091
+ doesBg: 'Показва се под бутоните на картата след „Върни скрипта за корекция“: какво чатът трябва да промени в скрипта, с ваши думи.',
1092
+ },
1093
+ {
1094
+ key: 'ho.reviseSend',
1095
+ kind: 'button',
1096
+ en: 'Send for correction',
1097
+ bg: 'Изпрати за корекция',
1098
+ doesEn: 'Sends the note; nothing is run, and the chat hands the script over again as the next revision.',
1099
+ doesBg: 'Изпраща бележката; нищо не се пуска, а чатът дава скрипта отново като следваща ревизия.',
1068
1100
  },
1069
1101
  {
1070
1102
  key: 'ho.notRun',
1071
1103
  kind: 'button',
1072
- en: 'I did not run it',
1073
- bg: 'Не го пуснах',
1074
- doesEn: 'Tells the chat you did not run the commands, with what you wrote as the reason; it goes on without them or ends blocked.',
1075
- doesBg: 'Казва на чата, че не сте пуснали командите, с написаното като причина; той продължава без тях или приключва като блокиран.',
1104
+ en: 'I will not run it',
1105
+ bg: 'Няма да го изпълнявам',
1106
+ doesEn: 'Final for that script: tells the chat you will not run it, with what you wrote as the reason; it goes on without it or ends blocked.',
1107
+ doesBg: 'Окончателно за този скрипт: казва на чата, че няма да го пуснете, с написаното като причина; той продължава без него или приключва като блокиран.',
1076
1108
  },
1077
1109
  {
1078
1110
  key: 'approval.openChat',
@@ -2491,13 +2523,21 @@ export const SYSTEM_GUIDE = [
2491
2523
  doesEn: 'The default: each command waits on a card in the conversation, which says who asks — Run, Run this and the rest, or Skip.',
2492
2524
  doesBg: 'По подразбиране: всяка команда чака на карта в разговора, на която пише кой иска — Изпълни, Изпълни тази и останалите или Пропусни.',
2493
2525
  },
2526
+ {
2527
+ key: 'exec.startModeAutoAsk',
2528
+ kind: 'select',
2529
+ en: 'Run without asking, except scripts the bot wrote',
2530
+ bg: 'Изпълнявай без питане, освен скриптовете на бота',
2531
+ doesEn: 'Commands run at once; one that runs a script the bot wrote during the work, of a kind "Scripts the bot may run" lets it run, waits on a card with the script in full. Chosen, it asks once to confirm. Allowed only when "Where the bot runs" allows runs with nobody watching; forbidden commands are refused either way.',
2532
+ doesBg: 'Командите се изпълняват веднага; команда, която пуска скрипт, написан от бота по време на работата, от вид, който „Скриптове, които ботът може да пуска“ позволява, чака на карта с целия скрипт. При избор пита веднъж за потвърждение. Позволено е само ако „Къде върви ботът“ позволява пускания без надзор; забранените команди се отказват и така.',
2533
+ },
2494
2534
  {
2495
2535
  key: 'exec.startModeAuto',
2496
2536
  kind: 'select',
2497
- en: 'Run commands without asking',
2498
- bg: 'Изпълнявай командите без питане',
2499
- doesEn: 'Commands run at once; chosen, it asks once to confirm. Allowed only when "Where the bot runs" allows runs with nobody watching, otherwise a message is refused with the reason; forbidden commands are refused either way.',
2500
- doesBg: 'Командите се изпълняват веднага; при избор пита веднъж за потвърждение. Позволено е само ако „Къде върви ботът“ позволява пускания без надзор, иначе съобщението се отказва с причината; забранените команди се отказват и така.',
2537
+ en: 'Run everything without asking, the bot\'s scripts too',
2538
+ bg: 'Изпълнявай всичко без питане, и скриптовете на бота',
2539
+ doesEn: 'Commands run at once, and so do the scripts the bot wrote of the kinds ticked under "Scripts the bot may run"; chosen, it asks once to confirm. Allowed only when "Where the bot runs" allows runs with nobody watching, otherwise a message is refused with the reason; forbidden commands are refused either way.',
2540
+ doesBg: 'Командите се изпълняват веднага, както и скриптовете, които ботът е написал, от видовете, отметнати в „Скриптове, които ботът може да пуска“; при избор пита веднъж за потвърждение. Позволено е само ако „Къде върви ботът“ позволява пускания без надзор, иначе съобщението се отказва с причината; забранените команди се отказват и така.',
2501
2541
  },
2502
2542
  {
2503
2543
  key: 'exec.networkFetch',
@@ -2683,6 +2723,45 @@ export const SYSTEM_GUIDE = [
2683
2723
  },
2684
2724
  ],
2685
2725
  },
2726
+ {
2727
+ headingKey: 'scr.title',
2728
+ en: 'Scripts the bot may run',
2729
+ bg: 'Скриптове, които ботът може да пуска',
2730
+ controls: [
2731
+ {
2732
+ key: 'scr.kind',
2733
+ kind: 'note',
2734
+ en: 'Kind',
2735
+ bg: 'Вид',
2736
+ doesEn: 'The table\'s first column: the kind of script, with its extensions, in the order of their names.',
2737
+ doesBg: 'Първата колона на таблицата: видът скрипт, с разширенията му, подредени по име.',
2738
+ },
2739
+ {
2740
+ key: 'scr.own',
2741
+ kind: 'checkbox',
2742
+ en: 'Ready-made (the project\'s)',
2743
+ bg: 'Готови (на проекта)',
2744
+ doesEn: 'One box per kind — TypeScript, JavaScript, Python, PowerShell, cmd, bash, Ruby/Perl/PHP, package.json scripts: whether the bot runs the project\'s own scripts of that kind, there before the work began. On by default; off, not even the project\'s run.',
2745
+ doesBg: 'По една отметка за всеки вид — TypeScript, JavaScript, Python, PowerShell, cmd, bash, Ruby/Perl/PHP, скриптове в package.json: дали ботът пуска собствените скриптове на проекта от този вид, били там преди началото на работата. Включено по подразбиране; изключено — не се пускат дори тези на проекта.',
2746
+ },
2747
+ {
2748
+ key: 'scr.written',
2749
+ kind: 'checkbox',
2750
+ en: 'Written by the bot',
2751
+ bg: 'Написани от бота',
2752
+ doesEn: 'Whether the bot runs the scripts of that kind it wrote during the work itself, .cop-tmp included. Off by default: such a script is handed to the operator on "Run this yourself". Ticked, the bot runs it — first on a card in "Run without asking, except scripts the bot wrote". The text of .ps1, .bat, .cmd, .sh and package.json scripts is checked like a command; .ts, .js and .py are not read.',
2753
+ doesBg: 'Дали ботът пуска сам скриптовете от този вид, които е написал по време на работата, включително в .cop-tmp. Изключено по подразбиране: такъв скрипт се дава на оператора на „Пуснете го сами“. Отметнато: ботът го пуска — първо на карта при „Изпълнявай без питане, освен скриптовете на бота“. Текстът на .ps1, .bat, .cmd, .sh и скриптовете в package.json се проверява като команда; .ts, .js и .py не се четат.',
2754
+ },
2755
+ {
2756
+ key: 'scr.restore',
2757
+ kind: 'button',
2758
+ en: 'Restore the defaults',
2759
+ bg: 'Върни по подразбиране',
2760
+ doesEn: 'Puts the boxes back, after asking: the project\'s scripts run, the bot\'s are handed to the operator.',
2761
+ doesBg: 'Връща отметките, след като попита: скриптовете на проекта се пускат, а тези на бота се дават на оператора.',
2762
+ },
2763
+ ],
2764
+ },
2686
2765
  ],
2687
2766
  },
2688
2767
  {
@@ -93,7 +93,14 @@ export const LeadReplySchema = z
93
93
  * `done` — the result, in the form the assignment asked for (`answer`). `blocked` — it cannot be taken further
94
94
  * without the operator (`summary`, `needed`).
95
95
  */
96
- status: z.enum(['delegate', 'plan', 'ask', 'done', 'blocked']),
96
+ /*
97
+ * A status of the worker's said by the lead (operator's specification, 2026-10-27: an unsupported "handoff" cost a
98
+ * format retry that said only "invalid option"): the lead is told whose it is and what to do instead.
99
+ */
100
+ status: z.enum(['delegate', 'plan', 'ask', 'done', 'blocked'], {
101
+ message: 'status is one of "delegate", "plan", "ask", "done", "blocked". "handoff" and "continue" are the worker\'s: the worker writes a ' +
102
+ 'script and hands it to the operator itself, so delegate the subtask that needs one; a question for the operator is status "ask".',
103
+ }),
97
104
  understanding: prose,
98
105
  notes: prose,
99
106
  plan: PlanSchema.optional(),
@@ -117,9 +117,11 @@ export const OptionSchema = z.preprocess((v) => (typeof v === 'string' ? { answe
117
117
  }));
118
118
  /**
119
119
  * Commands the operator runs themselves (operator, 2026-10-26: "the script is made, but the user runs it; the bot gives
120
- * the commands for the user to run and the result it expects"): a script written during the work is never run by the
121
- * runner (`scriptFiles.ts`), so the chat hands it over — the lines in order, the folder, what should be seen, and the
122
- * script files they run, which the card shows with their SHA-256 so the operator reads what they run.
120
+ * the commands for the user to run and the result it expects"): a script written during the work that the operator's
121
+ * boxes do not let the runner run (`scriptFiles.ts`) is handed over — the lines in order, the folder, what should be
122
+ * seen, and the script files they run, which the card shows in full so the operator reads what they run. Since
123
+ * 2026-10-27 also what it does besides: how it should end, what it reaches on the network and on a platform, and what
124
+ * it changes in the project — the card shows them beside what the runner itself reads in the lines and the scripts.
123
125
  */
124
126
  export const HandoffSchema = z.object({
125
127
  why: z.string().trim().min(1).optional(),
@@ -129,6 +131,14 @@ export const HandoffSchema = z.object({
129
131
  expect: z.string().trim().min(5, 'handoff.expect must say what the operator should see when it works.'),
130
132
  /** The script files the commands run, relative to the project. */
131
133
  files: z.array(z.preprocess(asText, z.string().trim().min(1))).default([]),
134
+ /** How it should end: the exit code, or what it prints last. */
135
+ exit: z.preprocess(asText, z.string().trim().min(1)).optional(),
136
+ /** What it reaches on the network: "nothing", or the hosts. */
137
+ network: z.preprocess(asText, z.string().trim().min(1)).optional(),
138
+ /** What it reaches on a platform with the operator's access (Azure, GitHub …): "nothing", or which. */
139
+ platforms: z.preprocess(asText, z.string().trim().min(1)).optional(),
140
+ /** What it changes in the project: "nothing", or the files and how. */
141
+ changes: z.preprocess(asText, z.string().trim().min(1)).optional(),
132
142
  });
133
143
  export const ReplySchema = z
134
144
  .object({
@@ -99,7 +99,10 @@ export const ReviewSchema = z
99
99
  * and fails: "I could not verify X because Y" is information the operator needs, and
100
100
  * quietly passing work nobody could check is the one outcome worth ruling out.
101
101
  */
102
- status: z.enum(['continue', 'pass', 'fail']),
102
+ status: z.enum(['continue', 'pass', 'fail'], {
103
+ message: 'status is one of "continue", "pass", "fail". A review hands nothing to the operator ("handoff" is the implementer\'s): check what a ' +
104
+ 'script would show with commands of your own, or say in a finding that the operator has to run it.',
105
+ }),
103
106
  steps: z.array(StepSchema).default([]),
104
107
  notes: z.string().optional(),
105
108
  /** Required on `pass` and `fail`: what you checked, how, and what you saw. */
@@ -22,6 +22,7 @@
22
22
  * Kept as `data/queue.json` (see `OperatorService.queue`). This module is the part that needs no browser: the shape,
23
23
  * the checks of an edit, and which task is next.
24
24
  */
25
+ import { handoffOutcomeOf } from '../orchestrator/handoff.js';
25
26
  import { branchExists } from '../vcs/git.js';
26
27
  export const DEFAULT_PARK_AFTER_SEC = 120;
27
28
  export const MAX_PARK_AFTER_SEC = 24 * 60 * 60;
@@ -214,11 +215,14 @@ export function parkedAnswerFrom(p, input) {
214
215
  return text(input.note) ? { kind: 'plan', decision: 'revise', note: text(input.note) } : { problem: 'Say what to change in the plan.' };
215
216
  return { problem: 'A plan is approved, or sent back for another.' };
216
217
  case 'question':
217
- // Commands handed over (2026-10-26): what they printed, or that the operator did not run them, with a word or none.
218
+ // Commands handed over (2026-10-26): what they printed, sent back with what to correct (2026-10-27), or not run.
218
219
  if (p.approval.question?.handoff) {
219
- if (input.ran === false)
220
- return { kind: 'question', answer: text(input.answer), ran: false };
221
- return text(input.answer) ? { kind: 'question', answer: text(input.answer), ran: true } : { problem: 'Paste what the commands printed first.' };
220
+ const outcome = handoffOutcomeOf(input.outcome, input.ran);
221
+ if (outcome === 'declined')
222
+ return { kind: 'question', answer: text(input.answer), ran: false, outcome };
223
+ if (outcome === 'revise')
224
+ return text(input.answer) ? { kind: 'question', answer: text(input.answer), outcome } : { problem: 'Say what to correct first.' };
225
+ return text(input.answer) ? { kind: 'question', answer: text(input.answer), ran: true, outcome } : { problem: 'Paste what the commands printed first.' };
222
226
  }
223
227
  return text(input.answer) ? { kind: 'question', answer: text(input.answer) } : { problem: 'Write the answer first.' };
224
228
  case 'retry': {
@@ -82,6 +82,42 @@ export async function changedSince(dir, before, id) {
82
82
  await git(dir, ['update-ref', '-d', ref]).catch(() => undefined);
83
83
  }
84
84
  }
85
+ /**
86
+ * Adds to the safety record what `git clean -f -d` would remove now: the record photographed the folder through the
87
+ * .gitignore of then, and a file it ignored is not in it. The record as it now is, or why it could not be kept.
88
+ */
89
+ async function keepWhatCleanTakes(dir, ref, safety) {
90
+ // `clean` has no -z: one name a line, quoted C-style only where it holds a quote, a backslash or a control character.
91
+ const doomed = await git(dir, ['-c', 'core.quotePath=false', 'clean', '-n', '-d'], 60_000);
92
+ if (!doomed.ok)
93
+ return { problem: `git could not tell which files going back removes: ${doomed.stderr.split('\n')[0]}. Nothing was removed.` };
94
+ const unquote = (p) => (p.startsWith('"') && p.endsWith('"') ? p.slice(1, -1).replace(/\\(["\\])/g, '$1') : p);
95
+ const paths = doomed.stdout.split(/\r?\n/).filter((l) => l.startsWith('Would remove ')).map((l) => unquote(l.slice('Would remove '.length)));
96
+ if (paths.length === 0)
97
+ return { commit: safety };
98
+ const kept = new Set((await git(dir, ['ls-tree', '-r', '--name-only', '-z', safety], 60_000)).stdout.split('\0').filter(Boolean));
99
+ const missing = paths.filter((p) => (p.endsWith('/') ? ![...kept].some((k) => k.startsWith(p)) : !kept.has(p)));
100
+ if (missing.length === 0)
101
+ return { commit: safety };
102
+ const scratch = await mkdtemp(join(tmpdir(), 'cop-checkpoint-'));
103
+ const env = { ...process.env, GIT_INDEX_FILE: join(scratch, 'index') };
104
+ try {
105
+ const problem = 'the files going back would remove could not be kept first, so nothing was removed';
106
+ if (!(await git(dir, ['read-tree', safety], 60_000, env)).ok)
107
+ return { problem: `${problem}.` };
108
+ const add = await git(dir, ['add', '-f', '--', ...missing], 120_000, env);
109
+ if (!add.ok)
110
+ return { problem: `${problem} (${add.stderr.split('\n')[0]}).` };
111
+ const tree = await git(dir, ['write-tree'], 60_000, env);
112
+ const commit = tree.ok ? await git(dir, [...AUTHOR, 'commit-tree', tree.stdout, '-p', safety, '-m', 'files going back removes, kept with the folder as it was']) : tree;
113
+ if (!commit.ok || !(await git(dir, ['update-ref', ref, commit.stdout])).ok)
114
+ return { problem: `${problem}.` };
115
+ return { commit: commit.stdout };
116
+ }
117
+ finally {
118
+ await rm(scratch, { recursive: true, force: true }).catch(() => undefined);
119
+ }
120
+ }
85
121
  /**
86
122
  * Puts the folder back as `cp` photographed it: its branch checked out at its commit, its working tree with the
87
123
  * same uncommitted changes. The folder as it is now is photographed first, under `refs/copilot-operator/safety/`.
@@ -102,6 +138,18 @@ export async function restoreCheckpoint(dir, cp) {
102
138
  : await step(['checkout', '--force', '--detach', cp.head], `${cp.head.slice(0, 8)} could not be checked out`)) ??
103
139
  // At the commit it was on: a commit made after it, by the chat or by hand, is undone here (kept in the safety record).
104
140
  (cp.branch ? await step(['reset', '--hard', cp.head], `${cp.branch} could not be put back at ${cp.head.slice(0, 8)}`) : null) ??
141
+ /*
142
+ * What git would remove now and the safety record does not hold — a file the .gitignore of now ignored, and the
143
+ * .gitignore put back does not (audit, 2026-10-27: a `.env` the chat had ignored went for good) — is added to the
144
+ * record first, so the clean below loses nothing.
145
+ */
146
+ (await (async () => {
147
+ const kept = await keepWhatCleanTakes(dir, `refs/copilot-operator/safety/${stamp}`, safety.commit);
148
+ if ('problem' in kept)
149
+ return kept.problem;
150
+ safety.commit = kept.commit;
151
+ return null;
152
+ })()) ??
105
153
  // Files made since that git does not track go; ignored ones (builds, installs) stay.
106
154
  (await step(['clean', '-f', '-d'], 'the files made since could not be removed')) ??
107
155
  // And the uncommitted changes as they were, untracked files included.
@@ -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.referenceNote, 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.scriptsNote, 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
  /**
@@ -249,6 +249,20 @@ export async function buildStory(runsDir, runId, task, live) {
249
249
  if (!placedReviews.has(round))
250
250
  entries.push(await reviewRound(join(dir, 'review', String(round)), round));
251
251
  }
252
+ // Each handoff where it happened: after the last entry before it was put to the operator.
253
+ for (const name of (await readdir(join(dir, 'handoffs')).catch(() => [])).filter((n) => n.endsWith('.json')).sort()) {
254
+ const kept = await readFile(join(dir, 'handoffs', name), 'utf8').then((t) => JSON.parse(t)).catch(() => null);
255
+ if (!kept?.card)
256
+ continue;
257
+ const at = kept.askedAt;
258
+ let place = entries.length;
259
+ if (at) {
260
+ const later = entries.findIndex((e) => e.at !== undefined && e.at > at);
261
+ if (later >= 0)
262
+ place = later;
263
+ }
264
+ entries.splice(place, 0, { kind: 'handoff', revision: kept.card.revision ?? 1, card: kept.card, outcome: kept.outcome ?? 'nobody', ...(kept.answer ? { answer: clip(kept.answer) } : {}), ...(at ? { at } : {}), ...(kept.answeredAt ? { answeredAt: kept.answeredAt } : {}) });
265
+ }
252
266
  const ended = task.status !== 'queued' && task.status !== 'running' && task.status !== 'waiting-approval';
253
267
  return {
254
268
  runId,
@@ -60,16 +60,25 @@ function addCounts(files, out) {
60
60
  }
61
61
  }
62
62
  }
63
- async function diffFiles(dir, args) {
63
+ /** The files a diff names, with their letters; their lines are left at 0. */
64
+ async function diffNames(dir, args) {
64
65
  const names = await gitBytes(dir, ['diff', '--name-status', '-M', '-z', ...args]);
65
- if (!names.ok)
66
- return [];
67
- const files = nameStatus(names.stdout.toString('utf8'));
66
+ return names.ok ? nameStatus(names.stdout.toString('utf8')) : [];
67
+ }
68
+ async function diffFiles(dir, args) {
69
+ const files = await diffNames(dir, args);
70
+ if (files.length === 0)
71
+ return files;
68
72
  const counts = await gitBytes(dir, ['diff', '--numstat', '-M', '-z', ...args]);
69
73
  if (counts.ok)
70
74
  addCounts(files, counts.stdout.toString('utf8'));
71
75
  return files;
72
76
  }
77
+ /** The files git does not track, as `ls-files` names them: ignored ones left out. */
78
+ async function untrackedPaths(dir) {
79
+ const others = await gitBytes(dir, ['ls-files', '--others', '--exclude-standard', '-z']);
80
+ return others.ok ? others.stdout.toString('utf8').split('\0').filter(Boolean) : [];
81
+ }
73
82
  /** A file git does not track yet: all of it added, counted in lines when it is text. */
74
83
  async function untracked(dir, path) {
75
84
  const full = join(dir, path);
@@ -100,8 +109,7 @@ export async function workspaceGit(dir) {
100
109
  for (const f of [...staged, ...unstaged])
101
110
  if (f.status === 'U')
102
111
  f.status = '!';
103
- const others = await gitBytes(dir, ['ls-files', '--others', '--exclude-standard', '-z']);
104
- const fresh = others.ok ? others.stdout.toString('utf8').split('\0').filter(Boolean).sort().slice(0, 2000) : [];
112
+ const fresh = (await untrackedPaths(dir)).sort().slice(0, 2000);
105
113
  const changes = [...unstaged, ...(await Promise.all(fresh.map((p) => untracked(dir, p))))];
106
114
  let upstream;
107
115
  const up = await git(dir, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}']);
@@ -159,25 +167,48 @@ async function defaultBase(dir, refs) {
159
167
  * not track among them — marked with whether it is in a commit of the branch, and what of it is not committed. `base`
160
168
  * must be one of the branches there are; left out, the one a pull request would go into. Read-only.
161
169
  */
162
- export async function branchChanges(dir, base) {
163
- const none = { dir, isRepo: false, bases: [], ahead: 0, behind: 0, commits: [], files: [], moreFiles: false };
164
- if (!dir || !looksLikeRepo(dir))
165
- return none;
170
+ /**
171
+ * The branch and what it is compared with: the branches there are, the one chosen — `base` when it is one of them,
172
+ * else the one a pull request would go into — and where the branch left it; or why there is nothing to compare.
173
+ */
174
+ async function branchBase(dir, base) {
166
175
  const branch = (await git(dir, ['rev-parse', '--abbrev-ref', 'HEAD'])).stdout || undefined;
167
- const out = { ...none, isRepo: true, ...(branch ? { branch } : {}) };
176
+ const named = branch ? { branch } : {};
168
177
  if (!(await hasHead(dir)))
169
- return { ...out, problem: 'no-commit' };
178
+ return { ...named, bases: [], problem: 'no-commit' };
170
179
  const bases = await branchRefs(dir, branch ?? '');
171
- out.bases = bases;
172
180
  // Only a branch the list names: nothing else of the request reaches git.
173
181
  const chosen = base && bases.includes(base) ? base : await defaultBase(dir, bases);
174
182
  if (!chosen)
175
- return { ...out, problem: 'no-base' };
176
- out.base = chosen;
183
+ return { ...named, bases, problem: 'no-base' };
177
184
  const mb = await git(dir, ['merge-base', chosen, 'HEAD']);
178
185
  if (!mb.ok || !mb.stdout)
179
- return { ...out, problem: 'no-common' };
180
- const mergeBase = mb.stdout.trim();
186
+ return { ...named, bases, base: chosen, problem: 'no-common' };
187
+ return { ...named, bases, base: chosen, mergeBase: mb.stdout.trim() };
188
+ }
189
+ /**
190
+ * The files "On this branch" lists: the whole branch against where it left the base, the files git does not track
191
+ * (as added), and the ones committed on it and undone since in the working tree — still the branch's, nothing of
192
+ * them left against the base. One list for the view and for the number on the Git button, so the two agree.
193
+ */
194
+ function branchList(net, fresh, committed) {
195
+ const files = [...net, ...fresh.map((f) => ({ ...f, status: 'A' }))];
196
+ const listed = new Set(files.map((f) => f.path));
197
+ for (const c of committed)
198
+ if (!listed.has(c.path))
199
+ files.push({ ...c, added: 0, removed: 0 });
200
+ return files;
201
+ }
202
+ export async function branchChanges(dir, base) {
203
+ const none = { dir, isRepo: false, bases: [], ahead: 0, behind: 0, commits: [], files: [], moreFiles: false };
204
+ if (!dir || !looksLikeRepo(dir))
205
+ return none;
206
+ const found = await branchBase(dir, base);
207
+ const out = { ...none, isRepo: true, ...(found.branch ? { branch: found.branch } : {}), bases: found.bases, ...(found.base ? { base: found.base } : {}) };
208
+ if (found.problem || !found.mergeBase || !found.base)
209
+ return { ...out, problem: found.problem ?? 'no-common' };
210
+ const chosen = found.base;
211
+ const mergeBase = found.mergeBase;
181
212
  out.mergeBase = mergeBase;
182
213
  const counts = await git(dir, ['rev-list', '--left-right', '--count', `${chosen}...HEAD`]);
183
214
  const [behind = '0', ahead = '0'] = counts.stdout.split(/\s+/);
@@ -190,14 +221,9 @@ export async function branchChanges(dir, base) {
190
221
  const net = await diffFiles(dir, [mergeBase]);
191
222
  const staged = new Set((await diffFiles(dir, ['--cached', 'HEAD'])).flatMap((f) => [f.path, ...(f.oldPath ? [f.oldPath] : [])]));
192
223
  const unstaged = new Set((await diffFiles(dir, [])).flatMap((f) => [f.path, ...(f.oldPath ? [f.oldPath] : [])]));
193
- const others = await gitBytes(dir, ['ls-files', '--others', '--exclude-standard', '-z']);
194
- const fresh = others.ok ? others.stdout.toString('utf8').split('\0').filter(Boolean) : [];
224
+ const fresh = await untrackedPaths(dir);
195
225
  const inCommits = new Set(committed.flatMap((f) => [f.path, ...(f.oldPath ? [f.oldPath] : [])]));
196
- const files = [...net, ...(await Promise.all(fresh.slice(0, MAX_BRANCH_FILES).map((p) => untracked(dir, p)))).map((f) => ({ ...f, status: 'A' }))];
197
- // Committed on the branch and undone since in the working tree: still the branch's, nothing of it left against the base.
198
- for (const c of committed)
199
- if (!files.some((f) => f.path === c.path))
200
- files.push({ ...c, added: 0, removed: 0 });
226
+ const files = branchList(net, await Promise.all(fresh.slice(0, MAX_BRANCH_FILES).map((p) => untracked(dir, p))), committed);
201
227
  const untrackedSet = new Set(fresh);
202
228
  const marked = files.map((f) => {
203
229
  const keys = [f.path, ...(f.oldPath ? [f.oldPath] : [])];
@@ -211,6 +237,20 @@ export async function branchChanges(dir, base) {
211
237
  out.moreFiles = marked.length > MAX_BRANCH_FILES || fresh.length > MAX_BRANCH_FILES;
212
238
  return out;
213
239
  }
240
+ export async function gitCounts(dir, base) {
241
+ if (!dir || !looksLikeRepo(dir))
242
+ return { isRepo: false, uncommitted: 0, branch: null };
243
+ const head = await hasHead(dir);
244
+ const staged = await diffNames(dir, ['--cached', head ? 'HEAD' : EMPTY_TREE]);
245
+ const unstaged = await diffNames(dir, []);
246
+ const fresh = await untrackedPaths(dir);
247
+ const uncommitted = new Set([...staged, ...unstaged].map((f) => f.path).concat(fresh)).size;
248
+ const found = await branchBase(dir, base);
249
+ if (found.problem || !found.mergeBase)
250
+ return { isRepo: true, uncommitted, branch: null, ...(found.base ? { base: found.base } : {}), problem: found.problem ?? 'no-common' };
251
+ const files = branchList(await diffNames(dir, [found.mergeBase]), fresh.map((path) => ({ status: 'U', path, added: 0, removed: 0 })), await diffNames(dir, [found.mergeBase, 'HEAD']));
252
+ return { isRepo: true, uncommitted, branch: files.length, ...(found.base ? { base: found.base } : {}) };
253
+ }
214
254
  /** One commit: who, when, what it says, and the files it changed (a first commit against nothing). */
215
255
  export async function workspaceCommit(dir, sha) {
216
256
  if (!SHA.test(sha))