robisie 0.2.1 → 0.2.2

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,21 @@
1
1
  # Historia zmian klienta / Client changelog
2
2
 
3
+ ## [0.2.2](https://github.com/chuppa12/robisie-app/compare/client-v0.2.1...client-v0.2.2) (2026-11-10)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **client:** 8f - jednolity szablon listy ochrony, przyczyna bledu konfiguracji, symlinki w stateDir ([e2a036a](https://github.com/chuppa12/robisie-app/commit/e2a036a55e3ee15236be76fbd896b02977fa7ccf))
9
+ * **client:** 8f - kontrakt paczki i domkniecie silnika po poprawkach recenzji ([83aa6f3](https://github.com/chuppa12/robisie-app/commit/83aa6f39fa35c0e4db896c862d116eee52ebd33e))
10
+ * **client:** 8f - szersza domyslna lista ochrony testera i porada z --engine-config ([9c388e3](https://github.com/chuppa12/robisie-app/commit/9c388e312a2198ef7407870d3445d62d2bf20670))
11
+ * **client:** doctor mówi prawdę o logowaniu pary Codex–Grok ([d8b0c3b](https://github.com/chuppa12/robisie-app/commit/d8b0c3bb71bf2b56325de8e9961cbf0345c197ae))
12
+ * **client:** doctor says the truth about the Codex–Grok pair login ([8787fe2](https://github.com/chuppa12/robisie-app/commit/8787fe259a78b3250d6075e30769878cd3bb6a47))
13
+ * **client:** init i doctor przygotowują wejścia lokalnego silnika (8f) ([7e374cb](https://github.com/chuppa12/robisie-app/commit/7e374cb264b92257e3e5566938c405e7321f019f))
14
+ * **client:** init i doctor przygotowują wejścia lokalnego silnika (8f) ([e511456](https://github.com/chuppa12/robisie-app/commit/e5114561e5855aa217476f71015c17e8fba00379))
15
+ * **client:** silnik na Linuksie - autor commitu, restart hosta, dostawa FF w drzewie, powody odmowy ([c5cfce5](https://github.com/chuppa12/robisie-app/commit/c5cfce56ecdcc4993f9095d89a6f5eabc3bf539e))
16
+ * **client:** silnik na Linuksie - autor commitu, restart hosta, dostawa FF w drzewie, powody odmowy ([dd7d5e5](https://github.com/chuppa12/robisie-app/commit/dd7d5e529b72360b1bdeb174af539cf1ae9d388e))
17
+ * **client:** type the doctor login env for the root typecheck ([3534724](https://github.com/chuppa12/robisie-app/commit/3534724a7924766030272884da008a02364b411f))
18
+
3
19
  ## [0.2.1](https://github.com/chuppa12/robisie-app/compare/client-v0.2.0...client-v0.2.1) (2026-11-09)
4
20
 
5
21
 
package/README.md CHANGED
@@ -1,8 +1,10 @@
1
1
  # robisie
2
2
 
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
+
3
5
  Przewodniki: [PL — konto → odbiór → odinstalowanie](docs/README.md) · [EN — account → acceptance → uninstall](docs/README.en.md). Przygotuj Node.js 24+ (wydanie użyte przy sprawdzeniach: 24.3.0), npm, program jednego dostawcy AI oraz pusty katalog; silnik w paczce (`dist/engine/tick.cjs`) wymaga systemu Linux. Nie potrzebujesz strony ani własnego pliku `package.json` — utworzy go poniższy krok Node.js przed instalacją. Zacznij od konta i projektu w panelu. Projekt w panelu i katalog na dysku to osobne rzeczy; CEO wymaga dokładnie jednego projektu z `list_projects`.
4
6
 
5
- Konto i klucz są potrzebne do init i pracy ról. Osobne wejście to walidacja offline, gdy CLI jest dostępne: nie sprawdza instalacji, nie uruchamia dostawców i nie wymaga podawania UUID projektu. Osobno `npx robisie doctor --engine-config ./robisie.config.json` sprawdza offline tylko strukturę: nie potwierdza UUID projektu, repo, modeli ani uruchomienia dostawców. Lokalne przewodniki są w `node_modules/robisie/docs/`.
7
+ Konto i klucz są potrzebne do init i pracy ról. Osobne wejście to walidacja offline, gdy CLI jest dostępne: nie sprawdza instalacji, nie uruchamia dostawców i nie wymaga podawania UUID projektu. Osobno `npx robisie doctor --engine-config ./robisie.config.json` sprawdza offline strukturę konfiguracji i wejścia instalacji lokalnej: nie potwierdza UUID projektu, repo, modeli ani uruchomienia dostawców. Lokalne przewodniki są w `node_modules/robisie/docs/`.
6
8
 
7
9
  ## Przed init — konto i pierwszy projekt
8
10
 
@@ -119,7 +121,7 @@ Po Connect, init i wczytaniu klucza według bloku powyżej uruchom `npx robisie
119
121
 
120
122
  - **0 projektów, exit 1:** `CEO wymaga dokładnie 1 projektu (projektów: 0).` Następny krok: `Sprawdź gotowość projektu na https://robisie.app/dashboard/plugins/planer.` Wróć do przygotowania projektu opisanego przed init.
121
123
  - **Więcej niż 1 projekt, exit 1** (np. `CEO wymaga dokładnie 1 projektu (projektów: 2).`): Uporządkuj widoczność projektów w `list_projects` do 1; sam wybór projektu w panelu nie zmienia wyniku `list_projects`. Człowiek sam decyduje, który projekt zachować aktywny; przy pozostałych na liście wybiera „Archiwizuj”. „Archiwum” → „Przywróć” cofa archiwizację. Nie usuwaj projektów. Kliknięcie projektu nie zawęża wyniku `list_projects`.
122
- - **1 projekt:** oczekuj dokładnie `✓ Połączenie działa: klucz otwiera tablicę (projektów: 1).` oraz końcowego `Wszystko działa. Uruchom swojego agenta i poproś o rolę robisie CEO.` i exit 0.
124
+ - **1 projekt:** oczekuj dokładnie `✓ Połączenie działa: klucz otwiera tablicę (projektów: 1).` oraz końcowego `Powyższe kontrole przeszły. Uruchom swojego agenta i poproś o rolę robisie CEO.` i exit 0. Linia `Gotowość wykonawców Codex–Grok:` mówi osobno, czy gotowość wykonawców jest `sprawdzona` (Grok tylko „prawdopodobnie zalogowany”), `niegotowa` czy `NIE SPRAWDZONO`.
123
125
 
124
126
  Po zmianie ponów `npx robisie doctor`. Rozwiąż też inne błędy doctor: sam licznik 1 nie wystarcza bez końcowego komunikatu sukcesu i exit 0.
125
127
 
package/dist/cli.js CHANGED
@@ -1,11 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  import { lstatSync, realpathSync } from "node:fs";
3
+ import { resolve } from "node:path";
3
4
  import { fileURLToPath } from "node:url";
4
5
  import { AGENT_IDS, isAgentId } from "./agents.js";
5
6
  import { doctor, init, recoveryStep, uninstall } from "./commands.js";
6
7
  import { HELPER_SERVERS, PACKAGE_VERSION } from "./constants.js";
7
8
  import { RobisieError, errorMessage, nodeCtx } from "./context.js";
8
9
  import { runFactory } from "./factory-run.js";
10
+ import { checkInputs, inputDirectory, INPUTS_OK } from "./engine-inputs.js";
9
11
  import { isHelperServer, runHelper } from "./helpers.js";
10
12
  import { ROLE_IDS, ROLE_STEP } from "./manifest.js";
11
13
  import { doctorEngineConfig } from "./role-registry.js";
@@ -26,7 +28,7 @@ Opcje factory run:
26
28
  Ctrl+C zatrzymuje nadzorcę i grupę taktu; odłączone joby mogą działać dalej.
27
29
 
28
30
  Opcje doctor:
29
- --engine-config <path> offline sprawdza strukturę konfiguracji projektu i przypisania czterech ról wykonania
31
+ --engine-config <path> offline sprawdza strukturę konfiguracji projektu i przypisania czterech ról wykonania oraz wejścia instalacji lokalnej
30
32
  --engine-config=<path> ta sama składnia; nie sprawdza uruchomienia dostawców
31
33
  Przykład: npx robisie doctor --engine-config ./robisie.config.json
32
34
  Bez klucza i kontroli instalacji; nie sprawdza UUID projektu, repo, dostępności modeli ani wykonania komend.
@@ -34,6 +36,7 @@ Opcje doctor:
34
36
  Przewodniki i przykłady: node_modules/robisie/docs/README.md oraz README.en.md w tym samym katalogu.
35
37
 
36
38
  Opcje init:
39
+ --engine-config <path> konfiguracja lokalnego silnika; init przygotuje brakujące wejścia projektu
37
40
  --agent <${AGENT_IDS.join("|")}> wybrany dostawca (można powtórzyć albo podać po przecinku); razem z dostawcami mapy, bez --agent również wykryci
38
41
  --role <rola=dostawca> wybór ceo, builder, quality → claude, codex, opencode (można powtórzyć)
39
42
  --role=rola=dostawca ta sama składnia; np. --role=builder=codex zachowuje resztę mapy
@@ -69,8 +72,8 @@ export function parseArgs(argv) {
69
72
  }
70
73
  if (arg === "--engine-config" || arg.startsWith("--engine-config=")) {
71
74
  const step = "Użyj `npx robisie doctor --engine-config <path>` z jedną niepustą ścieżką pliku.";
72
- if (command !== "doctor" && command !== "factory")
73
- throw new RobisieError("Opcja --engine-config jest dostępna tylko dla poleceń doctor i factory run.", step);
75
+ if (command !== "init" && command !== "doctor" && command !== "factory")
76
+ throw new RobisieError("Opcja --engine-config jest dostępna tylko dla poleceń init, doctor i factory run.", step);
74
77
  if (engineConfig !== null)
75
78
  throw new RobisieError("Opcję --engine-config można podać tylko raz.", step);
76
79
  const value = arg === "--engine-config" ? args.shift() ?? "" : arg.slice("--engine-config=".length);
@@ -144,11 +147,18 @@ export async function run(argv, ctx) {
144
147
  }
145
148
  switch (args.command) {
146
149
  case "init":
147
- await init(ctx, { agents: args.agents, roles: args.roles, shell: args.shell, keyStdin: args.keyStdin });
150
+ await init(ctx, { agents: args.agents, roles: args.roles, shell: args.shell, keyStdin: args.keyStdin, ...(args.engineConfig === null ? {} : { engineConfig: args.engineConfig }) });
148
151
  return 0;
149
152
  case "doctor":
150
- if (args.engineConfig !== null)
151
- return doctorEngineConfig(ctx, args.engineConfig);
153
+ if (args.engineConfig !== null) {
154
+ const configPath = resolve(ctx.cwd, args.engineConfig);
155
+ return doctorEngineConfig(ctx, args.engineConfig, config => {
156
+ if (config.engine.delivery === "local") {
157
+ checkInputs(inputDirectory(config), configPath);
158
+ ctx.out(INPUTS_OK);
159
+ }
160
+ });
161
+ }
152
162
  if (ctx.env.ROBISIE_KEY) {
153
163
  try {
154
164
  // Match the helper's directory rules without executing its code in doctor.
@@ -8,11 +8,19 @@ export interface InitOptions {
8
8
  /** Read the key from piped stdin — only on request, so an open non-TTY stdin can never hang init. */
9
9
  keyStdin: boolean;
10
10
  rolesDir?: string;
11
+ engineConfig?: string | null;
11
12
  }
12
13
  /** Advice chooses an executable CLI, not merely a leftover configuration directory. */
13
14
  export declare function initRecoveryStep(ctx: Ctx, preferred?: AgentId): string;
14
15
  export declare function recoveryStep(ctx: Ctx, step: string): string;
15
16
  export declare function init(ctx: Ctx, options: InitOptions): Promise<void>;
17
+ export declare const DOCTOR_SUCCESS = "Powy\u017Csze kontrole przesz\u0142y. Uruchom swojego agenta i popro\u015B o rol\u0119 robisie CEO.";
18
+ /** Provider CLI runs are replaceable so tests touch no real CLI or network. Output is never read or printed. */
19
+ export declare const loginIo: {
20
+ run(binary: string, args: readonly string[], env: NodeJS.ProcessEnv, cwd: string): {
21
+ status: number | null;
22
+ };
23
+ };
16
24
  /** Returns the process exit code: 0 = all good, 1 = something needs one action. */
17
25
  export declare function doctor(ctx: Ctx): Promise<number>;
18
26
  export declare function uninstall(ctx: Ctx): number;
package/dist/commands.js CHANGED
@@ -1,4 +1,6 @@
1
- import { lstatSync, readdirSync, rmdirSync, rmSync } from "node:fs";
1
+ import { spawnSync } from "node:child_process";
2
+ import { accessSync, constants, lstatSync, readdirSync, rmdirSync, rmSync, statSync } from "node:fs";
3
+ import { delimiter, join, resolve } from "node:path";
2
4
  import { parse } from "smol-toml";
3
5
  import { AGENT_IDS, AGENT_LABELS, SHELL_EXPORT, agentPaths, agentOnPath, detectAgents, planAgent, removeCodexTables, shellProfile } from "./agents.js";
4
6
  import { HELPER_SERVERS, KEY_ENV, KEY_PATTERN, PACKAGE_NAME, PACKAGE_VERSION } from "./constants.js";
@@ -10,6 +12,7 @@ import { HELPER_TOOLS, probeHelper } from "./helpers.js";
10
12
  import { clientPaths, ensurePrivateDir, readKey, readManifest, writeKey, writeManifest, roleProviders, ROLE_IDS, ROLE_STEP } from "./manifest.js";
11
13
  import { assertCompatible, checkConnection, fetchContractVersion } from "./mcp.js";
12
14
  import { loadRoles, MANAGED_LINE, rolesDir } from "./roles.js";
15
+ import { checkInputs, createInputs, INPUTS_OK, preflightInputs, selectInputDirectory } from "./engine-inputs.js";
13
16
  const NO_KEY_STEP = "Wygeneruj klucz worker na https://robisie.app/dashboard/connect; w zsh/bash wykonaj `unset ROBISIE_KEY`, potem lokalne `npx robisie init` i wklej klucz w ukrytym pytaniu (poza rozmową).";
14
17
  const KEY_FORMAT_STEP = `Skopiuj klucz jeszcze raz z https://robisie.app/dashboard/connect; ustaw poprawny ROBISIE_KEY w środowisku lokalnego init (poza rozmową i historią poleceń) albo przekaż klucz przez stdin z jawną flagą: \`npx robisie init --key-stdin\` (poza rozmową i historią poleceń). Następnie wczytaj zapisany klucz do bieżącej sesji POSIX z tym samym XDG_CONFIG_HOME: \`${SHELL_EXPORT}\`, potem uruchom \`npx robisie doctor\`.`;
15
18
  const ENV_KEY_FORMAT_STEP = `W zsh/bash wykonaj \`unset ROBISIE_KEY\` — ENV ma pierwszeństwo przed pytaniem, stdin i plikiem. ${KEY_FORMAT_STEP}`;
@@ -90,6 +93,9 @@ async function obtainKey(ctx, keyStdin, prior) {
90
93
  return key;
91
94
  }
92
95
  export async function init(ctx, options) {
96
+ const inputs = selectInputDirectory(ctx, options.engineConfig);
97
+ if (inputs)
98
+ preflightInputs(inputs.directory, inputs.configPath);
93
99
  const paths = clientPaths(agentPaths(ctx).clientDir);
94
100
  const prior = readManifest(paths.manifest);
95
101
  const detected = options.agents ?? prior?.agents ?? detectAgents(ctx);
@@ -132,6 +138,8 @@ export async function init(ctx, options) {
132
138
  prepareBlock(before.bytes?.toString("utf8") ?? null, op.comment, op.clean, op.body);
133
139
  checkRecovery(op, priorById.get(entryId(op)));
134
140
  }
141
+ if (inputs)
142
+ createInputs(inputs.directory, inputs.configPath);
135
143
  ensurePrivateDir(paths.dir);
136
144
  const done = new Map(priorById);
137
145
  const agents = [...new Set([...(prior?.agents ?? []), ...selected])];
@@ -246,6 +254,72 @@ function installedVersions(op, text) {
246
254
  return [];
247
255
  }
248
256
  // ── doctor ───────────────────────────────────────────────────────────────────
257
+ export const DOCTOR_SUCCESS = "Powyższe kontrole przeszły. Uruchom swojego agenta i poproś o rolę robisie CEO.";
258
+ /** Provider CLI runs are replaceable so tests touch no real CLI or network. Output is never read or printed. */
259
+ export const loginIo = {
260
+ run(binary, args, env, cwd) {
261
+ const result = spawnSync(binary, args, { cwd, env, stdio: "ignore", timeout: 20_000, killSignal: "SIGKILL", shell: false });
262
+ return { status: result.error ? null : result.status };
263
+ },
264
+ };
265
+ // The engine's provider env (engine-context/review-job allowlists), never the robisie keys.
266
+ const PAIR_ENV = ["HOME", "PATH", "TMPDIR", "USER", "LOGNAME", "SHELL", "LANG", "LC_ALL", "TERM", "NO_COLOR", "CODEX_HOME", "XDG_CONFIG_HOME"];
267
+ function findProgram(cwd, path, name) {
268
+ for (const dir of path.split(delimiter)) {
269
+ if (!dir)
270
+ continue;
271
+ const candidate = resolve(cwd, dir, name);
272
+ try {
273
+ if (!statSync(candidate).isFile())
274
+ continue;
275
+ accessSync(candidate, constants.X_OK);
276
+ return candidate;
277
+ }
278
+ catch {
279
+ // not here — keep looking
280
+ }
281
+ }
282
+ return null;
283
+ }
284
+ /** Login of the client execution pair (Codex worker, Grok reviewer) as the engine starts them. */
285
+ function pairReadiness(ctx, fail) {
286
+ const home = ctx.env.HOME || ctx.home;
287
+ const env = {};
288
+ for (const name of PAIR_ENV)
289
+ if (ctx.env[name] !== undefined)
290
+ env[name] = ctx.env[name];
291
+ env.HOME = home;
292
+ const grokEnv = { ...env, PATH: `${join(home, ".local/bin")}${delimiter}${env.PATH ?? ""}` };
293
+ const retry = "Potem ponów `npx robisie doctor`.";
294
+ let unchecked = false;
295
+ let failed = false;
296
+ const codex = findProgram(ctx.cwd, env.PATH ?? "", "codex");
297
+ if (!codex) {
298
+ unchecked = true;
299
+ ctx.out("! Codex: brak programu codex w PATH — logowania NIE SPRAWDZONO.");
300
+ }
301
+ else if (loginIo.run(codex, ["login", "status"], env, ctx.cwd).status === 0) {
302
+ ctx.out(`✓ Codex zalogowany (\`codex login status\`, HOME=${home}).`);
303
+ }
304
+ else {
305
+ failed = true;
306
+ fail(`Codex nie jest zalogowany w środowisku silnika (HOME=${home}).`, `Zaloguj Codex: \`codex login --device-auth\`. ${retry}`);
307
+ }
308
+ // Grok CLI has no login-status command; `grok models` lists models without a paid model call.
309
+ const grok = findProgram(ctx.cwd, grokEnv.PATH, "grok");
310
+ if (!grok) {
311
+ unchecked = true;
312
+ ctx.out("! Grok: brak programu grok w PATH — logowania NIE SPRAWDZONO.");
313
+ }
314
+ else if (loginIo.run(grok, ["models"], grokEnv, ctx.cwd).status === 0) {
315
+ ctx.out(`✓ Grok prawdopodobnie zalogowany (\`grok models\` działa; Grok CLI nie ma polecenia statusu logowania; HOME=${home}).`);
316
+ }
317
+ else {
318
+ failed = true;
319
+ fail(`Grok: nie potwierdzono zalogowania w środowisku silnika (HOME=${home}; \`grok models\` zakończył się błędem).`, `Zaloguj Grok: \`grok login --device-auth\`. ${retry}`);
320
+ }
321
+ return failed ? "niegotowa" : unchecked ? "NIE SPRAWDZONO" : "sprawdzona (Grok: prawdopodobnie zalogowany)";
322
+ }
249
323
  /** Returns the process exit code: 0 = all good, 1 = something needs one action. */
250
324
  export async function doctor(ctx) {
251
325
  ctx.out("! Polityka enforced: NIE SPRAWDZONO — klient nie ma API jej odczytu.");
@@ -267,6 +341,13 @@ export async function doctor(ctx) {
267
341
  };
268
342
  ctx.out(`Paczka ${PACKAGE_NAME} ${PACKAGE_VERSION}`);
269
343
  const paths = clientPaths(agentPaths(ctx).clientDir);
344
+ await guard(async () => {
345
+ const inputs = selectInputDirectory(ctx);
346
+ if (inputs) {
347
+ checkInputs(inputs.directory, inputs.configPath);
348
+ ctx.out(INPUTS_OK);
349
+ }
350
+ });
270
351
  // Same 15 HOLD / 18 unblock thresholds as the packaged engine (engine-context disk()).
271
352
  const disk = reportDoctorDisk(ctx.out, ctx.cwd);
272
353
  if (!disk.ok && disk.nextStep)
@@ -418,7 +499,7 @@ export async function doctor(ctx) {
418
499
  tools = await probeHelper(name, ctx.env, ctx.cwd);
419
500
  }
420
501
  catch (error) {
421
- throw new RobisieError(`Pomocnik ${name} nie działa na tym komputerze: ${errorMessage(error)}`, "Sprawdź Node.js (wymagany 20+). Przeinstaluj paczkę z npm w katalogu instalacji: `npm i robisie@latest`, potem lokalne `npx robisie init` i `npx robisie doctor`.");
502
+ throw new RobisieError(`Pomocnik ${name} nie działa na tym komputerze: ${errorMessage(error)}`, "Sprawdź Node.js (wymagany 24+). Przeinstaluj paczkę z npm w katalogu instalacji: `npm i robisie@latest`, potem lokalne `npx robisie init` i `npx robisie doctor`.");
422
503
  }
423
504
  const absent = HELPER_TOOLS[name].filter((tool) => !tools.includes(tool));
424
505
  if (absent.length > 0)
@@ -429,8 +510,9 @@ export async function doctor(ctx) {
429
510
  }
430
511
  if (!envKey)
431
512
  fail(`Zmienna ${KEY_ENV} nie jest ustawiona — role i agenci jej potrzebują.`, `Jeśli init zapisał profil zsh/bash, otwórz nowy terminal z tym samym XDG_CONFIG_HOME. Przy --no-shell/innej powłoce ustaw środowisko agenta bez ujawniania klucza; w powłoce POSIX: ${SHELL_EXPORT}`);
513
+ ctx.out(`Gotowość wykonawców Codex–Grok: ${pairReadiness(ctx, fail)}.`);
432
514
  if (problems.length === 0) {
433
- ctx.out("Wszystko działa. Uruchom swojego agenta i poproś o rolę robisie CEO.");
515
+ ctx.out(DOCTOR_SUCCESS);
434
516
  return 0;
435
517
  }
436
518
  ctx.out(`Następny krok: ${problems[0]}`);
@@ -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.2.1";
3
+ export declare const PACKAGE_VERSION = "0.2.2";
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.2.1"; // x-release-please-version
3
+ export const PACKAGE_VERSION = "0.2.2"; // 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,7 +1,7 @@
1
1
  /**
2
2
  * Dostawa lokalna (P4-a): scalenie karty do gałęzi celu bez GitHuba.
3
3
  * Kolejność: prepare (merge-tree --write-tree, bez dotykania drzewa roboczego) → check (komendy wywołującego)
4
- * → deliver (tylko fast-forward, `update-ref` z oczekiwaną starą wartością = CAS) → attachEvidence (notatki git).
4
+ * → deliver (tylko fast-forward: merge w wyewidencjonowanym drzewie, poza nim CAS update-ref) → attachEvidence (notatki git).
5
5
  * Żadna funkcja nie rzuca wyjątku z powodu gita ani komend — każdy wynik jest jawną wartością.
6
6
  * check uruchamia komendy w tymczasowym, odłączonym worktree na `taskSha` (poza repo klienta), sprzątanym zawsze w `finally`;
7
7
  * porażka sprzątania daje `cleanup-failed` (z zachowanymi wynikami komend), nigdy ukryte `ok: true`.
@@ -120,5 +120,5 @@ export declare function readEvidence(repo: string, kind: EvidenceKind, sha: stri
120
120
  reason: "invalid-kind" | "evidence-read-failed" | "error";
121
121
  message: string;
122
122
  };
123
- /** Adapter `local-ff` (domyślny): scalenie lokalne wyłącznie przez fast-forward z CAS. */
123
+ /** Adapter `local-ff` (domyślny): fast-forward w drzewie celu albo CAS niewyewidencjonowanego refa. */
124
124
  export declare function createLocalFfDelivery(repo: string): Delivery;
@@ -1,15 +1,23 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { mkdtempSync, rmSync } from "node:fs";
3
- import { tmpdir } from "node:os";
3
+ import { devNull, tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
+ import { gitCommitOptions } from "./git-commit.js";
5
6
  export const EVIDENCE_KINDS = ["review", "test", "deliver"];
6
7
  export const DEFAULT_DELIVERY_ADAPTER = "local-ff";
7
8
  const SHA_RE = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
8
9
  const OUTPUT_LIMIT = 4000;
9
10
  function runGit(repo, args, input) {
10
- const result = spawnSync("git", args, {
11
+ let options;
12
+ try {
13
+ options = args[0] === "notes" && args.includes("add") ? gitCommitOptions(args, repo) : { args, env: process.env };
14
+ }
15
+ catch (error) {
16
+ return { status: null, stdout: "", stderr: "", error: error instanceof Error ? error : new Error(String(error)) };
17
+ }
18
+ const result = spawnSync("git", options.args, {
11
19
  cwd: repo, encoding: "utf8", input, timeout: 60_000, maxBuffer: 20 * 1024 * 1024, shell: false,
12
- env: { ...process.env, LC_ALL: "C", GIT_TERMINAL_PROMPT: "0" },
20
+ env: { ...options.env, LC_ALL: "C", GIT_TERMINAL_PROMPT: "0" },
13
21
  });
14
22
  return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "", error: result.error };
15
23
  }
@@ -198,7 +206,20 @@ function deliver(repo, prepared) {
198
206
  if (typeof worktree === "object")
199
207
  return { ok: false, reason: "error", message: `git worktree list nie powiodło się: ${gitText(worktree)}` };
200
208
  if (worktree !== undefined) {
201
- return { ok: false, reason: "target-checked-out", message: `Odmowa: gałąź ${prepared.target} jest wyewidencjonowana w ${worktree}; przesunięcie refa rozjechałoby jej drzewo robocze.` };
209
+ const before = resolveCommit(repo, ref);
210
+ if (before !== targetSha) {
211
+ return { ok: false, reason: "target-moved", message: `Odmowa: ${prepared.target} przesunął się z ${targetSha} na ${before ?? "(brak)"} po prepare; nic nie zmieniono.` };
212
+ }
213
+ const merge = runGit(worktree, ["-c", `core.hooksPath=${devNull}`, "merge", "--ff-only", "--no-autostash", "--no-overwrite-ignore", taskSha]);
214
+ const after = resolveCommit(repo, ref);
215
+ if (after === taskSha)
216
+ return { ok: true, moved: true, ref, from: targetSha, to: taskSha };
217
+ if (after === targetSha) {
218
+ // Porada gita o commicie przesunęłaby main; zachowujemy błąd i listę plików, bez ogona z poradami.
219
+ const diagnostic = gitText(merge).replace(/\n(?:Please commit\b|Another git process seems to be running in this repository, e\.g\.)[\s\S]*$/, "").trim();
220
+ return { ok: false, reason: "target-checked-out", message: `Odmowa FF w ${worktree}: ${diagnostic}\nOdłóż zmiany (git stash) albo cofnij je i ponów dostawę.` };
221
+ }
222
+ return { ok: false, reason: "target-moved", message: `Odmowa: ${prepared.target} po próbie FF wskazuje ${after ?? "(brak)"} zamiast ${taskSha}; sprawdź stan repozytorium.` };
202
223
  }
203
224
  const update = runGit(repo, ["update-ref", "--no-deref", "-m", `robisie: dostawa local-ff ${taskSha}`, ref, taskSha, targetSha]);
204
225
  if (update.status !== 0) {
@@ -275,7 +296,7 @@ export function readEvidence(repo, kind, sha) {
275
296
  }
276
297
  return { ok: true, entries };
277
298
  }
278
- /** Adapter `local-ff` (domyślny): scalenie lokalne wyłącznie przez fast-forward z CAS. */
299
+ /** Adapter `local-ff` (domyślny): fast-forward w drzewie celu albo CAS niewyewidencjonowanego refa. */
279
300
  export function createLocalFfDelivery(repo) {
280
301
  return {
281
302
  prepare: input => prepare(repo, input),
@@ -655,6 +655,12 @@
655
655
  "kind": "import-statement",
656
656
  "category": "builtin"
657
657
  },
658
+ {
659
+ "module": "packages/client/src/git-commit.ts",
660
+ "path": "node:child_process",
661
+ "kind": "import-statement",
662
+ "category": "builtin"
663
+ },
658
664
  {
659
665
  "module": "packages/client/src/delivery-local.ts",
660
666
  "path": "node:child_process",
@@ -1649,20 +1655,20 @@
1649
1655
  "staticOperations": {
1650
1656
  "beforePreflight": {
1651
1657
  "module": "maszynista/tick.ts",
1652
- "startLine": 9155,
1653
- "endLine": 9267,
1658
+ "startLine": 9177,
1659
+ "endLine": 9289,
1654
1660
  "text": "export async function main(): Promise<number> {\n const start = standaloneStartCheck({ filename: __filename, env: process.env });\n if (start.standalone && !start.ok) {\n console.error(start.message);\n process.exitCode = 78;\n return 78;\n }\n let installation: EngineContext;\n try { installation = createEngineContext(currentEngine(), {\n loadEnvironment: loadEnvFiles, preflight, baseRef: engineBaseRef, refreshBase: fetchMain,\n disk: defaultDiskPressureDependencies, workerContext: loadNorthStar,\n controlEnv: hostEnv, workerEnv: executionEnv, prepareWorktree: prepareHostWorktree, workerArtifacts: createWorkerTmpdir,\n notify: async (card, reason) => { decisionForReksio(card, reason, \"Rozstrzygnij na karcie\", \"\", \"\"); return { outcome: \"recorded\", ref: DECISIONS_REKSIO }; },\n hostOperations: hostOperationsPhase,\n activation: { confirmLoaded, finishHostActivation, readActivationState, recoverTickTimeout, runEnabledAuto },\n }, git, log); }\n catch (error) {\n if (!engineClient()) throw error;\n console.error(`HOLD kontekst klienta: ${clientTickFailure(error)}`);\n process.exitCode = 78;\n return 78;\n }\n const previousInstallation = tickInstallation;\n const hostErrorText = errorText;\n const client = engineClient();\n const result: { outcome: \"ok\" | \"retry\" | \"stop\"; reason: string; cleanup: boolean } = { outcome: \"ok\", reason: \"\", cleanup: false };\n const stopClient = (reason = clientTickFailure()): void => {\n if (client && result.outcome !== \"stop\") { result.outcome = \"stop\"; result.reason = reason; }\n };\n let code = 2;\n try { code = await q.withPlannerQueries(installation.planner, async () => {\n tickInstallation = installation;\n const errorText = client ? clientTickFailure : hostErrorText;\n const loadEnvFiles = installation.loadEnvironment;\n const preflight = () => {\n const actor = installation.preflight();\n return { uid: actor.kind === \"db\" ? actor.uid : API_ACTOR };\n };\n const { confirmLoaded, finishHostActivation, readActivationState, recoverTickTimeout, runEnabledAuto } = installation.activation;\n const smokeOnly = DRY && process.env.MASZYNISTA_SMOKE === \"1\";\n if (!DRY) {\n const acquire = (): boolean => tryCreateTickLock(LOCK);\n if (!acquire()) {\n const raw = readFileSync(LOCK, \"utf8\"), pid = Number(raw);\n if (!Number.isSafeInteger(pid) || pid <= 0) { console.log(\"tick lock bez poprawnego PID — HOLD\"); return 0; }\n try { process.kill(pid, 0); console.log(`tick już trwa (pid ${pid})`); return 0; }\n catch (error) { if ((error as NodeJS.ErrnoException).code !== \"ESRCH\") throw error; }\n if (readFileSync(LOCK, \"utf8\") === raw) unlinkSync(LOCK);\n if (!acquire()) { console.log(\"tick już trwa\"); return 0; }\n }\n }\n skippedCardEvents.clear();\n let s = parseState(null).state;\n // Internal smoke handoff: the child cannot outlive the parent's reserved budget.\n const smokeLimit = DRY ? Number(process.env.MASZYNISTA_SMOKE_TIMEOUT_MS) : NaN;\n let stateLoaded = false;\n let tickStarted: string | undefined;\n let outcome: \"ok\" | \"failed\" = \"ok\";\n let runtimeFailed = false;\n let observedLoaded = \"UNKNOWN\";\n let tickPhase = \"startup\";\n const deadlineAlarm = armTickDeadline(() => s, Number.isSafeInteger(smokeLimit) && smokeLimit > 0\n ? Math.min(TICK_LIMIT_MS, smokeLimit) : TICK_LIMIT_MS, () => ({ phase: tickPhase, observedLoaded }));\n let hostReady = false;\n let hostBoard: { uid: string; projectId: string } | undefined;\n let activationCards: CardLike[] = [];\n let activationCardsKnown = false;\n let blockedBefore = 0;\n const clientStopped = (): boolean => {\n if (client && (outcome === \"failed\" || (!DRY && s.blocked > blockedBefore))) stopClient();\n if (client && result.outcome === \"stop\") outcome = \"failed\";\n return client && result.outcome === \"stop\";\n };\n let hostPhaseStarted = false;\n const hostPhase = async (): Promise<boolean> => {\n if (smokeOnly || !hostReady || hostPhaseStarted) return false;\n hostPhaseStarted = true;\n tickPhase = \"host\";\n if (hostBoard) {\n const { uid: boardUid, projectId: boardProject } = hostBoard;\n try {\n await runEnabledAuto({ state: s, loadedSha: observedLoaded, repo: REPO, logPath: LOG, tick: s.tick, stateDir: hostStateDir(),\n now: new Date().toISOString(), activation: readActivationState(hostStateDir()), dryRun: DRY }, {\n listCards: async () => scanTasks(boardUid, boardProject, { full: true, statuses: [\"delivered\"],\n detailsKeys: ENABLED_SCAN_DETAILS_KEYS }),\n getTask: id => q.getTask(boardUid, id),\n appendDetail: async (id, patch) => { await appendBoundedDetail(boardUid, id, patch); },\n saveState: writeState,\n alarm: hostActivationAlarm,\n log,\n });\n } catch (error) { runtimeFailed = true; outcome = \"failed\"; log(`FAIL ENABLED auto: ${errorText(error)}`); }\n } else log(\"ENABLED auto: UNKNOWN — brak odczytu projektu; dowód karty czeka na dostęp do tablicy\");\n try {\n const result = await engineRunHostActivation({ repo: REPO, stateDir: hostStateDir(), cards: activationCards, cardsKnown: activationCardsKnown, tick: s.tick, dryRun: DRY }, {\n git, remainingTickMs, alarm: hostActivationAlarm, infrastructureChecks, infrastructurePullRequest, log: line => log(`host-activation: ${line}`),\n });\n log(`host-activation: code=${result.code} target=${result.target ?? \"UNKNOWN\"}${result.detail ? ` reason=${result.detail}` : \"\"}`);\n if (result.code === \"activate\" && result.target) {\n lastTick(s, \"activation\", `aktywacja ${result.target}; ogon odroczony`, outcome === \"ok\");\n return true;\n }\n } catch (error) { runtimeFailed = true; outcome = \"failed\"; log(`FAIL aktywacja: ${errorText(error)}`); }\n return false;\n };\n try {\n observedLoaded = loadedSha = readLoadedSha(REPO);\n s = readState((await engineFjConfig()).enabled);\n stateLoaded = true; blockedBefore = s.blocked;\n s.tick++; tickStarted = new Date().toISOString(); s.lastTickAt = tickStarted;\n log(`tick_started tick=${s.tick} at=${tickStarted} duration=UNKNOWN loaded=${loadedSha}`);\n loadEnvFiles();\n const { uid } = preflight();"
1655
1661
  },
1656
1662
  "finalization": {
1657
1663
  "module": "maszynista/tick.ts",
1658
- "startLine": 9556,
1659
- "endLine": 9608,
1664
+ "startLine": 9578,
1665
+ "endLine": 9630,
1660
1666
  "text": " } finally {\n // A persisted terminal FAIL is a card result; every unexpected exception above\n // remains a runtime failure, including DB errors inside card handling.\n if (!DRY && s.blocked > blockedBefore) {\n outcome = \"failed\";\n try { log(`FAIL: licznik blocked wzrósł ${blockedBefore} → ${s.blocked}; outcome=failed`); }\n catch (error) { console.error(`zapis licznika blocked: ${errorText(error)}`); }\n }\n clientStopped();\n // Early board failure still reaches the same host phase, at most once per tick.\n await hostPhase();\n tickPhase = \"finalizing\";\n try { if (!DRY) await finishHostActivation({ stateDir: hostStateDir(), outcome, tick: s.tick, runtimeFailed, observedLoaded }, { alarm: hostActivationAlarm, log }); }\n catch (error) { runtimeFailed = true; outcome = \"failed\"; log(`FAIL breaker aktywacji: ${errorText(error)}`); }\n clientStopped();\n try { if (stateLoaded) writeState(s); }\n catch (error) { runtimeFailed = true; outcome = \"failed\"; if (!client) throw error; stopClient(); result.cleanup = true; }\n finally {\n if (!DRY) {\n try { if (readFileSync(LOCK, \"utf8\") === String(process.pid)) unlinkSync(LOCK); }\n catch (error) { if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") { if (!client) throw error; stopClient(); result.cleanup = true; } }\n }\n const at = new Date().toISOString();\n const duration = tickStarted ? `${(Date.parse(at) - Date.parse(tickStarted)) / 1000}s` : \"UNKNOWN\";\n try {\n const { total, ops } = drainEgressCounters();\n const sorted = Object.entries(ops).sort(([, a], [, b]) => b.bytes - a.bytes);\n const summary = sorted.filter(([op]) => !op.includes(\":\")).slice(0, 12)\n .map(([op, counter]) => `${op}:${counter.calls}:${counter.bytes}`).join(\",\");\n const variants = sorted.filter(([op]) => op.includes(\":\")).slice(0, 6)\n .map(([op, counter]) => `${op}:${counter.calls}:${counter.bytes}`).join(\",\");\n log(`egress tick=${s.tick} total=${total} ops=${summary} variants=${variants}`);\n } catch { /* Optional metrics must never interrupt tick cleanup. */ }\n try { refreshTickReport(observedLoaded); log(`tick_finished tick=${s.tick} at=${at} outcome=${client && result.outcome === \"retry\" ? \"retry\" : outcome} duration=${duration} loaded=${loadedSha}`); }\n finally { clearTimeout(deadlineAlarm); tickDeadline = Number.POSITIVE_INFINITY; }\n }\n }\n }); } catch (error) {\n if (!client) throw error;\n stopClient(); result.cleanup = true;\n } finally {\n tickInstallation = previousInstallation;\n try { await installation.close(); }\n catch (error) {\n if (client) { stopClient(); result.cleanup = true; }\n else safeLog(`Zamknięcie instalacji nieudane: ${String(error)}`);\n }\n }\n if (client && result.outcome !== \"ok\") console.error(`Fabryka ${result.outcome === \"stop\" ? \"zatrzymana\" : \"retry\"}: ${result.reason}${result.cleanup ? \"; finalizacja niepotwierdzona — sprawdź stan i blokadę\" : \"\"}`);\n return client && result.outcome === \"stop\" ? 2 : code;\n}\n\nif (require.main === module && process.argv[2] !== \"--opencode-runner\") {"
1661
1667
  },
1662
1668
  "refreshTickReport": {
1663
1669
  "module": "maszynista/tick.ts",
1664
- "startLine": 812,
1665
- "endLine": 823,
1670
+ "startLine": 813,
1671
+ "endLine": 824,
1666
1672
  "text": "export function refreshTickReport(observedLoaded = readLoadedSha(REPO)): void {\n loadedSha = observedLoaded;\n try { mainSha = git([\"rev-parse\", engineBranchRef()]); }\n catch (error) { mainSha = \"UNKNOWN\"; log(`Nie można odczytać main SHA: ${errorText(error)}`); }\n if (DRY) return;\n try {\n const content = readFileSync(LAST_TICK, \"utf8\");\n writeFileSync(LAST_TICK, `${content.replace(/^- (?:loaded|main):.*\\n?/gm, \"\")}- loaded: ${loadedSha}\\n- main: ${mainSha}\\n`);\n } catch (error) { if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error; }\n}\n\nfunction writeAtomic(file: string, content: string): void {"
1667
1673
  },
1668
1674
  "importTime": {
@@ -1682,6 +1688,6 @@
1682
1688
  "status": 0,
1683
1689
  "signal": null,
1684
1690
  "stdout": "v24.3.0\n",
1685
- "stderr": "(node:13304) 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"
1691
+ "stderr": "(node:13896) 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"
1686
1692
  }
1687
1693
  }