robisie 0.5.45 → 0.5.47

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # Historia zmian klienta / Client changelog
2
2
 
3
+ ## [0.5.47](https://github.com/chuppa12/robisie-app/compare/client-v0.5.46...client-v0.5.47) (2026-11-16)
4
+
5
+
6
+ ### Factory Cards
7
+
8
+ * praca workera task-mwixhhhn-z0hhj3 (auto-commit) ([af878e9](https://github.com/chuppa12/robisie-app/commit/af878e9afe2ed648c39aa7c01edcc337ca0c1221))
9
+
10
+ ## [0.5.46](https://github.com/chuppa12/robisie-app/compare/client-v0.5.45...client-v0.5.46) (2026-11-16)
11
+
12
+
13
+ ### Factory Cards
14
+
15
+ * flaga --effort Groka z osobnej zmiennej, receipt effort zostaje none (walidator klienta tick.ts:5062); atrapa Groka przyjmuje --effort ([353399a](https://github.com/chuppa12/robisie-app/commit/353399a7d2e3e5f104e366703d40a773e49d9254))
16
+ * praca workera task-mwizhyqk-1dtx7a (auto-commit) ([e814c19](https://github.com/chuppa12/robisie-app/commit/e814c19ffd38185d2b44c1a3aff9d10fad714634))
17
+ * praca workera task-mwj1ycmq-rv3ixk (auto-commit) ([51e40b4](https://github.com/chuppa12/robisie-app/commit/51e40b465192e348daa5d20cde960a7d32089f31))
18
+ * praca workera task-mwj2iwcu-tu7d05 (auto-commit) ([8b542ed](https://github.com/chuppa12/robisie-app/commit/8b542edf6bd84c41c36f2614f29f93cdd92b5cb9))
19
+ * praca workera task-mwj3zz6g-pd7sfw (auto-commit) ([1ce1765](https://github.com/chuppa12/robisie-app/commit/1ce1765c3fc9a5abf2677857e1a7fad41e916eb4))
20
+ * praca workera task-mwj54vqb-w5zy7c (auto-commit) ([50f8e0a](https://github.com/chuppa12/robisie-app/commit/50f8e0ad5b4c36f5d7d81e5e42facfb7f5013da0))
21
+ * praca workera task-mwj6ptow-aozigb (auto-commit) ([6c870f8](https://github.com/chuppa12/robisie-app/commit/6c870f8e915a1ac817da48bf32c8ab00ceb984be))
22
+ * praca workera task-mwj7ff7g-i59rea (auto-commit) ([71bb19b](https://github.com/chuppa12/robisie-app/commit/71bb19b3d1cb1ff9a53ac486ebe7237ce2b25f81))
23
+ * recenzent Grok dostaje jawny --effort (host low, klient z roli; none → low), żeby runda mieściła się w budżecie 45 min ([47a969f](https://github.com/chuppa12/robisie-app/commit/47a969fbc91664e33cd44ff9418677cbcab7d104))
24
+ * recenzent Grok dostaje jawny --effort (Z4 timeout) ([fdcaab5](https://github.com/chuppa12/robisie-app/commit/fdcaab5d83f8465414d852c7797cbdbcef7ac545))
25
+ * recenzent Grok dostaje jawny --effort (Z4 timeout) ([fdcaab5](https://github.com/chuppa12/robisie-app/commit/fdcaab5d83f8465414d852c7797cbdbcef7ac545))
26
+
3
27
  ## [0.5.45](https://github.com/chuppa12/robisie-app/compare/client-v0.5.44...client-v0.5.45) (2026-11-16)
4
28
 
5
29
 
package/README.md CHANGED
@@ -181,38 +181,20 @@ Przed aktualizacją wymagany jest brak plików `.tester-job.lock`, `.tester-job.
181
181
 
182
182
  Aktualizuj w katalogu instalacji po prywatnej kopii opisanej w przewodnikach, z tym samym XDG_CONFIG_HOME i CODEX_HOME. `npx robisie init` odświeża zapisanych agentów i mapę ról, używając poprawnego zapisanego klucza bez ponownego wpisywania. W ręcznej instalacji bez login ROBISIE_KEY ma pierwszeństwo; jawny `--key-stdin` zachowuje tor pytania/stdin i umożliwia wymianę klucza. Bez zapisanej instalacji lub przy braku/pustym kluczu init korzysta z dotychczasowego pytania. Wadliwy niepusty klucz, błąd odczytu lub dowiązanie wymagają naprawy lokalnej, bez nadpisywania.
183
183
 
184
- Doctor podaje rzeczywiste wersje starych pomocników i markerów ról oraz wersję paczki; wskazane init aktualizuje je przez zwykły zapis z kopiami. Po login doctor używa plików A/B z ostrzeżeniem przy różnym starym ENV; ręczny doctor wymaga obu ENV, a osobni agenci używają źródeł zależnych od dostawcy opisanych wyżej. Poniższy przykład usuwa wcześniejszy ROBISIE_KEY z sesji, aby init użył zapisanego pliku; po init wczytuje ENV dla doctor i agentów, bez xtrace i bez wydruku:
184
+ Doctor podaje rzeczywiste wersje starych pomocników i markerów ról oraz wersję paczki; wskazane init aktualizuje je przez zwykły zapis z kopiami. Po login doctor używa plików A/B z ostrzeżeniem przy różnym starym ENV; ręczny doctor wymaga obu ENV, a osobni agenci używają źródeł zależnych od dostawcy opisanych wyżej. Komenda update czyta klucze instalacji z chronionych plików, bez ponownego wpisywania i bez ich wydruku:
185
185
 
186
186
  Kopia i odtworzenie obejmują oba pliki key i review-key z prywatnymi uprawnieniami; przed init/doctor wczytaj oba odtworzone klucze. Uninstall raportuje osobno stan obu plików i usuwa je z zachowaniem dotychczasowej ochrony ewidencji oraz konfiguracji. Nie unieważnia żadnego klucza na serwerze.
187
187
 
188
+ Zwykła aktualizacja to `npx robisie update` (host: dodaj `--engine-config /absolutna/sciezka/robisie.config.json`). Pierwsze interaktywne wywołanie pyta jawnie o zgodę i zapisuje `update={consentedAt, enabled:true}`, zachowując pozostałe pola konfiguracji. Bez zgody lub przy `enabled:false` wywołanie w tle kończy się kodem 0 bez zmian. Po zgodzie launchd `com.robisie.update` albo `robisie-update.timer` uruchamia tę samą komendę co 120 sekund; fabryka wykonuje `factory run --once` na osobnym cyklu 120 sekund. Paczka przygotowuje dokładną wersję npm w osobnym katalogu, sprawdza build-id i integralność, potem wymienia prywatny wskaźnik current. Zdrowie wymaga dwóch różnych świeżych taktów OK z loaded oczekiwanego build-id w 1200 sekund, odczytywanych co 20 sekund. Przy błędzie powrót ma osobne okno 1200 sekund dla starego wydania; zarówno potwierdzony, jak i niepotwierdzony powrót ma kod niezerowy. Nowa praca blokuje przełączenie lub powrót. Host bez transportu tablicy poza tick odmawia jawnie; komenda nie dodaje klienta DB. Prywatny audyt i próby znajdziesz w `<stateDir>/update/`; błąd przygotowania też zapisuje wersję. Aby ponowić po wyjaśnieniu przyczyny, usuń jedną linię tej wersji z `attempts.jsonl`. Odroczenie nie oznacza nieudanej próby; po 7200 sekund zapisuje jeden alarm. `AUTO-UPDATE.off` nie steruje produktem. Zachowaj prywatną kopię i osobny awaryjny restore archiwum. Po odświeżeniu ról uruchom ponownie asystenta.
189
+
188
190
  <!-- update:start -->
189
191
  ```sh
190
192
  set +x
191
- unset ROBISIE_KEY ROBISIE_REVIEW_KEY &&
192
- npm i robisie@latest &&
193
- npx robisie init &&
194
- {
195
- if [ ! -L "${XDG_CONFIG_HOME:-$HOME/.config}/robisie/key" ] &&
196
- [ -f "${XDG_CONFIG_HOME:-$HOME/.config}/robisie/key" ] &&
197
- [ -r "${XDG_CONFIG_HOME:-$HOME/.config}/robisie/key" ] &&
198
- [ ! -L "${XDG_CONFIG_HOME:-$HOME/.config}/robisie/review-key" ] &&
199
- [ -f "${XDG_CONFIG_HOME:-$HOME/.config}/robisie/review-key" ] &&
200
- [ -r "${XDG_CONFIG_HOME:-$HOME/.config}/robisie/review-key" ] &&
201
- ROBISIE_REVIEW_KEY="$(cat "${XDG_CONFIG_HOME:-$HOME/.config}/robisie/review-key" 2>/dev/null)" &&
202
- [ -n "$ROBISIE_REVIEW_KEY" ] &&
203
- ROBISIE_KEY="$(cat "${XDG_CONFIG_HOME:-$HOME/.config}/robisie/key" 2>/dev/null)" &&
204
- [ -n "$ROBISIE_KEY" ]; then
205
- export ROBISIE_KEY ROBISIE_REVIEW_KEY
206
- else
207
- printf '%s\n' 'Nie można wczytać obu niepustych, zwykłych, czytelnych plików kluczy robisie (key, review-key).' 'Następny krok: sprawdź lokalnie plik klucza i jego odczyt; wyjaśnij link/katalog bez nadpisywania danych. Przy braku lub odmowie B podaj nowy owner_validator przez ROBISIE_REVIEW_KEY do init; --key-stdin wymienia tylko A. Nie wklejaj klucza do rozmowy.' >&2
208
- false
209
- fi
210
- } &&
211
- npx robisie doctor
193
+ npx robisie update
212
194
  ```
213
195
  <!-- update:end -->
214
196
 
215
- Doctor sprawdza MAJOR kontraktu. Przy niezgodności wybierz zgodne wydanie. Poprzedni zgodny tgz przygotuj przez `npm pack robisie@<wersja>`; komenda powrotu `npm i --no-save "$backup/robisie-$previous_version.tgz"` wymaga jawnie wybranej wersji, prywatnej kopii konfiguracji i porównania późniejszych własnych zmian według przewodników. Opcja `--no-save` zachowuje przywrócone `package.json` i `package-lock.json`, bez zapisywania zależności `file:` od ścieżki prywatnej kopii. Kolejność powrotu: konfiguracja i OBA manifesty projektu (`package.json`, `package-lock.json`) → ENV starego klucza → tgz → init → doctor. To nie jest automatyczny rollback.
197
+ Doctor sprawdza MAJOR kontraktu. Przy niezgodności wybierz zgodne wydanie. Poprzedni zgodny tgz przygotuj przez `npm pack robisie@<wersja>`; komenda powrotu `npm i --no-save "$backup/robisie-$previous_version.tgz"` wymaga jawnie wybranej wersji, prywatnej kopii konfiguracji i porównania późniejszych własnych zmian według przewodników. Opcja `--no-save` zachowuje przywrócone `package.json` i `package-lock.json`, bez zapisywania zależności `file:` od ścieżki prywatnej kopii. Kolejność powrotu: konfiguracja i OBA manifesty projektu (`package.json`, `package-lock.json`) → ENV starego klucza → tgz → init → doctor. Ten awaryjny restore archiwum jest osobny od automatycznego powrotu wskaźnika po niezdrowej aktualizacji.
216
198
 
217
199
  Pomocniki uruchamiaj z cwd instalacji przez `npx robisie mcp <nazwa>`; init nadal generuje transport dla wersji paczki. npx może pobrać brakującą wersję z sieci. Bez instalacji zacznij od konta → init; przy istniejącej instalacji rozwiąż błędy ewidencji i odczytu klucza przed błędami sieci. Odinstalowanie może zmienić package.json, package-lock.json i node_modules; cache npm może zostać, a npx może pobrać paczkę ponownie. Bez masowego kasowania. Windows/WSL są niezweryfikowane.
218
200
 
package/dist/cli.js CHANGED
@@ -8,6 +8,7 @@ import { doctor, doctorClientPair, init, recoveryStep, uninstall } from "./comma
8
8
  import { HELPER_SERVERS, PACKAGE_VERSION } from "./constants.js";
9
9
  import { RobisieError, errorMessage, nodeCtx } from "./context.js";
10
10
  import { DEFAULT_LOGIN_TIMEOUT_SECONDS } from "./device-login.js";
11
+ import { runInstallationUpdate } from "./installation-update.js";
11
12
  import { runFactory } from "./factory-run.js";
12
13
  import { CONFIG_FILE, loadEngineConfig } from "./engine-config.js";
13
14
  import { checkInputs, inputDirectory, INPUTS_OK, selectInputDirectory } from "./engine-inputs.js";
@@ -29,6 +30,7 @@ const HELP = `robisie ${PACKAGE_VERSION} — łączy Twojego agenta z tablicą r
29
30
  npx robisie login paruje instalację: kod i link zatwierdzasz w przeglądarce, klucze A i B trafiają prosto do plików
30
31
  npx robisie init klucze A (ROBISIE_KEY) i B (ROBISIE_REVIEW_KEY), osobne ukryte pytania + konfiguracja MCP + role klienta
31
32
  npx robisie doctor sprawdza A i B, wersję kontraktu, role i politykę enforced projektu
33
+ npx robisie update aktualizuje instalację; przy niezdrowym wydaniu sprawdza powrót do poprzedniej wersji
32
34
  npx robisie uninstall usuwa wpisy robisie i role; zachowuje kopie zapasowe
33
35
  npx robisie factory run nadzoruje takty (Linux/local klienta; Linux lub macOS jawnego hosta; Node.js >=24)
34
36
  npx robisie usage --input ./usage.json
@@ -36,6 +38,10 @@ const HELP = `robisie ${PACKAGE_VERSION} — łączy Twojego agenta z tablicą r
36
38
  npx robisie mcp <${HELPER_SERVERS.join("|")}>
37
39
  pomocnik ról (serwer MCP stdio) — uruchamia go agent, nie Ty
38
40
 
41
+ Opcje update:
42
+ --engine-config <path> lub --engine-config=<path> konfiguracja jak factory run; pierwsze interaktywne wywołanie pyta o zgodę
43
+ Bez konfiguracji domyślnej instaluje tylko robisie@latest; bez zgody w tle nic nie zmienia.
44
+
39
45
  Opcje factory run:
40
46
  --engine-config <path> plik konfiguracji; flaga wygrywa z ROBISIE_ENGINE_CONFIG
41
47
  --engine-config=<path> klient: local i stan poza repo; host: mode:host, pr|delivered i istniejący stan
@@ -105,8 +111,8 @@ export function parseArgs(argv) {
105
111
  }
106
112
  if (arg === "--engine-config" || arg.startsWith("--engine-config=")) {
107
113
  const step = "Użyj `npx robisie doctor --engine-config <path>` z jedną niepustą ścieżką pliku.";
108
- if (command !== "init" && command !== "doctor" && command !== "factory")
109
- throw new RobisieError("Opcja --engine-config jest dostępna tylko dla poleceń init, doctor i factory run.", step);
114
+ if (command !== "init" && command !== "doctor" && command !== "factory" && command !== "update")
115
+ throw new RobisieError("Opcja --engine-config jest dostępna tylko dla poleceń init, doctor, factory run i update.", step);
110
116
  if (engineConfig !== null)
111
117
  throw new RobisieError("Opcję --engine-config można podać tylko raz.", step);
112
118
  const value = arg === "--engine-config" ? args.shift() ?? "" : arg.slice("--engine-config=".length);
@@ -287,6 +293,8 @@ export async function run(argv, ctx) {
287
293
  return await doctor(ctx);
288
294
  case "uninstall":
289
295
  return uninstall(ctx);
296
+ case "update":
297
+ return await runInstallationUpdate(ctx, { engineConfig: args.engineConfig });
290
298
  case "factory":
291
299
  return await runFactory(ctx, { engineConfig: args.engineConfig, interval: args.interval, once: args.once });
292
300
  case "mcp":
@@ -1,6 +1,6 @@
1
1
  /** Package identity and the server contract it speaks. */
2
2
  export declare const PACKAGE_NAME = "robisie";
3
- export declare const PACKAGE_VERSION = "0.5.45";
3
+ export declare const PACKAGE_VERSION = "0.5.47";
4
4
  /**
5
5
  * MAJOR of the agent-API contract this package understands.
6
6
  * PARITY: src/lib/mcp/contract-version.ts (AGENT_API_CONTRACT_VERSION) on the server.
package/dist/constants.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /** Package identity and the server contract it speaks. */
2
2
  export const PACKAGE_NAME = "robisie";
3
- export const PACKAGE_VERSION = "0.5.45"; // x-release-please-version
3
+ export const PACKAGE_VERSION = "0.5.47"; // x-release-please-version
4
4
  /**
5
5
  * MAJOR of the agent-API contract this package understands.
6
6
  * PARITY: src/lib/mcp/contract-version.ts (AGENT_API_CONTRACT_VERSION) on the server.
@@ -1 +1 @@
1
- {"schema":1,"sha":"e1857d6e71bf5a7f33a89e6ee548f479a4a9547e","dirty":false}
1
+ {"schema":1,"sha":"1db2b153c8e868fd5a4e1c0c09592eb8657270ac","dirty":false}
@@ -1725,6 +1725,6 @@
1725
1725
  "status": 0,
1726
1726
  "signal": null,
1727
1727
  "stdout": "v24.3.0\n",
1728
- "stderr": "(node:21994) ExperimentalWarning: SQLite is an experimental feature and might change at any time\n(Use `node --trace-warnings ...` to show where the warning was created)\n"
1728
+ "stderr": "(node:22007) ExperimentalWarning: SQLite is an experimental feature and might change at any time\n(Use `node --trace-warnings ...` to show where the warning was created)\n"
1729
1729
  }
1730
1730
  }
@@ -37652,7 +37652,7 @@ var init_constants = __esm({
37652
37652
  "packages/client/src/constants.ts"() {
37653
37653
  "use strict";
37654
37654
  PACKAGE_NAME = "robisie";
37655
- PACKAGE_VERSION = "0.5.45";
37655
+ PACKAGE_VERSION = "0.5.47";
37656
37656
  SUPPORTED_CONTRACT_MAJOR = 1;
37657
37657
  DEFAULT_ORIGIN = "https://robisie.app";
37658
37658
  MCP_SERVER_NAME = "robisie";
@@ -37774,6 +37774,7 @@ function parseConfig(raw, configPath) {
37774
37774
  const stateDir = (0, import_node_path2.isAbsolute)(value.stateDir) ? value.stateDir : (0, import_node_path2.resolve)((0, import_node_path2.dirname)(configPath), value.stateDir);
37775
37775
  if (value.expectationProject !== void 0 && (typeof value.expectationProject !== "string" || !value.expectationProject.trim())) fail(label2, "expectationProject: gdy podane \u2014 niepusty UUID projektu");
37776
37776
  return {
37777
+ ...Object.hasOwn(value, "update") ? { update: parseUpdate(value.update, label2) } : {},
37777
37778
  project: value.project,
37778
37779
  tracks,
37779
37780
  stateDir,
@@ -37782,6 +37783,19 @@ function parseConfig(raw, configPath) {
37782
37783
  ...typeof value.expectationProject === "string" ? { expectationProject: value.expectationProject } : {}
37783
37784
  };
37784
37785
  }
37786
+ function parseUpdate(raw, label2) {
37787
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) fail(label2, "update: wymagany obiekt {consentedAt, enabled}");
37788
+ const value = raw;
37789
+ if (Object.keys(value).some((key) => key !== "consentedAt" && key !== "enabled") || typeof value.enabled !== "boolean")
37790
+ fail(label2, "update: wymagane wy\u0142\u0105cznie consentedAt i enabled (boolean)");
37791
+ const at3 = value.consentedAt;
37792
+ const match = typeof at3 === "string" ? at3.match(/^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])T([01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/) : null;
37793
+ if (!match || typeof at3 !== "string" || !Number.isFinite(Date.parse(at3))) fail(label2, "update.consentedAt: wymagany czas ISO z offsetem");
37794
+ const year = Number(match[1]), month = Number(match[2]), day = Number(match[3]);
37795
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
37796
+ if (day > [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1]) fail(label2, "update.consentedAt: niepoprawny dzie\u0144");
37797
+ return { consentedAt: at3, enabled: value.enabled };
37798
+ }
37785
37799
  function text2(value, path34, label2) {
37786
37800
  if (typeof value !== "string" || !value.trim()) fail(label2, `${path34}: wymagany niepusty tekst`);
37787
37801
  return value;
@@ -48255,6 +48269,7 @@ ${String(dutyVerdict.note)}` : ``,
48255
48269
  `- Odmowa jawnie opcjonalnej sondy lub diagnostyki spoza done_when: pomi\u0144 j\u0105, odnotuj brak jej dowodu w raporcie i kontynuuj niezale\u017Cne dozwolone kontrole.`,
48256
48270
  `- Odmowa dodatkowego efektu z\u0142o\u017Conego polecenia: gdy zakres odmowy jest jasny i dotyczy wy\u0142\u0105cznie dodatkowego efektu, wykonaj prostsz\u0105 dozwolon\u0105 zamierzon\u0105 czynno\u015B\u0107 bez tego efektu i kontynuuj. Pro\u015Bba narz\u0119dzia o dodatkow\u0105 flag\u0119 albo inny spos\xF3b odczytu (np. gh \u2026 --allow-escape-sequences) nie jest odmow\u0105 systemu \u2014 u\u017Cyj jej, je\u015Bli s\u0142u\u017Cy tylko odczytowi, bez nowego dost\u0119pu i bez sekretu.`,
48257
48271
  ...opts.installationBrief !== void 0 ? [] : [`- Dla diffu w src/services/modules/scripts/maszynista wymagane npm run env:check przed WORKER_FINISHED; docs-only nie wymaga lokalnego env:check. Zachowaj wymagane CI i odmowy. Nowy env opisz wy\u0142\u0105cznie w .env.example, bez warto\u015Bci. Dziedzicz TMPDIR tej pr\xF3by; bez nadpisywania, ponawiania ani obej\u015Bcia odmowy.`],
48272
+ ...opts.installationBrief !== void 0 ? [] : [`- Dla diffu w packages/client wymagane z katalogu g\u0142\xF3wnego \`npm run typecheck\` (jak krok CI \u201ETypecheck incl. tests\u201D) przed WORKER_FINISHED; \`tsc -p packages/client/tsconfig.json\` nie wystarcza (target ES2022 vs ES2018 i typy Next w root).`],
48258
48273
  opts.env ? `TMPDIR tej pr\xF3by: ${workerTmpdirForBrief(opts.env)}.` : ``,
48259
48274
  ...opts.installationBrief !== void 0 ? [] : [`- U\u017Cywaj \`npm run build:check\` zamiast \`npm run build\`.`],
48260
48275
  `- Sprawdzenia s\u0105 Twoim narz\u0119dziem, nie bram\u0105. Uruchom celowane testy zmienionego kodu i jego konsument\xF3w (znajd\u017A ich wyszukiwaniem import\xF3w i wywo\u0142a\u0144) oraz komendy wymienione w kryterium uko\u0144czenia.`,
@@ -81619,6 +81634,12 @@ var init_done_when_roles = __esm({
81619
81634
  });
81620
81635
 
81621
81636
  // maszynista/seed-bridge.ts
81637
+ function provenanceObject(value) {
81638
+ if (value == null || value === "") return {};
81639
+ const parsed = typeof value === "string" ? JSON.parse(value) : value;
81640
+ if (!record14(parsed)) throw new Error("seed_provenance/authoring_providers: oczekiwano obiektu");
81641
+ return parsed;
81642
+ }
81622
81643
  function generationOf(details2) {
81623
81644
  const raw = record14(details2.seed_obligation) ? details2.seed_obligation.generation : void 0;
81624
81645
  if (raw === void 0) return 0;
@@ -81677,6 +81698,23 @@ function verify(cardsRoot, card, dir, odbior) {
81677
81698
  if (k.quality_lane !== "LIGHT" && k.quality_lane !== "CAREFUL") return "kontrakt: quality_lane";
81678
81699
  if (k.card_class !== "executable" && k.card_class !== "non_executable") return "kontrakt: card_class";
81679
81700
  if (!["low", "medium", "high"].includes(String(k.codex_effort))) return "kontrakt: codex_effort";
81701
+ let provenance;
81702
+ try {
81703
+ localEffectCheck({ id: card.id, title: card.title, details: { done_when: k.done_when, effect_check: k.effect_check } });
81704
+ const effect = JSON.parse(String(k.effect_check));
81705
+ if (!record14(effect) || effect.source !== `produkt/${card.id}/usage.jsonl`) throw new Error("effect_check: obcy source");
81706
+ const authors = record14(k.seed_provenance) && record14(k.seed_provenance.authoring_providers) ? k.seed_provenance.authoring_providers : {};
81707
+ const roles = ["by", "proposal_by", "packager_by"];
81708
+ if (roles.some((role3) => typeof authors[role3] !== "string" || !["openai", "anthropic", "xai", "google", "moonshot", "deepseek", "alibaba", "minimax", "zhipu"].includes(authors[role3])))
81709
+ throw new Error("seed_provenance.authoring_providers: trzy kanoniczne role autorstwa");
81710
+ provenance = provenanceObject(details2.seed_provenance);
81711
+ provenance = { ...provenance, authoring_providers: {
81712
+ ...provenanceObject(provenance.authoring_providers),
81713
+ ...Object.fromEntries(roles.map((role3) => [role3, authors[role3]]))
81714
+ } };
81715
+ } catch (error48) {
81716
+ return `kontrakt: ${errorText3(error48)}`;
81717
+ }
81680
81718
  const declared = details2.card_class;
81681
81719
  if (nonempty2(declared) && declared !== k.card_class) return `card_class rozbie\u017Cny (karta ${declared}, kontrakt ${k.card_class}) \u2014 zadeklarowanego nie zmieniam`;
81682
81720
  const odbiorPath = import_node_path31.default.join(dir, "50-odbior.json");
@@ -81695,6 +81733,7 @@ function verify(cardsRoot, card, dir, odbior) {
81695
81733
  codex_effort: k.codex_effort,
81696
81734
  done_when: k.done_when,
81697
81735
  effect_check: k.effect_check,
81736
+ seed_provenance: provenance,
81698
81737
  ...typeof k.servesGoal === "string" && /^#[123]$/.test(k.servesGoal) ? { servesGoal: k.servesGoal } : {},
81699
81738
  ...nonempty2(declared) ? {} : { card_class: k.card_class }
81700
81739
  };
@@ -81792,6 +81831,7 @@ var init_seed_bridge = __esm({
81792
81831
  import_node_fs30 = require("node:fs");
81793
81832
  import_node_path31 = __toESM(require("node:path"));
81794
81833
  import_node_util9 = require("node:util");
81834
+ init_local_receiver();
81795
81835
  init_done_when_roles();
81796
81836
  init_lib();
81797
81837
  BRIDGE_DETAILS_KEYS = ["seed_obligation", "reksio_withheld", "hold", "superseded_by"];
@@ -94247,6 +94287,10 @@ function runReview(input) {
94247
94287
  if (bin === "claude") args.push("--effort", effort);
94248
94288
  if (bin === "codex") args = headlessCodexArgs(model, effort);
94249
94289
  }
94290
+ if (bin === "grok") {
94291
+ const grokEffort = clientReviewer && ["minimal", "low", "medium", "high", "xhigh", "max"].includes(clientReviewer.effort) ? clientReviewer.effort : "low";
94292
+ args.push("--effort", grokEffort);
94293
+ }
94250
94294
  if (policy && bin === "claude") {
94251
94295
  effort = "medium";
94252
94296
  args.push("--effort", effort);
@@ -27,6 +27,10 @@ export declare const DEFAULT_ROLES: RolesConfig;
27
27
  /** Formy wszystkich ról innych niż Worker — wejście reguły done_when (src/done-when-roles.ts). */
28
28
  export declare function nonWorkerRoleForms(roles: RolesConfig): string[];
29
29
  export interface InstanceConfig {
30
+ update?: {
31
+ consentedAt: string;
32
+ enabled: boolean;
33
+ };
30
34
  /** UUID projektu w Planerze, do którego trafia szkic. */
31
35
  project: string;
32
36
  /** Zweryfikowane tory projektu: kompilator przyjmuje dokładny UUID albo dokładną nazwę. */
@@ -45,10 +45,27 @@ export function parseConfig(raw, configPath) {
45
45
  if (value.expectationProject !== undefined && (typeof value.expectationProject !== 'string' || !value.expectationProject.trim()))
46
46
  fail(label, 'expectationProject: gdy podane — niepusty UUID projektu');
47
47
  return {
48
+ ...(Object.hasOwn(value, 'update') ? { update: parseUpdate(value.update, label) } : {}),
48
49
  project: value.project, tracks, stateDir, roles: parseRoles(value.roles, label), configPath,
49
50
  ...(typeof value.expectationProject === 'string' ? { expectationProject: value.expectationProject } : {}),
50
51
  };
51
52
  }
53
+ function parseUpdate(raw, label) {
54
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
55
+ fail(label, 'update: wymagany obiekt {consentedAt, enabled}');
56
+ const value = raw;
57
+ if (Object.keys(value).some(key => key !== 'consentedAt' && key !== 'enabled') || typeof value.enabled !== 'boolean')
58
+ fail(label, 'update: wymagane wyłącznie consentedAt i enabled (boolean)');
59
+ const at = value.consentedAt;
60
+ const match = typeof at === 'string' ? at.match(/^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])T([01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/) : null;
61
+ if (!match || typeof at !== 'string' || !Number.isFinite(Date.parse(at)))
62
+ fail(label, 'update.consentedAt: wymagany czas ISO z offsetem');
63
+ const year = Number(match[1]), month = Number(match[2]), day = Number(match[3]);
64
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
65
+ if (day > [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1])
66
+ fail(label, 'update.consentedAt: niepoprawny dzień');
67
+ return { consentedAt: at, enabled: value.enabled };
68
+ }
52
69
  function text(value, path, label) {
53
70
  if (typeof value !== 'string' || !value.trim())
54
71
  fail(label, `${path}: wymagany niepusty tekst`);
@@ -0,0 +1,26 @@
1
+ import * as fs from 'node:fs';
2
+ import { type Ctx } from './context.js';
3
+ import { type EngineConfig } from './engine-config.js';
4
+ import { PlanerClient } from './planer-client.js';
5
+ export type UpdateBoard = Pick<PlanerClient, 'listTasks' | 'getTask' | 'updateTask' | 'appendDetail' | 'close'>;
6
+ /** External effects only; no alternative update policy or hidden CLI flags. */
7
+ export interface UpdateRuntime {
8
+ fs: typeof fs;
9
+ exec: (command: string, args: readonly string[], cwd: string, env: NodeJS.ProcessEnv) => {
10
+ status: number | null;
11
+ signal: string | null;
12
+ stdout: string;
13
+ };
14
+ kill: typeof process.kill;
15
+ now: () => number;
16
+ sleep: (ms: number) => Promise<void>;
17
+ interactive: boolean;
18
+ ask: (question: string) => Promise<string>;
19
+ moduleUrl: string;
20
+ node: string;
21
+ pid: number;
22
+ board: (ctx: Ctx, config: EngineConfig) => Promise<UpdateBoard>;
23
+ }
24
+ export declare function runInstallationUpdate(ctx: Ctx, options: {
25
+ engineConfig: string | null;
26
+ }, overrides?: Partial<UpdateRuntime>): Promise<number>;
@@ -0,0 +1,696 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import * as fs from 'node:fs';
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { createInterface } from 'node:readline/promises';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { isDeepStrictEqual } from 'node:util';
7
+ import { agentPaths } from './agents.js';
8
+ import { RobisieError } from './context.js';
9
+ import { CONFIG_FILE, parseEngineConfig } from './engine-config.js';
10
+ import { readKey } from './manifest.js';
11
+ import { PlanerClient } from './planer-client.js';
12
+ function refuse(message) {
13
+ throw new RobisieError(message, 'Sprawdź konfigurację i prywatny audyt w <stateDir>/update; usuń przyczynę przed kolejnym wywołaniem update.');
14
+ }
15
+ function code(error) { return error?.code; }
16
+ function object(raw) { return raw !== null && typeof raw === 'object' && !Array.isArray(raw); }
17
+ function json(bytes) {
18
+ const raw = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes).replace(/^\uFEFF/, ''));
19
+ if (!object(raw))
20
+ refuse('Wymagany obiekt JSON.');
21
+ return raw;
22
+ }
23
+ function version(raw) {
24
+ if (typeof raw !== 'string' || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(raw))
25
+ refuse('Niepoprawna stabilna wersja npm.');
26
+ const parts = raw.split('.').map(Number);
27
+ if (!parts.every(Number.isSafeInteger))
28
+ refuse('Niepoprawna wersja npm.');
29
+ return parts;
30
+ }
31
+ function newer(candidate, current) {
32
+ const next = version(candidate), old = version(current);
33
+ for (let i = 0; i < 3; i++)
34
+ if (next[i] !== old[i])
35
+ return next[i] > old[i];
36
+ return false;
37
+ }
38
+ async function connectBoard(ctx, config) {
39
+ // Host DB queries remain in the host. Never import DB or execute tick to obtain them.
40
+ if (config.engine.mode === 'host')
41
+ refuse('Brak dostępnej hostowej drogi tablicy poza tick.ts; aktualizacja odmówiona.');
42
+ const token = readKey(agentPaths(ctx).clientDir);
43
+ if (!token)
44
+ refuse('Brak zapisanego klucza instalacji; uruchom npx robisie init.');
45
+ const client = new PlanerClient({ origin: ctx.env.MASZYNISTA_PLANNER_ORIGIN || ctx.origin, token, fetch: ctx.fetch });
46
+ try {
47
+ await client.connect();
48
+ return client;
49
+ }
50
+ catch {
51
+ await client.close();
52
+ refuse('Nie można połączyć tablicy instalacji.');
53
+ }
54
+ }
55
+ export async function runInstallationUpdate(ctx, options, overrides = {}) {
56
+ const runtime = {
57
+ fs, exec: (command, args, cwd, env) => {
58
+ const result = spawnSync(command, args, { cwd, env, encoding: 'utf8', shell: false, timeout: 120_000, maxBuffer: 4 * 1024 * 1024 });
59
+ return { status: result.status, signal: result.signal, stdout: result.stdout };
60
+ }, kill: process.kill, now: Date.now, sleep: ms => new Promise(done => setTimeout(done, ms)),
61
+ interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
62
+ ask: async (question) => {
63
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
64
+ try {
65
+ return await rl.question(question);
66
+ }
67
+ finally {
68
+ rl.close();
69
+ }
70
+ }, moduleUrl: import.meta.url, node: process.execPath, pid: process.pid, board: connectBoard, ...overrides,
71
+ };
72
+ const io = runtime.fs;
73
+ let board, serialRelease, tickRelease;
74
+ let mode;
75
+ let result = 2;
76
+ let completed = false;
77
+ const env = { ...ctx.env };
78
+ const command = (name, args, cwd = ctx.cwd) => {
79
+ const outcome = runtime.exec(name, args, cwd, env);
80
+ if (outcome.status !== 0 || outcome.signal !== null)
81
+ refuse('Polecenie aktualizacji nie zakończyło się poprawnie.');
82
+ return outcome.stdout;
83
+ };
84
+ const stat = (path) => {
85
+ try {
86
+ return io.lstatSync(path);
87
+ }
88
+ catch (error) {
89
+ if (code(error) === 'ENOENT')
90
+ return null;
91
+ throw error;
92
+ }
93
+ };
94
+ const regular = (path) => {
95
+ if (!stat(path)?.isFile())
96
+ refuse('Wymagany zwykły czytelny plik instalacji.');
97
+ return io.readFileSync(path);
98
+ };
99
+ const privateDir = (path) => {
100
+ io.mkdirSync(path, { recursive: true, mode: 0o700 });
101
+ if (!stat(path)?.isDirectory())
102
+ refuse('Katalog aktualizacji nie może być dowiązaniem.');
103
+ io.chmodSync(path, 0o700);
104
+ };
105
+ const acquire = (path) => {
106
+ const previous = stat(path);
107
+ if (previous) {
108
+ if (!previous.isFile())
109
+ refuse('Nieczytelna blokada aktualizacji.');
110
+ const bytes = regular(path), token = bytes.toString('utf8');
111
+ if (!/^[1-9]\d*$/.test(token) || !Number.isSafeInteger(Number(token)))
112
+ refuse('Nieczytelny PID blokady; odmowa.');
113
+ try {
114
+ runtime.kill(Number(token), 0);
115
+ return null;
116
+ }
117
+ catch (error) {
118
+ if (code(error) !== 'ESRCH')
119
+ refuse('Nie można ustalić stanu procesu blokady.');
120
+ }
121
+ const fresh = stat(path);
122
+ if (!fresh || fresh.ino !== previous.ino || fresh.dev !== previous.dev || !regular(path).equals(bytes))
123
+ refuse('Blokada zmieniła się podczas kontroli.');
124
+ io.unlinkSync(path);
125
+ }
126
+ let fd;
127
+ try {
128
+ fd = io.openSync(path, 'wx', 0o600);
129
+ }
130
+ catch (error) {
131
+ if (code(error) === 'EEXIST')
132
+ return null;
133
+ throw error;
134
+ }
135
+ let own;
136
+ const token = String(runtime.pid);
137
+ try {
138
+ io.writeFileSync(fd, token);
139
+ io.fsyncSync(fd);
140
+ own = io.fstatSync(fd);
141
+ }
142
+ finally {
143
+ io.closeSync(fd);
144
+ }
145
+ return () => {
146
+ const fresh = stat(path);
147
+ if (!fresh || fresh.ino !== own.ino || fresh.dev !== own.dev || regular(path).toString('utf8') !== token)
148
+ refuse('Własna blokada zmieniła się; nie usunięto cudzej blokady.');
149
+ io.unlinkSync(path);
150
+ };
151
+ };
152
+ try {
153
+ result = await (async () => {
154
+ const selected = options.engineConfig ?? ctx.env.ROBISIE_ENGINE_CONFIG;
155
+ if (selected !== undefined && selected !== null && !selected.trim())
156
+ refuse('Pusta ścieżka konfiguracji silnika.');
157
+ const selectedPath = resolve(ctx.cwd, selected ?? CONFIG_FILE);
158
+ let bytes, configPath;
159
+ try {
160
+ configPath = io.realpathSync(selectedPath);
161
+ bytes = regular(configPath);
162
+ }
163
+ catch (error) {
164
+ if (code(error) !== 'ENOENT' || selected !== undefined && selected !== null || stat(selectedPath))
165
+ throw error;
166
+ command('npm', ['install', 'robisie@latest']);
167
+ ctx.out('Zainstalowano robisie@latest; uruchom npx robisie init.');
168
+ return 0;
169
+ }
170
+ const raw = json(bytes);
171
+ let config = parseEngineConfig(raw, configPath);
172
+ if (!config.update?.enabled) {
173
+ if (!runtime.interactive || config.update?.enabled === false) {
174
+ ctx.out('Aktualizacja pominięta: brak włączonej zgody w konfiguracji.');
175
+ return 0;
176
+ }
177
+ const answer = await runtime.ask('Czy włączyć automatyczne aktualizacje robisie co 120 sekund z kontrolowanym powrotem? [Tak/Nie] ');
178
+ if (!/^(tak|t)$/i.test(answer.trim())) {
179
+ ctx.out('Aktualizacja pominięta bez zmiany zgody.');
180
+ return 0;
181
+ }
182
+ if (!regular(configPath).equals(bytes) || io.realpathSync(selectedPath) !== configPath)
183
+ refuse('Konfiguracja zmieniła się przed zapisem zgody.');
184
+ raw.update = { consentedAt: new Date(runtime.now()).toISOString(), enabled: true };
185
+ const temporary = `${configPath}.update-${runtime.pid}`;
186
+ io.writeFileSync(temporary, JSON.stringify(raw, null, 2) + '\n', { flag: 'wx', mode: 0o600, flush: true });
187
+ if (!regular(configPath).equals(bytes))
188
+ refuse('Konfiguracja zmieniła się przed zapisem zgody.');
189
+ io.renameSync(temporary, configPath);
190
+ bytes = regular(configPath);
191
+ config = parseEngineConfig(json(bytes), configPath);
192
+ }
193
+ if (ctx.platform !== 'linux' && ctx.platform !== 'darwin')
194
+ refuse('Aktualizacja wymaga Linuxa z systemd --user lub macOS z launchd.');
195
+ const repo = io.realpathSync(config.engine.repo), state = io.realpathSync(config.stateDir);
196
+ if (!stat(repo)?.isDirectory() || !stat(state)?.isDirectory())
197
+ refuse('Niepoprawne katalogi repo lub stanu.');
198
+ const host = config.engine.mode === 'host';
199
+ const rel = relative(repo, state);
200
+ if (!host && (rel === '' || rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)))
201
+ refuse('Stan klienta musi być poza repo.');
202
+ if (host ? config.engine.delivery === 'local' : config.engine.delivery !== 'local')
203
+ refuse('Niepoprawny tryb dostarczenia instalacji.');
204
+ const modePath = join(config.engine.hostPaths?.hostStateDir ?? state, 'HOST-ACTIVATION.mode');
205
+ const modeBytes = stat(modePath) ? regular(modePath) : null;
206
+ if (modeBytes && modeBytes.toString('utf8').trim().split(/\s+/)[0] !== 'live')
207
+ refuse('HOST-ACTIVATION.mode nie ma tokenu live; aktualizacja odmówiona.');
208
+ let attempt;
209
+ let pointerSnapshot;
210
+ const check = () => {
211
+ if (io.realpathSync(selectedPath) !== configPath || !regular(configPath).equals(bytes)
212
+ || io.realpathSync(config.engine.repo) !== repo || io.realpathSync(config.stateDir) !== state)
213
+ refuse('Konfiguracja lub ścieżki zmieniły się podczas aktualizacji.');
214
+ const currentMode = stat(modePath) ? regular(modePath) : null;
215
+ if (modeBytes ? !currentMode?.equals(modeBytes) : currentMode !== null)
216
+ refuse('HOST-ACTIVATION.mode zmienił się podczas aktualizacji.');
217
+ if (attempt && !regular(attempt.path).equals(attempt.saved))
218
+ refuse('Rejestr prób zmienił się podczas aktualizacji.');
219
+ if (pointerSnapshot && (stat(pointerSnapshot.path) ? io.realpathSync(pointerSnapshot.path) : null) !== pointerSnapshot.target)
220
+ refuse('Żywy wskaźnik zmienił się podczas aktualizacji.');
221
+ };
222
+ // Probe manager before any pointer, service, or card mutation.
223
+ const manager = ctx.platform === 'linux' ? 'systemctl' : 'launchctl';
224
+ const domain = `gui/${typeof process.getuid === 'function' ? process.getuid() : 0}`;
225
+ command(manager, ctx.platform === 'linux' ? ['--user', 'show-environment'] : ['print', domain]);
226
+ board = await runtime.board(ctx, config);
227
+ const update = join(state, 'update');
228
+ privateDir(update);
229
+ const auditPath = join(update, 'audit.jsonl');
230
+ const append = (path, value) => {
231
+ if (stat(path) && !stat(path)?.isFile())
232
+ refuse('Plik stanu aktualizacji nie jest zwykłym plikiem.');
233
+ io.appendFileSync(path, JSON.stringify(value) + '\n', { mode: 0o600, flush: true });
234
+ io.chmodSync(path, 0o600);
235
+ };
236
+ const audit = (event, value = {}) => append(auditPath, { at: new Date(runtime.now()).toISOString(), event, ...value });
237
+ const defer = () => {
238
+ if (attempt) {
239
+ if (!regular(attempt.path).equals(attempt.saved))
240
+ refuse('Rejestr prób zmienił się przed odroczeniem.');
241
+ if (attempt.before === null)
242
+ io.unlinkSync(attempt.path);
243
+ else {
244
+ const temporary = `${attempt.path}.${runtime.pid}`;
245
+ io.writeFileSync(temporary, attempt.before, { flag: 'wx', mode: 0o600, flush: true });
246
+ io.renameSync(temporary, attempt.path);
247
+ }
248
+ audit('attempt-deferred');
249
+ attempt = undefined;
250
+ }
251
+ const path = join(update, 'deferred.json');
252
+ const previous = stat(path) ? json(regular(path)) : null;
253
+ if (previous && (typeof previous.since !== 'number' || typeof previous.alarmed !== 'boolean'))
254
+ refuse('Nieczytelny rejestr odroczeń.');
255
+ const since = previous?.since ?? runtime.now();
256
+ const alarmed = previous?.alarmed === true || runtime.now() - since >= 7_200_000;
257
+ if (alarmed && previous?.alarmed !== true) {
258
+ audit('deferred-alarm', { since });
259
+ ctx.err('Alarm: aktualizacja odroczona od co najmniej 7200 sekund.');
260
+ }
261
+ io.writeFileSync(path, JSON.stringify({ since, alarmed }), { mode: 0o600, flush: true });
262
+ ctx.out('Aktualizacja odroczona: trwa praca fabryki.');
263
+ return 0;
264
+ };
265
+ serialRelease = acquire(join(update, '.update.lock')) ?? undefined;
266
+ if (!serialRelease) {
267
+ ctx.out('Aktualizacja odroczona: inny aktualizator już działa.');
268
+ return 0;
269
+ }
270
+ const processBusy = () => {
271
+ const output = command('ps', ['-axo', 'pid=,command=']);
272
+ for (const line of output.split('\n').filter(line => line.trim())) {
273
+ const match = line.match(/^\s*([1-9]\d*)\s+(.+)$/);
274
+ if (!match)
275
+ refuse('Nieustalony stan procesów fabryki.');
276
+ if (Number(match[1]) === runtime.pid)
277
+ continue;
278
+ if (/\bfactory\s+run\b|(?:^|[\/\s])tick\.(?:cjs|ts|js)(?:\s|$)|\bcodex\b[^\n]*\bexec\b/.test(match[2]))
279
+ return true;
280
+ }
281
+ return false;
282
+ };
283
+ const preflight = async () => {
284
+ check();
285
+ const busy = processBusy();
286
+ for (const claim of ['.tester-job.lock', '.tester-job.input.json', '.tester-job.result.json',
287
+ ...['claim.json', 'started', 'wynik.json', 'stop.json', 'ack.json'].map(name => `receiver-jobs/local/${name}`)]) {
288
+ for (const suffix of ['', '.pending'])
289
+ if (stat(join(state, claim + suffix)))
290
+ refuse('Nierozliczony claim testera lub odbiorcy; zachowaj stan.');
291
+ }
292
+ const rows = await board.listTasks({ projectId: config.project, statuses: ['in_progress'], detailsKeys: [] });
293
+ if (!Array.isArray(rows))
294
+ refuse('Nieczytelna lista kart in_progress.');
295
+ const own = [];
296
+ for (const row of rows) {
297
+ if (row.projectId !== config.project || row.status !== 'in_progress' || typeof row.assignee !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(row.assignee))
298
+ refuse('Nieznany właściciel karty in_progress.');
299
+ if (row.assignee !== 'maszynista')
300
+ continue;
301
+ const card = await board.getTask({ id: row.id, include: [], fullDetails: true });
302
+ if (!card || card.id !== row.id || card.projectId !== config.project || card.status !== 'in_progress' || card.assignee !== 'maszynista' || card.details !== null && !object(card.details))
303
+ refuse('Nieczytelny pełny stan własnej karty.');
304
+ if (card.details?.maszynista !== undefined && !object(card.details.maszynista))
305
+ refuse('Nieczytelny stan maszynista na karcie.');
306
+ own.push(card);
307
+ }
308
+ return { busy, own };
309
+ };
310
+ if ((await preflight()).busy)
311
+ return defer();
312
+ const pointer = join(update, 'current');
313
+ if (stat(pointer) && !stat(pointer)?.isSymbolicLink())
314
+ refuse('Żywy wskaźnik musi być dowiązaniem aktualizatora.');
315
+ const previous = stat(pointer) ? io.realpathSync(pointer) : io.realpathSync(fileURLToPath(new URL('../', runtime.moduleUrl)));
316
+ pointerSnapshot = { path: pointer, target: stat(pointer) ? previous : null };
317
+ const oldPackage = json(regular(join(previous, 'package.json')));
318
+ const oldBuild = json(regular(join(previous, 'dist/engine/build-id.json')));
319
+ const validBuild = (build) => {
320
+ if (build.schema !== 1 || build.dirty !== false || typeof build.sha !== 'string' || !/^[a-f0-9]{40}$/.test(build.sha))
321
+ refuse('Niepoprawny build-id wydania.');
322
+ return build.sha;
323
+ };
324
+ const oldSha = validBuild(oldBuild);
325
+ const metadata = JSON.parse(command('npm', ['view', 'robisie@latest', 'version', 'gitHead', 'dist', '--json']));
326
+ if (!object(metadata) || !object(metadata.dist) || typeof metadata.dist.integrity !== 'string' || !/^sha(?:256|384|512)-\S+$/.test(metadata.dist.integrity)
327
+ || typeof metadata.gitHead !== 'string' || !/^[a-f0-9]{40}$/.test(metadata.gitHead))
328
+ refuse('Niepoprawne metadane npm: wymagane gitHead i integralność.');
329
+ const latest = metadata.version;
330
+ if (!newer(latest, oldPackage.version) && (latest !== oldPackage.version || stat(pointer))) {
331
+ ctx.out('Zainstalowana wersja robisie jest aktualna; brak downgrade.');
332
+ return 0;
333
+ }
334
+ const attempts = join(update, 'attempts.jsonl');
335
+ const attemptBytes = stat(attempts) ? regular(attempts) : null;
336
+ if (attemptBytes)
337
+ for (const line of attemptBytes.toString('utf8').split('\n').filter(Boolean)) {
338
+ const entry = JSON.parse(line);
339
+ if (!object(entry) || typeof entry.version !== 'string' || typeof entry.at !== 'string')
340
+ refuse('Nieczytelny rejestr prób aktualizacji.');
341
+ if (entry.version === latest)
342
+ refuse(`Ta wersja była już próbowana; usuń ręcznie jej jedną linię z ${attempts} dopiero po wyjaśnieniu błędu.`);
343
+ }
344
+ // A second precheck under the same lock as tick precedes card writes and the release attempt.
345
+ tickRelease = acquire(join(state, '.tick.lock')) ?? undefined;
346
+ if (!tickRelease)
347
+ return defer();
348
+ const second = await preflight();
349
+ if (second.busy)
350
+ return defer();
351
+ for (const card of second.own) {
352
+ check();
353
+ if (processBusy())
354
+ return defer();
355
+ const echo = await board.updateTask({ id: card.id, status: 'blocked', expected: { status: 'in_progress', details: card.details } });
356
+ if (echo.id !== card.id || echo.status !== 'blocked')
357
+ refuse('Niepotwierdzony CAS blocked; nie ponowiono zapisu.');
358
+ const current = await board.getTask({ id: card.id, include: [], fullDetails: true });
359
+ if (!current || current.status !== 'blocked' || current.assignee !== card.assignee || !isDeepStrictEqual(current.details, card.details))
360
+ refuse('Niepotwierdzony stan po CAS blocked.');
361
+ const machine = object(current.details?.maszynista) ? current.details.maszynista : {};
362
+ const reason = `Aktualizacja instalacji: martwa praca zablokowana ${new Date(runtime.now()).toISOString()}; zachowano WIP.`;
363
+ const echoDetail = await board.appendDetail({ id: card.id, patch: { maszynista: { ...machine, updateReason: reason } } });
364
+ const projected = echoDetail.readback.ok ? echoDetail.readback.task : null;
365
+ if (echoDetail.write.status !== 'blocked' || !projected || projected.status !== 'blocked' || projected.assignee !== card.assignee
366
+ || !object(projected.details?.maszynista) || projected.details.maszynista.updateReason !== reason)
367
+ refuse('Niepotwierdzony powód blokady; nie ponowiono zapisu.');
368
+ const after = await board.getTask({ id: card.id, include: [], fullDetails: true });
369
+ if (!after || after.status !== 'blocked' || after.assignee !== card.assignee
370
+ || !isDeepStrictEqual(after.details, { ...current.details, maszynista: { ...machine, updateReason: reason } }))
371
+ refuse('Niepotwierdzone zachowanie WIP i pól maszynista po dopisaniu powodu.');
372
+ audit('card-blocked', { id: card.id, before: card, after, echo, echoDetail });
373
+ }
374
+ check();
375
+ if (attemptBytes ? !regular(attempts).equals(attemptBytes) : stat(attempts) !== null)
376
+ refuse('Rejestr prób zmienił się podczas aktualizacji.');
377
+ append(attempts, { version: latest, at: new Date(runtime.now()).toISOString() });
378
+ attempt = { path: attempts, before: attemptBytes, saved: regular(attempts) };
379
+ audit('attempt', { version: latest, previous: oldSha });
380
+ const releases = join(update, 'releases');
381
+ privateDir(releases);
382
+ const release = io.mkdtempSync(join(releases, `robisie-${latest}-`));
383
+ io.writeFileSync(join(release, 'package.json'), JSON.stringify({ private: true }) + '\n', { flag: 'wx', mode: 0o600, flush: true });
384
+ command('npm', ['install', `robisie@${latest}`, '--ignore-scripts', '--no-audit', '--no-fund', '--save-exact'], release);
385
+ const next = join(release, 'node_modules/robisie');
386
+ const build = json(regular(join(next, 'dist/engine/build-id.json'))), sha = validBuild(build);
387
+ const lock = json(regular(join(release, 'package-lock.json')));
388
+ const installed = object(lock.packages) ? lock.packages['node_modules/robisie'] : null;
389
+ if (sha !== metadata.gitHead || !object(installed) || installed.integrity !== metadata.dist.integrity
390
+ || json(regular(join(next, 'package.json'))).version !== latest)
391
+ refuse('Weryfikacja wydania npm nie powiodła się.');
392
+ regular(join(next, 'dist/cli.js'));
393
+ regular(join(next, 'dist/engine/tick.cjs'));
394
+ const prepared = await preflight();
395
+ if (prepared.busy)
396
+ return defer();
397
+ if (prepared.own.length)
398
+ return defer();
399
+ const launcher = join(update, 'launch.mjs');
400
+ const launcherText = `// robisie:update-managed
401
+ import {realpathSync} from 'node:fs';
402
+ import {join} from 'node:path';
403
+ import {pathToFileURL} from 'node:url';
404
+ import {spawnSync} from 'node:child_process';
405
+ try {
406
+ const root=realpathSync(${JSON.stringify(pointer)});
407
+ const env={...process.env};
408
+ if(process.argv[2]==='factory') {
409
+ const {readKey}=await import(pathToFileURL(join(root,'dist/manifest.js')).href);
410
+ const dir=${JSON.stringify(agentPaths(ctx).clientDir)};
411
+ env.ROBISIE_KEY=readKey(dir);
412
+ env.ROBISIE_REVIEW_KEY=readKey(dir,'review-key');
413
+ if(!env.ROBISIE_KEY||!env.ROBISIE_REVIEW_KEY) throw new Error('Brak plików kluczy instalacji');
414
+ }
415
+ const r=spawnSync(${JSON.stringify(runtime.node)},[join(root,'dist/cli.js'),...process.argv.slice(2)],{cwd:${JSON.stringify(ctx.cwd)},env,stdio:'inherit',shell:false});
416
+ if(r.status!==0||r.signal!==null) throw new Error('Polecenie robisie nie powiodło się');
417
+ process.exitCode=0;
418
+ } catch { process.stderr.write('Błąd uruchomienia robisie; sprawdź prywatny audyt aktualizacji.\\n'); process.exitCode=2; }
419
+ `;
420
+ const writeManaged = (path, content) => {
421
+ if (stat(path) && !regular(path).toString('utf8').includes('robisie:update-managed'))
422
+ refuse('Obcy plik jednostki lub launchera; odmowa nadpisania.');
423
+ io.writeFileSync(path, content, { mode: 0o600, flush: true });
424
+ };
425
+ const unitDir = ctx.platform === 'linux' ? join(dirname(agentPaths(ctx).clientDir), 'systemd/user') : join(ctx.home, 'Library/LaunchAgents');
426
+ io.mkdirSync(unitDir, { recursive: true, mode: 0o700 });
427
+ const factoryArgs = ['factory', 'run', '--once', '--engine-config', configPath];
428
+ const updateArgs = ['update', '--engine-config', configPath];
429
+ const factoryName = ctx.platform === 'linux' ? 'robisie-factory' : 'com.robisie.factory';
430
+ const ensureOwned = () => {
431
+ if (ctx.platform === 'linux') {
432
+ for (const name of [factoryName, 'robisie-update']) {
433
+ const info = runtime.exec(manager, ['--user', 'show', `${name}.service`, '--property=LoadState,ActiveState,ExecStart', '--value'], ctx.cwd, env);
434
+ if (info.signal !== null || info.status !== 0 && !(info.status === 1 && /^not-found$/m.test(info.stdout)))
435
+ refuse('Nie można potwierdzić właściciela usługi systemd.');
436
+ if (/^(?:active|activating|deactivating)$/m.test(info.stdout) && !info.stdout.includes(launcher))
437
+ refuse('Obca aktywna usługa fabryki lub aktualizacji; nie zatrzymano jej.');
438
+ }
439
+ }
440
+ else {
441
+ for (const name of [factoryName, 'com.robisie.update']) {
442
+ const info = runtime.exec(manager, ['print', `${domain}/${name}`], ctx.cwd, env);
443
+ if (info.signal !== null || info.status !== 0 && info.status !== 113)
444
+ refuse('Nie można potwierdzić właściciela usługi launchd.');
445
+ if (info.status === 0 && !info.stdout.includes(launcher))
446
+ refuse('Obca aktywna usługa fabryki lub aktualizacji; nie zatrzymano jej.');
447
+ }
448
+ }
449
+ };
450
+ ensureOwned();
451
+ writeManaged(launcher, launcherText);
452
+ const xml = (text) => text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;');
453
+ const systemArg = (text, execution = false) => '"' + text.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%').replace(/\$/g, () => execution ? '$$' : '$').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '"';
454
+ const unitEnv = Object.entries({ HOME: ctx.home, PATH: ctx.env.PATH, CODEX_HOME: ctx.env.CODEX_HOME, XDG_CONFIG_HOME: ctx.env.XDG_CONFIG_HOME })
455
+ .filter((entry) => entry[1] !== undefined);
456
+ for (const [name, args] of [['factory', factoryArgs], ['update', updateArgs]]) {
457
+ if (ctx.platform === 'linux') {
458
+ // Tick and update own their deadlines, including the separate rollback health window.
459
+ writeManaged(join(unitDir, `robisie-${name}.service`), `# robisie:update-managed\n[Unit]\nDescription=robisie ${name}\n[Service]\nType=oneshot\nTimeoutStartSec=infinity\n${unitEnv.map(([key, value]) => `Environment=${systemArg(`${key}=${value}`)}\n`).join('')}WorkingDirectory=${systemArg(ctx.cwd)}\nExecStart=${[runtime.node, launcher, ...args].map(arg => systemArg(arg, true)).join(' ')}\n`);
460
+ writeManaged(join(unitDir, `robisie-${name}.timer`), `# robisie:update-managed\n[Unit]\nDescription=robisie ${name}\n[Timer]\nOnBootSec=120s\nOnUnitInactiveSec=120s\nUnit=robisie-${name}.service\n[Install]\nWantedBy=timers.target\n`);
461
+ }
462
+ else {
463
+ writeManaged(join(unitDir, `com.robisie.${name}.plist`), `<?xml version="1.0" encoding="UTF-8"?>\n<!-- robisie:update-managed -->\n<plist version="1.0"><dict><key>Label</key><string>com.robisie.${name}</string><key>ProgramArguments</key><array>${[runtime.node, launcher, ...args].map(arg => `<string>${xml(arg)}</string>`).join('')}</array><key>EnvironmentVariables</key><dict>${unitEnv.map(([key, value]) => `<key>${xml(key)}</key><string>${xml(value)}</string>`).join('')}</dict><key>WorkingDirectory</key><string>${xml(ctx.cwd)}</string><key>StartInterval</key><integer>120</integer></dict></plist>\n`);
464
+ }
465
+ }
466
+ const switchPointer = (target) => {
467
+ const temporary = join(update, `.current-${runtime.pid}`);
468
+ io.symlinkSync(target, temporary);
469
+ io.renameSync(temporary, pointer);
470
+ if (io.realpathSync(pointer) !== io.realpathSync(target))
471
+ refuse('Niepotwierdzona wymiana wskaźnika.');
472
+ pointerSnapshot = { path: pointer, target: io.realpathSync(target) };
473
+ };
474
+ const start = () => {
475
+ if (ctx.platform === 'linux') {
476
+ command(manager, ['--user', 'daemon-reload']);
477
+ command(manager, ['--user', 'enable', '--now', 'robisie-factory.timer', 'robisie-update.timer']);
478
+ command(manager, ['--user', 'reset-failed', 'robisie-factory.service']);
479
+ command(manager, ['--user', 'start', '--no-block', 'robisie-factory.service']);
480
+ }
481
+ else {
482
+ for (const name of ['factory', 'update']) {
483
+ const loaded = runtime.exec(manager, ['print', `${domain}/com.robisie.${name}`], ctx.cwd, env);
484
+ if (loaded.signal !== null)
485
+ refuse('Nie można potwierdzić stanu jednostki launchd.');
486
+ if (loaded.status === 0) {
487
+ if (!loaded.stdout.includes(launcher))
488
+ refuse('Obca jednostka launchd; odmowa jej zatrzymania.');
489
+ // Both jobs resolve current at launch; reloading could kill work or the updater itself.
490
+ continue;
491
+ }
492
+ else if (loaded.status !== 113)
493
+ refuse('Nie można potwierdzić stanu jednostki launchd.');
494
+ command(manager, ['bootstrap', domain, join(unitDir, `com.robisie.${name}.plist`)]);
495
+ }
496
+ command(manager, ['kickstart', `${domain}/com.robisie.factory`]);
497
+ }
498
+ };
499
+ const refresh = (root) => {
500
+ // Reuse the package's installer/doctor with file-backed A/B, never a new role installer.
501
+ const key = readKey(agentPaths(ctx).clientDir), reviewKey = readKey(agentPaths(ctx).clientDir, 'review-key');
502
+ const childEnv = { ...env };
503
+ delete childEnv.ROBISIE_KEY;
504
+ delete childEnv.ROBISIE_REVIEW_KEY;
505
+ for (const name of ['init', 'doctor']) {
506
+ if (name === 'doctor') {
507
+ if (key)
508
+ childEnv.ROBISIE_KEY = key;
509
+ if (reviewKey)
510
+ childEnv.ROBISIE_REVIEW_KEY = reviewKey;
511
+ }
512
+ const outcome = runtime.exec(runtime.node, [join(root, 'dist/cli.js'), name, '--engine-config', configPath], ctx.cwd, childEnv);
513
+ if (outcome.status !== 0 || outcome.signal !== null)
514
+ refuse('Odświeżenie ról lub doctor nie powiodło się.');
515
+ }
516
+ };
517
+ const serviceOk = (sha, failureEvent) => {
518
+ if (ctx.platform !== 'linux')
519
+ return true;
520
+ let serviceResult;
521
+ try {
522
+ serviceResult = command(manager, ['--user', 'show', 'robisie-factory.service', '--property=Result', '--value']).trim();
523
+ }
524
+ catch {
525
+ audit(failureEvent, { sha });
526
+ return false;
527
+ }
528
+ // --no-block only queues the start. Result also detects later ExecStart failures.
529
+ if (serviceResult === 'success')
530
+ return true;
531
+ audit(failureEvent, { sha, serviceResult });
532
+ return false;
533
+ };
534
+ const activate = (root, sha, failureEvent) => {
535
+ try {
536
+ refresh(root);
537
+ }
538
+ catch {
539
+ audit(failureEvent, { sha });
540
+ return false;
541
+ }
542
+ finally {
543
+ const release = tickRelease;
544
+ tickRelease = undefined;
545
+ release();
546
+ }
547
+ try {
548
+ start();
549
+ }
550
+ catch {
551
+ audit(failureEvent, { sha });
552
+ return false;
553
+ }
554
+ return serviceOk(sha, failureEvent);
555
+ };
556
+ const priorTicks = new Set();
557
+ let highestTick = BigInt(0);
558
+ const rememberTick = () => {
559
+ try {
560
+ const report = regular(join(state, 'LAST-TICK.md')).toString('utf8');
561
+ const tick = report.match(/^- tick: ([1-9]\d*)$/m)?.[1];
562
+ if (tick) {
563
+ priorTicks.add(tick);
564
+ if (BigInt(tick) > highestTick)
565
+ highestTick = BigInt(tick);
566
+ }
567
+ }
568
+ catch { /* Missing or unreadable baseline provides no health evidence. */ }
569
+ };
570
+ const health = async (expected, switchedAt, event, failureEvent) => {
571
+ const seen = new Set(priorTicks);
572
+ let accepted = 0, lastAt = switchedAt;
573
+ const deadline = switchedAt + 1_200_000;
574
+ while (runtime.now() < deadline) {
575
+ await runtime.sleep(20_000);
576
+ if (runtime.now() > deadline)
577
+ break;
578
+ if (!serviceOk(expected, failureEvent) || runtime.now() > deadline)
579
+ return false;
580
+ let report;
581
+ try {
582
+ report = regular(join(state, 'LAST-TICK.md')).toString('utf8');
583
+ }
584
+ catch {
585
+ continue;
586
+ } // Unreadable evidence never proves health.
587
+ const values = (name) => [...report.matchAll(new RegExp(`^- ${name}: (.+)$`, 'gm'))].map(match => match[1]);
588
+ const ticks = values('tick'), dates = values('at'), loaded = values('loaded');
589
+ if (!/^# LAST TICK — OK\r?\n/.test(report) || ticks.length !== 1 || dates.length !== 1 || loaded.length !== 1
590
+ || !/^[1-9]\d*$/.test(ticks[0]) || loaded[0] !== expected)
591
+ continue;
592
+ const at = Date.parse(dates[0]);
593
+ if (!Number.isFinite(at) || at <= lastAt || at > runtime.now() || seen.has(ticks[0]) || BigInt(ticks[0]) <= highestTick)
594
+ continue;
595
+ seen.add(ticks[0]);
596
+ priorTicks.add(ticks[0]);
597
+ highestTick = BigInt(ticks[0]);
598
+ accepted++;
599
+ lastAt = at;
600
+ audit(event, { tick: ticks[0], sha: expected, reportedAt: dates[0] });
601
+ if (accepted >= 2)
602
+ return true;
603
+ }
604
+ return false;
605
+ };
606
+ if (modeBytes) {
607
+ mode = { path: modePath, bytes: modeBytes };
608
+ const backup = join(update, 'HOST-ACTIVATION.mode.backup');
609
+ if (stat(backup) && !stat(backup)?.isFile())
610
+ refuse('Kopia trybu hosta nie jest zwykłym plikiem.');
611
+ io.writeFileSync(backup, modeBytes, { mode: 0o600, flush: true });
612
+ if (!regular(backup).equals(modeBytes))
613
+ refuse('Niepotwierdzona kopia bajtów HOST-ACTIVATION.mode.');
614
+ }
615
+ ensureOwned();
616
+ const activating = await preflight();
617
+ if (activating.busy)
618
+ return defer();
619
+ if (activating.own.length)
620
+ return defer();
621
+ rememberTick();
622
+ const switchedAt = runtime.now();
623
+ switchPointer(next);
624
+ audit('switched', { sha, previous: oldSha });
625
+ const started = activate(next, sha, 'start-failed');
626
+ if (started && await health(sha, switchedAt, 'new-tick', 'start-failed')) {
627
+ audit('updated', { sha });
628
+ if (stat(join(update, 'deferred.json')))
629
+ io.unlinkSync(join(update, 'deferred.json'));
630
+ completed = true;
631
+ result = 0;
632
+ }
633
+ else {
634
+ // New work prevents rollback, exactly as it prevents forward activation.
635
+ const rollbackPre = await preflight();
636
+ if (rollbackPre.busy || rollbackPre.own.length)
637
+ refuse('Alarm: nowa praca blokuje powrót; poprzednia wersja niepotwierdzona.');
638
+ tickRelease = acquire(join(state, '.tick.lock')) ?? undefined;
639
+ if (!tickRelease)
640
+ refuse('Alarm: blokada taktu uniemożliwia powrót; poprzednia wersja niepotwierdzona.');
641
+ const rollbackLocked = await preflight();
642
+ if (rollbackLocked.busy || rollbackLocked.own.length)
643
+ refuse('Alarm: nowa praca pod blokadą uniemożliwia powrót.');
644
+ ensureOwned();
645
+ rememberTick();
646
+ const restoredAt = runtime.now();
647
+ switchPointer(previous);
648
+ audit('restored', { sha: oldSha, failed: sha });
649
+ const restarted = activate(previous, oldSha, 'rollback-start-failed');
650
+ const confirmed = restarted && await health(oldSha, restoredAt, 'old-tick', 'rollback-start-failed');
651
+ audit(confirmed ? 'rollback-confirmed' : 'rollback-unconfirmed', { sha: oldSha, failed: sha });
652
+ ctx.err(confirmed ? 'Nowa wersja nie wstała; powrót potwierdzony dwoma świeżymi taktami OK.' : 'Alarm: nie potwierdzono zdrowia poprzedniej wersji po powrocie.');
653
+ result = 1;
654
+ }
655
+ return result;
656
+ })();
657
+ }
658
+ catch (error) {
659
+ ctx.err(error instanceof RobisieError ? error.message : 'Odmowa aktualizacji: błąd IO, konfiguracji, transportu lub audytu; nie ponawiaj niepewnego zapisu.');
660
+ result = 2;
661
+ }
662
+ finally {
663
+ if (mode) {
664
+ try {
665
+ io.writeFileSync(mode.path, mode.bytes, { mode: 0o600, flush: true });
666
+ if (!regular(mode.path).equals(mode.bytes))
667
+ throw new Error('mode bytes');
668
+ }
669
+ catch {
670
+ ctx.err('Alarm: nie potwierdzono przywrócenia bajtów HOST-ACTIVATION.mode.');
671
+ result = 2;
672
+ }
673
+ }
674
+ for (const release of [tickRelease, serialRelease])
675
+ if (release) {
676
+ try {
677
+ release();
678
+ }
679
+ catch {
680
+ ctx.err('Alarm: nie udało się bezpiecznie zwolnić własnej blokady aktualizacji.');
681
+ result = 2;
682
+ }
683
+ }
684
+ if (board)
685
+ try {
686
+ await board.close();
687
+ }
688
+ catch {
689
+ ctx.err('Alarm: nie udało się zamknąć transportu tablicy.');
690
+ result = 2;
691
+ }
692
+ }
693
+ if (completed && result === 0)
694
+ ctx.out('Aktualizacja potwierdzona dwoma świeżymi taktami OK.');
695
+ return result;
696
+ }
package/dist/roles.d.ts CHANGED
@@ -17,7 +17,7 @@ export interface Role {
17
17
  export declare function rolesDir(): string;
18
18
  export declare function parseRole(file: Role["file"], text: string): Role;
19
19
  export declare function loadRoles(dir?: string): Role[];
20
- export declare const MANAGED_LINE = "<!-- robisie:managed 0.5.45 \u2014 plik zarz\u0105dzany przez `npx robisie`; `npx robisie uninstall` go usunie -->";
20
+ export declare const MANAGED_LINE = "<!-- robisie:managed 0.5.47 \u2014 plik zarz\u0105dzany przez `npx robisie`; `npx robisie uninstall` go usunie -->";
21
21
  export type AgentFlavor = "claude" | "codex" | "opencode";
22
22
  /** How the operator starts the Builder for one card in its own session (the card id is not a secret). */
23
23
  export declare function builderStartCommand(flavor: AgentFlavor, codexRolePath?: string): string;
package/docs/README.en.md CHANGED
@@ -1,4 +1,4 @@
1
- # robisie — from account to accepted card (package 0.5.45) <!-- x-release-please-version -->
1
+ # robisie — from account to accepted card (package 0.5.47) <!-- x-release-please-version -->
2
2
 
3
3
  In the project directory with its engine configuration, run `npx robisie init`, then `npx robisie doctor`: init prepares the project goal and tester protection list, and doctor checks both inputs.
4
4
 
@@ -568,31 +568,14 @@ cp -p -- "$backup/entries/$entry_id" "$entry_path"
568
568
 
569
569
  Once the tgz and selected copies are ready, update. After login, init and doctor use A/B from the installation files and ignore different stale ENV with a warning. For manual installation without login, init reuses saved A/B with ENV-first; explicit `--key-stdin` selects input for A. Manual doctor requires both environment variables; agent credentials depend on the provider as described above. Load the old key BEFORE init/doctor using the same XDG_CONFIG_HOME; separate assignment before export and `&&` retain read failures without printing the key:
570
570
 
571
+ The normal update is `npx robisie update` (host: add `--engine-config /absolute/path/robisie.config.json`). The first interactive invocation visibly asks for consent and saves `update={consentedAt, enabled:true}` while preserving other configuration fields. Without consent or with `enabled:false`, background invocations exit 0 without changes. After consent, launchd `com.robisie.update` or `robisie-update.timer` runs the same command every 120 seconds; factory runs `factory run --once` on its own 120-second timer. The package prepares an exact npm version in a separate directory, verifies its build-id and integrity, then switches its private current pointer. Health requires two distinct fresh OK ticks with the expected loaded build-id within 1200 seconds (polling every 20 seconds). Failure starts a separate 1200-second health window for the previous version; both confirmed and unconfirmed rollback exit nonzero. New work prevents switching or rollback. A host with no board transport outside tick refuses explicitly; this command does not add a DB client. Read the private audit and attempts in `<stateDir>/update/`; a failed preparation also records the version. To retry only after resolving the cause, remove that version’s one line from `attempts.jsonl`. Deferral is not a failed attempt; after 7200 seconds it records one alarm. `AUTO-UPDATE.off` is not a product switch. Keep the private backup and separate archive restore below. Restart the assistant after roles refresh.
572
+
571
573
  <!-- update:start -->
572
574
  ```sh
573
575
  set +x
574
576
  XDG_CONFIG_HOME="$config_home" &&
575
577
  export XDG_CONFIG_HOME &&
576
- {
577
- if [ ! -L "$XDG_CONFIG_HOME/robisie/key" ] &&
578
- [ -f "$XDG_CONFIG_HOME/robisie/key" ] &&
579
- [ -r "$XDG_CONFIG_HOME/robisie/key" ] &&
580
- [ ! -L "$XDG_CONFIG_HOME/robisie/review-key" ] &&
581
- [ -f "$XDG_CONFIG_HOME/robisie/review-key" ] &&
582
- [ -r "$XDG_CONFIG_HOME/robisie/review-key" ] &&
583
- ROBISIE_REVIEW_KEY="$(cat "$XDG_CONFIG_HOME/robisie/review-key" 2>/dev/null)" &&
584
- [ -n "$ROBISIE_REVIEW_KEY" ] &&
585
- ROBISIE_KEY="$(cat "$XDG_CONFIG_HOME/robisie/key" 2>/dev/null)" &&
586
- [ -n "$ROBISIE_KEY" ]; then
587
- export ROBISIE_KEY ROBISIE_REVIEW_KEY
588
- else
589
- printf '%s\n' 'Cannot load both nonempty regular readable robisie key files (key, review-key).' 'Next step: check the key file and its permissions locally; resolve links/directories without overwriting data. If B is missing or rejected, supply a fresh owner_validator key via ROBISIE_REVIEW_KEY to init; --key-stdin replaces only A. Never paste the key into chat.' >&2
590
- false
591
- fi
592
- } &&
593
- npm i robisie@latest &&
594
- npx robisie init &&
595
- npx robisie doctor
578
+ npx robisie update
596
579
  ```
597
580
  <!-- update:end -->
598
581
 
@@ -600,7 +583,7 @@ Doctor checks the contract MAJOR; exit 0 also requires its other checks. Choose
600
583
 
601
584
  ### Return to the previous release
602
585
 
603
- Before overwriting, preserve later user edits in a NEW private copy (`umask 077`, e.g. `later="$(mktemp -d "$HOME/robisie-later.XXXXXX")"`). Repeat directory preparation and the copy block, substituting `$later` for `$backup`, without altering the original backup. Compare locally and merge user edits with the previous release's copy; configuration can contain a key, so do not publish the diff. Stop overwriting for unreadable configuration, links or an unresolved comparison. There is no promise of automatic rollback.
586
+ Before overwriting, preserve later user edits in a NEW private copy (`umask 077`, e.g. `later="$(mktemp -d "$HOME/robisie-later.XXXXXX")"`). Repeat directory preparation and the copy block, substituting `$later` for `$backup`, without altering the original backup. Compare locally and merge user edits with the previous release's copy; configuration can contain a key, so do not publish the diff. Stop overwriting for unreadable configuration, links or an unresolved comparison. This emergency archive restore is separate from automatic pointer rollback.
604
587
 
605
588
  After comparison run the selected restore-block commands to the same destinations, honoring absent.txt. Directory commands copy contents through `/.` without nesting another directory; before restore prepare checked destination directories if missing. When merging `backups/` and `roles/codex/`, do not delete additional later files. Restore `package.json` AND `package-lock.json` first. Then in the same cwd load the restored old key into ENV, install the retained compatible tgz, and only then run init and doctor:
606
589
 
package/docs/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # robisie — od konta do odebranej karty (paczka 0.5.45) <!-- x-release-please-version -->
1
+ # robisie — od konta do odebranej karty (paczka 0.5.47) <!-- x-release-please-version -->
2
2
 
3
3
  W katalogu projektu z konfiguracją silnika uruchom `npx robisie init`, potem `npx robisie doctor`: init przygotuje cel projektu i listę ochrony testera, a doctor sprawdzi oba wejścia.
4
4
 
@@ -617,31 +617,14 @@ Gdy tgz i wszystkie wybrane kopie są gotowe, aktualizuj. Po login init i doctor
617
617
 
618
618
  Kopia i odtworzenie obejmują oba pliki key i review-key z prywatnymi uprawnieniami; przed init/doctor wczytaj oba odtworzone klucze. Uninstall raportuje osobno stan obu plików i usuwa je z zachowaniem dotychczasowej ochrony ewidencji oraz konfiguracji. Nie unieważnia żadnego klucza na serwerze.
619
619
 
620
+ Zwykła aktualizacja to `npx robisie update` (host: dodaj `--engine-config /absolutna/sciezka/robisie.config.json`). Pierwsze interaktywne wywołanie pyta jawnie o zgodę i zapisuje `update={consentedAt, enabled:true}`, zachowując pozostałe pola konfiguracji. Bez zgody lub przy `enabled:false` wywołanie w tle kończy się kodem 0 bez zmian. Po zgodzie launchd `com.robisie.update` albo `robisie-update.timer` uruchamia tę samą komendę co 120 sekund; fabryka wykonuje `factory run --once` na osobnym cyklu 120 sekund. Paczka przygotowuje dokładną wersję npm w osobnym katalogu, sprawdza build-id i integralność, potem wymienia prywatny wskaźnik current. Zdrowie wymaga dwóch różnych świeżych taktów OK z loaded oczekiwanego build-id w 1200 sekund, odczytywanych co 20 sekund. Przy błędzie powrót ma osobne okno 1200 sekund dla starego wydania; zarówno potwierdzony, jak i niepotwierdzony powrót ma kod niezerowy. Nowa praca blokuje przełączenie lub powrót. Host bez transportu tablicy poza tick odmawia jawnie; komenda nie dodaje klienta DB. Prywatny audyt i próby znajdziesz w `<stateDir>/update/`; błąd przygotowania też zapisuje wersję. Aby ponowić po wyjaśnieniu przyczyny, usuń jedną linię tej wersji z `attempts.jsonl`. Odroczenie nie oznacza nieudanej próby; po 7200 sekund zapisuje jeden alarm. `AUTO-UPDATE.off` nie steruje produktem. Zachowaj prywatną kopię i osobny awaryjny restore archiwum. Po odświeżeniu ról uruchom ponownie asystenta.
621
+
620
622
  <!-- update:start -->
621
623
  ```sh
622
624
  set +x
623
625
  XDG_CONFIG_HOME="$config_home" &&
624
626
  export XDG_CONFIG_HOME &&
625
- {
626
- if [ ! -L "$XDG_CONFIG_HOME/robisie/key" ] &&
627
- [ -f "$XDG_CONFIG_HOME/robisie/key" ] &&
628
- [ -r "$XDG_CONFIG_HOME/robisie/key" ] &&
629
- [ ! -L "$XDG_CONFIG_HOME/robisie/review-key" ] &&
630
- [ -f "$XDG_CONFIG_HOME/robisie/review-key" ] &&
631
- [ -r "$XDG_CONFIG_HOME/robisie/review-key" ] &&
632
- ROBISIE_REVIEW_KEY="$(cat "$XDG_CONFIG_HOME/robisie/review-key" 2>/dev/null)" &&
633
- [ -n "$ROBISIE_REVIEW_KEY" ] &&
634
- ROBISIE_KEY="$(cat "$XDG_CONFIG_HOME/robisie/key" 2>/dev/null)" &&
635
- [ -n "$ROBISIE_KEY" ]; then
636
- export ROBISIE_KEY ROBISIE_REVIEW_KEY
637
- else
638
- printf '%s\n' 'Nie można wczytać obu niepustych, zwykłych, czytelnych plików kluczy robisie (key, review-key).' 'Następny krok: sprawdź lokalnie plik klucza i jego odczyt; wyjaśnij link/katalog bez nadpisywania danych. Przy braku lub odmowie B podaj nowy owner_validator przez ROBISIE_REVIEW_KEY do init; --key-stdin wymienia tylko A. Nie wklejaj klucza do rozmowy.' >&2
639
- false
640
- fi
641
- } &&
642
- npm i robisie@latest &&
643
- npx robisie init &&
644
- npx robisie doctor
627
+ npx robisie update
645
628
  ```
646
629
  <!-- update:end -->
647
630
 
@@ -649,7 +632,7 @@ Doctor sprawdza MAJOR kontraktu; exit 0 wymaga także pozostałych kontroli. Prz
649
632
 
650
633
  ### Powrót do poprzedniego wydania
651
634
 
652
- Przed nadpisaniem zachowaj późniejsze własne zmiany w NOWEJ prywatnej kopii (`umask 077`, np. `later="$(mktemp -d "$HOME/robisie-later.XXXXXX")"`). Powtórz przygotowanie katalogów i blok kopii, podstawiając `$later` zamiast `$backup`, bez zmiany starej kopii. Porównaj lokalnie i scal własne zmiany z kopią poprzedniego wydania; konfiguracja może zawierać klucz, więc bez publikowania diffu. Przy nieczytelnej konfiguracji, linku lub nierozstrzygniętym porównaniu przerwij nadpisywanie. Nie ma obietnicy automatycznego rollbacku.
635
+ Przed nadpisaniem zachowaj późniejsze własne zmiany w NOWEJ prywatnej kopii (`umask 077`, np. `later="$(mktemp -d "$HOME/robisie-later.XXXXXX")"`). Powtórz przygotowanie katalogów i blok kopii, podstawiając `$later` zamiast `$backup`, bez zmiany starej kopii. Porównaj lokalnie i scal własne zmiany z kopią poprzedniego wydania; konfiguracja może zawierać klucz, więc bez publikowania diffu. Przy nieczytelnej konfiguracji, linku lub nierozstrzygniętym porównaniu przerwij nadpisywanie. Ten awaryjny restore archiwum pozostaje osobny od automatycznego powrotu wskaźnika.
653
636
 
654
637
  Po porównaniu wykonaj wybrane komendy z bloku przywracania do tych samych celów, zachowując pominięcia z absent.txt. Polecenia katalogów kopiują zawartość przez `/.`, bez zagnieżdżania kolejnego katalogu; przed restore przygotuj sprawdzone katalogi celów, jeśli ich brakuje. Przy scalaniu `backups/` i `roles/codex/` nie usuwaj dodatkowych późniejszych plików. Najpierw przywróć `package.json` ORAZ `package-lock.json`. Potem w tym samym cwd wczytaj przywrócony stary klucz do ENV, zainstaluj zachowany zgodny tgz i dopiero wykonaj init oraz doctor:
655
638
 
@@ -91,6 +91,7 @@ export const config = parseConfig({
91
91
  - `dist/fsops.js`
92
92
  - `dist/git-commit.js`
93
93
  - `dist/helpers.js`
94
+ - `dist/installation-update.js`
94
95
  - `dist/intent-rules/admission.js`
95
96
  - `dist/intent-rules/done-when-roles.js`
96
97
  - `dist/intent-rules/hooks.js`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "robisie",
3
- "version": "0.5.45",
3
+ "version": "0.5.47",
4
4
  "description": "Instalator klienta robisie: łączy agenta (Claude Code, Codex CLI, OpenCode) z tablicą robisie i instaluje role klienta.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",