robisie 0.5.23 → 0.5.25

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,27 @@
1
1
  # Historia zmian klienta / Client changelog
2
2
 
3
+ ## [0.5.25](https://github.com/chuppa12/robisie-app/compare/client-v0.5.24...client-v0.5.25) (2026-11-14)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **ci:** PR related dobiera recovery-contract dla packages/client/src (A: alias k3-helper-cli, B: selektor) ([13c0329](https://github.com/chuppa12/robisie-app/commit/13c032974986b31cb11f7d5ddb7e1e962fb1256f))
9
+ * **ci:** PR related dobiera recovery-contract dla packages/client/src (A: alias k3-helper-cli, B: selektor) ([40f109a](https://github.com/chuppa12/robisie-app/commit/40f109a334d4eb763d345449e2c2ccb83b43e622))
10
+
11
+
12
+ ### Factory Cards
13
+
14
+ * praca workera task-mwfnc1r7-6uwbox (auto-commit) ([f4e165f](https://github.com/chuppa12/robisie-app/commit/f4e165fdd7e42e92c08ad76c84a996b50984393a))
15
+
16
+ ## [0.5.24](https://github.com/chuppa12/robisie-app/compare/client-v0.5.23...client-v0.5.24) (2026-11-13)
17
+
18
+
19
+ ### Factory Cards
20
+
21
+ * praca workera task-mwex8hp7-5c9srd (auto-commit) ([eefbf38](https://github.com/chuppa12/robisie-app/commit/eefbf38d19b191b9a0d323c8ce884abedea8f71d))
22
+ * praca workera task-mwf0ui1x-ukvbs7 (auto-commit) ([b7fc19e](https://github.com/chuppa12/robisie-app/commit/b7fc19ebdc27ac0ac4bb771b4cc441a830940761))
23
+ * praca workera task-mwf2p4q3-k96mve (auto-commit) ([dafa069](https://github.com/chuppa12/robisie-app/commit/dafa069e3e40499703975ef8d2b4e88d88d2b24f))
24
+
3
25
  ## [0.5.23](https://github.com/chuppa12/robisie-app/compare/client-v0.5.22...client-v0.5.23) (2026-11-13)
4
26
 
5
27
 
@@ -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.23";
3
+ export declare const PACKAGE_VERSION = "0.5.25";
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.23"; // x-release-please-version
3
+ export const PACKAGE_VERSION = "0.5.25"; // 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":"7bb2831bc741ed7de66cb7f871174d1a1ab5d8aa","dirty":false}
1
+ {"schema":1,"sha":"1a5af8475a0ba57d216493b558309bcdbb93dbb4","dirty":false}
@@ -1655,15 +1655,15 @@
1655
1655
  "staticOperations": {
1656
1656
  "beforePreflight": {
1657
1657
  "module": "maszynista/tick.ts",
1658
- "startLine": 9534,
1659
- "endLine": 9647,
1658
+ "startLine": 9619,
1659
+ "endLine": 9732,
1660
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 seedGateSettings = installationSeedGateSettings();\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();"
1661
1661
  },
1662
1662
  "finalization": {
1663
1663
  "module": "maszynista/tick.ts",
1664
- "startLine": 9936,
1665
- "endLine": 9988,
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\") {"
1664
+ "startLine": 10021,
1665
+ "endLine": 10073,
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 && !([\"--opencode-runner\", \"--grok-runner\"].includes(process.argv[2] ?? \"\"))) {"
1667
1667
  },
1668
1668
  "refreshTickReport": {
1669
1669
  "module": "maszynista/tick.ts",
@@ -1688,6 +1688,6 @@
1688
1688
  "status": 0,
1689
1689
  "signal": null,
1690
1690
  "stdout": "v24.3.0\n",
1691
- "stderr": "(node:16360) 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:16242) 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"
1692
1692
  }
1693
1693
  }
@@ -37628,7 +37628,7 @@ var init_constants = __esm({
37628
37628
  "packages/client/src/constants.ts"() {
37629
37629
  "use strict";
37630
37630
  PACKAGE_NAME = "robisie";
37631
- PACKAGE_VERSION = "0.5.23";
37631
+ PACKAGE_VERSION = "0.5.25";
37632
37632
  SUPPORTED_CONTRACT_MAJOR = 1;
37633
37633
  DEFAULT_ORIGIN = "https://robisie.app";
37634
37634
  MCP_SERVER_NAME = "robisie";
@@ -49476,7 +49476,7 @@ function reconcileActive(input) {
49476
49476
  if (!nonempty(worker.worktree) || !nonempty(worker.branch) || !positiveInteger(attempts)) {
49477
49477
  throw new Error(`Niepe\u0142ne dane workera na karcie ${card.id}`);
49478
49478
  }
49479
- if (worker.backend !== void 0 && worker.backend !== "codex" && worker.backend !== "opencode") {
49479
+ if (worker.backend !== void 0 && worker.backend !== "codex" && worker.backend !== "opencode" && worker.backend !== "grok") {
49480
49480
  if (orphan) {
49481
49481
  skipped.push({ card, reason: "nieobs\u0142ugiwany backend Workera" });
49482
49482
  continue;
@@ -49498,6 +49498,7 @@ function reconcileActive(input) {
49498
49498
  }
49499
49499
  throw new Error(`Niepe\u0142na to\u017Csamo\u015B\u0107 OpenCode na karcie ${card.id}`);
49500
49500
  }
49501
+ if (worker.grok !== void 0 && worker.backend !== "grok" || worker.backend === "grok" && (!record2(worker.grok) || !positiveInteger(worker.grok.pid) || worker.provider !== "xai" || !nonempty(worker.model) || ![worker.grok.pidPath, worker.grok.promptPath, worker.grok.stdoutPath, worker.grok.stderrPath, worker.grok.exitPath].every(nonempty) || worker.grok.jobId !== cardJobId || worker.grok.model !== "UNKNOWN" || worker.grok.provider !== "xai" || !timestamp2(worker.grok.startedAt))) throw new Error(`Niepe\u0142na to\u017Csamo\u015B\u0107 Grok na karcie ${card.id}`);
49501
49502
  const old = previous.get(card.id);
49502
49503
  const active = {
49503
49504
  taskId: card.id,
@@ -49507,9 +49508,10 @@ function reconcileActive(input) {
49507
49508
  worktree: worker.worktree,
49508
49509
  branch: worker.branch,
49509
49510
  attempts,
49510
- startedAt: timestamp2(worker.at) ? worker.at : old?.startedAt ?? input.nowIso,
49511
- ...worker.backend === "opencode" || worker.backend === "codex" ? { backend: worker.backend } : {},
49511
+ startedAt: worker.backend === "grok" && record2(worker.grok) ? String(worker.grok.startedAt) : timestamp2(worker.at) ? worker.at : old?.startedAt ?? input.nowIso,
49512
+ ...worker.backend === "opencode" || worker.backend === "codex" || worker.backend === "grok" ? { backend: worker.backend } : {},
49512
49513
  ...nonempty(worker.model) ? { model: worker.model } : {},
49514
+ ...record2(worker.grok) ? { grok: worker.grok, provider: "xai" } : {},
49513
49515
  ...record2(worker.opencode) ? { opencode: worker.opencode } : {}
49514
49516
  };
49515
49517
  actives.push(active);
@@ -49539,7 +49541,7 @@ function parseState(raw) {
49539
49541
  const rawActives = value.actives === void 0 ? legacy == null ? [] : [legacy] : value.actives;
49540
49542
  if (!Array.isArray(rawActives)) throw new Error("b\u0142\u0119dna lista aktywnych worker\xF3w");
49541
49543
  const actives = rawActives.map((a) => {
49542
- if (!record2(a) || ![a.taskId, a.title, a.jobId, a.worktree, a.branch].every(nonempty) || !timestamp2(a.startedAt) || !positiveInteger(a.attempts) || !(a.trackId === void 0 || a.trackId === null || nonempty(a.trackId)) || !(a.backend === void 0 || a.backend === "codex" || a.backend === "opencode") || !(a.model === void 0 || nonempty(a.model))) throw new Error("b\u0142\u0119dny aktywny worker");
49544
+ if (!record2(a) || ![a.taskId, a.title, a.jobId, a.worktree, a.branch].every(nonempty) || !timestamp2(a.startedAt) || !positiveInteger(a.attempts) || !(a.trackId === void 0 || a.trackId === null || nonempty(a.trackId)) || !(a.backend === void 0 || a.backend === "codex" || a.backend === "opencode" || a.backend === "grok") || !(a.model === void 0 || nonempty(a.model))) throw new Error("b\u0142\u0119dny aktywny worker");
49543
49545
  if (a.opencode !== void 0 && a.backend !== "opencode" || a.backend === "opencode" && (!record2(a.opencode) || !positiveInteger(a.opencode.pid) || ![
49544
49546
  a.opencode.pidPath,
49545
49547
  a.opencode.promptPath,
@@ -49551,6 +49553,7 @@ function parseState(raw) {
49551
49553
  ].every(nonempty) || a.opencode.jobId !== a.jobId || a.opencode.model !== a.model || a.opencode.provider !== "opencode-go")) {
49552
49554
  throw new Error("niepe\u0142na to\u017Csamo\u015B\u0107 OpenCode w stanie workera");
49553
49555
  }
49556
+ if (a.grok !== void 0 && a.backend !== "grok" || a.backend === "grok" && (!record2(a.grok) || !positiveInteger(a.grok.pid) || a.provider !== "xai" || !nonempty(a.model) || ![a.grok.pidPath, a.grok.promptPath, a.grok.stdoutPath, a.grok.stderrPath, a.grok.exitPath].every(nonempty) || a.grok.jobId !== a.jobId || a.grok.provider !== "xai" || a.grok.model !== "UNKNOWN" || a.grok.startedAt !== a.startedAt)) throw new Error("niepe\u0142na to\u017Csamo\u015B\u0107 Grok w stanie workera");
49554
49557
  return {
49555
49558
  taskId: a.taskId,
49556
49559
  title: a.title,
@@ -49562,6 +49565,7 @@ function parseState(raw) {
49562
49565
  attempts: a.attempts,
49563
49566
  ...a.backend !== void 0 ? { backend: a.backend } : {},
49564
49567
  ...a.model !== void 0 ? { model: a.model } : {},
49568
+ ...a.grok !== void 0 ? { grok: a.grok, provider: "xai" } : {},
49565
49569
  ...a.opencode !== void 0 ? { opencode: a.opencode } : {}
49566
49570
  };
49567
49571
  });
@@ -49677,6 +49681,9 @@ function parseState(raw) {
49677
49681
  tested: value.tested,
49678
49682
  done_auto: value.done_auto,
49679
49683
  ...nonempty(value.testerIdentityCursor) ? { testerIdentityCursor: value.testerIdentityCursor } : {},
49684
+ ...timestamp2(value.grokPilotStartedAt) ? { grokPilotStartedAt: value.grokPilotStartedAt } : {},
49685
+ ...timestamp2(value.grokPilotCompletedAt) ? { grokPilotCompletedAt: value.grokPilotCompletedAt } : {},
49686
+ ...record2(value.grokPilotAcceptance) && timestamp2(value.grokPilotAcceptance.pilotStartedAt) && nonempty(value.grokPilotAcceptance.receipt) ? { grokPilotAcceptance: { pilotStartedAt: value.grokPilotAcceptance.pilotStartedAt, receipt: value.grokPilotAcceptance.receipt } } : {},
49680
49687
  ...value.opencodePilotStartedAt !== void 0 ? { opencodePilotStartedAt: value.opencodePilotStartedAt } : {},
49681
49688
  ...value.opencodePilotAcceptance !== void 0 ? { opencodePilotAcceptance: value.opencodePilotAcceptance } : {},
49682
49689
  diskAlarmActive: value.diskAlarmActive,
@@ -90878,7 +90885,14 @@ function readCompletedUsage(configPath, ledgerPath, now = /* @__PURE__ */ new Da
90878
90885
  }
90879
90886
  }
90880
90887
  function selectWorkerBackend(input, deps = {}) {
90881
- const requested = input.requestedBackend ?? "codex";
90888
+ let requested = input.requestedBackend ?? "codex";
90889
+ if (requested === "grok") {
90890
+ const pilot = input.grokPilot;
90891
+ const receipt = record14(pilot?.acceptance);
90892
+ const accepted = !!pilot?.startedAt && pilot.completedAt === pilot.startedAt && !pilot.active && receipt?.pilotStartedAt === pilot.startedAt && validString(receipt.receipt);
90893
+ if (input.qualityLane === "LIGHT" && input.cardClass === "ordinary" && !input.grokStartFallback && (!pilot?.startedAt || accepted)) return { ok: true, backend: "grok", model: "UNKNOWN" };
90894
+ requested = "codex";
90895
+ }
90882
90896
  if (requested !== "codex" && requested !== "opencode") return { ok: false, reason: "worker backend plan is malformed" };
90883
90897
  if (requested === "codex") {
90884
90898
  return validString(input.codexModel) ? { ok: true, backend: "codex", model: input.codexModel } : { ok: false, reason: "Codex model plan is malformed" };
@@ -91003,28 +91017,72 @@ function startWorker(input, deps = {}) {
91003
91017
  return { ok: false, status: "blocked", mayHaveStarted: false, reason: errorText3(error48) };
91004
91018
  }
91005
91019
  const runner = (0, import_node_url2.fileURLToPath)(__robisie_engine_bundle_url_5567750a);
91006
- const binary = input.openCodeBinary ?? "opencode";
91020
+ const grok = input.selection.backend === "grok";
91021
+ let cwd = input.cwd;
91022
+ let env = input.env;
91023
+ let binary = input.openCodeBinary ?? "opencode";
91024
+ let args = ["run", "--standalone", "--agent", "build", "--format", "json", "--model", `${PROVIDER}/${input.selection.model}`];
91025
+ if (grok) {
91026
+ try {
91027
+ if (!input.env.TMPDIR) throw new Error("Grok TMPDIR missing");
91028
+ cwd = (0, import_node_fs35.realpathSync)(input.cwd);
91029
+ const temporary = (0, import_node_fs35.realpathSync)(input.env.TMPDIR);
91030
+ env = { ...input.env, GROK_HOME: (0, import_node_fs35.realpathSync)(input.env.GROK_HOME || import_node_path38.default.join(input.env.HOME, ".grok")) };
91031
+ binary = input.grokBinary ?? "grok";
91032
+ args = [
91033
+ "--cwd",
91034
+ cwd,
91035
+ "--prompt-file",
91036
+ prepared.promptPath,
91037
+ "--sandbox",
91038
+ "workspace",
91039
+ "--permission-mode",
91040
+ "dontAsk",
91041
+ "--allow",
91042
+ "Read",
91043
+ "--allow",
91044
+ "Grep",
91045
+ "--allow",
91046
+ `Edit(${cwd}/**)`,
91047
+ "--allow",
91048
+ `Edit(${temporary}/**)`,
91049
+ "--allow",
91050
+ "Bash(*)",
91051
+ "--deny",
91052
+ "MCPTool(*)",
91053
+ "--deny",
91054
+ "WebSearch",
91055
+ "--deny",
91056
+ "WebFetch",
91057
+ "--deny",
91058
+ "Agent",
91059
+ "--disable-web-search",
91060
+ "--tools",
91061
+ "read_file,grep,list_dir,search_replace,write,run_terminal_cmd",
91062
+ "--output-format",
91063
+ "json",
91064
+ "--max-turns",
91065
+ "100",
91066
+ "--no-auto-update"
91067
+ ];
91068
+ } catch (error48) {
91069
+ return { ok: false, status: "blocked", mayHaveStarted: false, reason: errorText3(error48) };
91070
+ }
91071
+ }
91007
91072
  const command = [
91008
91073
  runner,
91009
- "--opencode-runner",
91074
+ grok ? "--grok-runner" : "--opencode-runner",
91010
91075
  prepared.exitPath,
91011
91076
  prepared.promptPath,
91012
91077
  prepared.stdoutPath,
91013
91078
  prepared.stderrPath,
91014
- input.cwd,
91079
+ cwd,
91015
91080
  binary,
91016
- "run",
91017
- "--standalone",
91018
- "--agent",
91019
- "build",
91020
- "--format",
91021
- "json",
91022
- "--model",
91023
- `${PROVIDER}/${input.selection.model}`
91081
+ ...args
91024
91082
  ];
91025
91083
  try {
91026
- const spawnDetached = deps.spawn ?? ((executable, args, options2) => (0, import_node_child_process16.spawn)(executable, [...args], options2));
91027
- const child = spawnDetached(process.execPath, command, { cwd: input.cwd, detached: true, stdio: "ignore", env: input.env });
91084
+ const spawnDetached = deps.spawn ?? ((executable, args2, options2) => (0, import_node_child_process16.spawn)(executable, [...args2], options2));
91085
+ const child = spawnDetached(process.execPath, command, { cwd, detached: true, stdio: "ignore", env });
91028
91086
  child.once?.("error", (error48) => {
91029
91087
  try {
91030
91088
  (0, import_node_fs35.writeFileSync)(
@@ -91042,7 +91100,16 @@ function startWorker(input, deps = {}) {
91042
91100
  }
91043
91101
  });
91044
91102
  if (!Number.isInteger(child.pid) || (child.pid ?? 0) <= 0) throw new Error("OpenCode runner returned no PID");
91045
- const job = artifactJob(import_node_path38.default.resolve(input.artifactsDir), localJobId, input.selection.model, prepared.startedAt, child.pid);
91103
+ const artifact = artifactJob(import_node_path38.default.resolve(input.artifactsDir), localJobId, input.selection.model, prepared.startedAt, child.pid);
91104
+ const job = grok ? { ...artifact, provider: "xai" } : artifact;
91105
+ const worker = {
91106
+ backend: input.selection.backend,
91107
+ jobId: localJobId,
91108
+ model: input.selection.model,
91109
+ startedAt: job.startedAt,
91110
+ cwd,
91111
+ ...grok ? { grok: job } : { opencode: job }
91112
+ };
91046
91113
  try {
91047
91114
  (0, import_node_fs35.writeFileSync)(job.pidPath, `${job.pid}
91048
91115
  `, { encoding: "utf8", flag: "wx", mode: 384 });
@@ -91051,23 +91118,23 @@ function startWorker(input, deps = {}) {
91051
91118
  child.unref();
91052
91119
  } catch {
91053
91120
  }
91054
- const uncertain = { backend: "opencode", jobId: localJobId, model: input.selection.model, startedAt: job.startedAt, cwd: input.cwd, opencode: job, ambiguousStart: true };
91121
+ const uncertain = { ...worker, ambiguousStart: true };
91055
91122
  return { ok: false, status: "unknown", mayHaveStarted: true, job: uncertain, reason: `OpenCode PID persistence failed: ${errorText3(error48)}` };
91056
91123
  }
91057
91124
  try {
91058
91125
  child.unref();
91059
91126
  } catch (error48) {
91060
- const uncertain = { backend: "opencode", jobId: localJobId, model: input.selection.model, startedAt: job.startedAt, cwd: input.cwd, opencode: job, ambiguousStart: true };
91127
+ const uncertain = { ...worker, ambiguousStart: true };
91061
91128
  return { ok: false, status: "unknown", mayHaveStarted: true, job: uncertain, reason: `OpenCode runner detach is ambiguous: ${errorText3(error48)}` };
91062
91129
  }
91063
- return { ok: true, status: "running", job: { backend: "opencode", jobId: localJobId, model: input.selection.model, startedAt: job.startedAt, cwd: input.cwd, opencode: job } };
91130
+ return { ok: true, status: "running", job: worker };
91064
91131
  } catch (error48) {
91065
91132
  return { ok: false, status: "blocked", mayHaveStarted: false, reason: `OpenCode runner did not start: ${errorText3(error48)}` };
91066
91133
  }
91067
91134
  }
91068
91135
  function validateOpenCodeJob(worker) {
91069
- const job = worker.opencode;
91070
- if (worker.backend !== "opencode" || !job || !validString(worker.jobId) || !SAFE_ID.test(worker.jobId) || !validString(worker.model) || !validString(worker.startedAt) || !Number.isFinite(Date.parse(worker.startedAt)) || job.jobId !== worker.jobId || job.model !== worker.model || job.startedAt !== worker.startedAt || job.provider !== PROVIDER || !Number.isSafeInteger(job.pid) || job.pid <= 0) throw new Error("OpenCode job identity is malformed");
91136
+ const job = worker.backend === "grok" ? worker.grok : worker.opencode;
91137
+ if (!["opencode", "grok"].includes(worker.backend) || !job || !validString(worker.jobId) || !SAFE_ID.test(worker.jobId) || !validString(worker.model) || !validString(worker.startedAt) || !Number.isFinite(Date.parse(worker.startedAt)) || job.jobId !== worker.jobId || (worker.backend === "grok" ? job.model !== "UNKNOWN" : job.model !== worker.model) || job.startedAt !== worker.startedAt || job.provider !== (worker.backend === "grok" ? "xai" : PROVIDER) || !Number.isSafeInteger(job.pid) || job.pid <= 0) throw new Error("OpenCode job identity is malformed");
91071
91138
  const root = import_node_path38.default.dirname(job.pidPath);
91072
91139
  const expected = {
91073
91140
  pidPath: `${job.jobId}.pid`,
@@ -91174,7 +91241,7 @@ function defaultVerifyPid(pid, job) {
91174
91241
  timeout: 5e3,
91175
91242
  maxBuffer: 1024 * 1024
91176
91243
  });
91177
- return Number(command.trim().split(/\s+/)[0]) === pid && command.includes((0, import_node_url2.fileURLToPath)(__robisie_engine_bundle_url_5567750a)) && command.includes("--opencode-runner") && command.includes(job.exitPath) && command.includes(job.jobId);
91244
+ return Number(command.trim().split(/\s+/)[0]) === pid && command.includes((0, import_node_url2.fileURLToPath)(__robisie_engine_bundle_url_5567750a)) && command.includes(job.provider === "xai" ? "--grok-runner" : "--opencode-runner") && command.includes(job.exitPath) && command.includes(job.jobId);
91178
91245
  } catch {
91179
91246
  return false;
91180
91247
  }
@@ -91328,8 +91395,9 @@ function workerResult(worker, deps = {}) {
91328
91395
  return { status: "unknown", reason: errorText3(error48) };
91329
91396
  }
91330
91397
  const status2 = workerStatus(worker, deps);
91331
- if (status2.status === "failed" || status2.status === "cancelled") return { status: status2.status, reason: status2.reason ?? status2.status };
91332
- if (status2.status !== "completed") return { status: "unknown", reason: status2.reason ?? `OpenCode result unavailable while ${status2.status}` };
91398
+ const terminalFailure = status2.status === "failed" || status2.status === "cancelled" ? { status: status2.status, reason: status2.reason ?? status2.status } : null;
91399
+ if (terminalFailure && worker.backend !== "grok") return terminalFailure;
91400
+ if (status2.status !== "completed" && !terminalFailure) return { status: "unknown", reason: status2.reason ?? `OpenCode result unavailable while ${status2.status}` };
91333
91401
  try {
91334
91402
  let raw;
91335
91403
  try {
@@ -91337,6 +91405,36 @@ function workerResult(worker, deps = {}) {
91337
91405
  } catch (error48) {
91338
91406
  throw new Error(`OpenCode stream is unreadable: ${errorText3(error48)}`);
91339
91407
  }
91408
+ if (worker.backend === "grok") {
91409
+ let envelope;
91410
+ try {
91411
+ envelope = record14(JSON.parse(raw));
91412
+ } catch (error48) {
91413
+ if (terminalFailure) return terminalFailure;
91414
+ throw error48;
91415
+ }
91416
+ if (envelope?.is_error === true) {
91417
+ if (typeof envelope.num_turns === "number" && Number.isInteger(envelope.num_turns) && envelope.num_turns > 0)
91418
+ return { status: "unknown", reason: "grok is_error after confirmed turns" };
91419
+ return terminalFailure ?? { status: "failed", reason: "grok is_error" };
91420
+ }
91421
+ if (terminalFailure) return terminalFailure;
91422
+ if (envelope?.stopReason === "cancelled") {
91423
+ const result2 = grokText(JSON.stringify({ ...envelope, stopReason: "end_turn" }));
91424
+ if (Object.keys(record14(envelope.modelUsage) ?? {}).length !== 1 || !validString(envelope.sessionId) || envelope.model !== void 0 && envelope.model !== result2.model)
91425
+ throw new Error("Grok cancelled identity is malformed");
91426
+ let stderr;
91427
+ try {
91428
+ stderr = (0, import_node_fs35.readFileSync)(job.stderrPath, "utf8");
91429
+ } catch (error48) {
91430
+ throw new Error(`Grok cancelled stderr is unreadable: ${errorText3(error48)}`);
91431
+ }
91432
+ return { status: "failed", reason: `Grok cancelled (${envelope.sessionId}): ${stderr.trim() ? stderr.split(/\r?\n/)[0] : result2.text}` };
91433
+ }
91434
+ const result = grokText(raw);
91435
+ if (countMarker(result.text) !== 1) throw new Error("Grok final report missing or ambiguous");
91436
+ return { status: "completed", report: result.text, model: result.model, provider: "xai" };
91437
+ }
91340
91438
  const stream = parseOpenCodeStream(raw, job.model);
91341
91439
  if (!deps.exportSession) throw new Error("OpenCode session export reader is unavailable");
91342
91440
  const exported = deps.exportSession(stream.sessionId, worker.cwd);
@@ -91415,7 +91513,7 @@ async function persistRunnerExit(exitPath, value) {
91415
91513
  `, { encoding: "utf8", flag: "wx", mode: 384 });
91416
91514
  (0, import_node_fs35.renameSync)(temporary, exitPath);
91417
91515
  }
91418
- async function runOpenCodeRunner(argv) {
91516
+ async function runOpenCodeRunner(argv, promptFile = false) {
91419
91517
  const [exitPath, promptPath, stdoutPath, stderrPath, cwd, binary, ...args] = argv;
91420
91518
  if (![exitPath, promptPath, stdoutPath, stderrPath, cwd, binary].every(validString)) return 2;
91421
91519
  let stdoutFd = null, stderrFd = null;
@@ -91423,7 +91521,7 @@ async function runOpenCodeRunner(argv) {
91423
91521
  const prompt2 = (0, import_node_fs35.readFileSync)(promptPath, "utf8");
91424
91522
  stdoutFd = (0, import_node_fs35.openSync)(stdoutPath, "a");
91425
91523
  stderrFd = (0, import_node_fs35.openSync)(stderrPath, "a");
91426
- const child = (0, import_node_child_process16.spawn)(binary, args, { cwd, stdio: ["pipe", stdoutFd, stderrFd] });
91524
+ const child = (0, import_node_child_process16.spawn)(binary, args, { cwd, stdio: [promptFile ? "ignore" : "pipe", stdoutFd, stderrFd] });
91427
91525
  let stoppingSignal = null;
91428
91526
  process.once("SIGTERM", () => {
91429
91527
  stoppingSignal = "SIGTERM";
@@ -91449,9 +91547,10 @@ async function runOpenCodeRunner(argv) {
91449
91547
  resolve7(value);
91450
91548
  }
91451
91549
  };
91452
- child.once("error", () => finish({ code: null, signal: null, error: "spawn" }));
91550
+ child.once("error", (error48) => finish({ code: null, signal: null, error: `spawn: ${errorText3(error48)}` }));
91453
91551
  child.once("close", (code, signal) => finish({ code, signal: signal ?? stoppingSignal }));
91454
- if (!child.stdin) {
91552
+ if (promptFile) {
91553
+ } else if (!child.stdin) {
91455
91554
  try {
91456
91555
  child.kill("SIGTERM");
91457
91556
  } catch {
@@ -91491,6 +91590,45 @@ async function runOpenCodeRunner(argv) {
91491
91590
  }
91492
91591
  }
91493
91592
  }
91593
+ function grokText(raw) {
91594
+ const envelope = record14(JSON.parse(raw)) ?? {};
91595
+ const hasResult = Object.hasOwn(envelope, "result"), hasText = Object.hasOwn(envelope, "text");
91596
+ const body = hasResult ? envelope.result : envelope.text;
91597
+ const models = Object.keys(record14(envelope.modelUsage) ?? {});
91598
+ const stated = typeof envelope.model === "string" ? envelope.model : null;
91599
+ const model = stated ?? (models.length === 1 ? models[0] : null);
91600
+ if (hasResult === hasText || typeof body !== "string" || !body.trim() || !model || !/^grok-[a-z0-9][a-z0-9._-]*$/i.test(model) || model === "grok-cli" || envelope.provider !== void 0 && envelope.provider !== "xai" || envelope.is_error === true || envelope.stopReason !== void 0 && envelope.stopReason !== "end_turn" || models.length > 1 || stated && models.length === 1 && stated !== models[0]) {
91601
+ throw new Error("grok-cli identity malformed");
91602
+ }
91603
+ return { text: body, model, quota: Object.keys(record14(envelope.usage) ?? {}).length ? record14(envelope.usage) : null };
91604
+ }
91605
+ function grokStartFailure(worker) {
91606
+ if (worker.backend !== "grok") return null;
91607
+ const job = validateOpenCodeJob(worker);
91608
+ let output, stderr;
91609
+ try {
91610
+ output = (0, import_node_fs35.readFileSync)(job.stdoutPath, "utf8").trim();
91611
+ stderr = (0, import_node_fs35.readFileSync)(job.stderrPath, "utf8");
91612
+ } catch (error48) {
91613
+ throw new Error(`Grok startup evidence unreadable: ${errorText3(error48)}`);
91614
+ }
91615
+ if (output) {
91616
+ let envelope;
91617
+ try {
91618
+ envelope = record14(JSON.parse(output));
91619
+ } catch {
91620
+ return null;
91621
+ }
91622
+ const beforeSession = envelope?.type === "error" && validString(envelope.message) && ["cwd", "sessionId", "requestId", "usage", "modelUsage", "num_turns"].every((key) => !Object.hasOwn(envelope, key));
91623
+ const zeroTurns = envelope?.is_error === true && envelope.num_turns === 0 && Object.keys(record14(envelope.modelUsage) ?? {}).length === 0;
91624
+ if (!beforeSession && !zeroTurns) return null;
91625
+ stderr += ` ${output}`;
91626
+ }
91627
+ const exit = readExit(job);
91628
+ if (!output && !/^opencode runner failed: spawn:/.test(exit?.reason ?? "") && !/^sandbox-exec:.*(?:execvp|sandbox.*(?:denied|failed)|operation not permitted)/im.test(stderr)) return null;
91629
+ const reason = `${exit?.reason ?? ""} ${stderr}`.trim();
91630
+ return exit?.status === "failed" && /ENOENT|no such file|not found|auth|unauthorized|permission|FS_PERMISSION_DENIED|quota|rate.limit|sandbox|isolation|operation not permitted/i.test(reason) ? reason.slice(0, 1e3) : null;
91631
+ }
91494
91632
  var import_node_child_process16, import_node_fs35, import_node_crypto24, import_node_path38, import_node_url2, import_node_sqlite3, PROVIDER, REPORT_MARKER, SAFE_ID, SAFE_STREAM_ID, SAFE_MODEL_ID, FIVE_HOURS, SEVEN_DAYS, THIRTY_DAYS, invokedPath;
91495
91633
  var init_worker_backend = __esm({
91496
91634
  "maszynista/worker-backend.ts"() {
@@ -91510,8 +91648,8 @@ var init_worker_backend = __esm({
91510
91648
  SEVEN_DAYS = 7 * 24 * 60 * 60 * 1e3;
91511
91649
  THIRTY_DAYS = 30 * 24 * 60 * 60 * 1e3;
91512
91650
  invokedPath = process.argv[1] ? import_node_path38.default.resolve(process.argv[1]) : "";
91513
- if (invokedPath === (0, import_node_url2.fileURLToPath)(__robisie_engine_bundle_url_5567750a) && process.argv[2] === "--opencode-runner") {
91514
- void runOpenCodeRunner(process.argv.slice(3)).then((code) => {
91651
+ if (invokedPath === (0, import_node_url2.fileURLToPath)(__robisie_engine_bundle_url_5567750a) && ["--opencode-runner", "--grok-runner"].includes(process.argv[2] ?? "")) {
91652
+ void runOpenCodeRunner(process.argv.slice(3), process.argv[2] === "--grok-runner").then((code) => {
91515
91653
  process.exitCode = code;
91516
91654
  });
91517
91655
  }
@@ -91922,18 +92060,6 @@ function openCodeExport(raw, session, message3, model, reviewText2) {
91922
92060
  if (assistant.id !== message3 || identity.id !== model || identity.providerID !== "opencode-go" || assistant.modelID !== void 0 && assistant.modelID !== model || assistant.providerID !== void 0 && assistant.providerID !== "opencode-go" || assistant.finish !== "stop" || assistant.error !== void 0 || contents.length === 0 || contents.some((item) => typeof item.text !== "string") || contents.map((item) => item.text).join("") !== reviewText2) throw new Error("opencode export identity malformed");
91923
92061
  return typeof identity.variant === "string" && ["high", "xhigh"].includes(identity.variant) ? identity.variant : null;
91924
92062
  }
91925
- function grokText(raw) {
91926
- const envelope = record15(JSON.parse(raw));
91927
- const hasResult = Object.hasOwn(envelope, "result"), hasText = Object.hasOwn(envelope, "text");
91928
- const body = hasResult ? envelope.result : envelope.text;
91929
- const models = Object.keys(record15(envelope.modelUsage));
91930
- const stated = typeof envelope.model === "string" ? envelope.model : null;
91931
- const model = stated ?? (models.length === 1 ? models[0] : null);
91932
- if (hasResult === hasText || typeof body !== "string" || !body.trim() || !model || !/^grok-/.test(model) || envelope.is_error === true || envelope.stopReason !== void 0 && envelope.stopReason !== "end_turn" || models.length > 1 || stated && models.length === 1 && stated !== models[0]) {
91933
- throw new Error("grok-cli identity malformed");
91934
- }
91935
- return { text: body, model, quota: Object.keys(record15(envelope.usage)).length ? record15(envelope.usage) : null };
91936
- }
91937
92063
  function claudeText(raw, requestedModel) {
91938
92064
  const envelope = record15(JSON.parse(raw));
91939
92065
  const models = Object.keys(record15(envelope.modelUsage));
@@ -92164,8 +92290,10 @@ function runReview(input) {
92164
92290
  return { ...receipt, status: "incomplete", diagnostic: errorText4(error48), text: errorText4(error48) };
92165
92291
  }
92166
92292
  }
92293
+ const worker = record15(record15(input.freshness).worker);
92294
+ const xaiWorker2 = worker.backend === "grok" || worker.provider === "xai";
92167
92295
  const policy = client ? void 0 : input.policy;
92168
- if (!client && (policy || readReviewPolicy()) && isReviewRecoveryKey(input.key, `${input.cardId}:${input.sha}:${input.round}`)) {
92296
+ if (!client && !xaiWorker2 && (policy || readReviewPolicy()) && isReviewRecoveryKey(input.key, `${input.cardId}:${input.sha}:${input.round}`)) {
92169
92297
  try {
92170
92298
  if (input.key !== reviewRecoveryKey(input.cardId, input.sha, input.round, input.packagingLoadedSha))
92171
92299
  throw new Error("review-backend: recovery configuration changed before execution");
@@ -92173,7 +92301,7 @@ function runReview(input) {
92173
92301
  return { ...receipt, status: "incomplete", diagnostic: errorText4(error48), text: errorText4(error48) };
92174
92302
  }
92175
92303
  }
92176
- receipt.attempts = client ? [] : retryAttempts(input);
92304
+ receipt.attempts = client || xaiWorker2 ? [] : retryAttempts(input);
92177
92305
  let materialPrompt;
92178
92306
  try {
92179
92307
  materialPrompt = reviewSourcePrompt(input);
@@ -92189,7 +92317,7 @@ function runReview(input) {
92189
92317
  let independent;
92190
92318
  let finalText = "";
92191
92319
  let finalVerdict = "UNAVAILABLE";
92192
- let route = client ? "grok" : policy ? policy.cardClass === "ordinary" ? "sol" : "grok" : input.retryGrok ? "grok" : "opencode";
92320
+ let route = xaiWorker2 ? "sol" : client ? "grok" : policy ? policy.cardClass === "ordinary" ? "sol" : "grok" : input.retryGrok ? "grok" : "opencode";
92193
92321
  let opusFallback = false;
92194
92322
  const qualification = record15(input.qualification);
92195
92323
  const tracks = [qualification.track, qualification.trackName];
@@ -92206,6 +92334,7 @@ function runReview(input) {
92206
92334
  const unknownEffort = qualifiedEffort2 === null || declaredEffort === null;
92207
92335
  const solEffort = solCareful || unknownEffort || qualifiedEffort2 === "high" || declaredEffort === "high" ? "high" : qualifiedEffort2 === "medium" || declaredEffort === "medium" ? "medium" : "low";
92208
92336
  while (route) {
92337
+ if (xaiWorker2 && route !== "sol") throw new Error("review-backend: worker vendor = reviewer vendor (xai)");
92209
92338
  let model;
92210
92339
  let effort;
92211
92340
  let bin;
@@ -92451,7 +92580,7 @@ function runReview(input) {
92451
92580
  durationMs: Date.now() - startedAt,
92452
92581
  ...route === "grok" ? { sourceSha: input.sha, sourcePromptSha256: (0, import_node_crypto26.createHash)("sha256").update(prompt2).digest("hex") } : {}
92453
92582
  });
92454
- if (client) break;
92583
+ if (client || xaiWorker2) break;
92455
92584
  if (policy) {
92456
92585
  if (policy.cardClass === "risky" && !opusFallback && bin === "grok" && errorClass !== null && FALLBACK_ERRORS.has(errorClass)) {
92457
92586
  opusFallback = true;
@@ -92567,6 +92696,7 @@ var init_review_job = __esm({
92567
92696
  init_opencode_session_export();
92568
92697
  init_claude_headless();
92569
92698
  init_host_activation();
92699
+ init_worker_backend();
92570
92700
  reviewBaseRef = () => engineBaseRef();
92571
92701
  reviewHostStateDir = () => engineHostStateDir();
92572
92702
  LUNA_MODEL = "gpt-6-luna";
@@ -317455,7 +317585,8 @@ function verifiedDualPass(card, sha5) {
317455
317585
  if ((0, import_node_fs47.existsSync)(file3)) claim = asRecord3(JSON.parse((0, import_node_fs47.readFileSync)(file3, "utf8")));
317456
317586
  } catch {
317457
317587
  }
317458
- const single = asRecord3(claim.policy).q14 === true && claim.requiredGrok === false && claim.key === full.jobKey && claim.sha === sha5 && claim.cardId === card.id && claim.round === full.round;
317588
+ const single = (xaiWorker(card) || asRecord3(claim.policy).q14 === true && claim.requiredGrok === false) && claim.key === full.jobKey && claim.sha === sha5 && claim.cardId === card.id && claim.round === full.round;
317589
+ if (xaiWorker(card) && (full.attempts.length !== 1 || asRecord3(full.attempts[0]).provider !== "openai" || !primaryPass(full.attempts[0]) || !(0, import_node_util12.isDeepStrictEqual)(asRecord3(asRecord3(claim.freshness).worker), asRecord3(reviewFreshness(card.details).worker)))) return false;
317459
317590
  if (!single && full.attempts.length < 2) return false;
317460
317591
  const passes = full.attempts.map((value) => {
317461
317592
  const attempt = asRecord3(value);
@@ -319092,6 +319223,10 @@ async function holdReviewJob(s, uid, card, reason, stopPackaging = false, review
319092
319223
  s
319093
319224
  );
319094
319225
  }
319226
+ function xaiWorker(card) {
319227
+ const worker = asRecord3(card.details?.maszynista);
319228
+ return worker.backend === "grok" || worker.provider === "xai";
319229
+ }
319095
319230
  function reviewFreshness(details2) {
319096
319231
  const object7 = (value) => {
319097
319232
  if (value === void 0 || value === null) return {};
@@ -319272,13 +319407,17 @@ async function consumeReviewClaim(s, uid, card, a, landing, file3, installation
319272
319407
  return;
319273
319408
  }
319274
319409
  }
319410
+ if (xaiWorker(card) && (!Array.isArray(result.attempts) || result.attempts.length !== 1 || asRecord3(result.attempts[0]).provider !== "openai")) {
319411
+ await holdReviewJob(s, uid, card, "review-backend: xAI Worker wymaga OpenAI; obcy receipt");
319412
+ return;
319413
+ }
319275
319414
  const savedReview = asRecord3(card.details?.review);
319276
319415
  if (asRecord3(claim.policy).cardClass === "risky" && Array.isArray(result.attempts) && asRecord3(result.attempts[0]).provider === "xai" && asRecord3(result.attempts[1]).requestedModel === "opus") {
319277
319416
  const reason = `Q14: Grok niedost\u0119pny; fallback Opus medium, SHA ${String(sha5)}`;
319278
319417
  log2(reason);
319279
319418
  await queueForReksio(card, reason, "Przywr\xF3ci\u0107 dost\u0119pno\u015B\u0107 Groka", "Sprawdzi\u0107 Grok CLI", "Recenzja Opus medium", void 0, "zg\u0142oszenie", s);
319280
319419
  }
319281
- if (claim.retryGrok) {
319420
+ if (claim.retryGrok && !xaiWorker(card)) {
319282
319421
  try {
319283
319422
  const previous = asRecord3(JSON.parse((0, import_node_fs47.readFileSync)(checkedReceipt(claim.retryGrok).path, "utf8")));
319284
319423
  const preparationOnly = result.status === "incomplete" && canRetryRequiredGrok(result) && asRecord3(result.sourcePreparation).status === "failed";
@@ -319362,7 +319501,7 @@ async function consumeReviewClaim(s, uid, card, a, landing, file3, installation
319362
319501
  return;
319363
319502
  }
319364
319503
  }
319365
- if (!engineClient() && (claim.requiredGrok === true || asRecord3(claim.policy).q14 !== true && card.details?.card_owner === "control-room") && result.verdict === "PASS" && (!independentAttempt(selected) || !result.attempts.slice(0, -1).some(primaryPass))) {
319504
+ if (!engineClient() && !xaiWorker(card) && (claim.requiredGrok === true || asRecord3(claim.policy).q14 !== true && card.details?.card_owner === "control-room") && result.verdict === "PASS" && (!independentAttempt(selected) || !result.attempts.slice(0, -1).some(primaryPass))) {
319366
319505
  await holdReviewJob(s, uid, card, "PARK_GROK_REQUIRED: primary PASS and independent review missing");
319367
319506
  return;
319368
319507
  }
@@ -319411,7 +319550,7 @@ function reviewRulesHash(round) {
319411
319550
  return (0, import_node_crypto31.createHash)("sha256").update(reviewPrompt({ id: "rules", title: "", details: { review: { round } } })).digest("hex");
319412
319551
  }
319413
319552
  function infrastructureRecoveryKey(card) {
319414
- if (engineClient()) return null;
319553
+ if (engineClient() || xaiWorker(card)) return null;
319415
319554
  const saved = asRecord3(card.details?.review);
319416
319555
  if (card.details?.card_owner !== "control-room" || counter(saved.unavailable) < 3 || !canRetryRequiredGrok(saved)) return null;
319417
319556
  const last2 = asRecord3(Array.isArray(saved.attempts) ? saved.attempts.at(-1) : null);
@@ -319446,7 +319585,7 @@ async function recoverPackagingHolds(s, uid, cards, landing) {
319446
319585
  try {
319447
319586
  infrastructureChanged = infrastructureRecoveryKey(fresh) !== null;
319448
319587
  const last2 = asRecord3(Array.isArray(saved.attempts) ? saved.attempts.at(-1) : null);
319449
- if (details2.card_owner === "control-room" && counter(saved.unavailable) > 0 && counter(saved.unavailable) < 3 && independentAttempt(last2)) {
319588
+ if (!xaiWorker(fresh) && details2.card_owner === "control-room" && counter(saved.unavailable) > 0 && counter(saved.unavailable) < 3 && independentAttempt(last2)) {
319450
319589
  const backend = readIndependentBackend();
319451
319590
  backendChanged = backend.backend === "opencode" ? last2.provider !== "opencode-go" || last2.requestedModel !== backend.model : backend.backend === "claude" ? last2.provider !== "anthropic" || last2.requestedModel !== backend.model : last2.provider !== "xai";
319452
319591
  }
@@ -319732,7 +319871,7 @@ async function reviewActive(s, uid, card, a, landing, installation = tickInstall
319732
319871
  removeActive(s, card.id);
319733
319872
  return;
319734
319873
  }
319735
- const retryGrok = card.details?.card_owner === "control-room" && canRetryRequiredGrok(savedReview);
319874
+ const retryGrok = !xaiWorker(card) && card.details?.card_owner === "control-room" && canRetryRequiredGrok(savedReview);
319736
319875
  const retryReview = savedReview.verdict === "UNAVAILABLE" && counter(savedReview.unavailable) > 0 && counter(savedReview.unavailable) < 3;
319737
319876
  const recoveryKey = infrastructureRecoveryKey(card);
319738
319877
  if (recoveryKey && (git(["rev-parse", "HEAD"], a.worktree) !== savedReview.sha || git(["status", "--porcelain"], a.worktree))) {
@@ -319928,7 +320067,7 @@ async function reviewActive(s, uid, card, a, landing, installation = tickInstall
319928
320067
  acceptanceSha256: reviewAcceptanceHash(card),
319929
320068
  rulesSha256: reviewRulesHash(round),
319930
320069
  ...policy ? { policy } : {},
319931
- requiredGrok: policy ? false : card.details?.card_owner === "control-room",
320070
+ requiredGrok: policy || xaiWorker(card) ? false : card.details?.card_owner === "control-room",
319932
320071
  ...retryReceipt ? { retryGrok: retryReceipt } : {},
319933
320072
  packagingLoadedSha: loadedSha,
319934
320073
  qualification: {
@@ -320082,6 +320221,7 @@ async function reconcileBoardActives(s, uid, boardCards2, installation = tickIns
320082
320221
  const firstOpenCode = s.actives.find((active) => active.backend === "opencode");
320083
320222
  if (firstOpenCode) s.opencodePilotStartedAt = firstOpenCode.startedAt;
320084
320223
  }
320224
+ if (!s.grokPilotStartedAt) s.grokPilotStartedAt = s.actives.find((active) => active.backend === "grok")?.startedAt;
320085
320225
  s.parallel_peak = Math.max(s.parallel_peak, s.actives.length);
320086
320226
  } finally {
320087
320227
  if (engineClient()) s.actives.push(...pendingActives);
@@ -320174,8 +320314,8 @@ async function consumeActive(s, uid, a = s.actives[0], landing = { available: tr
320174
320314
  return true;
320175
320315
  };
320176
320316
  if (!legacyDecimalAttempts && !matchesInitialStamp()) return true;
320177
- const openCodeJob = a.backend === "opencode" && a.opencode && a.model ? { backend: "opencode", jobId: a.jobId, model: a.model, startedAt: a.startedAt, cwd: a.worktree, opencode: a.opencode } : null;
320178
- if (a.backend === "opencode" && !openCodeJob) {
320317
+ const openCodeJob = a.backend === "grok" && a.grok && a.model ? { backend: "grok", jobId: a.jobId, model: a.model, startedAt: a.startedAt, cwd: a.worktree, grok: a.grok } : a.backend === "opencode" && a.opencode && a.model ? { backend: "opencode", jobId: a.jobId, model: a.model, startedAt: a.startedAt, cwd: a.worktree, opencode: a.opencode } : null;
320318
+ if ((a.backend === "opencode" || a.backend === "grok") && !openCodeJob) {
320179
320319
  return holdOpenCode("opencode-unknown", "niepe\u0142na to\u017Csamo\u015B\u0107 joba; bez wyniku");
320180
320320
  }
320181
320321
  const observed = openCodeJob ? workerStatus(openCodeJob) : null;
@@ -320344,10 +320484,31 @@ async function consumeActive(s, uid, a = s.actives[0], landing = { available: tr
320344
320484
  if (openCodeJob && !["completed", "failed", "cancelled", "timeout"].includes(status2)) {
320345
320485
  return holdOpenCode("opencode-terminal-hold", `${status2}; ${st.out.slice(0, 180)}; bez retry`);
320346
320486
  }
320487
+ if (a.backend === "grok" && a.startedAt === s.grokPilotStartedAt) s.grokPilotCompletedAt = a.startedAt;
320488
+ if (a.backend === "grok" && openCodeJob && status2 === "failed") {
320489
+ let reason;
320490
+ try {
320491
+ reason = grokStartFailure(openCodeJob);
320492
+ } catch (error48) {
320493
+ return holdOpenCode("grok-start-hold", errorText5(error48));
320494
+ }
320495
+ if (reason) {
320496
+ const grokStartFallback = { reason, at: (/* @__PURE__ */ new Date()).toISOString(), promptPath: a.grok.promptPath, worktree: a.worktree };
320497
+ const stamp2 = { ...metadata, grokStartFallback, worker_status: "failed", outcome: "grok_start_fallback", move: "retry" };
320498
+ await appendBoundedDetail(uid, card.id, { maszynista: stamp2 });
320499
+ card.details = { ...card.details, maszynista: stamp2 };
320500
+ await updateTask2(uid, card.id, { expected: { status: card.status, details: card.details }, ...readyTaskPatch(), status: "ready", assignee: null });
320501
+ log2(`ALARM Grok start ${card.id}: ${reason}; fallback Codex`);
320502
+ removeActive(s, card.id);
320503
+ return true;
320504
+ }
320505
+ }
320347
320506
  const openCodeResult = openCodeJob && status2 !== "timeout" ? workerResult(openCodeJob, { exportSession: exportOpenCodeSession }) : null;
320348
320507
  if (openCodeResult?.status === "unknown") {
320349
320508
  return holdOpenCode("opencode-result-hold", `${openCodeResult.status} ${openCodeResult.reason}; bez retry`);
320350
320509
  }
320510
+ if (a.backend === "grok" && openCodeResult?.status === "failed" && openCodeResult.reason.startsWith("Grok cancelled ("))
320511
+ log2(`ALARM Grok cancelled ${card.id}: ${openCodeResult.reason}`);
320351
320512
  const res = openCodeResult ? { ok: openCodeResult.status === "completed", out: openCodeResult.status === "completed" ? openCodeResult.report : openCodeResult.reason } : openCodeJob ? { ok: false, out: "timeout" } : helper(["result", a.jobId, "--json"], a.worktree);
320352
320513
  let output = openCodeResult ? res.out : "";
320353
320514
  let providerDiagnostic = "";
@@ -320372,6 +320533,10 @@ async function consumeActive(s, uid, a = s.actives[0], landing = { available: tr
320372
320533
  output = "";
320373
320534
  log2(`worker-capacity cardId=${a.taskId} jobId=${a.jobId} attempts=${a.attempts}: ${providerDiagnostic.replace(/\n/g, " ")}`);
320374
320535
  }
320536
+ if (a.backend === "grok" && openCodeResult?.status === "completed") {
320537
+ a.model = openCodeResult.model;
320538
+ a.provider = "xai";
320539
+ }
320375
320540
  const sparseDirectories = metadata.sparseDirectories;
320376
320541
  let outcome = openCodeResult && openCodeResult.status !== "completed" ? { status: "FAILED", report: `OpenCode ${openCodeResult.status}: ${openCodeResult.reason}` } : status2 === "timeout" ? { status: "FAILED", report: codexProcessDead ? `proces Workera (pid ${pid}) nie \u017Cyje po ${ageMin.toFixed(0)} min \u2014 bez wyniku` : `timeout po ${WORKER_TIMEOUT_MIN} min` } : parseWorkerOutput(output);
320377
320542
  const success3 = outcome.status === "WORKER_FINISHED" || outcome.status === "ALREADY_DONE";
@@ -320527,7 +320692,7 @@ async function consumeActive(s, uid, a = s.actives[0], landing = { available: tr
320527
320692
  }
320528
320693
  const blockerDependencies = outcome.status === "ACTIONABLE_BLOCKER" ? await factoryPredecessors(uid, [card]) : /* @__PURE__ */ new Map();
320529
320694
  const blockerResolved = (card.dependsOn ?? []).every((id2) => blockerDependencies.has(id2)) ? (card.dependsOn ?? []).filter((id2) => factoryDependenciesReady({ ...card, dependsOn: [id2] }, blockerDependencies)) : null;
320530
- const postUsage = openCodeJob ? readCompletedUsage(WORKER_MODELS_CONFIG, OPENCODE_LEDGER) : null;
320695
+ const postUsage = a.backend === "opencode" ? readCompletedUsage(WORKER_MODELS_CONFIG, OPENCODE_LEDGER) : null;
320531
320696
  const workerOutcome = atCapacity ? "MODEL_AT_CAPACITY" : outcome.status;
320532
320697
  const move = atCapacity ? { status: "retry", note: "Wybrany model jest zaj\u0119ty; ponowienie na tym samym modelu za 10 min bez zu\u017Cycia pr\xF3by jako\u015Bciowej" } : decideBoardMove(outcome, a.attempts, MAX_ATTEMPTS);
320533
320698
  log2(`karta ${a.taskId}: worker=${status2} outcome=${outcome.status} \u2192 ${move.status}`);
@@ -320559,7 +320724,8 @@ async function consumeActive(s, uid, a = s.actives[0], landing = { available: tr
320559
320724
  workerSha,
320560
320725
  workerReportReceipt,
320561
320726
  ...openCodeResult?.status === "completed" ? {
320562
- backend: "opencode",
320727
+ backend: a.backend,
320728
+ ...a.grok ? { grok: a.grok } : {},
320563
320729
  model: openCodeResult.model,
320564
320730
  provider: openCodeResult.provider,
320565
320731
  sessionId: openCodeResult.sessionId,
@@ -322537,7 +322703,30 @@ Rebase zosta\u0142 przerwany przez udany abort; HEAD, diff i indeks s\u0105 zach
322537
322703
  "## Ochrona zakresu zapisu",
322538
322704
  "Nowy plik wolno utworzy\u0107 tylko w katalogach wymienionych w `details.scope`. W innym katalogu zako\u0144cz ACTIONABLE_BLOCKER z komunikatem: katalog `<nazwa>/` poza sparse checkout \u2014 dopisz go do `details.scope` karty."
322539
322705
  ].join("\n");
322540
- const localArtifacts = (installation?.workerArtifacts ?? createWorkerTmpdir)(worktree, c.id);
322706
+ const previousWorker = asRecord3(c.details?.maszynista);
322707
+ const startFallback = asRecord3(previousWorker.grokStartFallback);
322708
+ let localArtifacts;
322709
+ if (typeof startFallback.promptPath === "string") {
322710
+ try {
322711
+ const owned2 = asRecord3(previousWorker.artifacts);
322712
+ const owner = {
322713
+ taskId: c.id,
322714
+ title: c.title,
322715
+ trackId: c.trackId ?? null,
322716
+ worktree,
322717
+ jobId: String(previousWorker.jobId ?? ""),
322718
+ branch: String(previousWorker.branch ?? ""),
322719
+ startedAt: String(previousWorker.at ?? ""),
322720
+ attempts: counter(previousWorker.attempts)
322721
+ };
322722
+ const candidates2 = ownedWorkerCandidates(owner, owned2);
322723
+ if (typeof owned2.tmpdir !== "string" || !candidates2.includes(owned2.tmpdir) || !(0, import_node_fs47.lstatSync)(owned2.tmpdir).isDirectory())
322724
+ throw new Error("brak w\u0142asnego TMPDIR pierwotnej pr\xF3by");
322725
+ localArtifacts = { tmpdir: owned2.tmpdir, nextVerifyOwned: owned2.nextVerifyOwned === true };
322726
+ } catch (error48) {
322727
+ throw new DispatchHold(`HOLD Grok fallback: TMPDIR: ${errorText5(error48)}`, false);
322728
+ }
322729
+ } else localArtifacts = (installation?.workerArtifacts ?? createWorkerTmpdir)(worktree, c.id);
322541
322730
  const workerEnv2 = taskMktempEnv({ ...installation?.kind === "client" ? installation.workerEnv() : selection.backend === "opencode" ? openCodeExecutionEnv() : installation?.workerEnv() ?? executionEnv2(), TMPDIR: localArtifacts.tmpdir });
322542
322731
  const northStar = await loadNorthStar2(uid, installation);
322543
322732
  let builtBrief;
@@ -322548,9 +322737,18 @@ Rebase zosta\u0142 przerwany przez udany abort; HEAD, diff i indeks s\u0105 zach
322548
322737
  throw new DispatchHold(error48.message);
322549
322738
  throw error48;
322550
322739
  }
322551
- const brief2 = builtBrief + sparseGuard + rebaseConflict + `
322740
+ let brief2 = builtBrief + sparseGuard + rebaseConflict + `
322552
322741
  TMPDIR tej pr\xF3by: ${localArtifacts.tmpdir}. Kopie tw\xF3rz przez mktemp -d "$TMPDIR/verify.XXXXXX"; automat sprz\u0105ta po potwierdzonym terminalu. Trwa\u0142e dowody/receipty zapisz poza TMPDIR przed raportem terminalnym. Testy i fixture dziedzicz\u0105 ten TMPDIR.
322553
- ` + (selection.backend === "opencode" ? "\nW RAPORT MASZYNISTY dodaj dok\u0142adnie jedn\u0105 lini\u0119 `compound_learning: zero|one|attempted_unavailable` z w\u0142a\u015Bciw\u0105 warto\u015Bci\u0105.\n" : "");
322742
+ ` + (selection.backend === "grok" ? 'ZASADA POW\u0141OKI (zmierzona): przekierowa\u0144 do pliku (`>`, `>>`, `2>`, `cat > plik << EOF`) NIE kieruj na \u015Bcie\u017Ck\u0119 ze zmienn\u0105 ($TMPDIR, ${X}, $PWD) \u2014 tryb bez pyta\u0144 ko\u0144czy wtedy CA\u0141\u0104 sesj\u0119, zanim cokolwiek zrobisz. Plik zapisuj przez `tee "$TMPDIR/\u2026"` (np. `cat << \'EOF\' | tee "$P/plik" >/dev/null`) albo narz\u0119dziem write ze \u015Bcie\u017Ck\u0105 literaln\u0105.\n' : "") + (selection.backend !== "codex" ? "\nW RAPORT MASZYNISTY dodaj dok\u0142adnie jedn\u0105 lini\u0119 `compound_learning: zero|one|attempted_unavailable` z w\u0142a\u015Bciw\u0105 warto\u015Bci\u0105.\n" : "");
322743
+ if (typeof startFallback.promptPath === "string") {
322744
+ if (startFallback.worktree !== worktree || startFallback.promptPath !== asRecord3(asRecord3(c.details?.maszynista).grok).promptPath)
322745
+ throw new DispatchHold("HOLD Grok fallback: zmieniona to\u017Csamo\u015B\u0107 briefu/worktree", false);
322746
+ try {
322747
+ brief2 = (0, import_node_fs47.readFileSync)(startFallback.promptPath, "utf8");
322748
+ } catch (error48) {
322749
+ throw new DispatchHold(`HOLD Grok fallback: brief nieczytelny: ${errorText5(error48)}`, false);
322750
+ }
322751
+ }
322554
322752
  const engine = clientConfig ? { model: clientConfig.selection.worker.model, effort: clientConfig.selection.worker.effort, note: null } : resolveCodexEngine(c.details, process.env);
322555
322753
  if (selection.backend === "codex" && engine.note) log2(`karta ${c.id}: ${engine.note}`);
322556
322754
  recreatedPreparing = false;
@@ -322574,7 +322772,7 @@ TMPDIR tej pr\xF3by: ${localArtifacts.tmpdir}. Kopie tw\xF3rz przez mktemp -d "$
322574
322772
  }
322575
322773
  if (clientConfig && !(0, import_node_util12.isDeepStrictEqual)(clientConfig, loadClientPair(process.env.ROBISIE_ENGINE_CONFIG)))
322576
322774
  throw new ClientPairHold("konfiguracja zmieni\u0142a si\u0119 przed startem");
322577
- const started = startWorker(
322775
+ let started = startWorker(
322578
322776
  {
322579
322777
  selection: selection.backend === "codex" ? { ...selection, model: engine.model } : selection,
322580
322778
  prompt: brief2,
@@ -322585,6 +322783,24 @@ TMPDIR tej pr\xF3by: ${localArtifacts.tmpdir}. Kopie tw\xF3rz przez mktemp -d "$
322585
322783
  },
322586
322784
  { codexHelper: (args, cwd) => helper([...args], cwd, workerEnv2) }
322587
322785
  );
322786
+ if (!started.ok && !started.mayHaveStarted && selection.backend === "grok") {
322787
+ const grokStartFallback = { reason: started.reason, at: (/* @__PURE__ */ new Date()).toISOString(), worktree };
322788
+ const fallbackStamp = { ...asRecord3(c.details?.maszynista), grokStartFallback };
322789
+ await appendBoundedDetail(uid, c.id, { maszynista: fallbackStamp });
322790
+ c.details = { ...c.details, maszynista: fallbackStamp };
322791
+ log2(`ALARM Grok start ${c.id}: ${started.reason}; fallback Codex`);
322792
+ started = startWorker(
322793
+ {
322794
+ selection: { ok: true, backend: "codex", model: engine.model },
322795
+ prompt: brief2,
322796
+ cwd: worktree,
322797
+ artifactsDir: import_node_path52.default.join(hostStateDir(), "worker-jobs"),
322798
+ effort: engine.effort,
322799
+ env: workerEnv2
322800
+ },
322801
+ { codexHelper: (args, cwd) => helper([...args], cwd, workerEnv2) }
322802
+ );
322803
+ }
322588
322804
  if (!started.ok && !started.mayHaveStarted) throw Object.assign(
322589
322805
  new Error(`spawn ${selection.backend === "codex" ? "Codex" : "OpenCode"} nieudany: ${started.reason}`),
322590
322806
  { errorCode: started.errorCode }
@@ -322621,10 +322837,12 @@ TMPDIR tej pr\xF3by: ${localArtifacts.tmpdir}. Kopie tw\xF3rz przez mktemp -d "$
322621
322837
  attempts,
322622
322838
  backend: job.backend,
322623
322839
  model: job.model,
322840
+ ...job.grok ? { grok: job.grok, provider: "xai" } : {},
322624
322841
  ...job.opencode ? { opencode: job.opencode } : {}
322625
322842
  };
322626
322843
  s.actives.push(active);
322627
322844
  uncertainStarts.get(s)?.delete(`worker-start:${c.id}`);
322845
+ if (job.backend === "grok" && !s.grokPilotStartedAt) s.grokPilotStartedAt = job.startedAt;
322628
322846
  if (job.backend === "opencode" && !s.opencodePilotStartedAt) s.opencodePilotStartedAt = job.startedAt;
322629
322847
  s.parallel_peak = Math.max(s.parallel_peak, s.actives.length);
322630
322848
  claimed = true;
@@ -322632,6 +322850,12 @@ TMPDIR tej pr\xF3by: ${localArtifacts.tmpdir}. Kopie tw\xF3rz przez mktemp -d "$
322632
322850
  engine: { model: job.model, effort: job.backend === "codex" ? engine.effort : "n/a", note: job.backend === "codex" ? engine.note : null },
322633
322851
  backend: job.backend,
322634
322852
  model: job.model,
322853
+ ...job.grok ? { grok: job.grok, provider: "xai" } : {},
322854
+ ...asRecord3(c.details?.maszynista).grokStartFallback ? { grokStartFallback: {
322855
+ reason: asRecord3(asRecord3(c.details?.maszynista).grokStartFallback).reason,
322856
+ at: asRecord3(asRecord3(c.details?.maszynista).grokStartFallback).at,
322857
+ worktree
322858
+ } } : {},
322635
322859
  ...job.opencode ? { opencode: job.opencode } : {},
322636
322860
  ...selection.backend === "opencode" ? { local_estimate: selection.usage } : {},
322637
322861
  branchLease: asRecord3(c.details?.maszynista).branchLease ?? null,
@@ -323824,7 +324048,7 @@ function readRequestedWorkerBackend() {
323824
324048
  return null;
323825
324049
  }
323826
324050
  }
323827
- if (backend !== "codex" && backend !== "opencode") {
324051
+ if (backend !== "codex" && backend !== "opencode" && backend !== "grok") {
323828
324052
  log2(`worker-backend NO_DISPATCH path=${file3} source=${source}: nieprawid\u0142owy backend`);
323829
324053
  return null;
323830
324054
  }
@@ -323918,7 +324142,7 @@ function createScopeReader(s, uid, projectId2, installation) {
323918
324142
  const absoluteOrNull = (value) => value === null || typeof value === "string" && import_node_path52.default.isAbsolute(value);
323919
324143
  const digest5 = (value) => typeof value === "string" && /^[a-fA-F0-9]{64}$/.test(value);
323920
324144
  const inventory = (value) => Array.isArray(value) && value.every((pid) => Number.isSafeInteger(pid) && pid > 0);
323921
- if (proof.version !== 1 || proof.card_id !== row.id || proof.park_branch !== park || typeof proof.branch_sha !== "string" || !/^[a-f0-9]{40}$/.test(proof.branch_sha) || !absoluteOrNull(proof.worktree) || proof.worktree !== metadata.worktree || !(proof.job_id === null || typeof proof.job_id === "string" && proof.job_id.trim()) || proof.job_id !== metadata.jobId || !Number.isSafeInteger(proof.attempts) || Number(proof.attempts) < 0 || proof.attempts !== metadata.attempts || !["codex", "opencode"].includes(String(backend)) || proof.backend !== backend || proof.owner_absent !== true || proof.process_inventory_complete !== true || !inventory(proof.process_ids) || !inventory(proof.process_groups) || !digest5(proof.wip_sha256) || !digest5(proof.audit_sha256) || typeof proof.audit_ref !== "string" || !import_node_path52.default.isAbsolute(proof.audit_ref)) fail4("niepe\u0142na lub zmieniona to\u017Csamo\u015B\u0107/dow\xF3d CR");
324145
+ if (proof.version !== 1 || proof.card_id !== row.id || proof.park_branch !== park || typeof proof.branch_sha !== "string" || !/^[a-f0-9]{40}$/.test(proof.branch_sha) || !absoluteOrNull(proof.worktree) || proof.worktree !== metadata.worktree || !(proof.job_id === null || typeof proof.job_id === "string" && proof.job_id.trim()) || proof.job_id !== metadata.jobId || !Number.isSafeInteger(proof.attempts) || Number(proof.attempts) < 0 || proof.attempts !== metadata.attempts || !["codex", "opencode", "grok"].includes(String(backend)) || proof.backend !== backend || proof.owner_absent !== true || proof.process_inventory_complete !== true || !inventory(proof.process_ids) || !inventory(proof.process_groups) || !digest5(proof.wip_sha256) || !digest5(proof.audit_sha256) || typeof proof.audit_ref !== "string" || !import_node_path52.default.isAbsolute(proof.audit_ref)) fail4("niepe\u0142na lub zmieniona to\u017Csamo\u015B\u0107/dow\xF3d CR");
323922
324146
  if (readBranchSha(park) !== proof.branch_sha || git(["rev-parse", "--verify", `refs/tags/${park}^{commit}`]) !== proof.branch_sha) fail4("ref/tag nie wi\u0105\u017Ce SHA");
323923
324147
  if (s.actives.some((a) => a.taskId === row.id || a.branch === metadata.branch || a.branch === park || proof.job_id !== null && a.jobId === proof.job_id || proof.worktree !== null && a.worktree === proof.worktree)) fail4("aktywny w\u0142a\u015Bciciel");
323924
324148
  if (proof.job_id !== null) {
@@ -323928,7 +324152,8 @@ function createScopeReader(s, uid, projectId2, installation) {
323928
324152
  jobId: proof.job_id,
323929
324153
  cwd: proof.worktree,
323930
324154
  model: typeof metadata.model === "string" ? metadata.model : CODEX_DEFAULT_MODEL,
323931
- startedAt: String(backend === "opencode" ? asRecord3(metadata.opencode).startedAt ?? "" : metadata.at ?? ""),
324155
+ grok: metadata.grok,
324156
+ startedAt: String(backend === "grok" ? asRecord3(metadata.grok).startedAt ?? "" : backend === "opencode" ? asRecord3(metadata.opencode).startedAt ?? "" : metadata.at ?? ""),
323932
324157
  opencode: metadata.opencode,
323933
324158
  ambiguousStart: metadata.outcome === "start_unknown"
323934
324159
  }, { codexHelper: (args, cwd) => helper([...args], cwd) });
@@ -324122,7 +324347,7 @@ function processWip(s, cards = /* @__PURE__ */ new Map()) {
324122
324347
  if (worker.jobId === active.jobId && ["completed", "failed", "cancelled"].includes(String(worker.worker_status))) continue;
324123
324348
  try {
324124
324349
  const backend = active.backend ?? "codex";
324125
- if (backend !== "codex" && backend !== "opencode") throw new Error(`nieobs\u0142ugiwany backend Workera: ${backend}`);
324350
+ if (backend !== "codex" && backend !== "opencode" && backend !== "grok") throw new Error(`nieobs\u0142ugiwany backend Workera: ${backend}`);
324126
324351
  const observed = workerStatus({
324127
324352
  backend,
324128
324353
  jobId: active.jobId,
@@ -324130,6 +324355,7 @@ function processWip(s, cards = /* @__PURE__ */ new Map()) {
324130
324355
  model: active.model ?? CODEX_DEFAULT_MODEL,
324131
324356
  startedAt: active.startedAt,
324132
324357
  opencode: active.opencode,
324358
+ grok: active.grok,
324133
324359
  ambiguousStart: worker.outcome === "start_unknown"
324134
324360
  }, { codexHelper: (args, cwd) => helper([...args], cwd) });
324135
324361
  if (["completed", "failed", "cancelled"].includes(observed.status)) continue;
@@ -324413,8 +324639,17 @@ async function dispatchNext(s, uid, projectId2, diskDependencies, cards = /* @__
324413
324639
  continue;
324414
324640
  }
324415
324641
  const engineDetails = c.details ?? {};
324416
- const selection = clientConfig ? { ok: true, backend: "codex", model: clientConfig.selection.worker.model } : selectWorkerBackend({
324642
+ let selection = clientConfig ? { ok: true, backend: "codex", model: clientConfig.selection.worker.model } : selectWorkerBackend({
324417
324643
  requestedBackend,
324644
+ qualityLane: engineDetails.quality_lane,
324645
+ cardClass: classifyReviewCard(c),
324646
+ grokStartFallback: !!asRecord3(c.details?.maszynista).grokStartFallback,
324647
+ grokPilot: {
324648
+ startedAt: s.grokPilotStartedAt,
324649
+ completedAt: s.grokPilotCompletedAt,
324650
+ acceptance: s.grokPilotAcceptance,
324651
+ active: s.actives.some((a) => a.backend === "grok" && a.startedAt === s.grokPilotStartedAt)
324652
+ },
324418
324653
  codexModel: resolveCodexEngine(engineDetails, process.env).model,
324419
324654
  pilotEnabled: true,
324420
324655
  pilotPending: !s.opencodePilotAcceptance,
@@ -324439,6 +324674,9 @@ async function dispatchNext(s, uid, projectId2, diskDependencies, cards = /* @__
324439
324674
  configPath: WORKER_MODELS_CONFIG,
324440
324675
  ledgerPath: OPENCODE_LEDGER
324441
324676
  });
324677
+ if (requestedBackend === "grok" && asRecord3(c.details?.maszynista).grokStartFallback) {
324678
+ selection = { ok: true, backend: "codex", model: resolveCodexEngine(engineDetails, process.env).model };
324679
+ }
324442
324680
  if (!selection.ok) {
324443
324681
  skipReady(c, `HOLD backend Workera: ${selection.reason}`);
324444
324682
  waitingWip.push(`${label2}: ${c.title} (${selection.reason})`);
@@ -325456,7 +325694,7 @@ var init_tick = __esm({
325456
325694
  selectorUnavailableTicks = /* @__PURE__ */ new WeakMap();
325457
325695
  uncertainStarts = /* @__PURE__ */ new WeakMap();
325458
325696
  processCards = /* @__PURE__ */ new WeakMap();
325459
- if (require.main === module && process.argv[2] !== "--opencode-runner") {
325697
+ if (require.main === module && !["--opencode-runner", "--grok-runner"].includes(process.argv[2] ?? "")) {
325460
325698
  if (process.argv[2] === "--job") {
325461
325699
  const [, , , job, input] = process.argv;
325462
325700
  if (process.argv.length !== 5 || !input || !["review", "tester", "receiver"].includes(job)) {
@@ -201,6 +201,8 @@ export async function cancelK3CodexJob(stateDir, jobId, deps = {}) {
201
201
  const stored = terminal(state);
202
202
  if (stored)
203
203
  return stored;
204
+ if (!alive(-state.pgid, deps) && !alive(state.pid, deps))
205
+ return publish(state, { status: "cancelled" });
204
206
  if (!alive(-state.pgid, deps) || !verify(state, deps))
205
207
  return terminal(state) ?? unknown("runner_not_verified");
206
208
  for (const signal of ["SIGTERM", "SIGKILL"]) {
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.23 \u2014 plik zarz\u0105dzany przez `npx robisie`; `npx robisie uninstall` go usunie -->";
20
+ export declare const MANAGED_LINE = "<!-- robisie:managed 0.5.25 \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.23) <!-- x-release-please-version -->
1
+ # robisie — from account to accepted card (package 0.5.25) <!-- 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
 
package/docs/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # robisie — od konta do odebranej karty (paczka 0.5.23) <!-- x-release-please-version -->
1
+ # robisie — od konta do odebranej karty (paczka 0.5.25) <!-- 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
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "robisie",
3
- "version": "0.5.23",
3
+ "version": "0.5.25",
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",