copilot-operator 0.1.96 → 0.1.99

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/src/api/apiLock.js +82 -0
  2. package/dist/src/api/folderPicker.js +22 -22
  3. package/dist/src/api/main.js +5 -0
  4. package/dist/src/api/operator.controller.js +37 -11
  5. package/dist/src/api/operator.service.js +493 -86
  6. package/dist/src/api/server.js +10 -0
  7. package/dist/src/config/exportHome.js +52 -10
  8. package/dist/src/config/home.js +27 -11
  9. package/dist/src/config/schema.js +13 -0
  10. package/dist/src/exec/authorizer.js +11 -4
  11. package/dist/src/exec/commandHeads.js +25 -0
  12. package/dist/src/exec/confinement.js +50 -4
  13. package/dist/src/exec/network.js +11 -1
  14. package/dist/src/exec/npmScripts.js +33 -0
  15. package/dist/src/exec/policy.js +79 -24
  16. package/dist/src/exec/processes.js +24 -5
  17. package/dist/src/exec/programs.js +21 -0
  18. package/dist/src/exec/reportFile.js +2 -1
  19. package/dist/src/exec/runner.js +31 -9
  20. package/dist/src/exec/scriptFiles.js +133 -6
  21. package/dist/src/orchestrator/handoff.js +3 -3
  22. package/dist/src/orchestrator/kerriganRunner.js +14 -6
  23. package/dist/src/orchestrator/leadRunner.js +43 -23
  24. package/dist/src/orchestrator/review.js +66 -10
  25. package/dist/src/orchestrator/taskRunner.js +73 -14
  26. package/dist/src/plan/kerrigan.js +253 -253
  27. package/dist/src/plan/schema.js +3 -13
  28. package/dist/src/plan/systemGuide.js +28 -28
  29. package/dist/src/protocol/kerriganSchema.js +5 -1
  30. package/dist/src/protocol/replySchema.js +2 -2
  31. package/dist/src/queue/queue.js +93 -0
  32. package/dist/src/session/compose.js +14 -10
  33. package/dist/src/session/locatorFailures.js +32 -12
  34. package/dist/src/session/model.js +23 -0
  35. package/dist/src/session/store.js +47 -0
  36. package/dist/src/session/workspace.js +20 -5
  37. package/dist/src/transport/copilotTransport.js +82 -62
  38. package/dist/src/util/zip.js +147 -44
  39. package/dist/src/vcs/newBranch.js +24 -2
  40. package/dist/src/vcs/operatorGit.js +9 -10
  41. package/dist/src/vcs/referenceGuard.js +9 -4
  42. package/dist/web/404.html +2 -2
  43. package/dist/web/_next/static/chunks/1024-c0eee3ec374816d1.js +1 -0
  44. package/dist/web/_next/static/chunks/1077.a4fe6ae48f3d3ff9.js +1 -0
  45. package/dist/web/_next/static/chunks/1548.765d6eed5325bd01.js +1 -0
  46. package/dist/web/_next/static/chunks/2163.e8d6c85412d5d411.js +1 -0
  47. package/dist/web/_next/static/chunks/6240-8ba644c53ffab87d.js +1 -0
  48. package/dist/web/_next/static/chunks/714.f2dcd6b41b58d1a7.js +1 -0
  49. package/dist/web/_next/static/chunks/7220.652a8a339c1e7401.js +1 -0
  50. package/dist/web/_next/static/chunks/7921-9cf1ece94fc89bb3.js +1 -0
  51. package/dist/web/_next/static/chunks/8584.7c438425140f1d8d.js +1 -0
  52. package/dist/web/_next/static/chunks/9067.8c4e6a64620a45d9.js +1 -0
  53. package/dist/web/_next/static/chunks/9747.43d25bdff8737d09.js +1 -0
  54. package/dist/web/_next/static/chunks/app/{layout-2364903896c2c175.js → layout-97259931ed97e20d.js} +1 -1
  55. package/dist/web/_next/static/chunks/app/page-26e4ea30eb076e6b.js +1 -0
  56. package/dist/web/_next/static/chunks/app/queue/page-7228e045f8ea10c4.js +1 -0
  57. package/dist/web/_next/static/chunks/app/settings/page-c915d61553e1025b.js +1 -0
  58. package/dist/web/_next/static/chunks/app/system/page-4d24f44eb9077fb7.js +1 -0
  59. package/dist/web/_next/static/chunks/{webpack-3f144d13be3516c2.js → webpack-31db88c3d5781520.js} +1 -1
  60. package/dist/web/_next/static/css/{523d11041085f836.css → 87999096d96266fd.css} +1 -1
  61. package/dist/web/defaults.html +2 -2
  62. package/dist/web/defaults.txt +26 -25
  63. package/dist/web/index.html +3 -3
  64. package/dist/web/index.txt +26 -25
  65. package/dist/web/queue.html +2 -2
  66. package/dist/web/queue.txt +26 -25
  67. package/dist/web/settings.html +2 -2
  68. package/dist/web/settings.txt +26 -25
  69. package/dist/web/system.html +2 -2
  70. package/dist/web/system.txt +26 -25
  71. package/package.json +3 -2
  72. package/prompts/kerrigan1.md +2 -1
  73. package/prompts/lead1.md +2 -1
  74. package/prompts/level1.md +6 -1
  75. package/prompts/review1.md +7 -4
  76. package/dist/web/_next/static/chunks/1024-214ded25b9048526.js +0 -1
  77. package/dist/web/_next/static/chunks/1077.161de82f740d47f0.js +0 -1
  78. package/dist/web/_next/static/chunks/1548.f2688468bf946e13.js +0 -1
  79. package/dist/web/_next/static/chunks/2163.b8ada3b7bde69f03.js +0 -1
  80. package/dist/web/_next/static/chunks/714.d1489788e598833b.js +0 -1
  81. package/dist/web/_next/static/chunks/7220.b85c8d105f394389.js +0 -1
  82. package/dist/web/_next/static/chunks/7921-00ebbcc6f65fbe35.js +0 -1
  83. package/dist/web/_next/static/chunks/8124-1dba8babfcfbc6e2.js +0 -1
  84. package/dist/web/_next/static/chunks/8584.a678bfced1cea938.js +0 -1
  85. package/dist/web/_next/static/chunks/9067.6da03ae052877b19.js +0 -1
  86. package/dist/web/_next/static/chunks/9747.ba29e64e97e8a15b.js +0 -1
  87. package/dist/web/_next/static/chunks/app/page-d031bf326e401246.js +0 -1
  88. package/dist/web/_next/static/chunks/app/queue/page-9cfc8f78d536cfb6.js +0 -1
  89. package/dist/web/_next/static/chunks/app/settings/page-9c2b961beb8b3dce.js +0 -1
  90. package/dist/web/_next/static/chunks/app/system/page-3466496814a70b62.js +0 -1
  91. /package/dist/web/_next/static/{kNfJ9jSwlboc-1sFBBfuI → n8n-2FmbL8PhXulu4hTV5}/_buildManifest.js +0 -0
  92. /package/dist/web/_next/static/{kNfJ9jSwlboc-1sFBBfuI → n8n-2FmbL8PhXulu4hTV5}/_ssgManifest.js +0 -0
@@ -170,22 +170,12 @@ const VcsInput = z
170
170
  * model of its own, so a check it cannot decide by running something and comparing is a check
171
171
  * it would have to take on trust — which is the thing the check exists to replace.
172
172
  */
173
+ /** What a check expects, as a plan, a skill and a reviewer's finding write it. */
174
+ export const CHECK_EXPECTS = ['exit-zero', 'exit-nonzero', 'output-contains', 'output-omits', 'output-matches', 'file-exists', 'file-missing', 'file-contains'];
173
175
  export const CheckInput = z
174
176
  .object({
175
177
  name: z.string().trim().min(3, 'A check needs a name saying what it is checking.'),
176
- expect: z.enum([
177
- 'exit-zero',
178
- 'exit-nonzero',
179
- 'output-contains',
180
- 'output-omits',
181
- 'output-matches',
182
- 'file-exists',
183
- 'file-missing',
184
- 'file-contains',
185
- ], {
186
- error: 'expect must be one of: exit-zero, exit-nonzero, output-contains, output-omits, output-matches, ' +
187
- 'file-exists, file-missing, file-contains.',
188
- }),
178
+ expect: z.enum(CHECK_EXPECTS, { error: `expect must be one of: ${CHECK_EXPECTS.join(', ')}.` }),
189
179
  run: z.string().trim().optional(),
190
180
  /**
191
181
  * The shell to run it in. Left out is the usual answer and the better one.
@@ -210,8 +210,8 @@ export const SYSTEM_GUIDE = [
210
210
  kind: 'link',
211
211
  en: 'Download the file for a chatbot',
212
212
  bg: 'Изтегли файл за чатбота',
213
- doesEn: 'One file with all a chatbot needs to give the right locator: what to do and why, what failed and when, the old locator, the part of the page where the element most likely is (around an element near it that was found), the whole page without scripts, styles and conversation names, and how the chatbot walks you through finding it in Edge (F12) when it is in neither. Attach it to Copilot or any other chatbot and send it, with nothing else to write; the chatbot speaks the interface\'s language.',
214
- doesBg: 'Един файл с всичко, което е нужно на чатбот, за да даде правилния локатор: какво да направи и защо, какво се е провалило и кога, старият локатор, частта от страницата, където елементът най-вероятно е (около близък елемент, който е намерен), цялата страница без скриптове, стилове и имена на разговори, и как чатботът да ви преведе през търсенето в Edge (F12), ако го няма в нито една от тях. Прикачете го в Copilot или друг чатбот и го пратете, без да пишете нищо друго; чатботът говори на езика на интерфейса.',
213
+ doesEn: 'One file with all a chatbot needs to give the right locator: what failed and the old locator, the part of the page where the element most likely is, the whole page without scripts and styles, and how to find it in Edge (F12) when it is in neither. Attach it to any chatbot and send it, writing nothing; it answers in the interface\'s language.',
214
+ doesBg: 'Един файл с всичко, нужно на чатбот, за да даде правилния локатор: какво се е провалило и старият локатор, частта от страницата, където елементът най-вероятно е, цялата страница без скриптове и стилове, и как да го намерите в Edge (F12), ако го няма в тях. Прикачете го на който и да е чатбот и го пратете, без да пишете нищо; той отговаря на езика на интерфейса.',
215
215
  },
216
216
  {
217
217
  key: 'chatloc.dismiss',
@@ -527,8 +527,8 @@ export const SYSTEM_GUIDE = [
527
527
  kind: 'button',
528
528
  en: 'Git',
529
529
  bg: 'Git',
530
- doesEn: 'Shows the open folder\'s git: the branch, the staged changes and the changes (each file with its letter — M, A, D, R, U, ! in conflict — and its lines), and the branch\'s commits; a file opens its two versions side by side, a commit its files. A file opens as a preview, as in VS Code: its tab in italics, replaced by the next file opened with one click; a double click keeps it. A file\'s "+" stages it and its "−" unstages it; beside a list\'s heading, the whole list. The button\'s two numbers: the files not committed yet, and every file changed on this branch.',
531
- doesBg: 'Показва git на отворената папка: клона, подготвените промени и промените (всеки файл с буквата си — M, A, D, R, U, ! в конфликт — и редовете си) и комитите на клона; файл отваря двете си версии една до друга, комит — файловете си. Файлът се отваря за преглед, както във VS Code: разделът му е в курсив и се заменя от следващия файл, отворен с едно щракване; двоен клик го задържа. „+“ на файл го подготвя, „−“ го изважда от подготвените; до заглавието на списък — целия списък. Двете числа на бутона: файловете, които още не са комитнати, и всички файлове, променени на този клон.',
530
+ doesEn: 'Shows the open folder\'s git: the branch, the staged changes and the changes (each file with its letter — M, A, D, R, U, ! in conflict), and the branch\'s commits; a file opens its two versions side by side, a commit its files. One click opens a preview (its tab in italics, replaced by the next); a double click keeps it. A file\'s "+" stages it, "−" unstages it; beside a heading, the whole list. The button\'s two numbers: the files not committed, and those changed on this branch.',
531
+ doesBg: 'Показва git на отворената папка: клона, подготвените промени и промените (всеки файл с буквата си — M, A, D, R, U, ! в конфликт) и комитите на клона; файл отваря двете си версии една до друга, комит — файловете си. Едно щракване отваря преглед (разделът в курсив, заменя се от следващия); двоен клик го задържа. „+“ на файл го подготвя, „−“ го изважда; до заглавие — целия списък. Двете числа на бутона: некомитнатите файлове и променените на този клон.',
532
532
  },
533
533
  {
534
534
  key: 'wb.refresh',
@@ -567,8 +567,8 @@ export const SYSTEM_GUIDE = [
567
567
  kind: 'button',
568
568
  en: 'Commit',
569
569
  bg: 'Комитни',
570
- doesEn: 'At the top of the git view, under the message box (Ctrl+Enter there does the same): commits the staged files with that message, under the person\'s own name for git — their commit, not the chat\'s. The project\'s hooks run as in a terminal, unless one is not the project\'s own: then it names it and asks — "Without hooks", "Run them anyway" or "Cancel". When it does not go through, a sentence says why over git\'s own words. Nothing is ever amended or forced.',
571
- doesBg: 'Най-горе в изгледа git, под полето за съобщението (Ctrl+Enter там прави същото): комитва подготвените файлове с това съобщение, с името на човека в git — неговият комит, не на чата. Hook-овете на проекта се пускат както в терминал, освен ако някой не е собствен на проекта: тогава го назовава и пита — „Без hook-ове“, „Пусни ги все пак“ или „Откажи“. Когато не мине, едно изречение казва защо, над собствените думи на git. Нищо никога не се поправя (amend) и не се налага насила.',
570
+ doesEn: 'At the top of the git view, under the message box (Ctrl+Enter there does the same): commits the staged files with that message, under the person\'s own git name. The project\'s hooks run as in a terminal; one not the project\'s own is named and asked about — "Without hooks", "Run them anyway" or "Cancel". A failure is said in a sentence over git\'s own words. Nothing is ever amended or forced.',
571
+ doesBg: 'Най-горе в изгледа git, под полето за съобщението (Ctrl+Enter там прави същото): комитва подготвените файлове с това съобщение, с името на човека в git. Hook-овете на проекта се пускат както в терминал; чужд на проекта се назовава и се пита — „Без hook-ове“, „Пусни ги все пак“ или „Откажи“. Неуспехът се казва с едно изречение над думите на git. Нищо не се поправя (amend) и не се налага насила.',
572
572
  },
573
573
  {
574
574
  key: 'git.commitAll',
@@ -806,8 +806,8 @@ export const SYSTEM_GUIDE = [
806
806
  kind: 'badge',
807
807
  en: 'LIVE',
808
808
  bg: 'LIVE',
809
- doesEn: 'Beside "Chat" while the bot works, red (amber while paused); on hover it says who is at work. The browser tab says how it stands, in English whatever language the page is in: "Working... — copilot-operator", "Paused", "Waiting for you (1)" when something waits for the operator, "Waiting for your password"; then how the last message ended — "Done", "Error", "Stopped", "Blocked", "Limit reached".',
810
- doesBg: 'До „Чат“, докато ботът работи — червено (жълто на пауза); при посочване казва кой работи. Табът на браузъра казва как стоят нещата, на английски на всеки език на страницата: „Working... — copilot-operator“, „Paused“, „Waiting for you (1)“, когато нещо чака оператора, „Waiting for your password“; после как е свършило последното съобщение — „Done“, „Error“, „Stopped“, „Blocked“, „Limit reached“.',
809
+ doesEn: 'Beside "Chat" while the bot works, red (amber while paused); on hover it says who is at work. The browser tab says how it stands, in English whatever language the page is in: "Working... — copilot-operator", "Paused", "Waiting for you (1)" when something waits for the operator, "Waiting for your password", "Waiting for you to sign in"; then how the last message ended — "Done", "Error", "Stopped", "Blocked", "Limit reached".',
810
+ doesBg: 'До „Чат“, докато ботът работи — червено (жълто на пауза); при посочване казва кой работи. Табът на браузъра казва как стоят нещата, на английски на всеки език на страницата: „Working... — copilot-operator“, „Paused“, „Waiting for you (1)“, когато нещо чака оператора, „Waiting for your password“, „Waiting for you to sign in“; после как е свършило последното съобщение — „Done“, „Error“, „Stopped“, „Blocked“, „Limit reached“.',
811
811
  },
812
812
  {
813
813
  key: 'actor.asks',
@@ -854,8 +854,8 @@ export const SYSTEM_GUIDE = [
854
854
  kind: 'button',
855
855
  en: '⎇ New branch from main',
856
856
  bg: '⎇ Нов бранч от main',
857
- doesEn: 'Under the chat\'s box, beside the skills: fetches the latest of the remote\'s main and opens a window to make a new local branch from it for the next task — not tracking main, so its work is never pushed there by mistake. A password or a key\'s passphrase goes into Git\'s own window. Off while a task works, and where the folder is not a repository.',
858
- doesBg: 'Под полето на чата, до skill-овете: взима последното от main на remote и отваря прозорец за нов локален клон от него за следващата задача — без да следи main, така че работата му никога не отива там по грешка. Парола или passphrase на ключ се въвежда в собствения прозорец на Git. Изключен, докато работи задача, и където папката не е хранилище.',
857
+ doesEn: 'Under the chat\'s box, beside the skills: fetches the latest of the remote\'s main and opens a window to make a new local branch from it for the next task — not tracking main, so its work is never pushed there by mistake. A password or a key\'s passphrase goes into Git\'s own window. Off while a task works, and where the folder is not a repository. Uncommitted work of a queue task set aside on the folder is put aside for it, not taken along.',
858
+ doesBg: 'Под полето на чата, до skill-овете: взима последното от main на remote и отваря прозорец за нов локален клон от него за следващата задача — без да следи main, така че работата му никога не отива там по грешка. Парола или passphrase на ключ се въвежда в собствения прозорец на Git. Изключен, докато работи задача, и където папката не е хранилище. Некомитнатата работа на задача от опашката, оставена настрана в папката, се оставя настрана за нея, не се взима.',
859
859
  },
860
860
  {
861
861
  key: 'nb.title',
@@ -958,8 +958,8 @@ export const SYSTEM_GUIDE = [
958
958
  kind: 'button',
959
959
  en: 'Open a folder',
960
960
  bg: 'Отвори папка',
961
- doesEn: 'Opens the machine\'s folder dialog; the folder chosen becomes the project the chat and the Files view work on (Settings → project folder).',
962
- doesBg: 'Отваря прозореца за избор на папка; избраната става проектът, върху който работят чатът и изгледът „Файлове“ (Настройки → папка на проекта).',
961
+ doesEn: 'Opens the machine\'s folder dialog; the folder chosen becomes the project the chat and the Files view work on, with its own name, level 2 and "for reference only" — those of the one before are kept for it.',
962
+ doesBg: 'Отваря прозореца за избор на папка; избраната става проектът, върху който работят чатът и „Файлове“, със свои име, ниво 2 и „само за справка“ — тези на предишния се пазят за него.',
963
963
  },
964
964
  {
965
965
  key: 'chat.input',
@@ -1030,8 +1030,8 @@ export const SYSTEM_GUIDE = [
1030
1030
  kind: 'button',
1031
1031
  en: 'Send',
1032
1032
  bg: 'Изпрати',
1033
- doesEn: 'Sends the message and starts it on the branch the folder is on; nothing is asked about branches. The Copilot window stays open when the work on it has ended, says so with an OK, and the next message works in it; close it with its X when nothing is at work. Closed in the middle of a message, it is opened again on its conversation and the answer asked for again, as many times as Settings → Execution allow (3 by default); then the message stops, and "Continue" carries it on.',
1034
- doesBg: 'Изпраща съобщението и го пуска на бранча, на който е папката; нищо не се пита за бранчове. Прозорецът на Copilot остава отворен, когато работата в него свърши, казва го с „ОК“ и следващото съобщение работи в него; затворете го с X, когато нищо не работи. Затворен по средата на съобщение, той се отваря отново на разговора си и отговорът се иска пак, толкова пъти, колкото позволява Настройки → Изпълнение (3 по подразбиране); после съобщението спира и „Продължи“ го продължава.',
1033
+ doesEn: 'Sends the message and starts it on the branch the folder is on. The Copilot window stays open when the work ends, says so with an OK, and the next message works in it; close it with its X when nothing works. Closed mid-message, it is opened again on its conversation and the answer asked again, as many times as Settings → Execution allow (3 by default); then the message stops, and "Continue" carries it on.',
1034
+ doesBg: 'Изпраща съобщението и го пуска на бранча, на който е папката. Прозорецът на Copilot остава отворен, когато работата свърши, казва го с „ОК“ и следващото съобщение работи в него; затворете го с X, когато нищо не работи. Затворен по средата на съобщение, се отваря отново на разговора си и отговорът се иска пак, колкото пъти позволява Настройки → Изпълнение (3 по подразбиране); после съобщението спира и „Продължи“ го продължава.',
1035
1035
  },
1036
1036
  {
1037
1037
  key: 'chat.sendNote',
@@ -1118,8 +1118,8 @@ export const SYSTEM_GUIDE = [
1118
1118
  kind: 'checkbox',
1119
1119
  en: 'Two chats',
1120
1120
  bg: 'Два чата',
1121
- doesEn: 'Two chats, for a new conversation: the message goes to a lead, which restates it, has a worker survey the project, plans, gives the worker one subtask at a time and judges each report, until the result is ready in the form asked for; the worker runs the commands. Both are conversations in the same Copilot window. A started conversation shows how it began. With it, there is no "Review": the lead judges the worker.',
1122
- doesBg: 'Два чата, за нов разговор: съобщението отива при ръководител, който го преразказва, пуска изпълнител да огледа проекта, прави план, дава на изпълнителя по една подзадача и преценява всеки доклад, докато резултатът стане готов в поискания вид; изпълнителят пуска командите. И двата са разговори в един и същ прозорец на Copilot. Започнатият разговор показва как е започнал. С него няма „Рецензия“: ръководителят преценява изпълнителя.',
1121
+ doesEn: 'Two chats, for a new conversation: the message goes to a lead, which restates it, has a worker survey the project, plans, gives the worker one subtask at a time and judges each report until the result is ready; the worker runs the commands. Both are conversations in the same Copilot window. With it, there is no "Review": the lead judges the worker.',
1122
+ doesBg: 'Два чата, за нов разговор: съобщението отива при ръководител, който го преразказва, пуска изпълнител да огледа проекта, прави план, дава на изпълнителя по една подзадача и преценява всеки доклад, докато резултатът е готов; изпълнителят пуска командите. И двата са разговори в един прозорец на Copilot. С него няма „Рецензия“: ръководителят преценява изпълнителя.',
1123
1123
  },
1124
1124
  {
1125
1125
  key: 'chat.kerrigan',
@@ -1470,8 +1470,8 @@ export const SYSTEM_GUIDE = [
1470
1470
  kind: 'button',
1471
1471
  en: 'Run this and the rest',
1472
1472
  bg: 'Изпълни тази и останалите',
1473
- doesEn: 'Runs it and stops asking for the rest of this message.',
1474
- doesBg: 'Изпълнява я и спира да пита за останалото от това съобщение.',
1473
+ doesEn: 'Runs it and stops asking for the rest of this message. Not offered where Settings do not let a run go on unasked (no isolation, no programs listed, a policy lock): the card says which.',
1474
+ doesBg: 'Изпълнява я и спира да пита за останалото от това съобщение. Не се предлага, където Настройки не позволяват това (без изолация, без изброени програми, заключване): картата казва кое.',
1475
1475
  },
1476
1476
  {
1477
1477
  key: 'chat.askSkip',
@@ -1517,8 +1517,8 @@ export const SYSTEM_GUIDE = [
1517
1517
  kind: 'button',
1518
1518
  en: 'Save',
1519
1519
  bg: 'Запази',
1520
- doesEn: 'Saves the file (also Ctrl+S), over the version that was opened: a file changed on disk meanwhile is not overwritten without asking. A tab with changes not saved has a dot; closing it asks first.',
1521
- doesBg: 'Запазва файла (и с Ctrl+S), върху версията, която е била отворена: файл, променен на диска междувременно, не се презаписва без питане. Раздел с незапазени промени има точка; затварянето му пита първо.',
1520
+ doesEn: 'Saves the file (also Ctrl+S), over the version that was opened: a file changed on disk meanwhile is not overwritten without asking. A tab with changes not saved has a dot; closing it asks first. Edits not saved are kept in this browser, by folder, with their tabs: back after Settings, a reload or another folder.',
1521
+ doesBg: 'Запазва файла (и с Ctrl+S), върху версията, която е била отворена: файл, променен на диска междувременно, не се презаписва без питане. Раздел с незапазени промени има точка; затварянето му пита първо. Незаписаните промени се пазят в този браузър, по папка, с табовете си: връщат се след Настройки, презареждане или друга папка.',
1522
1522
  },
1523
1523
  {
1524
1524
  key: 'ed.revert',
@@ -1786,8 +1786,8 @@ export const SYSTEM_GUIDE = [
1786
1786
  kind: 'tab',
1787
1787
  en: 'Problems',
1788
1788
  bg: 'Проблеми',
1789
- doesEn: 'What did not go well in the conversation open in the chat — a message that ended unfinished, stopped or at a limit, and why; a check that failed. A press on one opens it under its line: all of what it says (the line shows only its start), the review\'s evidence for a finding, what it comes from, when it happened, the chat and the message it is of; a second press folds it. The count is of the ones not marked seen. Empty on a new chat.',
1790
- doesBg: 'Какво не е минало добре в отворения в чата разговор — съобщение, завършило незавършено, спряно или при ограничение, и защо; проверка, която не е минала. Натискане на проблем го отваря под реда му: всичко, което казва (редът показва само началото), доказателството на прегледа за находка, от какво идва, кога се е случил, чатът и съобщението, към които е; второ натискане го свива. Броят е на тези, които не са отбелязани като видени. Празно при нов чат.',
1789
+ doesEn: 'What did not go well in the conversation open in the chat — a message that ended unfinished, stopped or at a limit, and why; a check that failed. A press opens one in full under its line — the review\'s evidence, where it comes from, when, its chat and message; a second press folds it. The count is of those not marked seen.',
1790
+ doesBg: 'Какво не е минало добре в отворения разговор — съобщение, завършило незавършено, спряно или при ограничение, и защо; проверка, която не е минала. Натискане го отваря изцяло под реда му — доказателството на прегледа, откъде идва, кога, чатът и съобщението му; второ натискане го свива. Броят е на неотбелязаните като видени.',
1791
1791
  },
1792
1792
  {
1793
1793
  key: 'wb.problemsInfoLabel',
@@ -1890,8 +1890,8 @@ export const SYSTEM_GUIDE = [
1890
1890
  kind: 'note',
1891
1891
  en: 'Waits for you',
1892
1892
  bg: 'Чака вас',
1893
- doesEn: 'The status of a task set aside while it waited for the operator: under it, its card with what it waits for, to answer now; it carries on from where it stopped at the queue\'s next turn.',
1894
- doesBg: 'Състоянието на задача, оставена настрана, докато е чакала оператора: под нея е картата ѝ с това, което чака, за отговор сега; продължава оттам, където е спряла, при следващия ход на опашката.',
1893
+ doesEn: 'The status of a task set aside while it waited for the operator: under it, its card with what it waits for, to answer now; it carries on from where it stopped at the queue\'s next turn. Taken out or run again, its chat\'s card closes and "Continue" carries it on there; answered, the queue carries it on.',
1894
+ doesBg: 'Състоянието на задача, оставена настрана, докато е чакала оператора: под нея е картата ѝ с това, което чака, за отговор сега; продължава оттам, където е спряла, при следващия ход на опашката. Махната или пусната отново, картата в чата ѝ се затваря и „Продължи“ я продължава там; отговорена — продължава я опашката.',
1895
1895
  },
1896
1896
  {
1897
1897
  key: 'pk.approve',
@@ -2591,8 +2591,8 @@ export const SYSTEM_GUIDE = [
2591
2591
  kind: 'button',
2592
2592
  en: 'Check the locators',
2593
2593
  bg: 'Провери локаторите',
2594
- doesEn: 'Opens the Copilot window, as reading the models does, and looks for each locator: the box and Send, the sidebar, the newest conversation (opened by its address) and its "More" menu (opened and closed again), and the steps to the chat. It only reads; nothing is sent or renamed. Under each field: found, not found (then in red, with the file for a chatbot), or not on the page then and why.',
2595
- doesBg: 'Отваря прозореца на Copilot, както при четенето на моделите, и търси всеки локатор: полето и „Send“, страничната лента, най-новия разговор (отворен по адреса му) и менюто му „More“ (отворено и затворено пак), и стъпките до чата. Само чете; нищо не се изпраща и не се преименува. Под всяко поле: намерен, не е намерен (тогава в червено, с файла за чатбота) или не е на страницата тогава и защо.',
2594
+ doesEn: 'Opens the Copilot window and looks for each locator — the box and Send, the sidebar, the newest conversation and its "More" menu (opened and closed again) — and the steps to the chat. It only reads; nothing is sent or renamed. Under each field: found, not found (in red, with the file for a chatbot), or not on the page then and why.',
2595
+ doesBg: 'Отваря прозореца на Copilot и търси всеки локатор — полето и „Send“, страничната лента, най-новия разговор и менюто му „More“ (отворено и затворено пак) — и стъпките до чата. Само чете; нищо не се изпраща и не се преименува. Под всяко поле: намерен, не е намерен (в червено, с файла за чатбота) или не е на страницата тогава и защо.',
2596
2596
  },
2597
2597
  {
2598
2598
  key: 'chatloc.composer',
@@ -3521,8 +3521,8 @@ export const SYSTEM_GUIDE = [
3521
3521
  kind: 'button',
3522
3522
  en: 'Change…',
3523
3523
  bg: 'Смени…',
3524
- doesEn: 'Opens a field for another folder (and the machine\'s folder dialog), with a checkbox to copy what is there now — settings, conversations, logs, the Edge profile — and the button that uses it. Nothing in the new folder is overwritten; it takes effect when the bot is started again. Not offered for a clone or when COP_HOME sets the folder, and refused while work is going on.',
3525
- doesBg: 'Отваря поле за друга папка (и прозореца за избор на папка), с отметка да се копира каквото има сега — настройки, разговори, логове, профилът на Edge — и бутона, който я ползва. Нищо в новата папка не се презаписва; важи, когато ботът се пусне отново. Не се предлага за клонинг или когато COP_HOME задава папката, и се отказва, докато върви работа.',
3524
+ doesEn: 'Opens a field for another folder (and the machine\'s folder dialog), with a checkbox to copy what is there now — settings, conversations, logs, the Edge profile — and the button that uses it. What the new folder has already is put aside beside it (<folder>.before-<when>), not used; it takes effect when the bot is started again. Not offered for a clone or when COP_HOME sets the folder, and refused while work is going on.',
3525
+ doesBg: 'Отваря поле за друга папка (и прозореца за избор на папка), с отметка да се копира каквото има сега — настройки, разговори, логове, профилът на Edge — и бутона, който я ползва. Каквото новата папка вече има, отива встрани до нея (<папка>.before-<кога>) и не се ползва; важи, когато ботът се пусне отново. Не се предлага за клонинг или когато COP_HOME задава папката, и се отказва, докато върви работа.',
3526
3526
  },
3527
3527
  {
3528
3528
  key: 'sys.homeReset',
@@ -66,7 +66,11 @@ export const KerriganReplySchema = z
66
66
  skill: z.preprocess((v) => (v === undefined || v === null ? undefined : String(v).trim().replace(/^\//, '')), z.string().optional()),
67
67
  // answer
68
68
  option: number.optional(),
69
- options: z.preprocess((v) => (v === undefined || v === null ? undefined : Array.isArray(v) ? v : [v]), z.array(z.union([number, z.string()])).optional()),
69
+ /*
70
+ * The numbers of the answers chosen (status "answer", read by number there), or the answers she offers the person
71
+ * (status "ask"): kept as written (third hunt, 2026-11-20). Read as numbers here, "Use Node 20" became 20 on the card.
72
+ */
73
+ options: z.preprocess((v) => (v === undefined || v === null ? undefined : Array.isArray(v) ? v : [v]), z.array(z.union([z.number(), z.string()])).optional()),
70
74
  text: prose,
71
75
  decision: z.preprocess((v) => (typeof v === 'string' ? v.trim().toLowerCase() : v), z.enum(['approve', 'revise'], { message: 'decision is "approve" or "revise".' })).optional(),
72
76
  note: prose,
@@ -21,8 +21,8 @@ const CommandStep = z.object({
21
21
  */
22
22
  type: z.literal('command', {
23
23
  error: 'this runner has no file steps: it never fetches or runs a file the chat provides. Every step is ' +
24
- 'a `command`. For something too long for one line, write the file with Set-Content in one command ' +
25
- 'step and run it with its interpreter in the next.',
24
+ 'a `command`. For something too long for one line, put it in the command itself: a command may be ' +
25
+ 'several lines. Never write a script only to run it.',
26
26
  }),
27
27
  shell: ShellSchema.optional(),
28
28
  cmd: z.string().min(1),
@@ -141,6 +141,92 @@ export function mergeItems(current, edited) {
141
141
  });
142
142
  return { items };
143
143
  }
144
+ /**
145
+ * An edit a page made on the list it had read (`seen`), put onto the queue as it is now (second bug hunt, 2026-11-19).
146
+ * The page sends the whole list, and a list read before a change — a second tab, or a page that had not read again yet —
147
+ * dropped a task added since, put back one taken out since (to run again), and undid an edit made elsewhere. What this
148
+ * page changed is taken; what it did not touch stays as the queue has it now:
149
+ * - a task added since stays, after the tasks it came after;
150
+ * - one taken out since stays out;
151
+ * - a field this page did not change keeps the queue's value, so an edit made elsewhere is not undone;
152
+ * - the order is this page's when it moved something, else the queue's.
153
+ * A new task whose id was given meanwhile to another gets one of its own.
154
+ */
155
+ export function rebaseEdit(current, seen, edited) {
156
+ const saw = new Map(seen.map((x) => [x.id, x]));
157
+ const now = new Map(current.map((x) => [x.id, x]));
158
+ const taken = new Set([...current.map((x) => x.id), ...seen.map((x) => x.id)]);
159
+ const renamed = new Map();
160
+ const kept = new Map();
161
+ const fresh = [];
162
+ const pageOrder = [];
163
+ for (const e of edited) {
164
+ const was = saw.get(e.id);
165
+ if (!was) {
166
+ let id = e.id;
167
+ while (taken.has(id))
168
+ id = `${id}x`;
169
+ taken.add(id);
170
+ if (id !== e.id)
171
+ renamed.set(e.id, id);
172
+ const dependsOn = e.dependsOn.map((d) => renamed.get(d) ?? d);
173
+ fresh.push({ ...e, id, dependsOn });
174
+ pageOrder.push(id);
175
+ continue;
176
+ }
177
+ const is = now.get(e.id);
178
+ if (!is)
179
+ continue;
180
+ const out = { id: e.id };
181
+ for (const key of GIVEN) {
182
+ if (key === 'id')
183
+ continue;
184
+ const v = asSaid(e[key]) === asSaid(was[key]) ? is[key] : e[key];
185
+ if (v !== undefined)
186
+ out[key] = v;
187
+ }
188
+ if (e.status)
189
+ out.status = e.status;
190
+ kept.set(e.id, out);
191
+ pageOrder.push(e.id);
192
+ }
193
+ const knownOnPage = pageOrder.filter((id) => kept.has(id));
194
+ const moved = knownOnPage.join('\n') !== seen.map((x) => x.id).filter((id) => kept.has(id)).join('\n');
195
+ const since = current.filter((x) => !saw.has(x.id));
196
+ let order;
197
+ if (moved) {
198
+ order = [...pageOrder];
199
+ // After every task it came after: one added at the end stays at the end.
200
+ for (const x of since) {
201
+ const i = current.indexOf(x);
202
+ const at = Math.max(0, ...current.slice(0, i).map((o) => order.indexOf(o.id) + 1));
203
+ order.splice(at, 0, x.id);
204
+ }
205
+ }
206
+ else {
207
+ order = [...current.filter((x) => kept.has(x.id) || !saw.has(x.id)).map((x) => x.id), ...fresh.map((x) => x.id)];
208
+ }
209
+ const byId = new Map([...kept, ...fresh.map((x) => [x.id, x]), ...since.map((x) => [x.id, asGiven(x)])]);
210
+ // What a task depends on is a task before it that is still there.
211
+ const before = new Set();
212
+ return order.map((id) => {
213
+ const x = byId.get(id);
214
+ const dependsOn = x.dependsOn.filter((d) => before.has(d));
215
+ before.add(id);
216
+ return dependsOn.length === x.dependsOn.length ? x : { ...x, dependsOn };
217
+ });
218
+ }
219
+ /**
220
+ * Whether an edit leaves a task carrying on in its own chat, as `mergeItems` keeps it: one that carries on, with nothing
221
+ * of what it does changed. It goes on as it was given there, its skill sent with it already, so a skill taken out of
222
+ * Settings since is not its concern (second bug hunt, 2026-11-19: it blocked every edit of the queue).
223
+ */
224
+ export function carriesOn(was, edit) {
225
+ if (!was.resume || was.status !== 'waiting')
226
+ return false;
227
+ const given = asGiven(edit);
228
+ return !WHAT_IT_DOES.some((key) => asSaid(was[key]) !== asSaid(given[key]));
229
+ }
144
230
  /** What the operator gives a task, apart from what its runs give it. */
145
231
  const GIVEN = ['id', 'name', 'prompt', 'model', 'dependsOn', 'branch', 'review', 'reviewModel', 'lead', 'workerModel', 'skill', 'plan'];
146
232
  /** Of what is given, what the task's chat is told: an edit of it starts over a task that carries on. */
@@ -197,6 +283,13 @@ export function skippedBecause(because) {
197
283
  const what = because.status === 'failed' ? 'failed' : because.status === 'stopped' ? 'was stopped' : because.status === 'skipped' ? 'was skipped' : `has not run (${because.status})`;
198
284
  return `it depends on "${itemTitle(because)}", which ${what}`;
199
285
  }
286
+ /**
287
+ * Whether the queue holds a chat for this task: set aside with its card, or carrying on in it at its next turn. A task
288
+ * the queue lets go of — taken out, run again, started over — has its chat's card closed (2026-11-19).
289
+ */
290
+ export function holdsChat(x) {
291
+ return !!x.sessionId && (x.status === 'parked' || (x.status === 'waiting' && x.resume === true));
292
+ }
200
293
  /** A task's status from how its message ended. */
201
294
  export function statusOfTask(taskStatus) {
202
295
  return taskStatus === 'done' ? 'done' : taskStatus === 'aborted' ? 'stopped' : 'failed';
@@ -86,20 +86,24 @@ const PARKED_FOR = {
86
86
  model: 'for the operator to choose the model by hand',
87
87
  password: 'for a password Git asked for in its own window',
88
88
  };
89
- export function whyItStopped(c) {
89
+ /**
90
+ * `committed`: whether what the task had changed was committed for it — not in the operator's chat, where nothing is
91
+ * branched or committed (third hunt, 2026-11-20: "what had changed is committed on this branch" was said there, beside
92
+ * the note that nothing is).
93
+ */
94
+ export function whyItStopped(c, committed = true) {
95
+ const kept = committed ? ', and what had changed is committed on this branch.' : '.';
90
96
  if (c.how === 'failed')
91
97
  return describeEnding(c.fromAttempt, c.ended, c.stoppedBecause);
92
98
  if (c.how === 'interrupted') {
93
99
  const where = c.interruption ? `\n\n${describeInterruption(c.interruption)}\n\n` : ' ';
94
100
  return ('The runner stopped unexpectedly while this task was in progress — the program was closed, the machine went off or it ' +
95
- 'crashed; nothing you did failed — and it has now started again. The files are as your work left them, and what had ' +
96
- `changed is committed on this branch.${where}`.trimEnd());
101
+ `crashed; nothing you did failed — and it has now started again. The files are as your work left them${kept}${where}`.trimEnd());
97
102
  }
98
103
  if (c.how === 'parked') {
99
104
  const what = c.parkedFor ? PARKED_FOR[c.parkedFor] : 'for the operator';
100
105
  return (`It waited ${what}, and was set aside so that the queue's other tasks could run while nobody was there — not because ` +
101
- 'anything failed. The operator has answered now: the answer is below. The files are as you left them, and what had ' +
102
- 'changed is committed on this branch.');
106
+ `anything failed. The operator has answered now: the answer is below. The files are as you left them${kept}`);
103
107
  }
104
108
  if (c.how === 'stopped') {
105
109
  const where = c.interruption ? `\n\n${describeInterruption(c.interruption).replace(/when the runner stopped/g, 'when it was stopped')}\n\n` : ' ';
@@ -169,10 +173,10 @@ export function composeOpening(input) {
169
173
  * operator approved — but plan first, as the plan-mode note says, and nothing changes until the plan is approved.
170
174
  */
171
175
  if (input.planNote) {
172
- const message = `Continue task ${input.taskNumber}: ${title}, in this same conversation. ${whyItStopped(input.continuing)} ` +
176
+ const message = `Continue task ${input.taskNumber}: ${title}, in this same conversation. ${whyItStopped(input.continuing, !input.noCommits)} ` +
173
177
  `Its plan was not approved yet, so the work does not go on from where it stopped: plan first, as below — look at ` +
174
178
  `what is there now, changing nothing — and send the plan for approval. Step numbering restarts at 1.\n\n` +
175
- `${input.planNote}\n\n` +
179
+ // The plan-mode note once, with the runner's notes below (second bug hunt, 2026-11-19: it was sent twice).
176
180
  (instruction ? `${instructionSection(instruction.text)}\n\n` : '') +
177
181
  `${runnerBlock(input)}`.trimEnd();
178
182
  return { messages: [message], firstMessage: message };
@@ -183,7 +187,7 @@ export function composeOpening(input) {
183
187
  */
184
188
  if (input.continuing.how === 'failed' && instruction) {
185
189
  const message = `Continue task ${input.taskNumber}: ${title}, in this same conversation, with a new instruction from the operator.\n\n` +
186
- `${whyItStopped(input.continuing)}\n\n` +
190
+ `${whyItStopped(input.continuing, !input.noCommits)}\n\n` +
187
191
  `The files are as that attempt left them, and what it changed is in your working tree. Do not start over: look at ` +
188
192
  `what is there first, keep what is right, and do what the instruction below says. The assignment is the one you ` +
189
193
  `were given above, with the instruction added to it. Verify the result as for any task. Step numbering restarts at 1.\n\n` +
@@ -192,7 +196,7 @@ export function composeOpening(input) {
192
196
  return { messages: [message], firstMessage: message };
193
197
  }
194
198
  const message = `Continue task ${input.taskNumber}: ${title}, in this same conversation. ` +
195
- `${whyItStopped(input.continuing)} ` +
199
+ `${whyItStopped(input.continuing, !input.noCommits)} ` +
196
200
  `Do not start over and do not repeat work that is done: start from ` +
197
201
  `your plan, say in \`notes\` which stages are done and which one you are on, and carry on. ` +
198
202
  (instruction
@@ -202,7 +206,7 @@ export function composeOpening(input) {
202
206
  return { messages: [message], firstMessage: message };
203
207
  }
204
208
  const continuationLine = input.continuing
205
- ? `\n\nThis continues an earlier attempt at this task. ${whyItStopped(input.continuing)}` +
209
+ ? `\n\nThis continues an earlier attempt at this task. ${whyItStopped(input.continuing, !input.noCommits)}` +
206
210
  (input.continuing.how === 'failed'
207
211
  ? `\n\nWhat that attempt changed is in your working tree. Look at it before changing anything, keep what is right, and do what the instruction below says.`
208
212
  : ` Look at what is already done before changing anything, and carry on from there.`) +
@@ -4,8 +4,8 @@
4
4
  * each. Kept in the data folder, so a failure seen before a restart is still shown; read by the banner on every page
5
5
  * and by Settings, where the locator's field is in red, until the locator is changed there or the operator closes it.
6
6
  */
7
- import { readFile } from 'node:fs/promises';
8
- import { writeFileAtomically } from './store.js';
7
+ import { rename } from 'node:fs/promises';
8
+ import { readStoreJson, StoreFileUnusable, writeFileAtomically } from './store.js';
9
9
  import { CHAT_LOCATOR_KEYS } from '../transport/locators.js';
10
10
  import { isStepKey } from '../transport/chatSteps.js';
11
11
  const isKey = (k) => typeof k === 'string' && (CHAT_LOCATOR_KEYS.includes(k) || isStepKey(k));
@@ -16,14 +16,33 @@ export class LocatorFailures {
16
16
  constructor(file) {
17
17
  this.file = file;
18
18
  }
19
+ /** As kept, for the banner and Settings: one that cannot be read shows none (the change below refuses it). */
19
20
  async list() {
21
+ return await this.read().catch(() => []);
22
+ }
23
+ /** As kept; one there but not readable is refused (2026-11-19), so a change never writes it over. */
24
+ async read() {
25
+ const raw = await readStoreJson(this.file);
26
+ if (!Array.isArray(raw))
27
+ return [];
28
+ return raw.filter((f) => !!f && typeof f === 'object' && isKey(f.key) && typeof f.locator === 'string' && typeof f.at === 'string');
29
+ }
30
+ /**
31
+ * As kept, or — the file there but not readable, after a power cut say — the file moved aside beside itself and the
32
+ * list begun again (third hunt, 2026-11-20): refused, every failure after it was dropped without a word, and the banner,
33
+ * the red field and the file for a chatbot were gone for good. These are notices, kept since; nothing of the operator's
34
+ * is lost, and where the old one went is said.
35
+ */
36
+ async readOrPutAside() {
20
37
  try {
21
- const raw = JSON.parse(await readFile(this.file, 'utf8'));
22
- if (!Array.isArray(raw))
23
- return [];
24
- return raw.filter((f) => !!f && typeof f === 'object' && isKey(f.key) && typeof f.locator === 'string' && typeof f.at === 'string');
38
+ return await this.read();
25
39
  }
26
- catch {
40
+ catch (e) {
41
+ if (!(e instanceof StoreFileUnusable))
42
+ throw e;
43
+ const aside = `${this.file}.unreadable-${new Date().toISOString().replace(/[:.]/g, '-')}`;
44
+ await rename(this.file, aside);
45
+ console.error(`[locators] ${this.file} could not be read; moved to ${aside}, and the list begun again`);
27
46
  return [];
28
47
  }
29
48
  }
@@ -34,12 +53,13 @@ export class LocatorFailures {
34
53
  async record(failure) {
35
54
  await this.change((all) => [failure, ...all.filter((f) => f.key !== failure.key)]);
36
55
  }
37
- /** Closed by the operator. True when there was one. */
38
- async dismiss(key) {
56
+ /** Closed by the operator, or found after all; with `locator`, only while it is the one kept. True when there was one. */
57
+ async dismiss(key, locator) {
39
58
  let had = false;
59
+ const goes = (f) => f.key === key && (locator === undefined || f.locator === locator);
40
60
  await this.change((all) => {
41
- had = all.some((f) => f.key === key);
42
- return all.filter((f) => f.key !== key);
61
+ had = all.some(goes);
62
+ return all.filter((f) => !goes(f));
43
63
  });
44
64
  return had;
45
65
  }
@@ -50,7 +70,7 @@ export class LocatorFailures {
50
70
  */
51
71
  async change(edit) {
52
72
  const run = async () => {
53
- await writeFileAtomically(this.file, async () => JSON.stringify(edit(await this.list()), null, 2));
73
+ await writeFileAtomically(this.file, async () => JSON.stringify(edit(await this.readOrPutAside()), null, 2));
54
74
  };
55
75
  const done = this.queue.then(run, run);
56
76
  this.queue = done.catch(() => undefined);
@@ -12,6 +12,29 @@ export function tidyVcsPlan(plan) {
12
12
  return undefined;
13
13
  return { ...(branch ? { branch } : {}), ...(commitMessage ? { commitMessage } : {}) };
14
14
  }
15
+ /**
16
+ * The approved plan a task works to: its own attempt's, else, carried on, the latest one approved in the conversation it
17
+ * carries on — back through the attempts it continues, to the one that began that conversation. Not one before it
18
+ * (second bug hunt, 2026-11-19): a plan approved before a retry in a fresh conversation was taken by a message carried
19
+ * on after that retry, and it went to the work on a plan its conversation never saw.
20
+ */
21
+ export function approvedPlanOf(task) {
22
+ if (task.plan?.approved)
23
+ return task.plan;
24
+ if (!task.continuing)
25
+ return undefined;
26
+ for (const a of [...(task.attempts ?? [])].reverse()) {
27
+ if (a.plan?.approved)
28
+ return a.plan;
29
+ if (!a.continuing || a.freshRetry)
30
+ return undefined;
31
+ }
32
+ return undefined;
33
+ }
34
+ /** Whether a set-aside task's card is over — stopped, or let go of by the queue — so that "Continue" carries it on. */
35
+ export function parkedOver(parked) {
36
+ return !parked || parked.answer?.kind === 'stopped' || parked.answer?.kind === 'released';
37
+ }
15
38
  export const clipText = (s, n) => {
16
39
  const t = (s ?? '').trim();
17
40
  if (!t)
@@ -786,6 +786,53 @@ function inTurn(path, work) {
786
786
  * setting put back whatever another had changed in between. If it throws, nothing is written. Like
787
787
  * any work in a turn, it must not wait for another turn on the same file (see `inTurn`).
788
788
  */
789
+ /**
790
+ * A file of the bot's own records that is there but cannot be used (2026-11-19). Read as empty, it was written over by
791
+ * the next change: a queue.json the machine lost power over, or another program held, came back as an empty queue,
792
+ * and the next task added wrote it over — every task and every card kept for the operator gone, without a word. As
793
+ * `SettingsUnusableError` refuses for settings.json.
794
+ */
795
+ export class StoreFileUnusable extends Error {
796
+ path;
797
+ constructor(path, problem) {
798
+ super(`${path} ${problem}. Nothing has been saved over it: mend it, or move it away to start that list again empty.`);
799
+ this.path = path;
800
+ this.name = 'StoreFileUnusable';
801
+ }
802
+ }
803
+ /**
804
+ * A JSON file of the bot's own records, read to be changed and written back: undefined when it is not there or holds
805
+ * nothing (a list not begun); a moment's lock by another program — a virus scanner, a sync client — waited out, as a
806
+ * write's is (`moveOver`); anything else refused (`StoreFileUnusable`), so it is never written over.
807
+ */
808
+ export async function readStoreJson(path) {
809
+ const backoffMs = [10, 25, 60, 120, 250, 500];
810
+ for (let attempt = 0;; attempt += 1) {
811
+ let text;
812
+ try {
813
+ text = await readFile(path, 'utf8');
814
+ }
815
+ catch (e) {
816
+ const code = e.code ?? '';
817
+ if (code === 'ENOENT')
818
+ return undefined;
819
+ if ((code === 'EBUSY' || code === 'EPERM' || code === 'EACCES') && attempt < backoffMs.length) {
820
+ await new Promise((r) => setTimeout(r, backoffMs[attempt]));
821
+ continue;
822
+ }
823
+ throw new StoreFileUnusable(path, `could not be read (${code || e.message})`);
824
+ }
825
+ const body = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
826
+ if (body.trim() === '')
827
+ return undefined;
828
+ try {
829
+ return JSON.parse(body);
830
+ }
831
+ catch (e) {
832
+ throw new StoreFileUnusable(path, `is not valid JSON (${e.message})`);
833
+ }
834
+ }
835
+ }
789
836
  export async function writeFileAtomically(path, content) {
790
837
  await inTurn(path, async () => replaceFile(path, typeof content === 'string' ? content : await content()));
791
838
  }